Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

strophe.jingle.session.js 29KB

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