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

JingleSessionPC.js 43KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149
  1. /* jshint -W117 */
  2. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3. var JingleSession = require("./JingleSession");
  4. var TraceablePeerConnection = require("./TraceablePeerConnection");
  5. var SDPDiffer = require("./SDPDiffer");
  6. var SDPUtil = require("./SDPUtil");
  7. var SDP = require("./SDP");
  8. var async = require("async");
  9. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10. var RTCBrowserType = require("../RTC/RTCBrowserType");
  11. var RTC = require("../RTC/RTC");
  12. /**
  13. * Constant tells how long we're going to wait for IQ response, before timeout
  14. * error is triggered.
  15. * @type {number}
  16. */
  17. const IQ_TIMEOUT = 10000;
  18. // Jingle stuff
  19. function JingleSessionPC(me, sid, peerjid, connection,
  20. media_constraints, ice_config, service, eventEmitter) {
  21. JingleSession.call(this, me, sid, peerjid, connection,
  22. media_constraints, ice_config, service, eventEmitter);
  23. this.localSDP = null;
  24. this.remoteSDP = null;
  25. this.hadstuncandidate = false;
  26. this.hadturncandidate = false;
  27. this.lasticecandidate = false;
  28. this.addssrc = [];
  29. this.removessrc = [];
  30. this.pendingop = null;
  31. this.modifyingLocalStreams = false;
  32. this.modifiedSSRCs = {};
  33. /**
  34. * A map that stores SSRCs of remote streams. And is used only locally
  35. * We store the mapping when jingle is received, and later is used
  36. * onaddstream webrtc event where we have only the ssrc
  37. * FIXME: This map got filled and never cleaned and can grow durring long
  38. * conference
  39. * @type {{}} maps SSRC number to jid
  40. */
  41. this.ssrcOwners = {};
  42. this.webrtcIceUdpDisable = !!this.service.options.webrtcIceUdpDisable;
  43. this.webrtcIceTcpDisable = !!this.service.options.webrtcIceTcpDisable;
  44. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  45. // We start with the queue paused. We resume it when the signaling state is
  46. // stable and the ice connection state is connected.
  47. this.modifySourcesQueue.pause();
  48. }
  49. //XXX this is badly broken...
  50. JingleSessionPC.prototype = JingleSession.prototype;
  51. JingleSessionPC.prototype.constructor = JingleSessionPC;
  52. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  53. var signalingState = this.peerconnection.signalingState;
  54. var iceConnectionState = this.peerconnection.iceConnectionState;
  55. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  56. this.modifySourcesQueue.resume();
  57. } else {
  58. this.modifySourcesQueue.pause();
  59. }
  60. };
  61. JingleSessionPC.prototype.doInitialize = function () {
  62. var self = this;
  63. this.hadstuncandidate = false;
  64. this.hadturncandidate = false;
  65. this.lasticecandidate = false;
  66. // True if reconnect is in progress
  67. this.isreconnect = false;
  68. // Set to true if the connection was ever stable
  69. this.wasstable = false;
  70. this.peerconnection = new TraceablePeerConnection(
  71. this.connection.jingle.ice_config,
  72. RTC.getPCConstraints(),
  73. this);
  74. this.peerconnection.onicecandidate = function (ev) {
  75. if (!ev) {
  76. // There was an incomplete check for ev before which left the last
  77. // line of the function unprotected from a potential throw of an
  78. // exception. Consequently, it may be argued that the check is
  79. // unnecessary. Anyway, I'm leaving it and making the check
  80. // complete.
  81. return;
  82. }
  83. var candidate = ev.candidate;
  84. if (candidate) {
  85. // Discard candidates of disabled protocols.
  86. var protocol = candidate.protocol;
  87. if (typeof protocol === 'string') {
  88. protocol = protocol.toLowerCase();
  89. if (protocol == 'tcp') {
  90. if (self.webrtcIceTcpDisable)
  91. return;
  92. } else if (protocol == 'udp') {
  93. if (self.webrtcIceUdpDisable)
  94. return;
  95. }
  96. }
  97. }
  98. self.sendIceCandidate(candidate);
  99. };
  100. this.peerconnection.onaddstream = function (event) {
  101. if (event.stream.id !== 'default') {
  102. logger.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  103. self.remoteStreamAdded(event);
  104. } else {
  105. // This is a recvonly stream. Clients that implement Unified Plan,
  106. // such as Firefox use recvonly "streams/channels/tracks" for
  107. // receiving remote stream/tracks, as opposed to Plan B where there
  108. // are only 3 channels: audio, video and data.
  109. logger.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  110. }
  111. };
  112. this.peerconnection.onremovestream = function (event) {
  113. // Remove the stream from remoteStreams
  114. if (event.stream.id !== 'default') {
  115. logger.log("REMOTE STREAM REMOVED: ", event.stream , event.stream.id);
  116. self.remoteStreamRemoved(event);
  117. } else {
  118. // This is a recvonly stream. Clients that implement Unified Plan,
  119. // such as Firefox use recvonly "streams/channels/tracks" for
  120. // receiving remote stream/tracks, as opposed to Plan B where there
  121. // are only 3 channels: audio, video and data.
  122. logger.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  123. }
  124. };
  125. this.peerconnection.onsignalingstatechange = function (event) {
  126. if (!(self && self.peerconnection)) return;
  127. if (self.peerconnection.signalingState === 'stable') {
  128. self.wasstable = true;
  129. }
  130. self.updateModifySourcesQueue();
  131. };
  132. /**
  133. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  134. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  135. * RTCPeerConnection.iceConnectionState changes.
  136. *
  137. * @param event the event containing information about the change
  138. */
  139. this.peerconnection.oniceconnectionstatechange = function (event) {
  140. if (!(self && self.peerconnection)) return;
  141. logger.log("(TIME) ICE " + self.peerconnection.iceConnectionState +
  142. ":\t", window.performance.now());
  143. self.updateModifySourcesQueue();
  144. switch (self.peerconnection.iceConnectionState) {
  145. case 'connected':
  146. // Informs interested parties that the connection has been restored.
  147. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  148. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  149. self.isreconnect = false;
  150. break;
  151. case 'disconnected':
  152. self.isreconnect = true;
  153. // Informs interested parties that the connection has been interrupted.
  154. if (self.wasstable)
  155. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  156. break;
  157. case 'failed':
  158. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  159. break;
  160. }
  161. };
  162. this.peerconnection.onnegotiationneeded = function (event) {
  163. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  164. };
  165. };
  166. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  167. var self = this;
  168. if (candidate && !this.lasticecandidate) {
  169. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  170. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  171. if (!(ice && jcand)) {
  172. logger.error('failed to get ice && jcand');
  173. return;
  174. }
  175. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  176. if (jcand.type === 'srflx') {
  177. this.hadstuncandidate = true;
  178. } else if (jcand.type === 'relay') {
  179. this.hadturncandidate = true;
  180. }
  181. if (this.usedrip) {
  182. if (this.drip_container.length === 0) {
  183. // start 20ms callout
  184. window.setTimeout(function () {
  185. if (self.drip_container.length === 0) return;
  186. self.sendIceCandidates(self.drip_container);
  187. self.drip_container = [];
  188. }, 20);
  189. }
  190. this.drip_container.push(candidate);
  191. } else {
  192. self.sendIceCandidates([candidate]);
  193. }
  194. } else {
  195. logger.log('sendIceCandidate: last candidate.');
  196. // FIXME: remember to re-think in ICE-restart
  197. this.lasticecandidate = true;
  198. logger.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  199. logger.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  200. }
  201. };
  202. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  203. logger.log('sendIceCandidates', candidates);
  204. var cand = $iq({to: this.peerjid, type: 'set'})
  205. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  206. action: 'transport-info',
  207. initiator: this.initiator,
  208. sid: this.sid});
  209. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  210. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  211. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  212. if (cands.length > 0) {
  213. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  214. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  215. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  216. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  217. }).c('transport', ice);
  218. for (var i = 0; i < cands.length; i++) {
  219. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  220. }
  221. // add fingerprint
  222. var fingerprint_line = SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session);
  223. if (fingerprint_line) {
  224. var tmp = SDPUtil.parse_fingerprint(fingerprint_line);
  225. tmp.required = true;
  226. cand.c(
  227. 'fingerprint',
  228. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  229. .t(tmp.fingerprint);
  230. delete tmp.fingerprint;
  231. cand.attrs(tmp);
  232. cand.up();
  233. }
  234. cand.up(); // transport
  235. cand.up(); // content
  236. }
  237. }
  238. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  239. //logger.log('was this the last candidate', this.lasticecandidate);
  240. this.connection.sendIQ(
  241. cand, null, this.newJingleErrorHandler(cand), IQ_TIMEOUT);
  242. };
  243. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  244. var self = this;
  245. $(contents).each(function (idx, content) {
  246. var name = $(content).attr('name');
  247. var mediaType = this.getAttribute('name');
  248. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  249. ssrcs.each(function () {
  250. var ssrc = this.getAttribute('ssrc');
  251. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  252. function () {
  253. var owner = this.getAttribute('owner');
  254. self.ssrcOwners[ssrc] = owner;
  255. }
  256. );
  257. });
  258. });
  259. };
  260. JingleSessionPC.prototype.acceptOffer = function(jingleOffer,
  261. success, failure) {
  262. this.state = 'active';
  263. this.setRemoteDescription(jingleOffer, 'offer',
  264. function() {
  265. this.sendAnswer(success, failure);
  266. }.bind(this),
  267. failure);
  268. };
  269. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype,
  270. success, failure) {
  271. //logger.log('setting remote description... ', desctype);
  272. this.remoteSDP = new SDP('');
  273. if (this.webrtcIceTcpDisable) {
  274. this.remoteSDP.removeTcpCandidates = true;
  275. }
  276. if (this.webrtcIceUdpDisable) {
  277. this.remoteSDP.removeUdpCandidates = true;
  278. }
  279. this.remoteSDP.fromJingle(elem);
  280. this.readSsrcInfo($(elem).find(">content"));
  281. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  282. this.peerconnection.setRemoteDescription(remotedesc,
  283. function () {
  284. //logger.log('setRemoteDescription success');
  285. if (success) {
  286. success();
  287. }
  288. },
  289. function (e) {
  290. logger.error('setRemoteDescription error', e);
  291. if (failure)
  292. failure(e);
  293. JingleSessionPC.onJingleFatalError(this, e);
  294. }.bind(this)
  295. );
  296. };
  297. JingleSessionPC.prototype.sendAnswer = function (success, failure) {
  298. //logger.log('createAnswer');
  299. this.peerconnection.createAnswer(
  300. function (sdp) {
  301. this.createdAnswer(sdp, success, failure);
  302. }.bind(this),
  303. function (error) {
  304. logger.error("createAnswer failed", error);
  305. if (failure)
  306. failure(error);
  307. this.room.eventEmitter.emit(
  308. XMPPEvents.CONFERENCE_SETUP_FAILED, error);
  309. }.bind(this),
  310. this.media_constraints
  311. );
  312. };
  313. JingleSessionPC.prototype.createdAnswer = function (sdp, success, failure) {
  314. //logger.log('createAnswer callback');
  315. const self = this;
  316. this.localSDP = new SDP(sdp.sdp);
  317. var sendJingle = function (ssrcs) {
  318. var accept = $iq({to: self.peerjid,
  319. type: 'set'})
  320. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  321. action: 'session-accept',
  322. initiator: self.initiator,
  323. responder: self.responder,
  324. sid: self.sid });
  325. if (self.webrtcIceTcpDisable) {
  326. self.localSDP.removeTcpCandidates = true;
  327. }
  328. if (self.webrtcIceUdpDisable) {
  329. self.localSDP.removeUdpCandidates = true;
  330. }
  331. self.localSDP.toJingle(
  332. accept,
  333. self.initiator == self.me ? 'initiator' : 'responder',
  334. ssrcs);
  335. self.fixJingle(accept);
  336. self.connection.sendIQ(accept,
  337. success,
  338. self.newJingleErrorHandler(accept, failure),
  339. IQ_TIMEOUT);
  340. };
  341. sdp.sdp = this.localSDP.raw;
  342. this.peerconnection.setLocalDescription(sdp,
  343. function () {
  344. //logger.log('setLocalDescription success');
  345. sendJingle(success, failure);
  346. },
  347. function (error) {
  348. logger.error('setLocalDescription failed', error);
  349. if (failure)
  350. failure(error);
  351. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  352. }
  353. );
  354. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  355. for (var j = 0; j < cands.length; j++) {
  356. var cand = SDPUtil.parse_icecandidate(cands[j]);
  357. if (cand.type == 'srflx') {
  358. this.hadstuncandidate = true;
  359. } else if (cand.type == 'relay') {
  360. this.hadturncandidate = true;
  361. }
  362. }
  363. };
  364. JingleSessionPC.prototype.terminate = function (reason, text,
  365. success, failure) {
  366. var term = $iq({to: this.peerjid,
  367. type: 'set'})
  368. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  369. action: 'session-terminate',
  370. initiator: this.initiator,
  371. sid: this.sid})
  372. .c('reason')
  373. .c(reason || 'success');
  374. if (text) {
  375. term.up().c('text').t(text);
  376. }
  377. this.connection.sendIQ(
  378. term, success, this.newJingleErrorHandler(term, failure), IQ_TIMEOUT);
  379. // this should result in 'onTerminated' being called by strope.jingle.js
  380. this.connection.jingle.terminate(this.sid);
  381. };
  382. JingleSessionPC.prototype.onTerminated = function (reasonCondition,
  383. reasonText) {
  384. this.state = 'ended';
  385. // Do something with reason and reasonCondition when we start to care
  386. //this.reasonCondition = reasonCondition;
  387. //this.reasonText = reasonText;
  388. logger.info("Session terminated", this, reasonCondition, reasonText);
  389. this.peerconnection.close();
  390. };
  391. /**
  392. * Handles a Jingle source-add message for this Jingle session.
  393. * @param elem An array of Jingle "content" elements.
  394. */
  395. JingleSessionPC.prototype.addSource = function (elem) {
  396. var self = this;
  397. // FIXME: dirty waiting
  398. if (!this.peerconnection.localDescription)
  399. {
  400. logger.warn("addSource - localDescription not ready yet")
  401. setTimeout(function()
  402. {
  403. self.addSource(elem);
  404. },
  405. 200
  406. );
  407. return;
  408. }
  409. logger.log('addssrc', new Date().getTime());
  410. logger.log('ice', this.peerconnection.iceConnectionState);
  411. this.readSsrcInfo(elem);
  412. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  413. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  414. $(elem).each(function (idx, content) {
  415. var name = $(content).attr('name');
  416. var lines = '';
  417. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  418. var semantics = this.getAttribute('semantics');
  419. var ssrcs = $(this).find('>source').map(function () {
  420. return this.getAttribute('ssrc');
  421. }).get();
  422. if (ssrcs.length) {
  423. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  424. }
  425. });
  426. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  427. tmp.each(function () {
  428. var ssrc = $(this).attr('ssrc');
  429. if(mySdp.containsSSRC(ssrc)){
  430. /**
  431. * This happens when multiple participants change their streams at the same time and
  432. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  433. * addssrc are scheduled for update IQ. See
  434. */
  435. logger.warn("Got add stream request for my own ssrc: "+ssrc);
  436. return;
  437. }
  438. if (sdp.containsSSRC(ssrc)) {
  439. logger.warn("Source-add request for existing SSRC: " + ssrc);
  440. return;
  441. }
  442. $(this).find('>parameter').each(function () {
  443. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  444. if ($(this).attr('value') && $(this).attr('value').length)
  445. lines += ':' + $(this).attr('value');
  446. lines += '\r\n';
  447. });
  448. });
  449. sdp.media.forEach(function(media, idx) {
  450. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  451. return;
  452. sdp.media[idx] += lines;
  453. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  454. self.addssrc[idx] += lines;
  455. });
  456. sdp.raw = sdp.session + sdp.media.join('');
  457. });
  458. this.modifySourcesQueue.push(function() {
  459. // When a source is added and if this is FF, a new channel is allocated
  460. // for receiving the added source. We need to diffuse the SSRC of this
  461. // new recvonly channel to the rest of the peers.
  462. logger.log('modify sources done');
  463. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  464. logger.log("SDPs", mySdp, newSdp);
  465. self.notifyMySSRCUpdate(mySdp, newSdp);
  466. });
  467. };
  468. /**
  469. * Handles a Jingle source-remove message for this Jingle session.
  470. * @param elem An array of Jingle "content" elements.
  471. */
  472. JingleSessionPC.prototype.removeSource = function (elem) {
  473. var self = this;
  474. // FIXME: dirty waiting
  475. if (!this.peerconnection.localDescription) {
  476. logger.warn("removeSource - localDescription not ready yet");
  477. setTimeout(function() {
  478. self.removeSource(elem);
  479. },
  480. 200
  481. );
  482. return;
  483. }
  484. logger.log('removessrc', new Date().getTime());
  485. logger.log('ice', this.peerconnection.iceConnectionState);
  486. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  487. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  488. $(elem).each(function (idx, content) {
  489. var name = $(content).attr('name');
  490. var lines = '';
  491. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  492. var semantics = this.getAttribute('semantics');
  493. var ssrcs = $(this).find('>source').map(function () {
  494. return this.getAttribute('ssrc');
  495. }).get();
  496. if (ssrcs.length) {
  497. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  498. }
  499. });
  500. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  501. tmp.each(function () {
  502. var ssrc = $(this).attr('ssrc');
  503. // This should never happen, but can be useful for bug detection
  504. if(mySdp.containsSSRC(ssrc)){
  505. logger.error("Got remove stream request for my own ssrc: "+ssrc);
  506. return;
  507. }
  508. $(this).find('>parameter').each(function () {
  509. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  510. if ($(this).attr('value') && $(this).attr('value').length)
  511. lines += ':' + $(this).attr('value');
  512. lines += '\r\n';
  513. });
  514. });
  515. sdp.media.forEach(function(media, idx) {
  516. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  517. return;
  518. sdp.media[idx] += lines;
  519. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  520. self.removessrc[idx] += lines;
  521. });
  522. sdp.raw = sdp.session + sdp.media.join('');
  523. });
  524. this.modifySourcesQueue.push(function() {
  525. // When a source is removed and if this is FF, the recvonly channel that
  526. // receives the remote stream is deactivated . We need to diffuse the
  527. // recvonly SSRC removal to the rest of the peers.
  528. logger.log('modify sources done');
  529. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  530. logger.log("SDPs", mySdp, newSdp);
  531. self.notifyMySSRCUpdate(mySdp, newSdp);
  532. });
  533. };
  534. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  535. var self = this;
  536. if (this.peerconnection.signalingState == 'closed') return;
  537. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null
  538. || this.modifyingLocalStreams)){
  539. // There is nothing to do since scheduled job might have been
  540. // executed by another succeeding call
  541. if(successCallback){
  542. successCallback();
  543. }
  544. queueCallback();
  545. return;
  546. }
  547. // Reset switch streams flags
  548. this.modifyingLocalStreams = false;
  549. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  550. // add sources
  551. this.addssrc.forEach(function(lines, idx) {
  552. sdp.media[idx] += lines;
  553. });
  554. this.addssrc = [];
  555. // remove sources
  556. this.removessrc.forEach(function(lines, idx) {
  557. lines = lines.split('\r\n');
  558. lines.pop(); // remove empty last element;
  559. lines.forEach(function(line) {
  560. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  561. });
  562. });
  563. this.removessrc = [];
  564. sdp.raw = sdp.session + sdp.media.join('');
  565. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  566. function() {
  567. if(self.signalingState == 'closed') {
  568. logger.error("createAnswer attempt on closed state");
  569. queueCallback("createAnswer attempt on closed state");
  570. return;
  571. }
  572. self.peerconnection.createAnswer(
  573. function(modifiedAnswer) {
  574. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  575. if (self.pendingop !== null) {
  576. var sdp = new SDP(modifiedAnswer.sdp);
  577. if (sdp.media.length > 1) {
  578. switch(self.pendingop) {
  579. case 'mute':
  580. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  581. break;
  582. case 'unmute':
  583. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  584. break;
  585. }
  586. sdp.raw = sdp.session + sdp.media.join('');
  587. modifiedAnswer.sdp = sdp.raw;
  588. }
  589. self.pendingop = null;
  590. }
  591. // FIXME: pushing down an answer while ice connection state
  592. // is still checking is bad...
  593. //logger.log(self.peerconnection.iceConnectionState);
  594. // trying to work around another chrome bug
  595. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  596. self.peerconnection.setLocalDescription(modifiedAnswer,
  597. function() {
  598. if(successCallback){
  599. successCallback();
  600. }
  601. queueCallback();
  602. },
  603. function(error) {
  604. logger.error('modified setLocalDescription failed', error);
  605. queueCallback(error);
  606. }
  607. );
  608. },
  609. function(error) {
  610. logger.error('modified answer failed', error);
  611. queueCallback(error);
  612. }
  613. );
  614. },
  615. function(error) {
  616. logger.error('modify failed', error);
  617. queueCallback(error);
  618. }
  619. );
  620. };
  621. /**
  622. * Adds stream.
  623. * @param stream new stream that will be added.
  624. * @param success_callback callback executed after successful stream addition.
  625. * @param ssrcInfo object with information about the SSRCs associated with the
  626. * stream.
  627. * @param dontModifySources {boolean} if true _modifySources won't be called.
  628. * Used for streams added before the call start.
  629. */
  630. JingleSessionPC.prototype.addStream = function (stream, callback, ssrcInfo,
  631. dontModifySources) {
  632. // Remember SDP to figure out added/removed SSRCs
  633. var oldSdp = null;
  634. if(this.peerconnection) {
  635. if(this.peerconnection.localDescription) {
  636. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  637. }
  638. //when adding muted stream we have to pass the ssrcInfo but we don't
  639. //have a stream
  640. if(stream || ssrcInfo)
  641. this.peerconnection.addStream(stream, ssrcInfo);
  642. }
  643. // Conference is not active
  644. if(!oldSdp || !this.peerconnection || dontModifySources) {
  645. if(ssrcInfo) {
  646. //available only on video unmute or when adding muted stream
  647. this.modifiedSSRCs[ssrcInfo.type] =
  648. this.modifiedSSRCs[ssrcInfo.type] || [];
  649. this.modifiedSSRCs[ssrcInfo.type].push(ssrcInfo);
  650. }
  651. callback();
  652. return;
  653. }
  654. this.modifyingLocalStreams = true;
  655. var self = this;
  656. this.modifySourcesQueue.push(function() {
  657. logger.log('modify sources done');
  658. if(ssrcInfo) {
  659. //available only on video unmute or when adding muted stream
  660. self.modifiedSSRCs[ssrcInfo.type] =
  661. self.modifiedSSRCs[ssrcInfo.type] || [];
  662. self.modifiedSSRCs[ssrcInfo.type].push(ssrcInfo);
  663. }
  664. callback();
  665. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  666. logger.log("SDPs", oldSdp, newSdp);
  667. self.notifyMySSRCUpdate(oldSdp, newSdp);
  668. });
  669. }
  670. /**
  671. * Generate ssrc info object for a stream with the following properties:
  672. * - ssrcs - Array of the ssrcs associated with the stream.
  673. * - groups - Array of the groups associated with the stream.
  674. */
  675. JingleSessionPC.prototype.generateNewStreamSSRCInfo = function () {
  676. return this.peerconnection.generateNewStreamSSRCInfo();
  677. };
  678. /**
  679. * Remove streams.
  680. * @param stream stream that will be removed.
  681. * @param success_callback callback executed after successful stream addition.
  682. * @param ssrcInfo object with information about the SSRCs associated with the
  683. * stream.
  684. */
  685. JingleSessionPC.prototype.removeStream = function (stream, callback, ssrcInfo) {
  686. // Remember SDP to figure out added/removed SSRCs
  687. var oldSdp = null;
  688. if(this.peerconnection) {
  689. if(this.peerconnection.localDescription) {
  690. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  691. }
  692. if (RTCBrowserType.getBrowserType() ===
  693. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  694. if(!stream)//There is nothing to be changed
  695. return;
  696. var sender = null;
  697. // On Firefox we don't replace MediaStreams as this messes up the
  698. // m-lines (which can't be removed in Plan Unified) and brings a lot
  699. // of complications. Instead, we use the RTPSender and remove just
  700. // the track.
  701. var track = null;
  702. if(stream.getAudioTracks() && stream.getAudioTracks().length) {
  703. track = stream.getAudioTracks()[0];
  704. } else if(stream.getVideoTracks() && stream.getVideoTracks().length)
  705. {
  706. track = stream.getVideoTracks()[0];
  707. }
  708. if(!track) {
  709. logger.log("Cannot remove tracks: no tracks.");
  710. return;
  711. }
  712. // Find the right sender (for audio or video)
  713. this.peerconnection.peerconnection.getSenders().some(function (s) {
  714. if (s.track === track) {
  715. sender = s;
  716. return true;
  717. }
  718. });
  719. if (sender) {
  720. this.peerconnection.peerconnection.removeTrack(sender);
  721. } else {
  722. logger.log("Cannot remove tracks: no RTPSender.");
  723. }
  724. } else if(stream)
  725. this.peerconnection.removeStream(stream, false, ssrcInfo);
  726. // else
  727. // NOTE: If there is no stream and the browser is not FF we still need to do
  728. // some transformation in order to send remove-source for the muted
  729. // streams. That's why we aren't calling return here.
  730. }
  731. // Conference is not active
  732. if(!oldSdp || !this.peerconnection) {
  733. callback();
  734. return;
  735. }
  736. this.modifyingLocalStreams = true;
  737. var self = this;
  738. this.modifySourcesQueue.push(function() {
  739. logger.log('modify sources done');
  740. callback();
  741. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  742. if(ssrcInfo) {
  743. self.modifiedSSRCs[ssrcInfo.type] =
  744. self.modifiedSSRCs[ssrcInfo.type] || [];
  745. self.modifiedSSRCs[ssrcInfo.type].push(ssrcInfo);
  746. }
  747. logger.log("SDPs", oldSdp, newSdp);
  748. self.notifyMySSRCUpdate(oldSdp, newSdp);
  749. });
  750. }
  751. /**
  752. * Figures out added/removed ssrcs and send update IQs.
  753. * @param old_sdp SDP object for old description.
  754. * @param new_sdp SDP object for new description.
  755. */
  756. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  757. if (!(this.peerconnection.signalingState == 'stable' &&
  758. this.peerconnection.iceConnectionState == 'connected')){
  759. logger.log("Too early to send updates");
  760. return;
  761. }
  762. // send source-remove IQ.
  763. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  764. var remove = $iq({to: this.peerjid, type: 'set'})
  765. .c('jingle', {
  766. xmlns: 'urn:xmpp:jingle:1',
  767. action: 'source-remove',
  768. initiator: this.initiator,
  769. sid: this.sid
  770. }
  771. );
  772. sdpDiffer.toJingle(remove);
  773. var removed = this.fixJingle(remove);
  774. if (removed && remove) {
  775. logger.info("Sending source-remove", remove.tree());
  776. this.connection.sendIQ(
  777. remove, null, this.newJingleErrorHandler(remove), IQ_TIMEOUT);
  778. } else {
  779. logger.log('removal not necessary');
  780. }
  781. // send source-add IQ.
  782. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  783. var add = $iq({to: this.peerjid, type: 'set'})
  784. .c('jingle', {
  785. xmlns: 'urn:xmpp:jingle:1',
  786. action: 'source-add',
  787. initiator: this.initiator,
  788. sid: this.sid
  789. }
  790. );
  791. sdpDiffer.toJingle(add);
  792. var added = this.fixJingle(add);
  793. if (added && add) {
  794. logger.info("Sending source-add", add.tree());
  795. this.connection.sendIQ(
  796. add, null, this.newJingleErrorHandler(add), IQ_TIMEOUT);
  797. } else {
  798. logger.log('addition not necessary');
  799. }
  800. };
  801. JingleSessionPC.prototype.newJingleErrorHandler = function(request, failureCb) {
  802. return function (errResponse) {
  803. var error = { };
  804. // Get XMPP error code and condition(reason)
  805. const errorElSel = $(errResponse).find('error');
  806. if (errorElSel.length) {
  807. error.code = errorElSel.attr('code');
  808. const errorReasonSel = $(errResponse).find('error :first');
  809. if (errorReasonSel.length)
  810. error.reason = errorReasonSel[0].tagName;
  811. }
  812. error.source = request ? request.tree() : null;
  813. error.session = this;
  814. logger.error("Jingle error", error);
  815. if (failureCb) {
  816. failureCb(error);
  817. }
  818. this.room.eventEmitter.emit(XMPPEvents.JINGLE_ERROR, error);
  819. }.bind(this);
  820. };
  821. JingleSessionPC.onJingleFatalError = function (session, error)
  822. {
  823. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  824. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  825. };
  826. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  827. var self = this;
  828. var thessrc;
  829. var streamId = RTC.getStreamID(data.stream);
  830. // look up an associated JID for a stream id
  831. if (!streamId) {
  832. logger.error("No stream ID for", data.stream);
  833. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  834. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  835. var ssrclines = this.peerconnection.remoteDescription?
  836. SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:') : [];
  837. ssrclines = ssrclines.filter(function (line) {
  838. // NOTE(gp) previously we filtered on the mslabel, but that property
  839. // is not always present.
  840. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  841. if (RTCBrowserType.isTemasysPluginUsed()) {
  842. return ((line.indexOf('mslabel:' + streamId) !== -1));
  843. } else {
  844. return ((line.indexOf('msid:' + streamId) !== -1));
  845. }
  846. });
  847. if (ssrclines.length) {
  848. thessrc = ssrclines[0].substring(7).split(' ')[0];
  849. if (!self.ssrcOwners[thessrc]) {
  850. logger.error("No SSRC owner known for: " + thessrc);
  851. return;
  852. }
  853. data.peerjid = self.ssrcOwners[thessrc];
  854. logger.log('associated jid', self.ssrcOwners[thessrc]);
  855. } else {
  856. logger.error("No SSRC lines for ", streamId);
  857. }
  858. }
  859. this.room.remoteStreamAdded(data, this.sid, thessrc);
  860. };
  861. /**
  862. * Handles remote stream removal.
  863. * @param event The event object associated with the removal.
  864. */
  865. JingleSessionPC.prototype.remoteStreamRemoved = function (event) {
  866. var thessrc;
  867. var streamId = RTC.getStreamID(event.stream);
  868. if (!streamId) {
  869. logger.error("No stream ID for", event.stream);
  870. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  871. this.room.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_REMOVED, streamId);
  872. }
  873. };
  874. /**
  875. * Returns the ice connection state for the peer connection.
  876. * @returns the ice connection state for the peer connection.
  877. */
  878. JingleSessionPC.prototype.getIceConnectionState = function () {
  879. return this.peerconnection.iceConnectionState;
  880. };
  881. /**
  882. * Fixes the outgoing jingle packets by removing the nodes related to the
  883. * muted/unmuted streams, handles removing of muted stream, etc.
  884. * @param jingle the jingle packet that is going to be sent
  885. * @returns {boolean} true if the jingle has to be sent and false otherwise.
  886. */
  887. JingleSessionPC.prototype.fixJingle = function(jingle) {
  888. var action = $(jingle.nodeTree).find("jingle").attr("action");
  889. switch (action) {
  890. case "source-add":
  891. case "session-accept":
  892. this.fixSourceAddJingle(jingle);
  893. break;
  894. case "source-remove":
  895. this.fixSourceRemoveJingle(jingle);
  896. break;
  897. default:
  898. logger.error("Unknown jingle action!");
  899. return false;
  900. }
  901. var sources = $(jingle.tree()).find(">jingle>content>description>source");
  902. return sources && sources.length > 0;
  903. };
  904. /**
  905. * Fixes the outgoing jingle packets with action source-add by removing the
  906. * nodes related to the unmuted streams
  907. * @param jingle the jingle packet that is going to be sent
  908. * @returns {boolean} true if the jingle has to be sent and false otherwise.
  909. */
  910. JingleSessionPC.prototype.fixSourceAddJingle = function (jingle) {
  911. var ssrcs = this.modifiedSSRCs["unmute"];
  912. this.modifiedSSRCs["unmute"] = [];
  913. if(ssrcs && ssrcs.length) {
  914. ssrcs.forEach(function (ssrcObj) {
  915. var desc = $(jingle.tree()).find(">jingle>content[name=\"" +
  916. ssrcObj.mtype + "\"]>description");
  917. if(!desc || !desc.length)
  918. return;
  919. ssrcObj.ssrc.ssrcs.forEach(function (ssrc) {
  920. var sourceNode = desc.find(">source[ssrc=\"" +
  921. ssrc + "\"]");
  922. sourceNode.remove();
  923. });
  924. ssrcObj.ssrc.groups.forEach(function (group) {
  925. var groupNode = desc.find(">ssrc-group[semantics=\"" +
  926. group.group.semantics + "\"]:has(source[ssrc=\"" +
  927. group.primarySSRC +
  928. "\"])");
  929. groupNode.remove();
  930. });
  931. });
  932. }
  933. ssrcs = this.modifiedSSRCs["addMuted"];
  934. this.modifiedSSRCs["addMuted"] = [];
  935. if(ssrcs && ssrcs.length) {
  936. ssrcs.forEach(function (ssrcObj) {
  937. var desc = createDescriptionNode(jingle, ssrcObj.mtype);
  938. var cname = Math.random().toString(36).substring(2);
  939. ssrcObj.ssrc.ssrcs.forEach(function (ssrc) {
  940. var sourceNode = desc.find(">source[ssrc=\"" +ssrc + "\"]");
  941. sourceNode.remove();
  942. var sourceXML = "<source " +
  943. "xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\" ssrc=\"" +
  944. ssrc + "\">" +
  945. "<parameter xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\"" +
  946. " value=\"" + ssrcObj.msid + "\" name=\"msid\"/>" +
  947. "<parameter xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\"" +
  948. " value=\"" + cname + "\" name=\"cname\" />" + "</source>";
  949. desc.append(sourceXML);
  950. });
  951. ssrcObj.ssrc.groups.forEach(function (group) {
  952. var groupNode = desc.find(">ssrc-group[semantics=\"" +
  953. group.group.semantics + "\"]:has(source[ssrc=\"" + group.primarySSRC +
  954. "\"])");
  955. groupNode.remove();
  956. desc.append("<ssrc-group semantics=\"" +
  957. group.group.semantics +
  958. "\" xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\"><source ssrc=\"" +
  959. group.group.ssrcs.split(" ").join("\"/><source ssrc=\"") + "\"/>" +
  960. "</ssrc-group>");
  961. });
  962. });
  963. }
  964. };
  965. /**
  966. * Fixes the outgoing jingle packets with action source-remove by removing the
  967. * nodes related to the muted streams, handles removing of muted stream
  968. * @param jingle the jingle packet that is going to be sent
  969. * @returns {boolean} true if the jingle has to be sent and false otherwise.
  970. */
  971. JingleSessionPC.prototype.fixSourceRemoveJingle = function(jingle) {
  972. var ssrcs = this.modifiedSSRCs["mute"];
  973. this.modifiedSSRCs["mute"] = [];
  974. if(ssrcs && ssrcs.length)
  975. ssrcs.forEach(function (ssrcObj) {
  976. ssrcObj.ssrc.ssrcs.forEach(function (ssrc) {
  977. var sourceNode = $(jingle.tree()).find(">jingle>content[name=\"" +
  978. ssrcObj.mtype + "\"]>description>source[ssrc=\"" +
  979. ssrc + "\"]");
  980. sourceNode.remove();
  981. });
  982. ssrcObj.ssrc.groups.forEach(function (group) {
  983. var groupNode = $(jingle.tree()).find(">jingle>content[name=\"" +
  984. ssrcObj.mtype + "\"]>description>ssrc-group[semantics=\"" +
  985. group.group.semantics + "\"]:has(source[ssrc=\"" + group.primarySSRC +
  986. "\"])");
  987. groupNode.remove();
  988. });
  989. });
  990. ssrcs = this.modifiedSSRCs["remove"];
  991. this.modifiedSSRCs["remove"] = [];
  992. if(ssrcs && ssrcs.length)
  993. ssrcs.forEach(function (ssrcObj) {
  994. var desc = createDescriptionNode(jingle, ssrcObj.mtype);
  995. ssrcObj.ssrc.ssrcs.forEach(function (ssrc) {
  996. var sourceNode = desc.find(">source[ssrc=\"" +ssrc + "\"]");
  997. if(!sourceNode || !sourceNode.length) {
  998. //Maybe we have to include cname, msid, etc here?
  999. desc.append("<source " +
  1000. "xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\" ssrc=\"" +
  1001. ssrc + "\"></source>");
  1002. }
  1003. });
  1004. ssrcObj.ssrc.groups.forEach(function (group) {
  1005. var groupNode = desc.find(">ssrc-group[semantics=\"" +
  1006. group.group.semantics + "\"]:has(source[ssrc=\"" + group.primarySSRC +
  1007. "\"])");
  1008. if(!groupNode || !groupNode.length) {
  1009. desc.append("<ssrc-group semantics=\"" +
  1010. group.group.semantics +
  1011. "\" xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\"><source ssrc=\"" +
  1012. group.group.ssrcs.split(" ").join("\"/><source ssrc=\"") + "\"/>" +
  1013. "</ssrc-group>");
  1014. }
  1015. });
  1016. });
  1017. };
  1018. /**
  1019. * Returns the description node related to the passed content type. If the node
  1020. * doesn't exists it will be created.
  1021. * @param jingle - the jingle packet
  1022. * @param mtype - the content type(audio, video, etc.)
  1023. */
  1024. function createDescriptionNode(jingle, mtype) {
  1025. var content = $(jingle.tree()).find(">jingle>content[name=\"" +
  1026. mtype + "\"]");
  1027. if(!content || !content.length) {
  1028. $(jingle.tree()).find(">jingle").append(
  1029. "<content name=\"" + mtype + "\"></content>");
  1030. content = $(jingle.tree()).find(">jingle>content[name=\"" +
  1031. mtype + "\"]");
  1032. }
  1033. var desc = content.find(">description");
  1034. if(!desc || !desc.length) {
  1035. content.append("<description " +
  1036. "xmlns=\"urn:xmpp:jingle:apps:rtp:1\" media=\"" +
  1037. mtype + "\"></description>");
  1038. desc = content.find(">description");
  1039. }
  1040. return desc;
  1041. }
  1042. module.exports = JingleSessionPC;