Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

strophe.jingle.adapter.js 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  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 = 300; // 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', event.srcElement.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', event.srcElement.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) {
  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() { return this.peerconnection.localDescription; });
  126. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() { return this.peerconnection.remoteDescription; });
  127. }
  128. TraceablePeerConnection.prototype.addStream = function (stream) {
  129. this.trace('addStream', stream.id);
  130. this.peerconnection.addStream(stream);
  131. };
  132. TraceablePeerConnection.prototype.removeStream = function (stream) {
  133. this.trace('removeStream', stream.id);
  134. this.peerconnection.removeStream(stream);
  135. };
  136. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  137. this.trace('createDataChannel', label, opts);
  138. this.peerconnection.createDataChannel(label, opts);
  139. }
  140. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  141. var self = this;
  142. this.trace('setLocalDescription', dumpSDP(description));
  143. this.peerconnection.setLocalDescription(description,
  144. function () {
  145. self.trace('setLocalDescriptionOnSuccess');
  146. successCallback();
  147. },
  148. function (err) {
  149. self.trace('setLocalDescriptionOnFailure', err);
  150. failureCallback(err);
  151. }
  152. );
  153. /*
  154. if (this.statsinterval === null && this.maxstats > 0) {
  155. // start gathering stats
  156. }
  157. */
  158. };
  159. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  160. var self = this;
  161. this.trace('setRemoteDescription', dumpSDP(description));
  162. this.peerconnection.setRemoteDescription(description,
  163. function () {
  164. self.trace('setRemoteDescriptionOnSuccess');
  165. successCallback();
  166. },
  167. function (err) {
  168. self.trace('setRemoteDescriptionOnFailure', err);
  169. failureCallback(err);
  170. }
  171. );
  172. /*
  173. if (this.statsinterval === null && this.maxstats > 0) {
  174. // start gathering stats
  175. }
  176. */
  177. };
  178. TraceablePeerConnection.prototype.hardMuteVideo = function (muted) {
  179. this.pendingop = muted ? 'mute' : 'unmute';
  180. };
  181. TraceablePeerConnection.prototype.enqueueAddSsrc = function(channel, ssrcLines) {
  182. if (!this.addssrc[channel]) {
  183. this.addssrc[channel] = '';
  184. }
  185. this.addssrc[channel] += ssrcLines;
  186. }
  187. TraceablePeerConnection.prototype.addSource = function (elem) {
  188. console.log('addssrc', new Date().getTime());
  189. console.log('ice', this.iceConnectionState);
  190. var sdp = new SDP(this.remoteDescription.sdp);
  191. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  192. var self = this;
  193. $(elem).each(function (idx, content) {
  194. var name = $(content).attr('name');
  195. var lines = '';
  196. tmp = $(content).find('>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  197. tmp.each(function () {
  198. var ssrc = $(this).attr('ssrc');
  199. if(mySdp.containsSSRC(ssrc)){
  200. /**
  201. * This happens when multiple participants change their streams at the same time and
  202. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  203. * addssrc are scheduled for update IQ. See
  204. */
  205. console.warn("Got add stream request for my own ssrc: "+ssrc);
  206. return;
  207. }
  208. $(this).find('>parameter').each(function () {
  209. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  210. if ($(this).attr('value') && $(this).attr('value').length)
  211. lines += ':' + $(this).attr('value');
  212. lines += '\r\n';
  213. });
  214. });
  215. sdp.media.forEach(function(media, idx) {
  216. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  217. return;
  218. sdp.media[idx] += lines;
  219. self.enqueueAddSsrc(idx, lines);
  220. });
  221. sdp.raw = sdp.session + sdp.media.join('');
  222. });
  223. };
  224. TraceablePeerConnection.prototype.enqueueRemoveSsrc = function(channel, ssrcLines) {
  225. if (!this.removessrc[channel]){
  226. this.removessrc[channel] = '';
  227. }
  228. this.removessrc[channel] += ssrcLines;
  229. }
  230. TraceablePeerConnection.prototype.removeSource = function (elem) {
  231. console.log('removessrc', new Date().getTime());
  232. console.log('ice', this.iceConnectionState);
  233. var sdp = new SDP(this.remoteDescription.sdp);
  234. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  235. var self = this;
  236. $(elem).each(function (idx, content) {
  237. var name = $(content).attr('name');
  238. var lines = '';
  239. tmp = $(content).find('>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  240. tmp.each(function () {
  241. var ssrc = $(this).attr('ssrc');
  242. // This should never happen, but can be useful for bug detection
  243. if(mySdp.containsSSRC(ssrc)){
  244. console.error("Got remove stream request for my own ssrc: "+ssrc);
  245. return;
  246. }
  247. $(this).find('>parameter').each(function () {
  248. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  249. if ($(this).attr('value') && $(this).attr('value').length)
  250. lines += ':' + $(this).attr('value');
  251. lines += '\r\n';
  252. });
  253. });
  254. sdp.media.forEach(function(media, idx) {
  255. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  256. return;
  257. sdp.media[idx] += lines;
  258. self.enqueueRemoveSsrc(idx, lines);
  259. });
  260. sdp.raw = sdp.session + sdp.media.join('');
  261. });
  262. };
  263. TraceablePeerConnection.prototype.modifySources = function(successCallback) {
  264. var self = this;
  265. if (this.signalingState == 'closed') return;
  266. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  267. // There is nothing to do since scheduled job might have been executed by another succeeding call
  268. if(successCallback){
  269. successCallback();
  270. }
  271. return;
  272. }
  273. // FIXME: this is a big hack
  274. // https://code.google.com/p/webrtc/issues/detail?id=2688
  275. if (!(this.signalingState == 'stable' && this.iceConnectionState == 'connected')) {
  276. console.warn('modifySources not yet', this.signalingState, this.iceConnectionState);
  277. this.wait = true;
  278. window.setTimeout(function() { self.modifySources(successCallback); }, 250);
  279. return;
  280. }
  281. if (this.wait) {
  282. window.setTimeout(function() { self.modifySources(successCallback); }, 2500);
  283. this.wait = false;
  284. return;
  285. }
  286. // Reset switch streams flag
  287. this.switchstreams = false;
  288. var sdp = new SDP(this.remoteDescription.sdp);
  289. // add sources
  290. this.addssrc.forEach(function(lines, idx) {
  291. sdp.media[idx] += lines;
  292. });
  293. this.addssrc = [];
  294. // remove sources
  295. this.removessrc.forEach(function(lines, idx) {
  296. lines = lines.split('\r\n');
  297. lines.pop(); // remove empty last element;
  298. lines.forEach(function(line) {
  299. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  300. });
  301. });
  302. this.removessrc = [];
  303. sdp.raw = sdp.session + sdp.media.join('');
  304. this.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  305. function() {
  306. self.createAnswer(
  307. function(modifiedAnswer) {
  308. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  309. if (self.pendingop !== null) {
  310. var sdp = new SDP(modifiedAnswer.sdp);
  311. if (sdp.media.length > 1) {
  312. switch(self.pendingop) {
  313. case 'mute':
  314. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  315. console.error("MUTE");
  316. break;
  317. case 'unmute':
  318. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  319. console.error("UNMUTE");
  320. break;
  321. }
  322. sdp.raw = sdp.session + sdp.media.join('');
  323. modifiedAnswer.sdp = sdp.raw;
  324. }
  325. self.pendingop = null;
  326. }
  327. // FIXME: pushing down an answer while ice connection state
  328. // is still checking is bad...
  329. //console.log(self.peerconnection.iceConnectionState);
  330. // trying to work around another chrome bug
  331. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  332. self.setLocalDescription(modifiedAnswer,
  333. function() {
  334. //console.log('modified setLocalDescription ok');
  335. if(successCallback){
  336. successCallback();
  337. }
  338. },
  339. function(error) {
  340. console.error('modified setLocalDescription failed', error);
  341. }
  342. );
  343. },
  344. function(error) {
  345. console.error('modified answer failed', error);
  346. }
  347. );
  348. },
  349. function(error) {
  350. console.error('modify failed', error);
  351. }
  352. );
  353. };
  354. TraceablePeerConnection.prototype.close = function () {
  355. this.trace('stop');
  356. if (this.statsinterval !== null) {
  357. window.clearInterval(this.statsinterval);
  358. this.statsinterval = null;
  359. }
  360. this.peerconnection.close();
  361. };
  362. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  363. var self = this;
  364. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  365. this.peerconnection.createOffer(
  366. function (offer) {
  367. self.trace('createOfferOnSuccess', dumpSDP(offer));
  368. successCallback(offer);
  369. },
  370. function(err) {
  371. self.trace('createOfferOnFailure', err);
  372. failureCallback(err);
  373. },
  374. constraints
  375. );
  376. };
  377. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  378. var self = this;
  379. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  380. this.peerconnection.createAnswer(
  381. function (answer) {
  382. self.trace('createAnswerOnSuccess', dumpSDP(answer));
  383. successCallback(answer);
  384. },
  385. function(err) {
  386. self.trace('createAnswerOnFailure', err);
  387. failureCallback(err);
  388. },
  389. constraints
  390. );
  391. };
  392. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  393. var self = this;
  394. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  395. this.peerconnection.addIceCandidate(candidate);
  396. /* maybe later
  397. this.peerconnection.addIceCandidate(candidate,
  398. function () {
  399. self.trace('addIceCandidateOnSuccess');
  400. successCallback();
  401. },
  402. function (err) {
  403. self.trace('addIceCandidateOnFailure', err);
  404. failureCallback(err);
  405. }
  406. );
  407. */
  408. };
  409. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  410. if (navigator.mozGetUserMedia) {
  411. // ignore for now...
  412. } else {
  413. this.peerconnection.getStats(callback);
  414. }
  415. };
  416. // mozilla chrome compat layer -- very similar to adapter.js
  417. function setupRTC() {
  418. var RTC = null;
  419. if (navigator.mozGetUserMedia) {
  420. console.log('This appears to be Firefox');
  421. var version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  422. if (version >= 22) {
  423. RTC = {
  424. peerconnection: mozRTCPeerConnection,
  425. browser: 'firefox',
  426. getUserMedia: navigator.mozGetUserMedia.bind(navigator),
  427. attachMediaStream: function (element, stream) {
  428. element[0].mozSrcObject = stream;
  429. element[0].play();
  430. },
  431. pc_constraints: {}
  432. };
  433. if (!MediaStream.prototype.getVideoTracks)
  434. MediaStream.prototype.getVideoTracks = function () { return []; };
  435. if (!MediaStream.prototype.getAudioTracks)
  436. MediaStream.prototype.getAudioTracks = function () { return []; };
  437. RTCSessionDescription = mozRTCSessionDescription;
  438. RTCIceCandidate = mozRTCIceCandidate;
  439. }
  440. } else if (navigator.webkitGetUserMedia) {
  441. console.log('This appears to be Chrome');
  442. RTC = {
  443. peerconnection: webkitRTCPeerConnection,
  444. browser: 'chrome',
  445. getUserMedia: navigator.webkitGetUserMedia.bind(navigator),
  446. attachMediaStream: function (element, stream) {
  447. element.attr('src', webkitURL.createObjectURL(stream));
  448. },
  449. // DTLS should now be enabled by default but..
  450. pc_constraints: {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]}
  451. };
  452. if (navigator.userAgent.indexOf('Android') != -1) {
  453. RTC.pc_constraints = {}; // disable DTLS on Android
  454. }
  455. if (!webkitMediaStream.prototype.getVideoTracks) {
  456. webkitMediaStream.prototype.getVideoTracks = function () {
  457. return this.videoTracks;
  458. };
  459. }
  460. if (!webkitMediaStream.prototype.getAudioTracks) {
  461. webkitMediaStream.prototype.getAudioTracks = function () {
  462. return this.audioTracks;
  463. };
  464. }
  465. }
  466. if (RTC === null) {
  467. try { console.log('Browser does not appear to be WebRTC-capable'); } catch (e) { }
  468. }
  469. return RTC;
  470. }
  471. function getUserMediaWithConstraints(um, success_callback, failure_callback, resolution, bandwidth, fps) {
  472. var constraints = {audio: false, video: false};
  473. if (um.indexOf('video') >= 0) {
  474. constraints.video = {mandatory: {}};// same behaviour as true
  475. }
  476. if (um.indexOf('audio') >= 0) {
  477. constraints.audio = {};// same behaviour as true
  478. }
  479. if (um.indexOf('screen') >= 0) {
  480. constraints.video = {
  481. mandatory: {
  482. chromeMediaSource: "screen",
  483. maxWidth: window.screen.width,
  484. maxHeight: window.screen.height,
  485. maxFrameRate: 3
  486. }
  487. };
  488. }
  489. if (resolution && !constraints.video) {
  490. constraints.video = {mandatory: {}};// same behaviour as true
  491. }
  492. // see https://code.google.com/p/chromium/issues/detail?id=143631#c9 for list of supported resolutions
  493. switch (resolution) {
  494. // 16:9 first
  495. case '1080':
  496. case 'fullhd':
  497. constraints.video.mandatory.minWidth = 1920;
  498. constraints.video.mandatory.minHeight = 1080;
  499. constraints.video.mandatory.minAspectRatio = 1.77;
  500. break;
  501. case '720':
  502. case 'hd':
  503. constraints.video.mandatory.minWidth = 1280;
  504. constraints.video.mandatory.minHeight = 720;
  505. constraints.video.mandatory.minAspectRatio = 1.77;
  506. break;
  507. case '360':
  508. constraints.video.mandatory.minWidth = 640;
  509. constraints.video.mandatory.minHeight = 360;
  510. constraints.video.mandatory.minAspectRatio = 1.77;
  511. break;
  512. case '180':
  513. constraints.video.mandatory.minWidth = 320;
  514. constraints.video.mandatory.minHeight = 180;
  515. constraints.video.mandatory.minAspectRatio = 1.77;
  516. break;
  517. // 4:3
  518. case '960':
  519. constraints.video.mandatory.minWidth = 960;
  520. constraints.video.mandatory.minHeight = 720;
  521. break;
  522. case '640':
  523. case 'vga':
  524. constraints.video.mandatory.minWidth = 640;
  525. constraints.video.mandatory.minHeight = 480;
  526. break;
  527. case '320':
  528. constraints.video.mandatory.minWidth = 320;
  529. constraints.video.mandatory.minHeight = 240;
  530. break;
  531. default:
  532. if (navigator.userAgent.indexOf('Android') != -1) {
  533. constraints.video.mandatory.minWidth = 320;
  534. constraints.video.mandatory.minHeight = 240;
  535. constraints.video.mandatory.maxFrameRate = 15;
  536. }
  537. break;
  538. }
  539. if (bandwidth) { // doesn't work currently, see webrtc issue 1846
  540. if (!constraints.video) constraints.video = {mandatory: {}};//same behaviour as true
  541. constraints.video.optional = [{bandwidth: bandwidth}];
  542. }
  543. if (fps) { // for some cameras it might be necessary to request 30fps
  544. // so they choose 30fps mjpg over 10fps yuy2
  545. if (!constraints.video) constraints.video = {mandatory: {}};// same behaviour as tru;
  546. constraints.video.mandatory.minFrameRate = fps;
  547. }
  548. try {
  549. RTC.getUserMedia(constraints,
  550. function (stream) {
  551. console.log('onUserMediaSuccess');
  552. success_callback(stream);
  553. },
  554. function (error) {
  555. console.warn('Failed to get access to local media. Error ', error);
  556. if(failure_callback) {
  557. failure_callback(error);
  558. }
  559. });
  560. } catch (e) {
  561. console.error('GUM failed: ', e);
  562. if(failure_callback) {
  563. failure_callback(e);
  564. }
  565. }
  566. }