You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JingleSession.js 52KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389
  1. /* jshint -W117 */
  2. var TraceablePeerConnection = require("./TraceablePeerConnection");
  3. var SDPDiffer = require("./SDPDiffer");
  4. var SDPUtil = require("./SDPUtil");
  5. var SDP = require("./SDP");
  6. // Jingle stuff
  7. function JingleSession(me, sid, connection, service) {
  8. this.me = me;
  9. this.sid = sid;
  10. this.connection = connection;
  11. this.initiator = null;
  12. this.responder = null;
  13. this.isInitiator = null;
  14. this.peerjid = null;
  15. this.state = null;
  16. this.localSDP = null;
  17. this.remoteSDP = null;
  18. this.relayedStreams = [];
  19. this.startTime = null;
  20. this.stopTime = null;
  21. this.media_constraints = null;
  22. this.pc_constraints = null;
  23. this.ice_config = {};
  24. this.drip_container = [];
  25. this.service = service;
  26. this.usetrickle = true;
  27. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  28. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  29. this.hadstuncandidate = false;
  30. this.hadturncandidate = false;
  31. this.lasticecandidate = false;
  32. this.statsinterval = null;
  33. this.reason = null;
  34. this.addssrc = [];
  35. this.removessrc = [];
  36. this.pendingop = null;
  37. this.switchstreams = false;
  38. this.wait = true;
  39. this.localStreamsSSRC = null;
  40. /**
  41. * The indicator which determines whether the (local) video has been muted
  42. * in response to a user command in contrast to an automatic decision made
  43. * by the application logic.
  44. */
  45. this.videoMuteByUser = false;
  46. }
  47. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  48. var self = this;
  49. if (this.state !== null) {
  50. console.error('attempt to initiate on session ' + this.sid +
  51. 'in state ' + this.state);
  52. return;
  53. }
  54. this.isInitiator = isInitiator;
  55. this.state = 'pending';
  56. this.initiator = isInitiator ? this.me : peerjid;
  57. this.responder = !isInitiator ? this.me : peerjid;
  58. this.peerjid = peerjid;
  59. this.hadstuncandidate = false;
  60. this.hadturncandidate = false;
  61. this.lasticecandidate = false;
  62. this.peerconnection
  63. = new TraceablePeerConnection(
  64. this.connection.jingle.ice_config,
  65. this.connection.jingle.pc_constraints );
  66. this.peerconnection.onicecandidate = function (event) {
  67. self.sendIceCandidate(event.candidate);
  68. };
  69. this.peerconnection.onaddstream = function (event) {
  70. console.log("REMOTE STREAM ADDED: " + event.stream + " - " + event.stream.id);
  71. self.remoteStreamAdded(event);
  72. };
  73. this.peerconnection.onremovestream = function (event) {
  74. // Remove the stream from remoteStreams
  75. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  76. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  77. };
  78. this.peerconnection.onsignalingstatechange = function (event) {
  79. if (!(self && self.peerconnection)) return;
  80. };
  81. this.peerconnection.oniceconnectionstatechange = function (event) {
  82. if (!(self && self.peerconnection)) return;
  83. switch (self.peerconnection.iceConnectionState) {
  84. case 'connected':
  85. this.startTime = new Date();
  86. break;
  87. case 'disconnected':
  88. this.stopTime = new Date();
  89. break;
  90. }
  91. onIceConnectionStateChange(self.sid, self);
  92. };
  93. // add any local and relayed stream
  94. RTC.localStreams.forEach(function(stream) {
  95. self.peerconnection.addStream(stream.getOriginalStream());
  96. });
  97. this.relayedStreams.forEach(function(stream) {
  98. self.peerconnection.addStream(stream);
  99. });
  100. };
  101. function onIceConnectionStateChange(sid, session) {
  102. switch (session.peerconnection.iceConnectionState) {
  103. case 'checking':
  104. session.timeChecking = (new Date()).getTime();
  105. session.firstconnect = true;
  106. break;
  107. case 'completed': // on caller side
  108. case 'connected':
  109. if (session.firstconnect) {
  110. session.firstconnect = false;
  111. var metadata = {};
  112. metadata.setupTime
  113. = (new Date()).getTime() - session.timeChecking;
  114. session.peerconnection.getStats(function (res) {
  115. if(res && res.result) {
  116. res.result().forEach(function (report) {
  117. if (report.type == 'googCandidatePair' &&
  118. report.stat('googActiveConnection') == 'true') {
  119. metadata.localCandidateType
  120. = report.stat('googLocalCandidateType');
  121. metadata.remoteCandidateType
  122. = report.stat('googRemoteCandidateType');
  123. // log pair as well so we can get nice pie
  124. // charts
  125. metadata.candidatePair
  126. = report.stat('googLocalCandidateType') +
  127. ';' +
  128. report.stat('googRemoteCandidateType');
  129. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  130. {
  131. metadata.ipv6 = true;
  132. }
  133. }
  134. });
  135. }
  136. });
  137. }
  138. break;
  139. }
  140. }
  141. JingleSession.prototype.accept = function () {
  142. var self = this;
  143. this.state = 'active';
  144. var pranswer = this.peerconnection.localDescription;
  145. if (!pranswer || pranswer.type != 'pranswer') {
  146. return;
  147. }
  148. console.log('going from pranswer to answer');
  149. if (this.usetrickle) {
  150. // remove candidates already sent from session-accept
  151. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  152. for (var i = 0; i < lines.length; i++) {
  153. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  154. }
  155. }
  156. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  157. // FIXME: change any inactive to sendrecv or whatever they were originally
  158. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  159. }
  160. pranswer = simulcast.reverseTransformLocalDescription(pranswer);
  161. var prsdp = new SDP(pranswer.sdp);
  162. var accept = $iq({to: this.peerjid,
  163. type: 'set'})
  164. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  165. action: 'session-accept',
  166. initiator: this.initiator,
  167. responder: this.responder,
  168. sid: this.sid });
  169. prsdp.toJingle(accept, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  170. var sdp = this.peerconnection.localDescription.sdp;
  171. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  172. // FIXME: change any inactive to sendrecv or whatever they were originally
  173. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  174. }
  175. var self = this;
  176. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  177. function () {
  178. //console.log('setLocalDescription success');
  179. self.setLocalDescription();
  180. self.connection.sendIQ(accept,
  181. function () {
  182. var ack = {};
  183. ack.source = 'answer';
  184. $(document).trigger('ack.jingle', [self.sid, ack]);
  185. },
  186. function (stanza) {
  187. var error = ($(stanza).find('error').length) ? {
  188. code: $(stanza).find('error').attr('code'),
  189. reason: $(stanza).find('error :first')[0].tagName
  190. }:{};
  191. error.source = 'answer';
  192. JingleSession.onJingleError(self.sid, error);
  193. },
  194. 10000);
  195. },
  196. function (e) {
  197. console.error('setLocalDescription failed', e);
  198. }
  199. );
  200. };
  201. JingleSession.prototype.terminate = function (reason) {
  202. this.state = 'ended';
  203. this.reason = reason;
  204. this.peerconnection.close();
  205. if (this.statsinterval !== null) {
  206. window.clearInterval(this.statsinterval);
  207. this.statsinterval = null;
  208. }
  209. };
  210. JingleSession.prototype.active = function () {
  211. return this.state == 'active';
  212. };
  213. JingleSession.prototype.sendIceCandidate = function (candidate) {
  214. var self = this;
  215. if (candidate && !this.lasticecandidate) {
  216. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  217. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  218. if (!(ice && jcand)) {
  219. console.error('failed to get ice && jcand');
  220. return;
  221. }
  222. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  223. if (jcand.type === 'srflx') {
  224. this.hadstuncandidate = true;
  225. } else if (jcand.type === 'relay') {
  226. this.hadturncandidate = true;
  227. }
  228. if (this.usetrickle) {
  229. if (this.usedrip) {
  230. if (this.drip_container.length === 0) {
  231. // start 20ms callout
  232. window.setTimeout(function () {
  233. if (self.drip_container.length === 0) return;
  234. self.sendIceCandidates(self.drip_container);
  235. self.drip_container = [];
  236. }, 20);
  237. }
  238. this.drip_container.push(candidate);
  239. return;
  240. } else {
  241. self.sendIceCandidate([candidate]);
  242. }
  243. }
  244. } else {
  245. //console.log('sendIceCandidate: last candidate.');
  246. if (!this.usetrickle) {
  247. //console.log('should send full offer now...');
  248. var init = $iq({to: this.peerjid,
  249. type: 'set'})
  250. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  251. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  252. initiator: this.initiator,
  253. sid: this.sid});
  254. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  255. var self = this;
  256. var sendJingle = function (ssrc) {
  257. if(!ssrc)
  258. ssrc = {};
  259. self.localSDP.toJingle(init, self.initiator == self.me ? 'initiator' : 'responder', ssrc);
  260. self.connection.sendIQ(init,
  261. function () {
  262. //console.log('session initiate ack');
  263. var ack = {};
  264. ack.source = 'offer';
  265. $(document).trigger('ack.jingle', [self.sid, ack]);
  266. },
  267. function (stanza) {
  268. self.state = 'error';
  269. self.peerconnection.close();
  270. var error = ($(stanza).find('error').length) ? {
  271. code: $(stanza).find('error').attr('code'),
  272. reason: $(stanza).find('error :first')[0].tagName,
  273. }:{};
  274. error.source = 'offer';
  275. JingleSession.onJingleError(self.sid, error);
  276. },
  277. 10000);
  278. }
  279. sendJingle();
  280. }
  281. this.lasticecandidate = true;
  282. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  283. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  284. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  285. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  286. }
  287. }
  288. };
  289. JingleSession.prototype.sendIceCandidates = function (candidates) {
  290. console.log('sendIceCandidates', candidates);
  291. var cand = $iq({to: this.peerjid, type: 'set'})
  292. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  293. action: 'transport-info',
  294. initiator: this.initiator,
  295. sid: this.sid});
  296. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  297. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  298. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  299. if (cands.length > 0) {
  300. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  301. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  302. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  303. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  304. }).c('transport', ice);
  305. for (var i = 0; i < cands.length; i++) {
  306. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  307. }
  308. // add fingerprint
  309. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  310. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  311. tmp.required = true;
  312. cand.c(
  313. 'fingerprint',
  314. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  315. .t(tmp.fingerprint);
  316. delete tmp.fingerprint;
  317. cand.attrs(tmp);
  318. cand.up();
  319. }
  320. cand.up(); // transport
  321. cand.up(); // content
  322. }
  323. }
  324. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  325. //console.log('was this the last candidate', this.lasticecandidate);
  326. this.connection.sendIQ(cand,
  327. function () {
  328. var ack = {};
  329. ack.source = 'transportinfo';
  330. $(document).trigger('ack.jingle', [this.sid, ack]);
  331. },
  332. function (stanza) {
  333. var error = ($(stanza).find('error').length) ? {
  334. code: $(stanza).find('error').attr('code'),
  335. reason: $(stanza).find('error :first')[0].tagName,
  336. }:{};
  337. error.source = 'transportinfo';
  338. JingleSession.onJingleError(this.sid, error);
  339. },
  340. 10000);
  341. };
  342. JingleSession.prototype.sendOffer = function () {
  343. //console.log('sendOffer...');
  344. var self = this;
  345. this.peerconnection.createOffer(function (sdp) {
  346. self.createdOffer(sdp);
  347. },
  348. function (e) {
  349. console.error('createOffer failed', e);
  350. },
  351. this.media_constraints
  352. );
  353. };
  354. JingleSession.prototype.createdOffer = function (sdp) {
  355. //console.log('createdOffer', sdp);
  356. var self = this;
  357. this.localSDP = new SDP(sdp.sdp);
  358. //this.localSDP.mangle();
  359. var sendJingle = function () {
  360. var init = $iq({to: this.peerjid,
  361. type: 'set'})
  362. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  363. action: 'session-initiate',
  364. initiator: this.initiator,
  365. sid: this.sid});
  366. self.localSDP.toJingle(init, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  367. self.connection.sendIQ(init,
  368. function () {
  369. var ack = {};
  370. ack.source = 'offer';
  371. $(document).trigger('ack.jingle', [self.sid, ack]);
  372. },
  373. function (stanza) {
  374. self.state = 'error';
  375. self.peerconnection.close();
  376. var error = ($(stanza).find('error').length) ? {
  377. code: $(stanza).find('error').attr('code'),
  378. reason: $(stanza).find('error :first')[0].tagName,
  379. }:{};
  380. error.source = 'offer';
  381. JingleSession.onJingleError(self.sid, error);
  382. },
  383. 10000);
  384. }
  385. sdp.sdp = this.localSDP.raw;
  386. this.peerconnection.setLocalDescription(sdp,
  387. function () {
  388. if(self.usetrickle)
  389. {
  390. sendJingle();
  391. }
  392. self.setLocalDescription();
  393. //console.log('setLocalDescription success');
  394. },
  395. function (e) {
  396. console.error('setLocalDescription failed', e);
  397. }
  398. );
  399. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  400. for (var i = 0; i < cands.length; i++) {
  401. var cand = SDPUtil.parse_icecandidate(cands[i]);
  402. if (cand.type == 'srflx') {
  403. this.hadstuncandidate = true;
  404. } else if (cand.type == 'relay') {
  405. this.hadturncandidate = true;
  406. }
  407. }
  408. };
  409. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  410. //console.log('setting remote description... ', desctype);
  411. this.remoteSDP = new SDP('');
  412. this.remoteSDP.fromJingle(elem);
  413. if (this.peerconnection.remoteDescription !== null) {
  414. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  415. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  416. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  417. for (var i = 0; i < pranswer.media.length; i++) {
  418. // make sure we have ice ufrag and pwd
  419. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  420. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  421. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  422. } else {
  423. console.warn('no ice ufrag?');
  424. }
  425. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  426. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  427. } else {
  428. console.warn('no ice pwd?');
  429. }
  430. }
  431. // copy over candidates
  432. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  433. for (var j = 0; j < lines.length; j++) {
  434. this.remoteSDP.media[i] += lines[j] + '\r\n';
  435. }
  436. }
  437. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  438. }
  439. }
  440. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  441. this.peerconnection.setRemoteDescription(remotedesc,
  442. function () {
  443. //console.log('setRemoteDescription success');
  444. },
  445. function (e) {
  446. console.error('setRemoteDescription error', e);
  447. JingleSession.onJingleFatalError(self, e);
  448. }
  449. );
  450. };
  451. JingleSession.prototype.addIceCandidate = function (elem) {
  452. var self = this;
  453. if (this.peerconnection.signalingState == 'closed') {
  454. return;
  455. }
  456. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  457. console.log('trickle ice candidate arriving before session accept...');
  458. // create a PRANSWER for setRemoteDescription
  459. if (!this.remoteSDP) {
  460. var cobbled = 'v=0\r\n' +
  461. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  462. 's=-\r\n' +
  463. 't=0 0\r\n';
  464. // first, take some things from the local description
  465. for (var i = 0; i < this.localSDP.media.length; i++) {
  466. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  467. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  468. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  469. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  470. }
  471. cobbled += 'a=inactive\r\n';
  472. }
  473. this.remoteSDP = new SDP(cobbled);
  474. }
  475. // then add things like ice and dtls from remote candidate
  476. elem.each(function () {
  477. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  478. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  479. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  480. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  481. var tmp = $(this).find('transport');
  482. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  483. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  484. tmp = $(this).find('transport>fingerprint');
  485. if (tmp.length) {
  486. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  487. } else {
  488. console.log('no dtls fingerprint (webrtc issue #1718?)');
  489. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  490. }
  491. break;
  492. }
  493. }
  494. }
  495. });
  496. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  497. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  498. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  499. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  500. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  501. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  502. }).length == this.remoteSDP.media.length;
  503. if (iscomplete) {
  504. console.log('setting pranswer');
  505. try {
  506. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  507. function() {
  508. },
  509. function(e) {
  510. console.log('setRemoteDescription pranswer failed', e.toString());
  511. });
  512. } catch (e) {
  513. console.error('setting pranswer failed', e);
  514. }
  515. } else {
  516. //console.log('not yet setting pranswer');
  517. }
  518. }
  519. // operate on each content element
  520. elem.each(function () {
  521. // would love to deactivate this, but firefox still requires it
  522. var idx = -1;
  523. var i;
  524. for (i = 0; i < self.remoteSDP.media.length; i++) {
  525. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  526. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  527. idx = i;
  528. break;
  529. }
  530. }
  531. if (idx == -1) { // fall back to localdescription
  532. for (i = 0; i < self.localSDP.media.length; i++) {
  533. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  534. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  535. idx = i;
  536. break;
  537. }
  538. }
  539. }
  540. var name = $(this).attr('name');
  541. // TODO: check ice-pwd and ice-ufrag?
  542. $(this).find('transport>candidate').each(function () {
  543. var line, candidate;
  544. line = SDPUtil.candidateFromJingle(this);
  545. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  546. sdpMid: name,
  547. candidate: line});
  548. try {
  549. self.peerconnection.addIceCandidate(candidate);
  550. } catch (e) {
  551. console.error('addIceCandidate failed', e.toString(), line);
  552. }
  553. });
  554. });
  555. };
  556. JingleSession.prototype.sendAnswer = function (provisional) {
  557. //console.log('createAnswer', provisional);
  558. var self = this;
  559. this.peerconnection.createAnswer(
  560. function (sdp) {
  561. self.createdAnswer(sdp, provisional);
  562. },
  563. function (e) {
  564. console.error('createAnswer failed', e);
  565. },
  566. this.media_constraints
  567. );
  568. };
  569. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  570. //console.log('createAnswer callback');
  571. var self = this;
  572. this.localSDP = new SDP(sdp.sdp);
  573. //this.localSDP.mangle();
  574. this.usepranswer = provisional === true;
  575. if (this.usetrickle) {
  576. if (this.usepranswer) {
  577. sdp.type = 'pranswer';
  578. for (var i = 0; i < this.localSDP.media.length; i++) {
  579. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  580. }
  581. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  582. }
  583. }
  584. var self = this;
  585. var sendJingle = function (ssrcs) {
  586. var accept = $iq({to: self.peerjid,
  587. type: 'set'})
  588. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  589. action: 'session-accept',
  590. initiator: self.initiator,
  591. responder: self.responder,
  592. sid: self.sid });
  593. var publicLocalDesc = simulcast.reverseTransformLocalDescription(sdp);
  594. var publicLocalSDP = new SDP(publicLocalDesc.sdp);
  595. publicLocalSDP.toJingle(accept, self.initiator == self.me ? 'initiator' : 'responder', ssrcs);
  596. self.connection.sendIQ(accept,
  597. function () {
  598. var ack = {};
  599. ack.source = 'answer';
  600. $(document).trigger('ack.jingle', [self.sid, ack]);
  601. },
  602. function (stanza) {
  603. var error = ($(stanza).find('error').length) ? {
  604. code: $(stanza).find('error').attr('code'),
  605. reason: $(stanza).find('error :first')[0].tagName,
  606. }:{};
  607. error.source = 'answer';
  608. JingleSession.onJingleError(self.sid, error);
  609. },
  610. 10000);
  611. }
  612. sdp.sdp = this.localSDP.raw;
  613. this.peerconnection.setLocalDescription(sdp,
  614. function () {
  615. //console.log('setLocalDescription success');
  616. if (self.usetrickle && !self.usepranswer) {
  617. sendJingle();
  618. }
  619. self.setLocalDescription();
  620. },
  621. function (e) {
  622. console.error('setLocalDescription failed', e);
  623. }
  624. );
  625. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  626. for (var j = 0; j < cands.length; j++) {
  627. var cand = SDPUtil.parse_icecandidate(cands[j]);
  628. if (cand.type == 'srflx') {
  629. this.hadstuncandidate = true;
  630. } else if (cand.type == 'relay') {
  631. this.hadturncandidate = true;
  632. }
  633. }
  634. };
  635. JingleSession.prototype.sendTerminate = function (reason, text) {
  636. var self = this,
  637. term = $iq({to: this.peerjid,
  638. type: 'set'})
  639. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  640. action: 'session-terminate',
  641. initiator: this.initiator,
  642. sid: this.sid})
  643. .c('reason')
  644. .c(reason || 'success');
  645. if (text) {
  646. term.up().c('text').t(text);
  647. }
  648. this.connection.sendIQ(term,
  649. function () {
  650. self.peerconnection.close();
  651. self.peerconnection = null;
  652. self.terminate();
  653. var ack = {};
  654. ack.source = 'terminate';
  655. $(document).trigger('ack.jingle', [self.sid, ack]);
  656. },
  657. function (stanza) {
  658. var error = ($(stanza).find('error').length) ? {
  659. code: $(stanza).find('error').attr('code'),
  660. reason: $(stanza).find('error :first')[0].tagName,
  661. }:{};
  662. $(document).trigger('ack.jingle', [self.sid, error]);
  663. },
  664. 10000);
  665. if (this.statsinterval !== null) {
  666. window.clearInterval(this.statsinterval);
  667. this.statsinterval = null;
  668. }
  669. };
  670. JingleSession.prototype.addSource = function (elem, fromJid) {
  671. var self = this;
  672. // FIXME: dirty waiting
  673. if (!this.peerconnection.localDescription)
  674. {
  675. console.warn("addSource - localDescription not ready yet")
  676. setTimeout(function()
  677. {
  678. self.addSource(elem, fromJid);
  679. },
  680. 200
  681. );
  682. return;
  683. }
  684. console.log('addssrc', new Date().getTime());
  685. console.log('ice', this.peerconnection.iceConnectionState);
  686. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  687. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  688. $(elem).each(function (idx, content) {
  689. var name = $(content).attr('name');
  690. var lines = '';
  691. tmp = $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  692. var semantics = this.getAttribute('semantics');
  693. var ssrcs = $(this).find('>source').map(function () {
  694. return this.getAttribute('ssrc');
  695. }).get();
  696. if (ssrcs.length != 0) {
  697. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  698. }
  699. });
  700. tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  701. tmp.each(function () {
  702. var ssrc = $(this).attr('ssrc');
  703. if(mySdp.containsSSRC(ssrc)){
  704. /**
  705. * This happens when multiple participants change their streams at the same time and
  706. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  707. * addssrc are scheduled for update IQ. See
  708. */
  709. console.warn("Got add stream request for my own ssrc: "+ssrc);
  710. return;
  711. }
  712. $(this).find('>parameter').each(function () {
  713. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  714. if ($(this).attr('value') && $(this).attr('value').length)
  715. lines += ':' + $(this).attr('value');
  716. lines += '\r\n';
  717. });
  718. });
  719. sdp.media.forEach(function(media, idx) {
  720. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  721. return;
  722. sdp.media[idx] += lines;
  723. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  724. self.addssrc[idx] += lines;
  725. });
  726. sdp.raw = sdp.session + sdp.media.join('');
  727. });
  728. this.modifySources();
  729. };
  730. JingleSession.prototype.removeSource = function (elem, fromJid) {
  731. var self = this;
  732. // FIXME: dirty waiting
  733. if (!this.peerconnection.localDescription)
  734. {
  735. console.warn("removeSource - localDescription not ready yet")
  736. setTimeout(function()
  737. {
  738. self.removeSource(elem, fromJid);
  739. },
  740. 200
  741. );
  742. return;
  743. }
  744. console.log('removessrc', new Date().getTime());
  745. console.log('ice', this.peerconnection.iceConnectionState);
  746. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  747. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  748. $(elem).each(function (idx, content) {
  749. var name = $(content).attr('name');
  750. var lines = '';
  751. tmp = $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  752. var semantics = this.getAttribute('semantics');
  753. var ssrcs = $(this).find('>source').map(function () {
  754. return this.getAttribute('ssrc');
  755. }).get();
  756. if (ssrcs.length != 0) {
  757. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  758. }
  759. });
  760. tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  761. tmp.each(function () {
  762. var ssrc = $(this).attr('ssrc');
  763. // This should never happen, but can be useful for bug detection
  764. if(mySdp.containsSSRC(ssrc)){
  765. console.error("Got remove stream request for my own ssrc: "+ssrc);
  766. return;
  767. }
  768. $(this).find('>parameter').each(function () {
  769. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  770. if ($(this).attr('value') && $(this).attr('value').length)
  771. lines += ':' + $(this).attr('value');
  772. lines += '\r\n';
  773. });
  774. });
  775. sdp.media.forEach(function(media, idx) {
  776. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  777. return;
  778. sdp.media[idx] += lines;
  779. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  780. self.removessrc[idx] += lines;
  781. });
  782. sdp.raw = sdp.session + sdp.media.join('');
  783. });
  784. this.modifySources();
  785. };
  786. JingleSession.prototype.modifySources = function (successCallback) {
  787. var self = this;
  788. if (this.peerconnection.signalingState == 'closed') return;
  789. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  790. // There is nothing to do since scheduled job might have been executed by another succeeding call
  791. this.setLocalDescription();
  792. if(successCallback){
  793. successCallback();
  794. }
  795. return;
  796. }
  797. // FIXME: this is a big hack
  798. // https://code.google.com/p/webrtc/issues/detail?id=2688
  799. // ^ has been fixed.
  800. if (!(this.peerconnection.signalingState == 'stable' && this.peerconnection.iceConnectionState == 'connected')) {
  801. console.warn('modifySources not yet', this.peerconnection.signalingState, this.peerconnection.iceConnectionState);
  802. this.wait = true;
  803. window.setTimeout(function() { self.modifySources(successCallback); }, 250);
  804. return;
  805. }
  806. if (this.wait) {
  807. window.setTimeout(function() { self.modifySources(successCallback); }, 2500);
  808. this.wait = false;
  809. return;
  810. }
  811. // Reset switch streams flag
  812. this.switchstreams = false;
  813. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  814. // add sources
  815. this.addssrc.forEach(function(lines, idx) {
  816. sdp.media[idx] += lines;
  817. });
  818. this.addssrc = [];
  819. // remove sources
  820. this.removessrc.forEach(function(lines, idx) {
  821. lines = lines.split('\r\n');
  822. lines.pop(); // remove empty last element;
  823. lines.forEach(function(line) {
  824. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  825. });
  826. });
  827. this.removessrc = [];
  828. // FIXME:
  829. // this was a hack for the situation when only one peer exists
  830. // in the conference.
  831. // check if still required and remove
  832. if (sdp.media[0])
  833. sdp.media[0] = sdp.media[0].replace('a=recvonly', 'a=sendrecv');
  834. if (sdp.media[1])
  835. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  836. sdp.raw = sdp.session + sdp.media.join('');
  837. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  838. function() {
  839. if(self.signalingState == 'closed') {
  840. console.error("createAnswer attempt on closed state");
  841. return;
  842. }
  843. self.peerconnection.createAnswer(
  844. function(modifiedAnswer) {
  845. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  846. if (self.pendingop !== null) {
  847. var sdp = new SDP(modifiedAnswer.sdp);
  848. if (sdp.media.length > 1) {
  849. switch(self.pendingop) {
  850. case 'mute':
  851. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  852. break;
  853. case 'unmute':
  854. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  855. break;
  856. }
  857. sdp.raw = sdp.session + sdp.media.join('');
  858. modifiedAnswer.sdp = sdp.raw;
  859. }
  860. self.pendingop = null;
  861. }
  862. // FIXME: pushing down an answer while ice connection state
  863. // is still checking is bad...
  864. //console.log(self.peerconnection.iceConnectionState);
  865. // trying to work around another chrome bug
  866. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  867. self.peerconnection.setLocalDescription(modifiedAnswer,
  868. function() {
  869. //console.log('modified setLocalDescription ok');
  870. self.setLocalDescription();
  871. if(successCallback){
  872. successCallback();
  873. }
  874. },
  875. function(error) {
  876. console.error('modified setLocalDescription failed', error);
  877. }
  878. );
  879. },
  880. function(error) {
  881. console.error('modified answer failed', error);
  882. }
  883. );
  884. },
  885. function(error) {
  886. console.error('modify failed', error);
  887. }
  888. );
  889. };
  890. /**
  891. * Switches video streams.
  892. * @param new_stream new stream that will be used as video of this session.
  893. * @param oldStream old video stream of this session.
  894. * @param success_callback callback executed after successful stream switch.
  895. */
  896. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback) {
  897. var self = this;
  898. // Remember SDP to figure out added/removed SSRCs
  899. var oldSdp = null;
  900. if(self.peerconnection) {
  901. if(self.peerconnection.localDescription) {
  902. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  903. }
  904. self.peerconnection.removeStream(oldStream, true);
  905. self.peerconnection.addStream(new_stream);
  906. }
  907. RTC.switchVideoStreams(new_stream, oldStream);
  908. // Conference is not active
  909. if(!oldSdp || !self.peerconnection) {
  910. success_callback();
  911. return;
  912. }
  913. self.switchstreams = true;
  914. self.modifySources(function() {
  915. console.log('modify sources done');
  916. success_callback();
  917. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  918. console.log("SDPs", oldSdp, newSdp);
  919. self.notifyMySSRCUpdate(oldSdp, newSdp);
  920. });
  921. };
  922. /**
  923. * Figures out added/removed ssrcs and send update IQs.
  924. * @param old_sdp SDP object for old description.
  925. * @param new_sdp SDP object for new description.
  926. */
  927. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  928. if (!(this.peerconnection.signalingState == 'stable' &&
  929. this.peerconnection.iceConnectionState == 'connected')){
  930. console.log("Too early to send updates");
  931. return;
  932. }
  933. // send source-remove IQ.
  934. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  935. var remove = $iq({to: this.peerjid, type: 'set'})
  936. .c('jingle', {
  937. xmlns: 'urn:xmpp:jingle:1',
  938. action: 'source-remove',
  939. initiator: this.initiator,
  940. sid: this.sid
  941. }
  942. );
  943. var removed = sdpDiffer.toJingle(remove);
  944. if (removed) {
  945. this.connection.sendIQ(remove,
  946. function (res) {
  947. console.info('got remove result', res);
  948. },
  949. function (err) {
  950. console.error('got remove error', err);
  951. }
  952. );
  953. } else {
  954. console.log('removal not necessary');
  955. }
  956. // send source-add IQ.
  957. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  958. var add = $iq({to: this.peerjid, type: 'set'})
  959. .c('jingle', {
  960. xmlns: 'urn:xmpp:jingle:1',
  961. action: 'source-add',
  962. initiator: this.initiator,
  963. sid: this.sid
  964. }
  965. );
  966. var added = sdpDiffer.toJingle(add);
  967. if (added) {
  968. this.connection.sendIQ(add,
  969. function (res) {
  970. console.info('got add result', res);
  971. },
  972. function (err) {
  973. console.error('got add error', err);
  974. }
  975. );
  976. } else {
  977. console.log('addition not necessary');
  978. }
  979. };
  980. /**
  981. * Determines whether the (local) video is mute i.e. all video tracks are
  982. * disabled.
  983. *
  984. * @return <tt>true</tt> if the (local) video is mute i.e. all video tracks are
  985. * disabled; otherwise, <tt>false</tt>
  986. */
  987. JingleSession.prototype.isVideoMute = function () {
  988. var tracks = RTC.localVideo.getVideoTracks();
  989. var mute = true;
  990. for (var i = 0; i < tracks.length; ++i) {
  991. if (tracks[i].enabled) {
  992. mute = false;
  993. break;
  994. }
  995. }
  996. return mute;
  997. };
  998. /**
  999. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  1000. *
  1001. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  1002. * tracks; otherwise, <tt>false</tt>
  1003. * @param callback a function to be invoked with <tt>mute</tt> after all video
  1004. * tracks have been enabled/disabled. The function may, optionally, return
  1005. * another function which is to be invoked after the whole mute/unmute operation
  1006. * has completed successfully.
  1007. * @param options an object which specifies optional arguments such as the
  1008. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  1009. * specifies whether the method was initiated in response to a user command (in
  1010. * contrast to an automatic decision made by the application logic)
  1011. */
  1012. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  1013. var byUser;
  1014. if (options) {
  1015. byUser = options.byUser;
  1016. if (typeof byUser === 'undefined') {
  1017. byUser = true;
  1018. }
  1019. } else {
  1020. byUser = true;
  1021. }
  1022. // The user's command to mute the (local) video takes precedence over any
  1023. // automatic decision made by the application logic.
  1024. if (byUser) {
  1025. this.videoMuteByUser = mute;
  1026. } else if (this.videoMuteByUser) {
  1027. return;
  1028. }
  1029. var self = this;
  1030. var localCallback = function (mute) {
  1031. self.connection.emuc.addVideoInfoToPresence(mute);
  1032. self.connection.emuc.sendPresence();
  1033. return callback(mute)
  1034. };
  1035. if (mute == RTC.localVideo.isMuted())
  1036. {
  1037. // Even if no change occurs, the specified callback is to be executed.
  1038. // The specified callback may, optionally, return a successCallback
  1039. // which is to be executed as well.
  1040. var successCallback = localCallback(mute);
  1041. if (successCallback) {
  1042. successCallback();
  1043. }
  1044. } else {
  1045. RTC.localVideo.setMute(!mute);
  1046. this.hardMuteVideo(mute);
  1047. this.modifySources(localCallback(mute));
  1048. }
  1049. };
  1050. // SDP-based mute by going recvonly/sendrecv
  1051. // FIXME: should probably black out the screen as well
  1052. JingleSession.prototype.toggleVideoMute = function (callback) {
  1053. this.service.setVideoMute(RTC.localVideo.isMuted(), callback);
  1054. };
  1055. JingleSession.prototype.hardMuteVideo = function (muted) {
  1056. this.pendingop = muted ? 'mute' : 'unmute';
  1057. };
  1058. JingleSession.prototype.sendMute = function (muted, content) {
  1059. var info = $iq({to: this.peerjid,
  1060. type: 'set'})
  1061. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  1062. action: 'session-info',
  1063. initiator: this.initiator,
  1064. sid: this.sid });
  1065. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  1066. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  1067. if (content) {
  1068. info.attrs({'name': content});
  1069. }
  1070. this.connection.send(info);
  1071. };
  1072. JingleSession.prototype.sendRinging = function () {
  1073. var info = $iq({to: this.peerjid,
  1074. type: 'set'})
  1075. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  1076. action: 'session-info',
  1077. initiator: this.initiator,
  1078. sid: this.sid });
  1079. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  1080. this.connection.send(info);
  1081. };
  1082. JingleSession.prototype.getStats = function (interval) {
  1083. var self = this;
  1084. var recv = {audio: 0, video: 0};
  1085. var lost = {audio: 0, video: 0};
  1086. var lastrecv = {audio: 0, video: 0};
  1087. var lastlost = {audio: 0, video: 0};
  1088. var loss = {audio: 0, video: 0};
  1089. var delta = {audio: 0, video: 0};
  1090. this.statsinterval = window.setInterval(function () {
  1091. if (self && self.peerconnection && self.peerconnection.getStats) {
  1092. self.peerconnection.getStats(function (stats) {
  1093. var results = stats.result();
  1094. // TODO: there are so much statistics you can get from this..
  1095. for (var i = 0; i < results.length; ++i) {
  1096. if (results[i].type == 'ssrc') {
  1097. var packetsrecv = results[i].stat('packetsReceived');
  1098. var packetslost = results[i].stat('packetsLost');
  1099. if (packetsrecv && packetslost) {
  1100. packetsrecv = parseInt(packetsrecv, 10);
  1101. packetslost = parseInt(packetslost, 10);
  1102. if (results[i].stat('googFrameRateReceived')) {
  1103. lastlost.video = lost.video;
  1104. lastrecv.video = recv.video;
  1105. recv.video = packetsrecv;
  1106. lost.video = packetslost;
  1107. } else {
  1108. lastlost.audio = lost.audio;
  1109. lastrecv.audio = recv.audio;
  1110. recv.audio = packetsrecv;
  1111. lost.audio = packetslost;
  1112. }
  1113. }
  1114. }
  1115. }
  1116. delta.audio = recv.audio - lastrecv.audio;
  1117. delta.video = recv.video - lastrecv.video;
  1118. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  1119. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  1120. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  1121. });
  1122. }
  1123. }, interval || 3000);
  1124. return this.statsinterval;
  1125. };
  1126. JingleSession.onJingleError = function (session, error)
  1127. {
  1128. console.error("Jingle error", error);
  1129. }
  1130. JingleSession.onJingleFatalError = function (session, error)
  1131. {
  1132. this.service.sessionTerminated = true;
  1133. connection.emuc.doLeave();
  1134. UI.messageHandler.showError( "Sorry",
  1135. "Internal application error[setRemoteDescription]");
  1136. }
  1137. JingleSession.prototype.setLocalDescription = function () {
  1138. // put our ssrcs into presence so other clients can identify our stream
  1139. var newssrcs = [];
  1140. var media = simulcast.parseMedia(this.peerconnection.localDescription);
  1141. media.forEach(function (media) {
  1142. if(Object.keys(media.sources).length > 0) {
  1143. // TODO(gp) maybe exclude FID streams?
  1144. Object.keys(media.sources).forEach(function (ssrc) {
  1145. newssrcs.push({
  1146. 'ssrc': ssrc,
  1147. 'type': media.type,
  1148. 'direction': media.direction
  1149. });
  1150. });
  1151. }
  1152. else if(this.localStreamsSSRC && this.localStreamsSSRC[media.type])
  1153. {
  1154. newssrcs.push({
  1155. 'ssrc': this.localStreamsSSRC[media.type],
  1156. 'type': media.type,
  1157. 'direction': media.direction
  1158. });
  1159. }
  1160. });
  1161. console.log('new ssrcs', newssrcs);
  1162. // Have to clear presence map to get rid of removed streams
  1163. this.connection.emuc.clearPresenceMedia();
  1164. if (newssrcs.length > 0) {
  1165. for (var i = 1; i <= newssrcs.length; i ++) {
  1166. // Change video type to screen
  1167. if (newssrcs[i-1].type === 'video' && desktopsharing.isUsingScreenStream()) {
  1168. newssrcs[i-1].type = 'screen';
  1169. }
  1170. this.connection.emuc.addMediaToPresence(i,
  1171. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  1172. }
  1173. this.connection.emuc.sendPresence();
  1174. }
  1175. }
  1176. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  1177. function sendKeyframe(pc) {
  1178. console.log('sendkeyframe', pc.iceConnectionState);
  1179. if (pc.iceConnectionState !== 'connected') return; // safe...
  1180. pc.setRemoteDescription(
  1181. pc.remoteDescription,
  1182. function () {
  1183. pc.createAnswer(
  1184. function (modifiedAnswer) {
  1185. pc.setLocalDescription(
  1186. modifiedAnswer,
  1187. function () {
  1188. // noop
  1189. },
  1190. function (error) {
  1191. console.log('triggerKeyframe setLocalDescription failed', error);
  1192. UI.messageHandler.showError();
  1193. }
  1194. );
  1195. },
  1196. function (error) {
  1197. console.log('triggerKeyframe createAnswer failed', error);
  1198. UI.messageHandler.showError();
  1199. }
  1200. );
  1201. },
  1202. function (error) {
  1203. console.log('triggerKeyframe setRemoteDescription failed', error);
  1204. UI.messageHandler.showError();
  1205. }
  1206. );
  1207. }
  1208. JingleSession.prototype.remoteStreamAdded = function (data) {
  1209. var self = this;
  1210. var thessrc;
  1211. // look up an associated JID for a stream id
  1212. if (data.stream.id && data.stream.id.indexOf('mixedmslabel') === -1) {
  1213. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  1214. var ssrclines
  1215. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  1216. ssrclines = ssrclines.filter(function (line) {
  1217. // NOTE(gp) previously we filtered on the mslabel, but that property
  1218. // is not always present.
  1219. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  1220. return ((line.indexOf('msid:' + data.stream.id) !== -1));
  1221. });
  1222. if (ssrclines.length) {
  1223. thessrc = ssrclines[0].substring(7).split(' ')[0];
  1224. // We signal our streams (through Jingle to the focus) before we set
  1225. // our presence (through which peers associate remote streams to
  1226. // jids). So, it might arrive that a remote stream is added but
  1227. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  1228. // successfully set. Here we wait for up to a second for the
  1229. // presence to arrive.
  1230. if (!ssrc2jid[thessrc]) {
  1231. // TODO(gp) limit wait duration to 1 sec.
  1232. setTimeout(function(d) {
  1233. return function() {
  1234. self.remoteStreamAdded(d);
  1235. }
  1236. }(data), 250);
  1237. return;
  1238. }
  1239. // ok to overwrite the one from focus? might save work in colibri.js
  1240. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  1241. if (ssrc2jid[thessrc]) {
  1242. data.peerjid = ssrc2jid[thessrc];
  1243. }
  1244. }
  1245. }
  1246. //TODO: this code should be removed when firefox implement multistream support
  1247. if(RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_FIREFOX)
  1248. {
  1249. if((notReceivedSSRCs.length == 0) ||
  1250. !ssrc2jid[notReceivedSSRCs[notReceivedSSRCs.length - 1]])
  1251. {
  1252. // TODO(gp) limit wait duration to 1 sec.
  1253. setTimeout(function(d) {
  1254. return function() {
  1255. self.remoteStreamAdded(d);
  1256. }
  1257. }(data), 250);
  1258. return;
  1259. }
  1260. thessrc = notReceivedSSRCs.pop();
  1261. if (ssrc2jid[thessrc]) {
  1262. data.peerjid = ssrc2jid[thessrc];
  1263. }
  1264. }
  1265. RTC.createRemoteStream(data, this.sid, thessrc);
  1266. var isVideo = data.stream.getVideoTracks().length > 0;
  1267. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  1268. if (isVideo &&
  1269. data.peerjid && this.peerjid === data.peerjid &&
  1270. data.stream.getVideoTracks().length === 0 &&
  1271. RTC.localVideo.getTracks().length > 0) {
  1272. window.setTimeout(function () {
  1273. sendKeyframe(self.peerconnection);
  1274. }, 3000);
  1275. }
  1276. }
  1277. module.exports = JingleSession;