Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

strophe.jingle.adapter.js 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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. // override as desired
  27. this.trace = function(what, info) {
  28. //console.warn('WTRACE', what, info);
  29. self.updateLog.push({
  30. time: new Date(),
  31. type: what,
  32. value: info || ""
  33. });
  34. };
  35. this.onicecandidate = null;
  36. this.peerconnection.onicecandidate = function (event) {
  37. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  38. if (self.onicecandidate !== null) {
  39. self.onicecandidate(event);
  40. }
  41. };
  42. this.onaddstream = null;
  43. this.peerconnection.onaddstream = function (event) {
  44. self.trace('onaddstream', event.stream.id);
  45. if (self.onaddstream !== null) {
  46. self.onaddstream(event);
  47. }
  48. };
  49. this.onremovestream = null;
  50. this.peerconnection.onremovestream = function (event) {
  51. self.trace('onremovestream', event.stream.id);
  52. if (self.onremovestream !== null) {
  53. self.onremovestream(event);
  54. }
  55. };
  56. this.onsignalingstatechange = null;
  57. this.peerconnection.onsignalingstatechange = function (event) {
  58. self.trace('onsignalingstatechange', event.srcElement.signalingState);
  59. if (self.onsignalingstatechange !== null) {
  60. self.onsignalingstatechange(event);
  61. }
  62. };
  63. this.oniceconnectionstatechange = null;
  64. this.peerconnection.oniceconnectionstatechange = function (event) {
  65. self.trace('oniceconnectionstatechange', event.srcElement.iceConnectionState);
  66. if (self.oniceconnectionstatechange !== null) {
  67. self.oniceconnectionstatechange(event);
  68. }
  69. };
  70. this.onnegotiationneeded = null;
  71. this.peerconnection.onnegotiationneeded = function (event) {
  72. self.trace('onnegotiationneeded');
  73. if (self.onnegotiationneeded !== null) {
  74. self.onnegotiationneeded(event);
  75. }
  76. };
  77. self.ondatachannel = null;
  78. this.peerconnection.ondatachannel = function (event) {
  79. self.trace('ondatachannel', event);
  80. if (self.ondatachannel !== null) {
  81. self.ondatachannel(event);
  82. }
  83. }
  84. if (!navigator.mozGetUserMedia) {
  85. this.statsinterval = window.setInterval(function() {
  86. self.peerconnection.getStats(function(stats) {
  87. var results = stats.result();
  88. for (var i = 0; i < results.length; ++i) {
  89. //console.log(results[i].type, results[i].id, results[i].names())
  90. var now = new Date();
  91. results[i].names().forEach(function (name) {
  92. var id = results[i].id + '-' + name;
  93. if (!self.stats[id]) {
  94. self.stats[id] = {
  95. startTime: now,
  96. endTime: now,
  97. values: [],
  98. times: []
  99. };
  100. }
  101. self.stats[id].values.push(results[i].stat(name));
  102. self.stats[id].times.push(now.getTime());
  103. if (self.stats[id].values.length > self.maxstats) {
  104. self.stats[id].values.shift();
  105. self.stats[id].times.shift();
  106. }
  107. self.stats[id].endTime = now;
  108. });
  109. }
  110. });
  111. }, 1000);
  112. }
  113. };
  114. dumpSDP = function(description) {
  115. return 'type: ' + description.type + '\r\n' + description.sdp;
  116. }
  117. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  118. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  119. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  120. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() { return this.peerconnection.localDescription; });
  121. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() { return this.peerconnection.remoteDescription; });
  122. }
  123. TraceablePeerConnection.prototype.addStream = function (stream) {
  124. this.trace('addStream', stream.id);
  125. this.peerconnection.addStream(stream);
  126. };
  127. TraceablePeerConnection.prototype.removeStream = function (stream) {
  128. this.trace('removeStream', stream.id);
  129. this.peerconnection.removeStream(stream);
  130. };
  131. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  132. this.trace('createDataChannel', label, opts);
  133. this.peerconnection.createDataChannel(label, opts);
  134. }
  135. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  136. var self = this;
  137. this.trace('setLocalDescription', dumpSDP(description));
  138. this.peerconnection.setLocalDescription(description,
  139. function () {
  140. self.trace('setLocalDescriptionOnSuccess');
  141. successCallback();
  142. },
  143. function (err) {
  144. self.trace('setLocalDescriptionOnFailure', err);
  145. failureCallback(err);
  146. }
  147. );
  148. /*
  149. if (this.statsinterval === null && this.maxstats > 0) {
  150. // start gathering stats
  151. }
  152. */
  153. };
  154. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  155. var self = this;
  156. this.trace('setRemoteDescription', dumpSDP(description));
  157. this.peerconnection.setRemoteDescription(description,
  158. function () {
  159. self.trace('setRemoteDescriptionOnSuccess');
  160. successCallback();
  161. },
  162. function (err) {
  163. self.trace('setRemoteDescriptionOnFailure', err);
  164. failureCallback(err);
  165. }
  166. );
  167. /*
  168. if (this.statsinterval === null && this.maxstats > 0) {
  169. // start gathering stats
  170. }
  171. */
  172. };
  173. TraceablePeerConnection.prototype.hardMuteVideo = function (muted) {
  174. this.pendingop = muted ? 'mute' : 'unmute';
  175. this.modifySources();
  176. };
  177. TraceablePeerConnection.prototype.enqueueAddSsrc = function(channel, ssrcLines) {
  178. if (!this.addssrc[channel]) {
  179. this.addssrc[channel] = '';
  180. }
  181. this.addssrc[channel] += ssrcLines;
  182. }
  183. TraceablePeerConnection.prototype.addSource = function (elem) {
  184. console.log('addssrc', new Date().getTime());
  185. console.log('ice', this.iceConnectionState);
  186. var sdp = new SDP(this.remoteDescription.sdp);
  187. var self = this;
  188. $(elem).each(function (idx, content) {
  189. var name = $(content).attr('name');
  190. var lines = '';
  191. tmp = $(content).find('>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  192. tmp.each(function () {
  193. var ssrc = $(this).attr('ssrc');
  194. $(this).find('>parameter').each(function () {
  195. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  196. if ($(this).attr('value') && $(this).attr('value').length)
  197. lines += ':' + $(this).attr('value');
  198. lines += '\r\n';
  199. });
  200. });
  201. sdp.media.forEach(function(media, idx) {
  202. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  203. return;
  204. sdp.media[idx] += lines;
  205. self.enqueueAddSsrc(idx, lines);
  206. });
  207. sdp.raw = sdp.session + sdp.media.join('');
  208. });
  209. };
  210. TraceablePeerConnection.prototype.enqueueRemoveSsrc = function(channel, ssrcLines) {
  211. if (!this.removessrc[channel]){
  212. this.removessrc[channel] = '';
  213. }
  214. this.removessrc[channel] += ssrcLines;
  215. }
  216. TraceablePeerConnection.prototype.removeSource = function (elem) {
  217. console.log('removessrc', new Date().getTime());
  218. console.log('ice', this.iceConnectionState);
  219. var sdp = new SDP(this.remoteDescription.sdp);
  220. var self = this;
  221. $(elem).each(function (idx, content) {
  222. var name = $(content).attr('name');
  223. var lines = '';
  224. tmp = $(content).find('>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  225. tmp.each(function () {
  226. var ssrc = $(this).attr('ssrc');
  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.enqueueRemoveSsrc(idx, lines);
  239. });
  240. sdp.raw = sdp.session + sdp.media.join('');
  241. });
  242. };
  243. TraceablePeerConnection.prototype.modifySources = function(successCallback) {
  244. var self = this;
  245. if (this.signalingState == 'closed') return;
  246. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null)){
  247. if(successCallback){
  248. successCallback();
  249. }
  250. return;
  251. }
  252. // FIXME: this is a big hack
  253. // https://code.google.com/p/webrtc/issues/detail?id=2688
  254. if (!(this.signalingState == 'stable' && this.iceConnectionState == 'connected')) {
  255. console.warn('modifySources not yet', this.signalingState, this.iceConnectionState);
  256. this.wait = true;
  257. window.setTimeout(function() { self.modifySources(successCallback); }, 250);
  258. return;
  259. }
  260. if (this.wait) {
  261. window.setTimeout(function() { self.modifySources(successCallback); }, 2500);
  262. this.wait = false;
  263. return;
  264. }
  265. var sdp = new SDP(this.remoteDescription.sdp);
  266. // add sources
  267. this.addssrc.forEach(function(lines, idx) {
  268. sdp.media[idx] += lines;
  269. });
  270. this.addssrc = [];
  271. // remove sources
  272. this.removessrc.forEach(function(lines, idx) {
  273. lines = lines.split('\r\n');
  274. lines.pop(); // remove empty last element;
  275. lines.forEach(function(line) {
  276. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  277. });
  278. });
  279. this.removessrc = [];
  280. sdp.raw = sdp.session + sdp.media.join('');
  281. this.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  282. function() {
  283. self.createAnswer(
  284. function(modifiedAnswer) {
  285. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  286. if (self.pendingop !== null) {
  287. var sdp = new SDP(modifiedAnswer.sdp);
  288. if (sdp.media.length > 1) {
  289. switch(self.pendingop) {
  290. case 'mute':
  291. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  292. break;
  293. case 'unmute':
  294. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  295. break;
  296. }
  297. sdp.raw = sdp.session + sdp.media.join('');
  298. modifiedAnswer.sdp = sdp.raw;
  299. }
  300. self.pendingop = null;
  301. }
  302. // FIXME: pushing down an answer while ice connection state
  303. // is still checking is bad...
  304. //console.log(self.peerconnection.iceConnectionState);
  305. // trying to work around another chrome bug
  306. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  307. self.setLocalDescription(modifiedAnswer,
  308. function() {
  309. //console.log('modified setLocalDescription ok');
  310. if(successCallback){
  311. successCallback();
  312. }
  313. },
  314. function(error) {
  315. console.error('modified setLocalDescription failed', error);
  316. }
  317. );
  318. },
  319. function(error) {
  320. console.error('modified answer failed', error);
  321. }
  322. );
  323. },
  324. function(error) {
  325. console.error('modify failed', error);
  326. }
  327. );
  328. };
  329. TraceablePeerConnection.prototype.close = function () {
  330. this.trace('stop');
  331. if (this.statsinterval !== null) {
  332. window.clearInterval(this.statsinterval);
  333. this.statsinterval = null;
  334. }
  335. this.peerconnection.close();
  336. };
  337. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  338. var self = this;
  339. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  340. this.peerconnection.createOffer(
  341. function (offer) {
  342. self.trace('createOfferOnSuccess', dumpSDP(offer));
  343. successCallback(offer);
  344. },
  345. function(err) {
  346. self.trace('createOfferOnFailure', err);
  347. failureCallback(err);
  348. },
  349. constraints
  350. );
  351. };
  352. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  353. var self = this;
  354. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  355. this.peerconnection.createAnswer(
  356. function (answer) {
  357. self.trace('createAnswerOnSuccess', dumpSDP(answer));
  358. successCallback(answer);
  359. },
  360. function(err) {
  361. self.trace('createAnswerOnFailure', err);
  362. failureCallback(err);
  363. },
  364. constraints
  365. );
  366. };
  367. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  368. var self = this;
  369. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  370. this.peerconnection.addIceCandidate(candidate);
  371. /* maybe later
  372. this.peerconnection.addIceCandidate(candidate,
  373. function () {
  374. self.trace('addIceCandidateOnSuccess');
  375. successCallback();
  376. },
  377. function (err) {
  378. self.trace('addIceCandidateOnFailure', err);
  379. failureCallback(err);
  380. }
  381. );
  382. */
  383. };
  384. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  385. if (navigator.mozGetUserMedia) {
  386. // ignore for now...
  387. } else {
  388. this.peerconnection.getStats(callback);
  389. }
  390. };
  391. // mozilla chrome compat layer -- very similar to adapter.js
  392. function setupRTC() {
  393. var RTC = null;
  394. if (navigator.mozGetUserMedia) {
  395. console.log('This appears to be Firefox');
  396. var version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  397. if (version >= 22) {
  398. RTC = {
  399. peerconnection: mozRTCPeerConnection,
  400. browser: 'firefox',
  401. getUserMedia: navigator.mozGetUserMedia.bind(navigator),
  402. attachMediaStream: function (element, stream) {
  403. element[0].mozSrcObject = stream;
  404. element[0].play();
  405. },
  406. pc_constraints: {}
  407. };
  408. if (!MediaStream.prototype.getVideoTracks)
  409. MediaStream.prototype.getVideoTracks = function () { return []; };
  410. if (!MediaStream.prototype.getAudioTracks)
  411. MediaStream.prototype.getAudioTracks = function () { return []; };
  412. RTCSessionDescription = mozRTCSessionDescription;
  413. RTCIceCandidate = mozRTCIceCandidate;
  414. }
  415. } else if (navigator.webkitGetUserMedia) {
  416. console.log('This appears to be Chrome');
  417. RTC = {
  418. peerconnection: webkitRTCPeerConnection,
  419. browser: 'chrome',
  420. getUserMedia: navigator.webkitGetUserMedia.bind(navigator),
  421. attachMediaStream: function (element, stream) {
  422. element.attr('src', webkitURL.createObjectURL(stream));
  423. },
  424. // DTLS should now be enabled by default but..
  425. pc_constraints: {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]}
  426. };
  427. if (navigator.userAgent.indexOf('Android') != -1) {
  428. RTC.pc_constraints = {}; // disable DTLS on Android
  429. }
  430. if (!webkitMediaStream.prototype.getVideoTracks) {
  431. webkitMediaStream.prototype.getVideoTracks = function () {
  432. return this.videoTracks;
  433. };
  434. }
  435. if (!webkitMediaStream.prototype.getAudioTracks) {
  436. webkitMediaStream.prototype.getAudioTracks = function () {
  437. return this.audioTracks;
  438. };
  439. }
  440. }
  441. if (RTC === null) {
  442. try { console.log('Browser does not appear to be WebRTC-capable'); } catch (e) { }
  443. }
  444. return RTC;
  445. }
  446. function getUserMediaWithConstraints(um, success_callback, failure_callback, resolution, bandwidth, fps) {
  447. var constraints = {audio: false, video: false};
  448. if (um.indexOf('video') >= 0) {
  449. constraints.video = {mandatory: {}};// same behaviour as true
  450. }
  451. if (um.indexOf('audio') >= 0) {
  452. constraints.audio = {};// same behaviour as true
  453. }
  454. if (um.indexOf('screen') >= 0) {
  455. constraints.video = {
  456. "mandatory": {
  457. "chromeMediaSource": "screen"
  458. }
  459. };
  460. }
  461. if (resolution && !constraints.video) {
  462. constraints.video = {mandatory: {}};// same behaviour as true
  463. }
  464. // see https://code.google.com/p/chromium/issues/detail?id=143631#c9 for list of supported resolutions
  465. switch (resolution) {
  466. // 16:9 first
  467. case '1080':
  468. case 'fullhd':
  469. constraints.video.mandatory.minWidth = 1920;
  470. constraints.video.mandatory.minHeight = 1080;
  471. constraints.video.mandatory.minAspectRatio = 1.77;
  472. break;
  473. case '720':
  474. case 'hd':
  475. constraints.video.mandatory.minWidth = 1280;
  476. constraints.video.mandatory.minHeight = 720;
  477. constraints.video.mandatory.minAspectRatio = 1.77;
  478. break;
  479. case '360':
  480. constraints.video.mandatory.minWidth = 640;
  481. constraints.video.mandatory.minHeight = 360;
  482. constraints.video.mandatory.minAspectRatio = 1.77;
  483. break;
  484. case '180':
  485. constraints.video.mandatory.minWidth = 320;
  486. constraints.video.mandatory.minHeight = 180;
  487. constraints.video.mandatory.minAspectRatio = 1.77;
  488. break;
  489. // 4:3
  490. case '960':
  491. constraints.video.mandatory.minWidth = 960;
  492. constraints.video.mandatory.minHeight = 720;
  493. break;
  494. case '640':
  495. case 'vga':
  496. constraints.video.mandatory.minWidth = 640;
  497. constraints.video.mandatory.minHeight = 480;
  498. break;
  499. case '320':
  500. constraints.video.mandatory.minWidth = 320;
  501. constraints.video.mandatory.minHeight = 240;
  502. break;
  503. default:
  504. if (navigator.userAgent.indexOf('Android') != -1) {
  505. constraints.video.mandatory.minWidth = 320;
  506. constraints.video.mandatory.minHeight = 240;
  507. constraints.video.mandatory.maxFrameRate = 15;
  508. }
  509. break;
  510. }
  511. if (bandwidth) { // doesn't work currently, see webrtc issue 1846
  512. if (!constraints.video) constraints.video = {mandatory: {}};//same behaviour as true
  513. constraints.video.optional = [{bandwidth: bandwidth}];
  514. }
  515. if (fps) { // for some cameras it might be necessary to request 30fps
  516. // so they choose 30fps mjpg over 10fps yuy2
  517. if (!constraints.video) constraints.video = {mandatory: {}};// same behaviour as tru;
  518. constraints.video.mandatory.minFrameRate = fps;
  519. }
  520. try {
  521. RTC.getUserMedia(constraints,
  522. function (stream) {
  523. console.log('onUserMediaSuccess');
  524. success_callback(stream);
  525. },
  526. function (error) {
  527. console.warn('Failed to get access to local media. Error ', error);
  528. if(failure_callback) {
  529. failure_callback(error);
  530. }
  531. });
  532. } catch (e) {
  533. console.error('GUM failed: ', e);
  534. if(failure_callback) {
  535. failure_callback(e);
  536. }
  537. }
  538. }