Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

strophe.jingle.session.js 28KB

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