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

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