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.

strophe.jingle.adapter.js 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. function TraceablePeerConnection(ice_config, constraints) {
  2. var self = this;
  3. var RTCPeerconnection = navigator.mozGetUserMedia ? mozRTCPeerConnection : webkitRTCPeerConnection;
  4. this.peerconnection = new RTCPeerconnection(ice_config, constraints);
  5. this.updateLog = [];
  6. this.stats = {};
  7. this.statsinterval = null;
  8. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  9. /**
  10. * Array of ssrcs that will be added on next modifySources call.
  11. * @type {Array}
  12. */
  13. this.addssrc = [];
  14. /**
  15. * Array of ssrcs that will be added on next modifySources call.
  16. * @type {Array}
  17. */
  18. this.removessrc = [];
  19. /**
  20. * Pending operation that will be done during modifySources call.
  21. * Currently 'mute'/'unmute' operations are supported.
  22. *
  23. * @type {String}
  24. */
  25. this.pendingop = null;
  26. /**
  27. * Flag indicates that peer connection stream have changed and modifySources should proceed.
  28. * @type {boolean}
  29. */
  30. this.switchstreams = false;
  31. // override as desired
  32. this.trace = function (what, info) {
  33. //console.warn('WTRACE', what, info);
  34. self.updateLog.push({
  35. time: new Date(),
  36. type: what,
  37. value: info || ""
  38. });
  39. };
  40. this.onicecandidate = null;
  41. this.peerconnection.onicecandidate = function (event) {
  42. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  43. if (self.onicecandidate !== null) {
  44. self.onicecandidate(event);
  45. }
  46. };
  47. this.onaddstream = null;
  48. this.peerconnection.onaddstream = function (event) {
  49. self.trace('onaddstream', event.stream.id);
  50. if (self.onaddstream !== null) {
  51. self.onaddstream(event);
  52. }
  53. };
  54. this.onremovestream = null;
  55. this.peerconnection.onremovestream = function (event) {
  56. self.trace('onremovestream', event.stream.id);
  57. if (self.onremovestream !== null) {
  58. self.onremovestream(event);
  59. }
  60. };
  61. this.onsignalingstatechange = null;
  62. this.peerconnection.onsignalingstatechange = function (event) {
  63. self.trace('onsignalingstatechange', self.signalingState);
  64. if (self.onsignalingstatechange !== null) {
  65. self.onsignalingstatechange(event);
  66. }
  67. };
  68. this.oniceconnectionstatechange = null;
  69. this.peerconnection.oniceconnectionstatechange = function (event) {
  70. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  71. if (self.oniceconnectionstatechange !== null) {
  72. self.oniceconnectionstatechange(event);
  73. }
  74. };
  75. this.onnegotiationneeded = null;
  76. this.peerconnection.onnegotiationneeded = function (event) {
  77. self.trace('onnegotiationneeded');
  78. if (self.onnegotiationneeded !== null) {
  79. self.onnegotiationneeded(event);
  80. }
  81. };
  82. self.ondatachannel = null;
  83. this.peerconnection.ondatachannel = function (event) {
  84. self.trace('ondatachannel', event);
  85. if (self.ondatachannel !== null) {
  86. self.ondatachannel(event);
  87. }
  88. };
  89. if (!navigator.mozGetUserMedia && this.maxstats) {
  90. this.statsinterval = window.setInterval(function() {
  91. self.peerconnection.getStats(function(stats) {
  92. var results = stats.result();
  93. for (var i = 0; i < results.length; ++i) {
  94. //console.log(results[i].type, results[i].id, results[i].names())
  95. var now = new Date();
  96. results[i].names().forEach(function (name) {
  97. var id = results[i].id + '-' + name;
  98. if (!self.stats[id]) {
  99. self.stats[id] = {
  100. startTime: now,
  101. endTime: now,
  102. values: [],
  103. times: []
  104. };
  105. }
  106. self.stats[id].values.push(results[i].stat(name));
  107. self.stats[id].times.push(now.getTime());
  108. if (self.stats[id].values.length > self.maxstats) {
  109. self.stats[id].values.shift();
  110. self.stats[id].times.shift();
  111. }
  112. self.stats[id].endTime = now;
  113. });
  114. }
  115. });
  116. }, 1000);
  117. }
  118. };
  119. dumpSDP = function(description) {
  120. return 'type: ' + description.type + '\r\n' + description.sdp;
  121. }
  122. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  123. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  124. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  125. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
  126. var publicLocalDescription = simulcast.reverseTransformLocalDescription(this.peerconnection.localDescription);
  127. return publicLocalDescription;
  128. });
  129. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
  130. var publicRemoteDescription = simulcast.reverseTransformRemoteDescription(this.peerconnection.remoteDescription);
  131. return publicRemoteDescription;
  132. });
  133. }
  134. TraceablePeerConnection.prototype.addStream = function (stream) {
  135. this.trace('addStream', stream.id);
  136. simulcast.resetSender();
  137. this.peerconnection.addStream(stream);
  138. };
  139. TraceablePeerConnection.prototype.removeStream = function (stream) {
  140. this.trace('removeStream', stream.id);
  141. simulcast.resetSender();
  142. this.peerconnection.removeStream(stream);
  143. };
  144. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  145. this.trace('createDataChannel', label, opts);
  146. return this.peerconnection.createDataChannel(label, opts);
  147. };
  148. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  149. var self = this;
  150. description = simulcast.transformLocalDescription(description);
  151. this.trace('setLocalDescription', dumpSDP(description));
  152. this.peerconnection.setLocalDescription(description,
  153. function () {
  154. self.trace('setLocalDescriptionOnSuccess');
  155. successCallback();
  156. },
  157. function (err) {
  158. self.trace('setLocalDescriptionOnFailure', err);
  159. failureCallback(err);
  160. }
  161. );
  162. /*
  163. if (this.statsinterval === null && this.maxstats > 0) {
  164. // start gathering stats
  165. }
  166. */
  167. };
  168. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  169. var self = this;
  170. description = simulcast.transformRemoteDescription(description);
  171. this.trace('setRemoteDescription', dumpSDP(description));
  172. this.peerconnection.setRemoteDescription(description,
  173. function () {
  174. self.trace('setRemoteDescriptionOnSuccess');
  175. successCallback();
  176. },
  177. function (err) {
  178. self.trace('setRemoteDescriptionOnFailure', err);
  179. failureCallback(err);
  180. }
  181. );
  182. /*
  183. if (this.statsinterval === null && this.maxstats > 0) {
  184. // start gathering stats
  185. }
  186. */
  187. };
  188. TraceablePeerConnection.prototype.hardMuteVideo = function (muted) {
  189. this.pendingop = muted ? 'mute' : 'unmute';
  190. };
  191. TraceablePeerConnection.prototype.enqueueAddSsrc = function(channel, ssrcLines) {
  192. if (!this.addssrc[channel]) {
  193. this.addssrc[channel] = '';
  194. }
  195. this.addssrc[channel] += ssrcLines;
  196. };
  197. TraceablePeerConnection.prototype.addSource = function (elem) {
  198. console.log('addssrc', new Date().getTime());
  199. console.log('ice', this.iceConnectionState);
  200. var sdp = new SDP(this.remoteDescription.sdp);
  201. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  202. var self = this;
  203. $(elem).each(function (idx, content) {
  204. var name = $(content).attr('name');
  205. var lines = '';
  206. tmp = $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  207. var semantics = this.getAttribute('semantics');
  208. var ssrcs = $(this).find('>source').map(function () {
  209. return this.getAttribute('ssrc');
  210. }).get();
  211. if (ssrcs.length != 0) {
  212. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  213. }
  214. });
  215. tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  216. tmp.each(function () {
  217. var ssrc = $(this).attr('ssrc');
  218. if(mySdp.containsSSRC(ssrc)){
  219. /**
  220. * This happens when multiple participants change their streams at the same time and
  221. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  222. * addssrc are scheduled for update IQ. See
  223. */
  224. console.warn("Got add stream request for my own ssrc: "+ssrc);
  225. return;
  226. }
  227. $(this).find('>parameter').each(function () {
  228. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  229. if ($(this).attr('value') && $(this).attr('value').length)
  230. lines += ':' + $(this).attr('value');
  231. lines += '\r\n';
  232. });
  233. });
  234. sdp.media.forEach(function(media, idx) {
  235. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  236. return;
  237. sdp.media[idx] += lines;
  238. self.enqueueAddSsrc(idx, lines);
  239. });
  240. sdp.raw = sdp.session + sdp.media.join('');
  241. });
  242. };
  243. TraceablePeerConnection.prototype.enqueueRemoveSsrc = function(channel, ssrcLines) {
  244. if (!this.removessrc[channel]){
  245. this.removessrc[channel] = '';
  246. }
  247. this.removessrc[channel] += ssrcLines;
  248. };
  249. TraceablePeerConnection.prototype.removeSource = function (elem) {
  250. console.log('removessrc', new Date().getTime());
  251. console.log('ice', this.iceConnectionState);
  252. var sdp = new SDP(this.remoteDescription.sdp);
  253. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  254. var self = this;
  255. $(elem).each(function (idx, content) {
  256. var name = $(content).attr('name');
  257. var lines = '';
  258. tmp = $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  259. var semantics = this.getAttribute('semantics');
  260. var ssrcs = $(this).find('>source').map(function () {
  261. return this.getAttribute('ssrc');
  262. }).get();
  263. if (ssrcs.length != 0) {
  264. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  265. }
  266. });
  267. tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  268. tmp.each(function () {
  269. var ssrc = $(this).attr('ssrc');
  270. // This should never happen, but can be useful for bug detection
  271. if(mySdp.containsSSRC(ssrc)){
  272. console.error("Got remove stream request for my own ssrc: "+ssrc);
  273. return;
  274. }
  275. $(this).find('>parameter').each(function () {
  276. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  277. if ($(this).attr('value') && $(this).attr('value').length)
  278. lines += ':' + $(this).attr('value');
  279. lines += '\r\n';
  280. });
  281. });
  282. sdp.media.forEach(function(media, idx) {
  283. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  284. return;
  285. sdp.media[idx] += lines;
  286. self.enqueueRemoveSsrc(idx, lines);
  287. });
  288. sdp.raw = sdp.session + sdp.media.join('');
  289. });
  290. };
  291. TraceablePeerConnection.prototype.modifySources = function(successCallback) {
  292. var self = this;
  293. if (this.signalingState == 'closed') return;
  294. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  295. // There is nothing to do since scheduled job might have been executed by another succeeding call
  296. if(successCallback){
  297. successCallback();
  298. }
  299. return;
  300. }
  301. // FIXME: this is a big hack
  302. // https://code.google.com/p/webrtc/issues/detail?id=2688
  303. // ^ has been fixed.
  304. if (!(this.signalingState == 'stable' && this.iceConnectionState == 'connected')) {
  305. console.warn('modifySources not yet', this.signalingState, this.iceConnectionState);
  306. this.wait = true;
  307. window.setTimeout(function() { self.modifySources(successCallback); }, 250);
  308. return;
  309. }
  310. if (this.wait) {
  311. window.setTimeout(function() { self.modifySources(successCallback); }, 2500);
  312. this.wait = false;
  313. return;
  314. }
  315. // Reset switch streams flag
  316. this.switchstreams = false;
  317. var sdp = new SDP(this.remoteDescription.sdp);
  318. // add sources
  319. this.addssrc.forEach(function(lines, idx) {
  320. sdp.media[idx] += lines;
  321. });
  322. this.addssrc = [];
  323. // remove sources
  324. this.removessrc.forEach(function(lines, idx) {
  325. lines = lines.split('\r\n');
  326. lines.pop(); // remove empty last element;
  327. lines.forEach(function(line) {
  328. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  329. });
  330. });
  331. this.removessrc = [];
  332. // FIXME:
  333. // this was a hack for the situation when only one peer exists
  334. // in the conference.
  335. // check if still required and remove
  336. if (sdp.media[0])
  337. sdp.media[0] = sdp.media[0].replace('a=recvonly', 'a=sendrecv');
  338. if (sdp.media[1])
  339. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  340. sdp.raw = sdp.session + sdp.media.join('');
  341. this.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  342. function() {
  343. if(self.signalingState == 'closed') {
  344. console.error("createAnswer attempt on closed state");
  345. return;
  346. }
  347. self.createAnswer(
  348. function(modifiedAnswer) {
  349. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  350. if (self.pendingop !== null) {
  351. var sdp = new SDP(modifiedAnswer.sdp);
  352. if (sdp.media.length > 1) {
  353. switch(self.pendingop) {
  354. case 'mute':
  355. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  356. break;
  357. case 'unmute':
  358. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  359. break;
  360. }
  361. sdp.raw = sdp.session + sdp.media.join('');
  362. modifiedAnswer.sdp = sdp.raw;
  363. }
  364. self.pendingop = null;
  365. }
  366. // FIXME: pushing down an answer while ice connection state
  367. // is still checking is bad...
  368. //console.log(self.peerconnection.iceConnectionState);
  369. // trying to work around another chrome bug
  370. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  371. self.setLocalDescription(modifiedAnswer,
  372. function() {
  373. //console.log('modified setLocalDescription ok');
  374. if(successCallback){
  375. successCallback();
  376. }
  377. },
  378. function(error) {
  379. console.error('modified setLocalDescription failed', error);
  380. }
  381. );
  382. },
  383. function(error) {
  384. console.error('modified answer failed', error);
  385. }
  386. );
  387. },
  388. function(error) {
  389. console.error('modify failed', error);
  390. }
  391. );
  392. };
  393. TraceablePeerConnection.prototype.close = function () {
  394. this.trace('stop');
  395. if (this.statsinterval !== null) {
  396. window.clearInterval(this.statsinterval);
  397. this.statsinterval = null;
  398. }
  399. this.peerconnection.close();
  400. };
  401. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  402. var self = this;
  403. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  404. this.peerconnection.createOffer(
  405. function (offer) {
  406. self.trace('createOfferOnSuccess', dumpSDP(offer));
  407. successCallback(offer);
  408. },
  409. function(err) {
  410. self.trace('createOfferOnFailure', err);
  411. failureCallback(err);
  412. },
  413. constraints
  414. );
  415. };
  416. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  417. var self = this;
  418. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  419. this.peerconnection.createAnswer(
  420. function (answer) {
  421. answer = simulcast.transformAnswer(answer);
  422. self.trace('createAnswerOnSuccess', dumpSDP(answer));
  423. successCallback(answer);
  424. },
  425. function(err) {
  426. self.trace('createAnswerOnFailure', err);
  427. failureCallback(err);
  428. },
  429. constraints
  430. );
  431. };
  432. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  433. var self = this;
  434. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  435. this.peerconnection.addIceCandidate(candidate);
  436. /* maybe later
  437. this.peerconnection.addIceCandidate(candidate,
  438. function () {
  439. self.trace('addIceCandidateOnSuccess');
  440. successCallback();
  441. },
  442. function (err) {
  443. self.trace('addIceCandidateOnFailure', err);
  444. failureCallback(err);
  445. }
  446. );
  447. */
  448. };
  449. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  450. if (navigator.mozGetUserMedia) {
  451. // ignore for now...
  452. } else {
  453. this.peerconnection.getStats(callback);
  454. }
  455. };
  456. // mozilla chrome compat layer -- very similar to adapter.js
  457. function setupRTC() {
  458. var RTC = null;
  459. if (navigator.mozGetUserMedia) {
  460. console.log('This appears to be Firefox');
  461. var version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  462. if (version >= 22) {
  463. RTC = {
  464. peerconnection: mozRTCPeerConnection,
  465. browser: 'firefox',
  466. getUserMedia: navigator.mozGetUserMedia.bind(navigator),
  467. attachMediaStream: function (element, stream) {
  468. element[0].mozSrcObject = stream;
  469. element[0].play();
  470. },
  471. pc_constraints: {}
  472. };
  473. if (!MediaStream.prototype.getVideoTracks)
  474. MediaStream.prototype.getVideoTracks = function () { return []; };
  475. if (!MediaStream.prototype.getAudioTracks)
  476. MediaStream.prototype.getAudioTracks = function () { return []; };
  477. RTCSessionDescription = mozRTCSessionDescription;
  478. RTCIceCandidate = mozRTCIceCandidate;
  479. }
  480. } else if (navigator.webkitGetUserMedia) {
  481. console.log('This appears to be Chrome');
  482. RTC = {
  483. peerconnection: webkitRTCPeerConnection,
  484. browser: 'chrome',
  485. getUserMedia: navigator.webkitGetUserMedia.bind(navigator),
  486. attachMediaStream: function (element, stream) {
  487. element.attr('src', webkitURL.createObjectURL(stream));
  488. },
  489. // DTLS should now be enabled by default but..
  490. pc_constraints: {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]}
  491. };
  492. if (navigator.userAgent.indexOf('Android') != -1) {
  493. RTC.pc_constraints = {}; // disable DTLS on Android
  494. }
  495. if (!webkitMediaStream.prototype.getVideoTracks) {
  496. webkitMediaStream.prototype.getVideoTracks = function () {
  497. return this.videoTracks;
  498. };
  499. }
  500. if (!webkitMediaStream.prototype.getAudioTracks) {
  501. webkitMediaStream.prototype.getAudioTracks = function () {
  502. return this.audioTracks;
  503. };
  504. }
  505. }
  506. if (RTC === null) {
  507. try { console.log('Browser does not appear to be WebRTC-capable'); } catch (e) { }
  508. }
  509. return RTC;
  510. }
  511. function getUserMediaWithConstraints(um, success_callback, failure_callback, resolution, bandwidth, fps, desktopStream) {
  512. var constraints = {audio: false, video: false};
  513. if (um.indexOf('video') >= 0) {
  514. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  515. }
  516. if (um.indexOf('audio') >= 0) {
  517. constraints.audio = { mandatory: {}, optional: []};// same behaviour as true
  518. }
  519. if (um.indexOf('screen') >= 0) {
  520. constraints.video = {
  521. mandatory: {
  522. chromeMediaSource: "screen",
  523. googLeakyBucket: true,
  524. maxWidth: window.screen.width,
  525. maxHeight: window.screen.height,
  526. maxFrameRate: 3
  527. },
  528. optional: []
  529. };
  530. }
  531. if (um.indexOf('desktop') >= 0) {
  532. constraints.video = {
  533. mandatory: {
  534. chromeMediaSource: "desktop",
  535. chromeMediaSourceId: desktopStream,
  536. googLeakyBucket: true,
  537. maxWidth: window.screen.width,
  538. maxHeight: window.screen.height,
  539. maxFrameRate: 3
  540. },
  541. optional: []
  542. }
  543. }
  544. if (constraints.audio) {
  545. // if it is good enough for hangouts...
  546. constraints.audio.optional.push(
  547. {googEchoCancellation: true},
  548. {googAutoGainControl: true},
  549. {googNoiseSupression: true},
  550. {googHighpassFilter: true},
  551. {googNoisesuppression2: true},
  552. {googEchoCancellation2: true},
  553. {googAutoGainControl2: true}
  554. );
  555. }
  556. if (constraints.video) {
  557. constraints.video.optional.push(
  558. {googNoiseReduction: false} // chrome 37 workaround for issue 3807, reenable in M38
  559. );
  560. if (um.indexOf('video') >= 0) {
  561. constraints.video.optional.push(
  562. {googLeakyBucket: true}
  563. );
  564. }
  565. }
  566. // Check if we are running on Android device
  567. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  568. if (resolution && !constraints.video || isAndroid) {
  569. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  570. }
  571. // see https://code.google.com/p/chromium/issues/detail?id=143631#c9 for list of supported resolutions
  572. switch (resolution) {
  573. // 16:9 first
  574. case '1080':
  575. case 'fullhd':
  576. constraints.video.mandatory.minWidth = 1920;
  577. constraints.video.mandatory.minHeight = 1080;
  578. break;
  579. case '720':
  580. case 'hd':
  581. constraints.video.mandatory.minWidth = 1280;
  582. constraints.video.mandatory.minHeight = 720;
  583. break;
  584. case '360':
  585. constraints.video.mandatory.minWidth = 640;
  586. constraints.video.mandatory.minHeight = 360;
  587. break;
  588. case '180':
  589. constraints.video.mandatory.minWidth = 320;
  590. constraints.video.mandatory.minHeight = 180;
  591. break;
  592. // 4:3
  593. case '960':
  594. constraints.video.mandatory.minWidth = 960;
  595. constraints.video.mandatory.minHeight = 720;
  596. break;
  597. case '640':
  598. case 'vga':
  599. constraints.video.mandatory.minWidth = 640;
  600. constraints.video.mandatory.minHeight = 480;
  601. break;
  602. case '320':
  603. constraints.video.mandatory.minWidth = 320;
  604. constraints.video.mandatory.minHeight = 240;
  605. break;
  606. default:
  607. if (isAndroid) {
  608. constraints.video.mandatory.minWidth = 320;
  609. constraints.video.mandatory.minHeight = 240;
  610. constraints.video.mandatory.maxFrameRate = 15;
  611. }
  612. break;
  613. }
  614. if (constraints.video.mandatory.minWidth)
  615. constraints.video.mandatory.maxWidth = constraints.video.mandatory.minWidth;
  616. if (constraints.video.mandatory.minHeight)
  617. constraints.video.mandatory.maxHeight = constraints.video.mandatory.minHeight;
  618. if (bandwidth) { // doesn't work currently, see webrtc issue 1846
  619. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};//same behaviour as true
  620. constraints.video.optional.push({bandwidth: bandwidth});
  621. }
  622. if (fps) { // for some cameras it might be necessary to request 30fps
  623. // so they choose 30fps mjpg over 10fps yuy2
  624. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};// same behaviour as true;
  625. constraints.video.mandatory.minFrameRate = fps;
  626. }
  627. var isFF = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
  628. try {
  629. if (config.enableSimulcast
  630. && constraints.video
  631. && constraints.video.chromeMediaSource !== 'screen'
  632. && constraints.video.chromeMediaSource !== 'desktop'
  633. && !isAndroid
  634. // We currently do not support FF, as it doesn't have multistream support.
  635. && !isFF) {
  636. simulcast.getUserMedia(constraints, function (stream) {
  637. console.log('onUserMediaSuccess');
  638. success_callback(stream);
  639. },
  640. function (error) {
  641. console.warn('Failed to get access to local media. Error ', error);
  642. if (failure_callback) {
  643. failure_callback(error);
  644. }
  645. });
  646. } else {
  647. RTC.getUserMedia(constraints,
  648. function (stream) {
  649. console.log('onUserMediaSuccess');
  650. success_callback(stream);
  651. },
  652. function (error) {
  653. console.warn('Failed to get access to local media. Error ', error);
  654. if (failure_callback) {
  655. failure_callback(error);
  656. }
  657. });
  658. }
  659. } catch (e) {
  660. console.error('GUM failed: ', e);
  661. if(failure_callback) {
  662. failure_callback(e);
  663. }
  664. }
  665. }