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.session.js 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  1. /* jshint -W117 */
  2. // Jingle stuff
  3. JingleSession.prototype = Object.create(SessionBase.prototype);
  4. function JingleSession(me, sid, connection) {
  5. SessionBase.call(this, connection, sid);
  6. this.me = me;
  7. this.initiator = null;
  8. this.responder = null;
  9. this.isInitiator = null;
  10. this.peerjid = null;
  11. this.state = null;
  12. this.localSDP = null;
  13. this.remoteSDP = null;
  14. this.localStreams = [];
  15. this.relayedStreams = [];
  16. this.remoteStreams = [];
  17. this.startTime = null;
  18. this.stopTime = null;
  19. this.media_constraints = null;
  20. this.pc_constraints = null;
  21. this.ice_config = {};
  22. this.drip_container = [];
  23. this.usetrickle = true;
  24. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  25. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  26. this.hadstuncandidate = false;
  27. this.hadturncandidate = false;
  28. this.lasticecandidate = false;
  29. this.statsinterval = null;
  30. this.reason = null;
  31. this.wait = true;
  32. }
  33. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  34. var self = this;
  35. if (this.state !== null) {
  36. console.error('attempt to initiate on session ' + this.sid +
  37. 'in state ' + this.state);
  38. return;
  39. }
  40. this.isInitiator = isInitiator;
  41. this.state = 'pending';
  42. this.initiator = isInitiator ? this.me : peerjid;
  43. this.responder = !isInitiator ? this.me : peerjid;
  44. this.peerjid = peerjid;
  45. this.hadstuncandidate = false;
  46. this.hadturncandidate = false;
  47. this.lasticecandidate = false;
  48. this.peerconnection
  49. = new TraceablePeerConnection(
  50. this.connection.jingle.ice_config,
  51. this.connection.jingle.pc_constraints );
  52. this.peerconnection.onicecandidate = function (event) {
  53. self.sendIceCandidate(event.candidate);
  54. };
  55. this.peerconnection.onaddstream = function (event) {
  56. self.remoteStreams.push(event.stream);
  57. $(document).trigger('remotestreamadded.jingle', [event, self.sid]);
  58. };
  59. this.peerconnection.onremovestream = function (event) {
  60. // Remove the stream from remoteStreams
  61. var streamIdx = self.remoteStreams.indexOf(event.stream);
  62. if(streamIdx !== -1){
  63. self.remoteStreams.splice(streamIdx, 1);
  64. }
  65. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  66. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  67. };
  68. this.peerconnection.onsignalingstatechange = function (event) {
  69. if (!(self && self.peerconnection)) return;
  70. };
  71. this.peerconnection.oniceconnectionstatechange = function (event) {
  72. if (!(self && self.peerconnection)) return;
  73. switch (self.peerconnection.iceConnectionState) {
  74. case 'connected':
  75. this.startTime = new Date();
  76. break;
  77. case 'disconnected':
  78. this.stopTime = new Date();
  79. break;
  80. }
  81. $(document).trigger('iceconnectionstatechange.jingle', [self.sid, self]);
  82. };
  83. // add any local and relayed stream
  84. this.localStreams.forEach(function(stream) {
  85. self.peerconnection.addStream(stream);
  86. });
  87. this.relayedStreams.forEach(function(stream) {
  88. self.peerconnection.addStream(stream);
  89. });
  90. };
  91. JingleSession.prototype.accept = function () {
  92. var self = this;
  93. this.state = 'active';
  94. var pranswer = this.peerconnection.localDescription;
  95. if (!pranswer || pranswer.type != 'pranswer') {
  96. return;
  97. }
  98. console.log('going from pranswer to answer');
  99. if (this.usetrickle) {
  100. // remove candidates already sent from session-accept
  101. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  102. for (var i = 0; i < lines.length; i++) {
  103. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  104. }
  105. }
  106. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  107. // FIXME: change any inactive to sendrecv or whatever they were originally
  108. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  109. }
  110. var prsdp = new SDP(pranswer.sdp);
  111. var accept = $iq({to: this.peerjid,
  112. type: 'set'})
  113. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  114. action: 'session-accept',
  115. initiator: this.initiator,
  116. responder: this.responder,
  117. sid: this.sid });
  118. prsdp.toJingle(accept, this.initiator == this.me ? 'initiator' : 'responder');
  119. this.connection.sendIQ(accept,
  120. function () {
  121. var ack = {};
  122. ack.source = 'answer';
  123. $(document).trigger('ack.jingle', [self.sid, ack]);
  124. },
  125. function (stanza) {
  126. var error = ($(stanza).find('error').length) ? {
  127. code: $(stanza).find('error').attr('code'),
  128. reason: $(stanza).find('error :first')[0].tagName,
  129. }:{};
  130. error.source = 'answer';
  131. $(document).trigger('error.jingle', [self.sid, error]);
  132. },
  133. 10000);
  134. var sdp = this.peerconnection.localDescription.sdp;
  135. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  136. // FIXME: change any inactive to sendrecv or whatever they were originally
  137. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  138. }
  139. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  140. function () {
  141. //console.log('setLocalDescription success');
  142. $(document).trigger('setLocalDescription.jingle', [self.sid]);
  143. },
  144. function (e) {
  145. console.error('setLocalDescription failed', e);
  146. }
  147. );
  148. };
  149. /**
  150. * Implements SessionBase.sendSSRCUpdate.
  151. */
  152. JingleSession.prototype.sendSSRCUpdate = function(sdpMediaSsrcs, fromJid, isadd) {
  153. var self = this;
  154. console.log('tell', self.peerjid, 'about ' + (isadd ? 'new' : 'removed') + ' ssrcs from' + self.me);
  155. if (!(this.peerconnection.signalingState == 'stable' && this.peerconnection.iceConnectionState == 'connected')){
  156. console.log("Too early to send updates");
  157. return;
  158. }
  159. this.sendSSRCUpdateIq(sdpMediaSsrcs, self.sid, self.initiator, self.peerjid, isadd);
  160. };
  161. JingleSession.prototype.terminate = function (reason) {
  162. this.state = 'ended';
  163. this.reason = reason;
  164. this.peerconnection.close();
  165. if (this.statsinterval !== null) {
  166. window.clearInterval(this.statsinterval);
  167. this.statsinterval = null;
  168. }
  169. };
  170. JingleSession.prototype.active = function () {
  171. return this.state == 'active';
  172. };
  173. JingleSession.prototype.sendIceCandidate = function (candidate) {
  174. var self = this;
  175. if (candidate && !this.lasticecandidate) {
  176. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  177. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  178. if (!(ice && jcand)) {
  179. console.error('failed to get ice && jcand');
  180. return;
  181. }
  182. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  183. if (jcand.type === 'srflx') {
  184. this.hadstuncandidate = true;
  185. } else if (jcand.type === 'relay') {
  186. this.hadturncandidate = true;
  187. }
  188. if (this.usetrickle) {
  189. if (this.usedrip) {
  190. if (this.drip_container.length === 0) {
  191. // start 20ms callout
  192. window.setTimeout(function () {
  193. if (self.drip_container.length === 0) return;
  194. self.sendIceCandidates(self.drip_container);
  195. self.drip_container = [];
  196. }, 20);
  197. }
  198. this.drip_container.push(event.candidate);
  199. return;
  200. } else {
  201. self.sendIceCandidate([event.candidate]);
  202. }
  203. }
  204. } else {
  205. //console.log('sendIceCandidate: last candidate.');
  206. if (!this.usetrickle) {
  207. //console.log('should send full offer now...');
  208. var init = $iq({to: this.peerjid,
  209. type: 'set'})
  210. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  211. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  212. initiator: this.initiator,
  213. sid: this.sid});
  214. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  215. this.localSDP.toJingle(init, this.initiator == this.me ? 'initiator' : 'responder');
  216. this.connection.sendIQ(init,
  217. function () {
  218. //console.log('session initiate ack');
  219. var ack = {};
  220. ack.source = 'offer';
  221. $(document).trigger('ack.jingle', [self.sid, ack]);
  222. },
  223. function (stanza) {
  224. self.state = 'error';
  225. self.peerconnection.close();
  226. var error = ($(stanza).find('error').length) ? {
  227. code: $(stanza).find('error').attr('code'),
  228. reason: $(stanza).find('error :first')[0].tagName,
  229. }:{};
  230. error.source = 'offer';
  231. $(document).trigger('error.jingle', [self.sid, error]);
  232. },
  233. 10000);
  234. }
  235. this.lasticecandidate = true;
  236. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  237. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  238. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  239. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  240. }
  241. }
  242. };
  243. JingleSession.prototype.sendIceCandidates = function (candidates) {
  244. console.log('sendIceCandidates', candidates);
  245. var cand = $iq({to: this.peerjid, type: 'set'})
  246. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  247. action: 'transport-info',
  248. initiator: this.initiator,
  249. sid: this.sid});
  250. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  251. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  252. if (cands.length > 0) {
  253. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  254. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  255. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  256. name: cands[0].sdpMid
  257. }).c('transport', ice);
  258. for (var i = 0; i < cands.length; i++) {
  259. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  260. }
  261. // add fingerprint
  262. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  263. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  264. tmp.required = true;
  265. cand.c('fingerprint').t(tmp.fingerprint);
  266. delete tmp.fingerprint;
  267. cand.attrs(tmp);
  268. cand.up();
  269. }
  270. cand.up(); // transport
  271. cand.up(); // content
  272. }
  273. }
  274. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  275. //console.log('was this the last candidate', this.lasticecandidate);
  276. this.connection.sendIQ(cand,
  277. function () {
  278. var ack = {};
  279. ack.source = 'transportinfo';
  280. $(document).trigger('ack.jingle', [this.sid, ack]);
  281. },
  282. function (stanza) {
  283. var error = ($(stanza).find('error').length) ? {
  284. code: $(stanza).find('error').attr('code'),
  285. reason: $(stanza).find('error :first')[0].tagName,
  286. }:{};
  287. error.source = 'transportinfo';
  288. $(document).trigger('error.jingle', [this.sid, error]);
  289. },
  290. 10000);
  291. };
  292. JingleSession.prototype.sendOffer = function () {
  293. //console.log('sendOffer...');
  294. var self = this;
  295. this.peerconnection.createOffer(function (sdp) {
  296. self.createdOffer(sdp);
  297. },
  298. function (e) {
  299. console.error('createOffer failed', e);
  300. },
  301. this.media_constraints
  302. );
  303. };
  304. JingleSession.prototype.createdOffer = function (sdp) {
  305. //console.log('createdOffer', sdp);
  306. var self = this;
  307. this.localSDP = new SDP(sdp.sdp);
  308. //this.localSDP.mangle();
  309. if (this.usetrickle) {
  310. var init = $iq({to: this.peerjid,
  311. type: 'set'})
  312. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  313. action: 'session-initiate',
  314. initiator: this.initiator,
  315. sid: this.sid});
  316. this.localSDP.toJingle(init, this.initiator == this.me ? 'initiator' : 'responder');
  317. this.connection.sendIQ(init,
  318. function () {
  319. var ack = {};
  320. ack.source = 'offer';
  321. $(document).trigger('ack.jingle', [self.sid, ack]);
  322. },
  323. function (stanza) {
  324. self.state = 'error';
  325. self.peerconnection.close();
  326. var error = ($(stanza).find('error').length) ? {
  327. code: $(stanza).find('error').attr('code'),
  328. reason: $(stanza).find('error :first')[0].tagName,
  329. }:{};
  330. error.source = 'offer';
  331. $(document).trigger('error.jingle', [self.sid, error]);
  332. },
  333. 10000);
  334. }
  335. sdp.sdp = this.localSDP.raw;
  336. this.peerconnection.setLocalDescription(sdp,
  337. function () {
  338. $(document).trigger('setLocalDescription.jingle', [self.sid]);
  339. //console.log('setLocalDescription success');
  340. },
  341. function (e) {
  342. console.error('setLocalDescription failed', e);
  343. }
  344. );
  345. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  346. for (var i = 0; i < cands.length; i++) {
  347. var cand = SDPUtil.parse_icecandidate(cands[i]);
  348. if (cand.type == 'srflx') {
  349. this.hadstuncandidate = true;
  350. } else if (cand.type == 'relay') {
  351. this.hadturncandidate = true;
  352. }
  353. }
  354. };
  355. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  356. //console.log('setting remote description... ', desctype);
  357. this.remoteSDP = new SDP('');
  358. this.remoteSDP.fromJingle(elem);
  359. if (this.peerconnection.remoteDescription !== null) {
  360. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  361. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  362. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  363. for (var i = 0; i < pranswer.media.length; i++) {
  364. // make sure we have ice ufrag and pwd
  365. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  366. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  367. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  368. } else {
  369. console.warn('no ice ufrag?');
  370. }
  371. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  372. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  373. } else {
  374. console.warn('no ice pwd?');
  375. }
  376. }
  377. // copy over candidates
  378. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  379. for (var j = 0; j < lines.length; j++) {
  380. this.remoteSDP.media[i] += lines[j] + '\r\n';
  381. }
  382. }
  383. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  384. }
  385. }
  386. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  387. this.peerconnection.setRemoteDescription(remotedesc,
  388. function () {
  389. //console.log('setRemoteDescription success');
  390. },
  391. function (e) {
  392. console.error('setRemoteDescription error', e);
  393. }
  394. );
  395. };
  396. JingleSession.prototype.addIceCandidate = function (elem) {
  397. var self = this;
  398. if (this.peerconnection.signalingState == 'closed') {
  399. return;
  400. }
  401. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  402. console.log('trickle ice candidate arriving before session accept...');
  403. // create a PRANSWER for setRemoteDescription
  404. if (!this.remoteSDP) {
  405. var cobbled = 'v=0\r\n' +
  406. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  407. 's=-\r\n' +
  408. 't=0 0\r\n';
  409. // first, take some things from the local description
  410. for (var i = 0; i < this.localSDP.media.length; i++) {
  411. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  412. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  413. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  414. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  415. }
  416. cobbled += 'a=inactive\r\n';
  417. }
  418. this.remoteSDP = new SDP(cobbled);
  419. }
  420. // then add things like ice and dtls from remote candidate
  421. elem.each(function () {
  422. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  423. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  424. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  425. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  426. var tmp = $(this).find('transport');
  427. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  428. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  429. tmp = $(this).find('transport>fingerprint');
  430. if (tmp.length) {
  431. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  432. } else {
  433. console.log('no dtls fingerprint (webrtc issue #1718?)');
  434. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  435. }
  436. break;
  437. }
  438. }
  439. }
  440. });
  441. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  442. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  443. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  444. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  445. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  446. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  447. }).length == this.remoteSDP.media.length;
  448. if (iscomplete) {
  449. console.log('setting pranswer');
  450. try {
  451. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  452. function() {
  453. },
  454. function(e) {
  455. console.log('setRemoteDescription pranswer failed', e.toString());
  456. });
  457. } catch (e) {
  458. console.error('setting pranswer failed', e);
  459. }
  460. } else {
  461. //console.log('not yet setting pranswer');
  462. }
  463. }
  464. // operate on each content element
  465. elem.each(function () {
  466. // would love to deactivate this, but firefox still requires it
  467. var idx = -1;
  468. var i;
  469. for (i = 0; i < self.remoteSDP.media.length; i++) {
  470. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  471. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  472. idx = i;
  473. break;
  474. }
  475. }
  476. if (idx == -1) { // fall back to localdescription
  477. for (i = 0; i < self.localSDP.media.length; i++) {
  478. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  479. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  480. idx = i;
  481. break;
  482. }
  483. }
  484. }
  485. var name = $(this).attr('name');
  486. // TODO: check ice-pwd and ice-ufrag?
  487. $(this).find('transport>candidate').each(function () {
  488. var line, candidate;
  489. line = SDPUtil.candidateFromJingle(this);
  490. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  491. sdpMid: name,
  492. candidate: line});
  493. try {
  494. self.peerconnection.addIceCandidate(candidate);
  495. } catch (e) {
  496. console.error('addIceCandidate failed', e.toString(), line);
  497. }
  498. });
  499. });
  500. };
  501. JingleSession.prototype.sendAnswer = function (provisional) {
  502. //console.log('createAnswer', provisional);
  503. var self = this;
  504. this.peerconnection.createAnswer(
  505. function (sdp) {
  506. self.createdAnswer(sdp, provisional);
  507. },
  508. function (e) {
  509. console.error('createAnswer failed', e);
  510. },
  511. this.media_constraints
  512. );
  513. };
  514. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  515. //console.log('createAnswer callback');
  516. var self = this;
  517. this.localSDP = new SDP(sdp.sdp);
  518. //this.localSDP.mangle();
  519. this.usepranswer = provisional === true;
  520. if (this.usetrickle) {
  521. if (!this.usepranswer) {
  522. var accept = $iq({to: this.peerjid,
  523. type: 'set'})
  524. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  525. action: 'session-accept',
  526. initiator: this.initiator,
  527. responder: this.responder,
  528. sid: this.sid });
  529. this.localSDP.toJingle(accept, this.initiator == this.me ? 'initiator' : 'responder');
  530. this.connection.sendIQ(accept,
  531. function () {
  532. var ack = {};
  533. ack.source = 'answer';
  534. $(document).trigger('ack.jingle', [self.sid, ack]);
  535. },
  536. function (stanza) {
  537. var error = ($(stanza).find('error').length) ? {
  538. code: $(stanza).find('error').attr('code'),
  539. reason: $(stanza).find('error :first')[0].tagName,
  540. }:{};
  541. error.source = 'answer';
  542. $(document).trigger('error.jingle', [self.sid, error]);
  543. },
  544. 10000);
  545. } else {
  546. sdp.type = 'pranswer';
  547. for (var i = 0; i < this.localSDP.media.length; i++) {
  548. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  549. }
  550. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  551. }
  552. }
  553. sdp.sdp = this.localSDP.raw;
  554. this.peerconnection.setLocalDescription(sdp,
  555. function () {
  556. $(document).trigger('setLocalDescription.jingle', [self.sid]);
  557. //console.log('setLocalDescription success');
  558. },
  559. function (e) {
  560. console.error('setLocalDescription failed', e);
  561. }
  562. );
  563. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  564. for (var j = 0; j < cands.length; j++) {
  565. var cand = SDPUtil.parse_icecandidate(cands[j]);
  566. if (cand.type == 'srflx') {
  567. this.hadstuncandidate = true;
  568. } else if (cand.type == 'relay') {
  569. this.hadturncandidate = true;
  570. }
  571. }
  572. };
  573. JingleSession.prototype.sendTerminate = function (reason, text) {
  574. var self = this,
  575. term = $iq({to: this.peerjid,
  576. type: 'set'})
  577. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  578. action: 'session-terminate',
  579. initiator: this.initiator,
  580. sid: this.sid})
  581. .c('reason')
  582. .c(reason || 'success');
  583. if (text) {
  584. term.up().c('text').t(text);
  585. }
  586. this.connection.sendIQ(term,
  587. function () {
  588. self.peerconnection.close();
  589. self.peerconnection = null;
  590. self.terminate();
  591. var ack = {};
  592. ack.source = 'terminate';
  593. $(document).trigger('ack.jingle', [self.sid, ack]);
  594. },
  595. function (stanza) {
  596. var error = ($(stanza).find('error').length) ? {
  597. code: $(stanza).find('error').attr('code'),
  598. reason: $(stanza).find('error :first')[0].tagName,
  599. }:{};
  600. $(document).trigger('ack.jingle', [self.sid, error]);
  601. },
  602. 10000);
  603. if (this.statsinterval !== null) {
  604. window.clearInterval(this.statsinterval);
  605. this.statsinterval = null;
  606. }
  607. };
  608. JingleSession.prototype.sendMute = function (muted, content) {
  609. var info = $iq({to: this.peerjid,
  610. type: 'set'})
  611. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  612. action: 'session-info',
  613. initiator: this.initiator,
  614. sid: this.sid });
  615. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  616. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  617. if (content) {
  618. info.attrs({'name': content});
  619. }
  620. this.connection.send(info);
  621. };
  622. JingleSession.prototype.sendRinging = function () {
  623. var info = $iq({to: this.peerjid,
  624. type: 'set'})
  625. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  626. action: 'session-info',
  627. initiator: this.initiator,
  628. sid: this.sid });
  629. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  630. this.connection.send(info);
  631. };
  632. JingleSession.prototype.getStats = function (interval) {
  633. var self = this;
  634. var recv = {audio: 0, video: 0};
  635. var lost = {audio: 0, video: 0};
  636. var lastrecv = {audio: 0, video: 0};
  637. var lastlost = {audio: 0, video: 0};
  638. var loss = {audio: 0, video: 0};
  639. var delta = {audio: 0, video: 0};
  640. this.statsinterval = window.setInterval(function () {
  641. if (self && self.peerconnection && self.peerconnection.getStats) {
  642. self.peerconnection.getStats(function (stats) {
  643. var results = stats.result();
  644. // TODO: there are so much statistics you can get from this..
  645. for (var i = 0; i < results.length; ++i) {
  646. if (results[i].type == 'ssrc') {
  647. var packetsrecv = results[i].stat('packetsReceived');
  648. var packetslost = results[i].stat('packetsLost');
  649. if (packetsrecv && packetslost) {
  650. packetsrecv = parseInt(packetsrecv, 10);
  651. packetslost = parseInt(packetslost, 10);
  652. if (results[i].stat('googFrameRateReceived')) {
  653. lastlost.video = lost.video;
  654. lastrecv.video = recv.video;
  655. recv.video = packetsrecv;
  656. lost.video = packetslost;
  657. } else {
  658. lastlost.audio = lost.audio;
  659. lastrecv.audio = recv.audio;
  660. recv.audio = packetsrecv;
  661. lost.audio = packetslost;
  662. }
  663. }
  664. }
  665. }
  666. delta.audio = recv.audio - lastrecv.audio;
  667. delta.video = recv.video - lastrecv.video;
  668. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  669. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  670. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  671. });
  672. }
  673. }, interval || 3000);
  674. return this.statsinterval;
  675. };