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

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