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

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