您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

strophe.jingle.session.js 29KB

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