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

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