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 29KB

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