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

strophe.jingle.session.js 31KB

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