Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

strophe.jingle.session.js 29KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  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(
  266. 'fingerprint',
  267. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  268. .t(tmp.fingerprint);
  269. delete tmp.fingerprint;
  270. cand.attrs(tmp);
  271. cand.up();
  272. }
  273. cand.up(); // transport
  274. cand.up(); // content
  275. }
  276. }
  277. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  278. //console.log('was this the last candidate', this.lasticecandidate);
  279. this.connection.sendIQ(cand,
  280. function () {
  281. var ack = {};
  282. ack.source = 'transportinfo';
  283. $(document).trigger('ack.jingle', [this.sid, ack]);
  284. },
  285. function (stanza) {
  286. var error = ($(stanza).find('error').length) ? {
  287. code: $(stanza).find('error').attr('code'),
  288. reason: $(stanza).find('error :first')[0].tagName,
  289. }:{};
  290. error.source = 'transportinfo';
  291. $(document).trigger('error.jingle', [this.sid, error]);
  292. },
  293. 10000);
  294. };
  295. JingleSession.prototype.sendOffer = function () {
  296. //console.log('sendOffer...');
  297. var self = this;
  298. this.peerconnection.createOffer(function (sdp) {
  299. self.createdOffer(sdp);
  300. },
  301. function (e) {
  302. console.error('createOffer failed', e);
  303. },
  304. this.media_constraints
  305. );
  306. };
  307. JingleSession.prototype.createdOffer = function (sdp) {
  308. //console.log('createdOffer', sdp);
  309. var self = this;
  310. this.localSDP = new SDP(sdp.sdp);
  311. //this.localSDP.mangle();
  312. if (this.usetrickle) {
  313. var init = $iq({to: this.peerjid,
  314. type: 'set'})
  315. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  316. action: 'session-initiate',
  317. initiator: this.initiator,
  318. sid: this.sid});
  319. this.localSDP.toJingle(init, this.initiator == this.me ? 'initiator' : 'responder');
  320. this.connection.sendIQ(init,
  321. function () {
  322. var ack = {};
  323. ack.source = 'offer';
  324. $(document).trigger('ack.jingle', [self.sid, ack]);
  325. },
  326. function (stanza) {
  327. self.state = 'error';
  328. self.peerconnection.close();
  329. var error = ($(stanza).find('error').length) ? {
  330. code: $(stanza).find('error').attr('code'),
  331. reason: $(stanza).find('error :first')[0].tagName,
  332. }:{};
  333. error.source = 'offer';
  334. $(document).trigger('error.jingle', [self.sid, error]);
  335. },
  336. 10000);
  337. }
  338. sdp.sdp = this.localSDP.raw;
  339. this.peerconnection.setLocalDescription(sdp,
  340. function () {
  341. $(document).trigger('setLocalDescription.jingle', [self.sid]);
  342. //console.log('setLocalDescription success');
  343. },
  344. function (e) {
  345. console.error('setLocalDescription failed', e);
  346. }
  347. );
  348. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  349. for (var i = 0; i < cands.length; i++) {
  350. var cand = SDPUtil.parse_icecandidate(cands[i]);
  351. if (cand.type == 'srflx') {
  352. this.hadstuncandidate = true;
  353. } else if (cand.type == 'relay') {
  354. this.hadturncandidate = true;
  355. }
  356. }
  357. };
  358. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  359. //console.log('setting remote description... ', desctype);
  360. this.remoteSDP = new SDP('');
  361. this.remoteSDP.fromJingle(elem);
  362. if (this.peerconnection.remoteDescription !== null) {
  363. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  364. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  365. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  366. for (var i = 0; i < pranswer.media.length; i++) {
  367. // make sure we have ice ufrag and pwd
  368. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  369. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  370. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  371. } else {
  372. console.warn('no ice ufrag?');
  373. }
  374. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  375. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  376. } else {
  377. console.warn('no ice pwd?');
  378. }
  379. }
  380. // copy over candidates
  381. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  382. for (var j = 0; j < lines.length; j++) {
  383. this.remoteSDP.media[i] += lines[j] + '\r\n';
  384. }
  385. }
  386. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  387. }
  388. }
  389. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  390. this.peerconnection.setRemoteDescription(remotedesc,
  391. function () {
  392. //console.log('setRemoteDescription success');
  393. },
  394. function (e) {
  395. console.error('setRemoteDescription error', e);
  396. $(document).trigger('fatalError.jingle', [self, e]);
  397. }
  398. );
  399. };
  400. JingleSession.prototype.addIceCandidate = function (elem) {
  401. var self = this;
  402. if (this.peerconnection.signalingState == 'closed') {
  403. return;
  404. }
  405. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  406. console.log('trickle ice candidate arriving before session accept...');
  407. // create a PRANSWER for setRemoteDescription
  408. if (!this.remoteSDP) {
  409. var cobbled = 'v=0\r\n' +
  410. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  411. 's=-\r\n' +
  412. 't=0 0\r\n';
  413. // first, take some things from the local description
  414. for (var i = 0; i < this.localSDP.media.length; i++) {
  415. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  416. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  417. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  418. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  419. }
  420. cobbled += 'a=inactive\r\n';
  421. }
  422. this.remoteSDP = new SDP(cobbled);
  423. }
  424. // then add things like ice and dtls from remote candidate
  425. elem.each(function () {
  426. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  427. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  428. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  429. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  430. var tmp = $(this).find('transport');
  431. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  432. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  433. tmp = $(this).find('transport>fingerprint');
  434. if (tmp.length) {
  435. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  436. } else {
  437. console.log('no dtls fingerprint (webrtc issue #1718?)');
  438. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  439. }
  440. break;
  441. }
  442. }
  443. }
  444. });
  445. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  446. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  447. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  448. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  449. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  450. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  451. }).length == this.remoteSDP.media.length;
  452. if (iscomplete) {
  453. console.log('setting pranswer');
  454. try {
  455. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  456. function() {
  457. },
  458. function(e) {
  459. console.log('setRemoteDescription pranswer failed', e.toString());
  460. });
  461. } catch (e) {
  462. console.error('setting pranswer failed', e);
  463. }
  464. } else {
  465. //console.log('not yet setting pranswer');
  466. }
  467. }
  468. // operate on each content element
  469. elem.each(function () {
  470. // would love to deactivate this, but firefox still requires it
  471. var idx = -1;
  472. var i;
  473. for (i = 0; i < self.remoteSDP.media.length; i++) {
  474. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  475. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  476. idx = i;
  477. break;
  478. }
  479. }
  480. if (idx == -1) { // fall back to localdescription
  481. for (i = 0; i < self.localSDP.media.length; i++) {
  482. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  483. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  484. idx = i;
  485. break;
  486. }
  487. }
  488. }
  489. var name = $(this).attr('name');
  490. // TODO: check ice-pwd and ice-ufrag?
  491. $(this).find('transport>candidate').each(function () {
  492. var line, candidate;
  493. line = SDPUtil.candidateFromJingle(this);
  494. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  495. sdpMid: name,
  496. candidate: line});
  497. try {
  498. self.peerconnection.addIceCandidate(candidate);
  499. } catch (e) {
  500. console.error('addIceCandidate failed', e.toString(), line);
  501. }
  502. });
  503. });
  504. };
  505. JingleSession.prototype.sendAnswer = function (provisional) {
  506. //console.log('createAnswer', provisional);
  507. var self = this;
  508. this.peerconnection.createAnswer(
  509. function (sdp) {
  510. self.createdAnswer(sdp, provisional);
  511. },
  512. function (e) {
  513. console.error('createAnswer failed', e);
  514. },
  515. this.media_constraints
  516. );
  517. };
  518. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  519. //console.log('createAnswer callback');
  520. var self = this;
  521. this.localSDP = new SDP(sdp.sdp);
  522. //this.localSDP.mangle();
  523. this.usepranswer = provisional === true;
  524. if (this.usetrickle) {
  525. if (!this.usepranswer) {
  526. var accept = $iq({to: this.peerjid,
  527. type: 'set'})
  528. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  529. action: 'session-accept',
  530. initiator: this.initiator,
  531. responder: this.responder,
  532. sid: this.sid });
  533. this.localSDP.toJingle(accept, this.initiator == this.me ? 'initiator' : 'responder');
  534. this.connection.sendIQ(accept,
  535. function () {
  536. var ack = {};
  537. ack.source = 'answer';
  538. $(document).trigger('ack.jingle', [self.sid, ack]);
  539. },
  540. function (stanza) {
  541. var error = ($(stanza).find('error').length) ? {
  542. code: $(stanza).find('error').attr('code'),
  543. reason: $(stanza).find('error :first')[0].tagName,
  544. }:{};
  545. error.source = 'answer';
  546. $(document).trigger('error.jingle', [self.sid, error]);
  547. },
  548. 10000);
  549. } else {
  550. sdp.type = 'pranswer';
  551. for (var i = 0; i < this.localSDP.media.length; i++) {
  552. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  553. }
  554. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  555. }
  556. }
  557. sdp.sdp = this.localSDP.raw;
  558. this.peerconnection.setLocalDescription(sdp,
  559. function () {
  560. $(document).trigger('setLocalDescription.jingle', [self.sid]);
  561. //console.log('setLocalDescription success');
  562. },
  563. function (e) {
  564. console.error('setLocalDescription failed', e);
  565. }
  566. );
  567. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  568. for (var j = 0; j < cands.length; j++) {
  569. var cand = SDPUtil.parse_icecandidate(cands[j]);
  570. if (cand.type == 'srflx') {
  571. this.hadstuncandidate = true;
  572. } else if (cand.type == 'relay') {
  573. this.hadturncandidate = true;
  574. }
  575. }
  576. };
  577. JingleSession.prototype.sendTerminate = function (reason, text) {
  578. var self = this,
  579. term = $iq({to: this.peerjid,
  580. type: 'set'})
  581. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  582. action: 'session-terminate',
  583. initiator: this.initiator,
  584. sid: this.sid})
  585. .c('reason')
  586. .c(reason || 'success');
  587. if (text) {
  588. term.up().c('text').t(text);
  589. }
  590. this.connection.sendIQ(term,
  591. function () {
  592. self.peerconnection.close();
  593. self.peerconnection = null;
  594. self.terminate();
  595. var ack = {};
  596. ack.source = 'terminate';
  597. $(document).trigger('ack.jingle', [self.sid, ack]);
  598. },
  599. function (stanza) {
  600. var error = ($(stanza).find('error').length) ? {
  601. code: $(stanza).find('error').attr('code'),
  602. reason: $(stanza).find('error :first')[0].tagName,
  603. }:{};
  604. $(document).trigger('ack.jingle', [self.sid, error]);
  605. },
  606. 10000);
  607. if (this.statsinterval !== null) {
  608. window.clearInterval(this.statsinterval);
  609. this.statsinterval = null;
  610. }
  611. };
  612. JingleSession.prototype.sendMute = function (muted, content) {
  613. var info = $iq({to: this.peerjid,
  614. type: 'set'})
  615. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  616. action: 'session-info',
  617. initiator: this.initiator,
  618. sid: this.sid });
  619. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  620. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  621. if (content) {
  622. info.attrs({'name': content});
  623. }
  624. this.connection.send(info);
  625. };
  626. JingleSession.prototype.sendRinging = function () {
  627. var info = $iq({to: this.peerjid,
  628. type: 'set'})
  629. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  630. action: 'session-info',
  631. initiator: this.initiator,
  632. sid: this.sid });
  633. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  634. this.connection.send(info);
  635. };
  636. JingleSession.prototype.getStats = function (interval) {
  637. var self = this;
  638. var recv = {audio: 0, video: 0};
  639. var lost = {audio: 0, video: 0};
  640. var lastrecv = {audio: 0, video: 0};
  641. var lastlost = {audio: 0, video: 0};
  642. var loss = {audio: 0, video: 0};
  643. var delta = {audio: 0, video: 0};
  644. this.statsinterval = window.setInterval(function () {
  645. if (self && self.peerconnection && self.peerconnection.getStats) {
  646. self.peerconnection.getStats(function (stats) {
  647. var results = stats.result();
  648. // TODO: there are so much statistics you can get from this..
  649. for (var i = 0; i < results.length; ++i) {
  650. if (results[i].type == 'ssrc') {
  651. var packetsrecv = results[i].stat('packetsReceived');
  652. var packetslost = results[i].stat('packetsLost');
  653. if (packetsrecv && packetslost) {
  654. packetsrecv = parseInt(packetsrecv, 10);
  655. packetslost = parseInt(packetslost, 10);
  656. if (results[i].stat('googFrameRateReceived')) {
  657. lastlost.video = lost.video;
  658. lastrecv.video = recv.video;
  659. recv.video = packetsrecv;
  660. lost.video = packetslost;
  661. } else {
  662. lastlost.audio = lost.audio;
  663. lastrecv.audio = recv.audio;
  664. recv.audio = packetsrecv;
  665. lost.audio = packetslost;
  666. }
  667. }
  668. }
  669. }
  670. delta.audio = recv.audio - lastrecv.audio;
  671. delta.video = recv.video - lastrecv.video;
  672. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  673. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  674. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  675. });
  676. }
  677. }, interval || 3000);
  678. return this.statsinterval;
  679. };