Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

JingleSession.js 51KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335
  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. this.modifySourcesQueue.push(callback(mute));
  1012. };
  1013. JingleSession.prototype.hardMuteVideo = function (muted) {
  1014. this.pendingop = muted ? 'mute' : 'unmute';
  1015. };
  1016. JingleSession.prototype.sendMute = function (muted, content) {
  1017. var info = $iq({to: this.peerjid,
  1018. type: 'set'})
  1019. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  1020. action: 'session-info',
  1021. initiator: this.initiator,
  1022. sid: this.sid });
  1023. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  1024. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  1025. if (content) {
  1026. info.attrs({'name': content});
  1027. }
  1028. this.connection.send(info);
  1029. };
  1030. JingleSession.prototype.sendRinging = function () {
  1031. var info = $iq({to: this.peerjid,
  1032. type: 'set'})
  1033. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  1034. action: 'session-info',
  1035. initiator: this.initiator,
  1036. sid: this.sid });
  1037. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  1038. this.connection.send(info);
  1039. };
  1040. JingleSession.prototype.getStats = function (interval) {
  1041. var self = this;
  1042. var recv = {audio: 0, video: 0};
  1043. var lost = {audio: 0, video: 0};
  1044. var lastrecv = {audio: 0, video: 0};
  1045. var lastlost = {audio: 0, video: 0};
  1046. var loss = {audio: 0, video: 0};
  1047. var delta = {audio: 0, video: 0};
  1048. this.statsinterval = window.setInterval(function () {
  1049. if (self && self.peerconnection && self.peerconnection.getStats) {
  1050. self.peerconnection.getStats(function (stats) {
  1051. var results = stats.result();
  1052. // TODO: there are so much statistics you can get from this..
  1053. for (var i = 0; i < results.length; ++i) {
  1054. if (results[i].type == 'ssrc') {
  1055. var packetsrecv = results[i].stat('packetsReceived');
  1056. var packetslost = results[i].stat('packetsLost');
  1057. if (packetsrecv && packetslost) {
  1058. packetsrecv = parseInt(packetsrecv, 10);
  1059. packetslost = parseInt(packetslost, 10);
  1060. if (results[i].stat('googFrameRateReceived')) {
  1061. lastlost.video = lost.video;
  1062. lastrecv.video = recv.video;
  1063. recv.video = packetsrecv;
  1064. lost.video = packetslost;
  1065. } else {
  1066. lastlost.audio = lost.audio;
  1067. lastrecv.audio = recv.audio;
  1068. recv.audio = packetsrecv;
  1069. lost.audio = packetslost;
  1070. }
  1071. }
  1072. }
  1073. }
  1074. delta.audio = recv.audio - lastrecv.audio;
  1075. delta.video = recv.video - lastrecv.video;
  1076. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  1077. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  1078. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  1079. });
  1080. }
  1081. }, interval || 3000);
  1082. return this.statsinterval;
  1083. };
  1084. JingleSession.onJingleError = function (session, error)
  1085. {
  1086. console.error("Jingle error", error);
  1087. }
  1088. JingleSession.onJingleFatalError = function (session, error)
  1089. {
  1090. this.service.sessionTerminated = true;
  1091. this.connection.emuc.doLeave();
  1092. APP.UI.messageHandler.showError("dialog.sorry",
  1093. "dialog.internalError");
  1094. }
  1095. JingleSession.prototype.setLocalDescription = function () {
  1096. // put our ssrcs into presence so other clients can identify our stream
  1097. var newssrcs = [];
  1098. var media = APP.simulcast.parseMedia(this.peerconnection.localDescription);
  1099. media.forEach(function (media) {
  1100. if(Object.keys(media.sources).length > 0) {
  1101. // TODO(gp) maybe exclude FID streams?
  1102. Object.keys(media.sources).forEach(function (ssrc) {
  1103. newssrcs.push({
  1104. 'ssrc': ssrc,
  1105. 'type': media.type,
  1106. 'direction': media.direction
  1107. });
  1108. });
  1109. }
  1110. else if(this.localStreamsSSRC && this.localStreamsSSRC[media.type])
  1111. {
  1112. newssrcs.push({
  1113. 'ssrc': this.localStreamsSSRC[media.type],
  1114. 'type': media.type,
  1115. 'direction': media.direction
  1116. });
  1117. }
  1118. });
  1119. console.log('new ssrcs', newssrcs);
  1120. // Have to clear presence map to get rid of removed streams
  1121. this.connection.emuc.clearPresenceMedia();
  1122. if (newssrcs.length > 0) {
  1123. for (var i = 1; i <= newssrcs.length; i ++) {
  1124. // Change video type to screen
  1125. if (newssrcs[i-1].type === 'video' && APP.desktopsharing.isUsingScreenStream()) {
  1126. newssrcs[i-1].type = 'screen';
  1127. }
  1128. this.connection.emuc.addMediaToPresence(i,
  1129. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  1130. }
  1131. this.connection.emuc.sendPresence();
  1132. }
  1133. }
  1134. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  1135. function sendKeyframe(pc) {
  1136. console.log('sendkeyframe', pc.iceConnectionState);
  1137. if (pc.iceConnectionState !== 'connected') return; // safe...
  1138. pc.setRemoteDescription(
  1139. pc.remoteDescription,
  1140. function () {
  1141. pc.createAnswer(
  1142. function (modifiedAnswer) {
  1143. pc.setLocalDescription(
  1144. modifiedAnswer,
  1145. function () {
  1146. // noop
  1147. },
  1148. function (error) {
  1149. console.log('triggerKeyframe setLocalDescription failed', error);
  1150. APP.UI.messageHandler.showError();
  1151. }
  1152. );
  1153. },
  1154. function (error) {
  1155. console.log('triggerKeyframe createAnswer failed', error);
  1156. APP.UI.messageHandler.showError();
  1157. }
  1158. );
  1159. },
  1160. function (error) {
  1161. console.log('triggerKeyframe setRemoteDescription failed', error);
  1162. APP.UI.messageHandler.showError();
  1163. }
  1164. );
  1165. }
  1166. JingleSession.prototype.remoteStreamAdded = function (data, times) {
  1167. var self = this;
  1168. var thessrc;
  1169. var ssrc2jid = this.connection.emuc.ssrc2jid;
  1170. // look up an associated JID for a stream id
  1171. if (data.stream.id && data.stream.id.indexOf('mixedmslabel') === -1) {
  1172. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  1173. var ssrclines
  1174. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  1175. ssrclines = ssrclines.filter(function (line) {
  1176. // NOTE(gp) previously we filtered on the mslabel, but that property
  1177. // is not always present.
  1178. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  1179. return ((line.indexOf('msid:' + data.stream.id) !== -1));
  1180. });
  1181. if (ssrclines.length) {
  1182. thessrc = ssrclines[0].substring(7).split(' ')[0];
  1183. // We signal our streams (through Jingle to the focus) before we set
  1184. // our presence (through which peers associate remote streams to
  1185. // jids). So, it might arrive that a remote stream is added but
  1186. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  1187. // successfully set. Here we wait for up to a second for the
  1188. // presence to arrive.
  1189. if (!ssrc2jid[thessrc]) {
  1190. if (typeof times === 'undefined')
  1191. {
  1192. times = 0;
  1193. }
  1194. if (times > 10)
  1195. {
  1196. console.warning('Waiting for jid timed out', thessrc);
  1197. }
  1198. else
  1199. {
  1200. setTimeout(function(d) {
  1201. return function() {
  1202. self.remoteStreamAdded(d, times++);
  1203. }
  1204. }(data), 250);
  1205. }
  1206. return;
  1207. }
  1208. // ok to overwrite the one from focus? might save work in colibri.js
  1209. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  1210. if (ssrc2jid[thessrc]) {
  1211. data.peerjid = ssrc2jid[thessrc];
  1212. }
  1213. }
  1214. }
  1215. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  1216. var isVideo = data.stream.getVideoTracks().length > 0;
  1217. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  1218. if (isVideo &&
  1219. data.peerjid && this.peerjid === data.peerjid &&
  1220. data.stream.getVideoTracks().length === 0 &&
  1221. APP.RTC.localVideo.getTracks().length > 0) {
  1222. window.setTimeout(function () {
  1223. sendKeyframe(self.peerconnection);
  1224. }, 3000);
  1225. }
  1226. }
  1227. module.exports = JingleSession;