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

JingleSessionPC.js 47KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255
  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. var 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. /**
  261. * Does accept incoming Jingle 'session-initiate' and should send
  262. * 'session-accept' in result.
  263. * @param jingleOffer jQuery selector pointing to the jingle element of
  264. * the offer IQ
  265. * @param success callback called when we accept incoming session successfully
  266. * and receive RESULT packet to 'session-accept' sent.
  267. * @param failure function(error) called if for any reason we fail to accept
  268. * the incoming offer. 'error' argument can be used to log some details
  269. * about the error.
  270. */
  271. JingleSessionPC.prototype.acceptOffer = function(jingleOffer,
  272. success, failure) {
  273. this.state = 'active';
  274. this.setOfferCycle(jingleOffer,
  275. function() {
  276. // setOfferCycle succeeded, now we have self.localSDP up to date
  277. // Let's send an answer !
  278. // FIXME we may not care about RESULT packet for session-accept
  279. // then we should either call 'success' here immediately or
  280. // modify sendSessionAccept method to do that
  281. this.sendSessionAccept(this.localSDP, success, failure);
  282. }.bind(this),
  283. failure);
  284. };
  285. /**
  286. * This is a setRemoteDescription/setLocalDescription cycle which starts at
  287. * converting Strophe Jingle IQ into remote offer SDP. Once converted
  288. * setRemoteDescription, createAnswer and setLocalDescription calls follow.
  289. * @param jingleOfferIq jQuery selector pointing to the jingle element of
  290. * the offer IQ
  291. * @param success callback called when sRD/sLD cycle finishes successfully.
  292. * @param failure callback called with an error object as an argument if we fail
  293. * at any point during setRD, createAnswer, setLD.
  294. */
  295. JingleSessionPC.prototype.setOfferCycle = function (jingleOfferIq,
  296. success,
  297. failure) {
  298. // Set Jingle offer as RD
  299. this.setOffer(jingleOfferIq,
  300. function() {
  301. // Set offer OK, now let's try create an answer
  302. this.createAnswer(function(answer) {
  303. // Create answer OK, set it as local SDP
  304. this.setLocalDescription(answer, success, failure);
  305. }.bind(this),
  306. failure);
  307. }.bind(this),
  308. failure);
  309. };
  310. /**
  311. * Sets remote offer on PeerConnection by converting given Jingle offer IQ into
  312. * SDP and setting it as remote description.
  313. * @param jingleOfferIq jQuery selector pointing to the jingle element of
  314. * the offer IQ
  315. * @param success callback called when setRemoteDescription on PeerConnection
  316. * succeeds
  317. * @param failure callback called with an error argument when
  318. * setRemoteDescription fails.
  319. */
  320. JingleSessionPC.prototype.setOffer = function (jingleOfferIq, success, failure) {
  321. this.remoteSDP = new SDP('');
  322. if (this.webrtcIceTcpDisable) {
  323. this.remoteSDP.removeTcpCandidates = true;
  324. }
  325. if (this.webrtcIceUdpDisable) {
  326. this.remoteSDP.removeUdpCandidates = true;
  327. }
  328. this.remoteSDP.fromJingle(jingleOfferIq);
  329. this.readSsrcInfo($(jingleOfferIq).find(">content"));
  330. var remotedesc
  331. = new RTCSessionDescription({type: 'offer', sdp: this.remoteSDP.raw});
  332. this.peerconnection.setRemoteDescription(remotedesc,
  333. function () {
  334. //logger.log('setRemoteDescription success');
  335. if (success) {
  336. success();
  337. }
  338. },
  339. function (e) {
  340. logger.error('setRemoteDescription error', e);
  341. if (failure)
  342. failure(e);
  343. JingleSessionPC.onJingleFatalError(this, e);
  344. }.bind(this)
  345. );
  346. };
  347. /**
  348. * This is a wrapper to PeerConnection.createAnswer in order to generate failure
  349. * event when error occurs. It also includes "media_constraints" if any are set
  350. * on this JingleSessionPC instance.
  351. * @param success callback called when PC.createAnswer succeeds, SDP will be
  352. * the first argument
  353. * @param failure callback called with error argument when setAnswer fails
  354. */
  355. JingleSessionPC.prototype.createAnswer = function (success, failure) {
  356. //logger.log('createAnswer');
  357. var self = this;
  358. this.peerconnection.createAnswer(
  359. success,
  360. function (error) {
  361. logger.error("createAnswer failed", error);
  362. if (failure)
  363. failure(error);
  364. self.room.eventEmitter.emit(
  365. XMPPEvents.CONFERENCE_SETUP_FAILED, error);
  366. },
  367. this.media_constraints
  368. );
  369. };
  370. JingleSessionPC.prototype.setLocalDescription = function (sdp, success,
  371. failure) {
  372. var self = this;
  373. this.localSDP = new SDP(sdp.sdp);
  374. sdp.sdp = this.localSDP.raw;
  375. this.peerconnection.setLocalDescription(sdp,
  376. function () {
  377. if (success)
  378. success();
  379. },
  380. function (error) {
  381. logger.error('setLocalDescription failed', error);
  382. if (failure)
  383. failure(error);
  384. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  385. }
  386. );
  387. // Some checks for STUN and TURN candiates present in local SDP
  388. // Eventually could be removed as we don't really care
  389. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  390. for (var j = 0; j < cands.length; j++) {
  391. var cand = SDPUtil.parse_icecandidate(cands[j]);
  392. if (cand.type == 'srflx') {
  393. this.hadstuncandidate = true;
  394. } else if (cand.type == 'relay') {
  395. this.hadturncandidate = true;
  396. }
  397. }
  398. };
  399. /**
  400. * Sends Jingle 'session-accept' message.
  401. * @param localSDP the 'SDP' object with local session description
  402. * @param success callback called when we recive 'RESULT' packet for
  403. * 'session-accept'
  404. * @param failure function(error) called when we receive an error response or
  405. * when the request has timed out.
  406. */
  407. JingleSessionPC.prototype.sendSessionAccept = function (localSDP,
  408. success, failure) {
  409. var accept = $iq({to: this.peerjid,
  410. type: 'set'})
  411. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  412. action: 'session-accept',
  413. initiator: this.initiator,
  414. responder: this.responder,
  415. sid: this.sid });
  416. if (this.webrtcIceTcpDisable) {
  417. localSDP.removeTcpCandidates = true;
  418. }
  419. if (this.webrtcIceUdpDisable) {
  420. localSDP.removeUdpCandidates = true;
  421. }
  422. localSDP.toJingle(
  423. accept,
  424. this.initiator == this.me ? 'initiator' : 'responder',
  425. null);
  426. this.fixJingle(accept);
  427. // Calling tree() to print something useful
  428. accept = accept.tree();
  429. logger.info("Sending session-accept", accept);
  430. this.connection.sendIQ(accept,
  431. success,
  432. this.newJingleErrorHandler(accept, failure),
  433. IQ_TIMEOUT);
  434. };
  435. JingleSessionPC.prototype.terminate = function (reason, text,
  436. success, failure) {
  437. var term = $iq({to: this.peerjid,
  438. type: 'set'})
  439. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  440. action: 'session-terminate',
  441. initiator: this.initiator,
  442. sid: this.sid})
  443. .c('reason')
  444. .c(reason || 'success');
  445. if (text) {
  446. term.up().c('text').t(text);
  447. }
  448. // Calling tree() to print something useful
  449. term = term.tree();
  450. logger.info("Sending session-terminate", term);
  451. this.connection.sendIQ(
  452. term, success, this.newJingleErrorHandler(term, failure), IQ_TIMEOUT);
  453. // this should result in 'onTerminated' being called by strope.jingle.js
  454. this.connection.jingle.terminate(this.sid);
  455. };
  456. JingleSessionPC.prototype.onTerminated = function (reasonCondition,
  457. reasonText) {
  458. this.state = 'ended';
  459. // Do something with reason and reasonCondition when we start to care
  460. //this.reasonCondition = reasonCondition;
  461. //this.reasonText = reasonText;
  462. logger.info("Session terminated", this, reasonCondition, reasonText);
  463. if (this.peerconnection)
  464. this.peerconnection.close();
  465. };
  466. /**
  467. * Handles a Jingle source-add message for this Jingle session.
  468. * @param elem An array of Jingle "content" elements.
  469. */
  470. JingleSessionPC.prototype.addSource = function (elem) {
  471. var self = this;
  472. // FIXME: dirty waiting
  473. if (!this.peerconnection.localDescription)
  474. {
  475. logger.warn("addSource - localDescription not ready yet")
  476. setTimeout(function()
  477. {
  478. self.addSource(elem);
  479. },
  480. 200
  481. );
  482. return;
  483. }
  484. logger.log('addssrc', new Date().getTime());
  485. logger.log('ice', this.peerconnection.iceConnectionState);
  486. this.readSsrcInfo(elem);
  487. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  488. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  489. $(elem).each(function (idx, content) {
  490. var name = $(content).attr('name');
  491. var lines = '';
  492. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  493. var semantics = this.getAttribute('semantics');
  494. var ssrcs = $(this).find('>source').map(function () {
  495. return this.getAttribute('ssrc');
  496. }).get();
  497. if (ssrcs.length) {
  498. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  499. }
  500. });
  501. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  502. tmp.each(function () {
  503. var ssrc = $(this).attr('ssrc');
  504. if(mySdp.containsSSRC(ssrc)){
  505. /**
  506. * This happens when multiple participants change their streams at the same time and
  507. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  508. * addssrc are scheduled for update IQ. See
  509. */
  510. logger.warn("Got add stream request for my own ssrc: "+ssrc);
  511. return;
  512. }
  513. if (sdp.containsSSRC(ssrc)) {
  514. logger.warn("Source-add request for existing SSRC: " + ssrc);
  515. return;
  516. }
  517. $(this).find('>parameter').each(function () {
  518. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  519. if ($(this).attr('value') && $(this).attr('value').length)
  520. lines += ':' + $(this).attr('value');
  521. lines += '\r\n';
  522. });
  523. });
  524. sdp.media.forEach(function(media, idx) {
  525. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  526. return;
  527. sdp.media[idx] += lines;
  528. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  529. self.addssrc[idx] += lines;
  530. });
  531. sdp.raw = sdp.session + sdp.media.join('');
  532. });
  533. this.modifySourcesQueue.push(function() {
  534. // When a source is added and if this is FF, a new channel is allocated
  535. // for receiving the added source. We need to diffuse the SSRC of this
  536. // new recvonly channel to the rest of the peers.
  537. logger.log('modify sources done');
  538. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  539. logger.log("SDPs", mySdp, newSdp);
  540. self.notifyMySSRCUpdate(mySdp, newSdp);
  541. });
  542. };
  543. /**
  544. * Handles a Jingle source-remove message for this Jingle session.
  545. * @param elem An array of Jingle "content" elements.
  546. */
  547. JingleSessionPC.prototype.removeSource = function (elem) {
  548. var self = this;
  549. // FIXME: dirty waiting
  550. if (!this.peerconnection.localDescription) {
  551. logger.warn("removeSource - localDescription not ready yet");
  552. setTimeout(function() {
  553. self.removeSource(elem);
  554. },
  555. 200
  556. );
  557. return;
  558. }
  559. logger.log('removessrc', new Date().getTime());
  560. logger.log('ice', this.peerconnection.iceConnectionState);
  561. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  562. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  563. $(elem).each(function (idx, content) {
  564. var name = $(content).attr('name');
  565. var lines = '';
  566. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  567. var semantics = this.getAttribute('semantics');
  568. var ssrcs = $(this).find('>source').map(function () {
  569. return this.getAttribute('ssrc');
  570. }).get();
  571. if (ssrcs.length) {
  572. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  573. }
  574. });
  575. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  576. tmp.each(function () {
  577. var ssrc = $(this).attr('ssrc');
  578. // This should never happen, but can be useful for bug detection
  579. if(mySdp.containsSSRC(ssrc)){
  580. logger.error("Got remove stream request for my own ssrc: "+ssrc);
  581. return;
  582. }
  583. $(this).find('>parameter').each(function () {
  584. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  585. if ($(this).attr('value') && $(this).attr('value').length)
  586. lines += ':' + $(this).attr('value');
  587. lines += '\r\n';
  588. });
  589. });
  590. sdp.media.forEach(function(media, idx) {
  591. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  592. return;
  593. sdp.media[idx] += lines;
  594. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  595. self.removessrc[idx] += lines;
  596. });
  597. sdp.raw = sdp.session + sdp.media.join('');
  598. });
  599. this.modifySourcesQueue.push(function() {
  600. // When a source is removed and if this is FF, the recvonly channel that
  601. // receives the remote stream is deactivated . We need to diffuse the
  602. // recvonly SSRC removal to the rest of the peers.
  603. logger.log('modify sources done');
  604. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  605. logger.log("SDPs", mySdp, newSdp);
  606. self.notifyMySSRCUpdate(mySdp, newSdp);
  607. });
  608. };
  609. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  610. var self = this;
  611. if (this.peerconnection.signalingState == 'closed') return;
  612. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null
  613. || this.modifyingLocalStreams)){
  614. // There is nothing to do since scheduled job might have been
  615. // executed by another succeeding call
  616. if(successCallback){
  617. successCallback();
  618. }
  619. queueCallback();
  620. return;
  621. }
  622. // Reset switch streams flags
  623. this.modifyingLocalStreams = false;
  624. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  625. // add sources
  626. this.addssrc.forEach(function(lines, idx) {
  627. sdp.media[idx] += lines;
  628. });
  629. this.addssrc = [];
  630. // remove sources
  631. this.removessrc.forEach(function(lines, idx) {
  632. lines = lines.split('\r\n');
  633. lines.pop(); // remove empty last element;
  634. lines.forEach(function(line) {
  635. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  636. });
  637. });
  638. this.removessrc = [];
  639. sdp.raw = sdp.session + sdp.media.join('');
  640. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  641. function() {
  642. if(self.signalingState == 'closed') {
  643. logger.error("createAnswer attempt on closed state");
  644. queueCallback("createAnswer attempt on closed state");
  645. return;
  646. }
  647. self.peerconnection.createAnswer(
  648. function(modifiedAnswer) {
  649. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  650. if (self.pendingop !== null) {
  651. var sdp = new SDP(modifiedAnswer.sdp);
  652. if (sdp.media.length > 1) {
  653. switch(self.pendingop) {
  654. case 'mute':
  655. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  656. break;
  657. case 'unmute':
  658. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  659. break;
  660. }
  661. sdp.raw = sdp.session + sdp.media.join('');
  662. modifiedAnswer.sdp = sdp.raw;
  663. }
  664. self.pendingop = null;
  665. }
  666. // FIXME: pushing down an answer while ice connection state
  667. // is still checking is bad...
  668. //logger.log(self.peerconnection.iceConnectionState);
  669. // trying to work around another chrome bug
  670. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  671. self.peerconnection.setLocalDescription(modifiedAnswer,
  672. function() {
  673. if(successCallback){
  674. successCallback();
  675. }
  676. queueCallback();
  677. },
  678. function(error) {
  679. logger.error('modified setLocalDescription failed', error);
  680. queueCallback(error);
  681. }
  682. );
  683. },
  684. function(error) {
  685. logger.error('modified answer failed', error);
  686. queueCallback(error);
  687. }
  688. );
  689. },
  690. function(error) {
  691. logger.error('modify failed', error);
  692. queueCallback(error);
  693. }
  694. );
  695. };
  696. /**
  697. * Adds stream.
  698. * @param stream new stream that will be added.
  699. * @param success_callback callback executed after successful stream addition.
  700. * @param ssrcInfo object with information about the SSRCs associated with the
  701. * stream.
  702. * @param dontModifySources {boolean} if true _modifySources won't be called.
  703. * Used for streams added before the call start.
  704. */
  705. JingleSessionPC.prototype.addStream = function (stream, callback, ssrcInfo,
  706. dontModifySources) {
  707. // Remember SDP to figure out added/removed SSRCs
  708. var oldSdp = null;
  709. if(this.peerconnection) {
  710. if(this.peerconnection.localDescription) {
  711. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  712. }
  713. //when adding muted stream we have to pass the ssrcInfo but we don't
  714. //have a stream
  715. if(stream || ssrcInfo)
  716. this.peerconnection.addStream(stream, ssrcInfo);
  717. }
  718. // Conference is not active
  719. if(!oldSdp || !this.peerconnection || dontModifySources) {
  720. if(ssrcInfo) {
  721. //available only on video unmute or when adding muted stream
  722. this.modifiedSSRCs[ssrcInfo.type] =
  723. this.modifiedSSRCs[ssrcInfo.type] || [];
  724. this.modifiedSSRCs[ssrcInfo.type].push(ssrcInfo);
  725. }
  726. callback();
  727. return;
  728. }
  729. this.modifyingLocalStreams = true;
  730. var self = this;
  731. this.modifySourcesQueue.push(function() {
  732. logger.log('modify sources done');
  733. if(ssrcInfo) {
  734. //available only on video unmute or when adding muted stream
  735. self.modifiedSSRCs[ssrcInfo.type] =
  736. self.modifiedSSRCs[ssrcInfo.type] || [];
  737. self.modifiedSSRCs[ssrcInfo.type].push(ssrcInfo);
  738. }
  739. callback();
  740. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  741. logger.log("SDPs", oldSdp, newSdp);
  742. self.notifyMySSRCUpdate(oldSdp, newSdp);
  743. });
  744. }
  745. /**
  746. * Generate ssrc info object for a stream with the following properties:
  747. * - ssrcs - Array of the ssrcs associated with the stream.
  748. * - groups - Array of the groups associated with the stream.
  749. */
  750. JingleSessionPC.prototype.generateNewStreamSSRCInfo = function () {
  751. return this.peerconnection.generateNewStreamSSRCInfo();
  752. };
  753. /**
  754. * Remove streams.
  755. * @param stream stream that will be removed.
  756. * @param success_callback callback executed after successful stream addition.
  757. * @param ssrcInfo object with information about the SSRCs associated with the
  758. * stream.
  759. */
  760. JingleSessionPC.prototype.removeStream = function (stream, callback, ssrcInfo) {
  761. // Remember SDP to figure out added/removed SSRCs
  762. var oldSdp = null;
  763. if(this.peerconnection) {
  764. if(this.peerconnection.localDescription) {
  765. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  766. }
  767. if (RTCBrowserType.getBrowserType() ===
  768. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  769. if(!stream)//There is nothing to be changed
  770. return;
  771. var sender = null;
  772. // On Firefox we don't replace MediaStreams as this messes up the
  773. // m-lines (which can't be removed in Plan Unified) and brings a lot
  774. // of complications. Instead, we use the RTPSender and remove just
  775. // the track.
  776. var track = null;
  777. if(stream.getAudioTracks() && stream.getAudioTracks().length) {
  778. track = stream.getAudioTracks()[0];
  779. } else if(stream.getVideoTracks() && stream.getVideoTracks().length)
  780. {
  781. track = stream.getVideoTracks()[0];
  782. }
  783. if(!track) {
  784. logger.log("Cannot remove tracks: no tracks.");
  785. return;
  786. }
  787. // Find the right sender (for audio or video)
  788. this.peerconnection.peerconnection.getSenders().some(function (s) {
  789. if (s.track === track) {
  790. sender = s;
  791. return true;
  792. }
  793. });
  794. if (sender) {
  795. this.peerconnection.peerconnection.removeTrack(sender);
  796. } else {
  797. logger.log("Cannot remove tracks: no RTPSender.");
  798. }
  799. } else if(stream)
  800. this.peerconnection.removeStream(stream, false, ssrcInfo);
  801. // else
  802. // NOTE: If there is no stream and the browser is not FF we still need to do
  803. // some transformation in order to send remove-source for the muted
  804. // streams. That's why we aren't calling return here.
  805. }
  806. // Conference is not active
  807. if(!oldSdp || !this.peerconnection) {
  808. callback();
  809. return;
  810. }
  811. this.modifyingLocalStreams = true;
  812. var self = this;
  813. this.modifySourcesQueue.push(function() {
  814. logger.log('modify sources done');
  815. callback();
  816. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  817. if(ssrcInfo) {
  818. self.modifiedSSRCs[ssrcInfo.type] =
  819. self.modifiedSSRCs[ssrcInfo.type] || [];
  820. self.modifiedSSRCs[ssrcInfo.type].push(ssrcInfo);
  821. }
  822. logger.log("SDPs", oldSdp, newSdp);
  823. self.notifyMySSRCUpdate(oldSdp, newSdp);
  824. });
  825. }
  826. /**
  827. * Figures out added/removed ssrcs and send update IQs.
  828. * @param old_sdp SDP object for old description.
  829. * @param new_sdp SDP object for new description.
  830. */
  831. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  832. if (!(this.peerconnection.signalingState == 'stable' &&
  833. this.peerconnection.iceConnectionState == 'connected')){
  834. logger.log("Too early to send updates");
  835. return;
  836. }
  837. // send source-remove IQ.
  838. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  839. var remove = $iq({to: this.peerjid, type: 'set'})
  840. .c('jingle', {
  841. xmlns: 'urn:xmpp:jingle:1',
  842. action: 'source-remove',
  843. initiator: this.initiator,
  844. sid: this.sid
  845. }
  846. );
  847. sdpDiffer.toJingle(remove);
  848. var removed = this.fixJingle(remove);
  849. if (removed && remove) {
  850. logger.info("Sending source-remove", remove.tree());
  851. this.connection.sendIQ(
  852. remove, null, this.newJingleErrorHandler(remove), IQ_TIMEOUT);
  853. } else {
  854. logger.log('removal not necessary');
  855. }
  856. // send source-add IQ.
  857. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  858. var add = $iq({to: this.peerjid, type: 'set'})
  859. .c('jingle', {
  860. xmlns: 'urn:xmpp:jingle:1',
  861. action: 'source-add',
  862. initiator: this.initiator,
  863. sid: this.sid
  864. }
  865. );
  866. sdpDiffer.toJingle(add);
  867. var added = this.fixJingle(add);
  868. if (added && add) {
  869. logger.info("Sending source-add", add.tree());
  870. this.connection.sendIQ(
  871. add, null, this.newJingleErrorHandler(add), IQ_TIMEOUT);
  872. } else {
  873. logger.log('addition not necessary');
  874. }
  875. };
  876. /**
  877. * Method returns function(errorResponse) which is a callback to be passed to
  878. * Strophe connection.sendIQ method. An 'error' structure is created that is
  879. * passed as 1st argument to given <tt>failureCb</tt>. The format of this
  880. * structure is as follows:
  881. * {
  882. * code: {XMPP error response code}
  883. * reason: {the name of XMPP error reason element or 'timeout' if the request
  884. * has timed out within <tt>IQ_TIMEOUT</tt> milliseconds}
  885. * source: {request.tree() that provides original request}
  886. * session: {JingleSessionPC instance on which the error occurred}
  887. * }
  888. * @param request Strophe IQ instance which is the request to be dumped into
  889. * the error structure
  890. * @param failureCb function(error) called when error response was returned or
  891. * when a timeout has occurred.
  892. * @returns {function(this:JingleSessionPC)}
  893. */
  894. JingleSessionPC.prototype.newJingleErrorHandler = function(request, failureCb) {
  895. return function (errResponse) {
  896. var error = { };
  897. // Get XMPP error code and condition(reason)
  898. var errorElSel = $(errResponse).find('error');
  899. if (errorElSel.length) {
  900. error.code = errorElSel.attr('code');
  901. var errorReasonSel = $(errResponse).find('error :first');
  902. if (errorReasonSel.length)
  903. error.reason = errorReasonSel[0].tagName;
  904. }
  905. if (!errResponse) {
  906. error.reason = 'timeout';
  907. }
  908. error.source = null;
  909. if (request && "function" == typeof request.tree) {
  910. error.source = request.tree();
  911. }
  912. error.session = this;
  913. logger.error("Jingle error", error);
  914. if (failureCb) {
  915. failureCb(error);
  916. }
  917. this.room.eventEmitter.emit(XMPPEvents.JINGLE_ERROR, error);
  918. }.bind(this);
  919. };
  920. JingleSessionPC.onJingleFatalError = function (session, error)
  921. {
  922. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  923. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  924. };
  925. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  926. var self = this;
  927. var thessrc;
  928. var streamId = RTC.getStreamID(data.stream);
  929. // look up an associated JID for a stream id
  930. if (!streamId) {
  931. logger.error("No stream ID for", data.stream);
  932. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  933. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  934. var ssrclines = this.peerconnection.remoteDescription?
  935. SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:') : [];
  936. ssrclines = ssrclines.filter(function (line) {
  937. // NOTE(gp) previously we filtered on the mslabel, but that property
  938. // is not always present.
  939. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  940. if (RTCBrowserType.isTemasysPluginUsed()) {
  941. return ((line.indexOf('mslabel:' + streamId) !== -1));
  942. } else {
  943. return ((line.indexOf('msid:' + streamId) !== -1));
  944. }
  945. });
  946. if (ssrclines.length) {
  947. thessrc = ssrclines[0].substring(7).split(' ')[0];
  948. if (!self.ssrcOwners[thessrc]) {
  949. logger.error("No SSRC owner known for: " + thessrc);
  950. return;
  951. }
  952. data.peerjid = self.ssrcOwners[thessrc];
  953. logger.log('associated jid', self.ssrcOwners[thessrc]);
  954. } else {
  955. logger.error("No SSRC lines for ", streamId);
  956. }
  957. }
  958. this.room.remoteStreamAdded(data, this.sid, thessrc);
  959. };
  960. /**
  961. * Handles remote stream removal.
  962. * @param event The event object associated with the removal.
  963. */
  964. JingleSessionPC.prototype.remoteStreamRemoved = function (event) {
  965. var thessrc;
  966. var streamId = RTC.getStreamID(event.stream);
  967. if (!streamId) {
  968. logger.error("No stream ID for", event.stream);
  969. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  970. this.room.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_REMOVED, streamId);
  971. }
  972. };
  973. /**
  974. * Returns the ice connection state for the peer connection.
  975. * @returns the ice connection state for the peer connection.
  976. */
  977. JingleSessionPC.prototype.getIceConnectionState = function () {
  978. return this.peerconnection.iceConnectionState;
  979. };
  980. /**
  981. * Fixes the outgoing jingle packets by removing the nodes related to the
  982. * muted/unmuted streams, handles removing of muted stream, etc.
  983. * @param jingle the jingle packet that is going to be sent
  984. * @returns {boolean} true if the jingle has to be sent and false otherwise.
  985. */
  986. JingleSessionPC.prototype.fixJingle = function(jingle) {
  987. var action = $(jingle.nodeTree).find("jingle").attr("action");
  988. switch (action) {
  989. case "source-add":
  990. case "session-accept":
  991. this.fixSourceAddJingle(jingle);
  992. break;
  993. case "source-remove":
  994. this.fixSourceRemoveJingle(jingle);
  995. break;
  996. default:
  997. logger.error("Unknown jingle action!");
  998. return false;
  999. }
  1000. var sources = $(jingle.tree()).find(">jingle>content>description>source");
  1001. return sources && sources.length > 0;
  1002. };
  1003. /**
  1004. * Fixes the outgoing jingle packets with action source-add by removing the
  1005. * nodes related to the unmuted streams
  1006. * @param jingle the jingle packet that is going to be sent
  1007. * @returns {boolean} true if the jingle has to be sent and false otherwise.
  1008. */
  1009. JingleSessionPC.prototype.fixSourceAddJingle = function (jingle) {
  1010. var ssrcs = this.modifiedSSRCs["unmute"];
  1011. this.modifiedSSRCs["unmute"] = [];
  1012. if(ssrcs && ssrcs.length) {
  1013. ssrcs.forEach(function (ssrcObj) {
  1014. var desc = $(jingle.tree()).find(">jingle>content[name=\"" +
  1015. ssrcObj.mtype + "\"]>description");
  1016. if(!desc || !desc.length)
  1017. return;
  1018. ssrcObj.ssrc.ssrcs.forEach(function (ssrc) {
  1019. var sourceNode = desc.find(">source[ssrc=\"" +
  1020. ssrc + "\"]");
  1021. sourceNode.remove();
  1022. });
  1023. ssrcObj.ssrc.groups.forEach(function (group) {
  1024. var groupNode = desc.find(">ssrc-group[semantics=\"" +
  1025. group.group.semantics + "\"]:has(source[ssrc=\"" +
  1026. group.primarySSRC +
  1027. "\"])");
  1028. groupNode.remove();
  1029. });
  1030. });
  1031. }
  1032. ssrcs = this.modifiedSSRCs["addMuted"];
  1033. this.modifiedSSRCs["addMuted"] = [];
  1034. if(ssrcs && ssrcs.length) {
  1035. ssrcs.forEach(function (ssrcObj) {
  1036. var desc = createDescriptionNode(jingle, ssrcObj.mtype);
  1037. var cname = Math.random().toString(36).substring(2);
  1038. ssrcObj.ssrc.ssrcs.forEach(function (ssrc) {
  1039. var sourceNode = desc.find(">source[ssrc=\"" +ssrc + "\"]");
  1040. sourceNode.remove();
  1041. var sourceXML = "<source " +
  1042. "xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\" ssrc=\"" +
  1043. ssrc + "\">" +
  1044. "<parameter xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\"" +
  1045. " value=\"" + ssrcObj.msid + "\" name=\"msid\"/>" +
  1046. "<parameter xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\"" +
  1047. " value=\"" + cname + "\" name=\"cname\" />" + "</source>";
  1048. desc.append(sourceXML);
  1049. });
  1050. ssrcObj.ssrc.groups.forEach(function (group) {
  1051. var groupNode = desc.find(">ssrc-group[semantics=\"" +
  1052. group.group.semantics + "\"]:has(source[ssrc=\"" + group.primarySSRC +
  1053. "\"])");
  1054. groupNode.remove();
  1055. desc.append("<ssrc-group semantics=\"" +
  1056. group.group.semantics +
  1057. "\" xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\"><source ssrc=\"" +
  1058. group.group.ssrcs.split(" ").join("\"/><source ssrc=\"") + "\"/>" +
  1059. "</ssrc-group>");
  1060. });
  1061. });
  1062. }
  1063. };
  1064. /**
  1065. * Fixes the outgoing jingle packets with action source-remove by removing the
  1066. * nodes related to the muted streams, handles removing of muted stream
  1067. * @param jingle the jingle packet that is going to be sent
  1068. * @returns {boolean} true if the jingle has to be sent and false otherwise.
  1069. */
  1070. JingleSessionPC.prototype.fixSourceRemoveJingle = function(jingle) {
  1071. var ssrcs = this.modifiedSSRCs["mute"];
  1072. this.modifiedSSRCs["mute"] = [];
  1073. if(ssrcs && ssrcs.length)
  1074. ssrcs.forEach(function (ssrcObj) {
  1075. ssrcObj.ssrc.ssrcs.forEach(function (ssrc) {
  1076. var sourceNode = $(jingle.tree()).find(">jingle>content[name=\"" +
  1077. ssrcObj.mtype + "\"]>description>source[ssrc=\"" +
  1078. ssrc + "\"]");
  1079. sourceNode.remove();
  1080. });
  1081. ssrcObj.ssrc.groups.forEach(function (group) {
  1082. var groupNode = $(jingle.tree()).find(">jingle>content[name=\"" +
  1083. ssrcObj.mtype + "\"]>description>ssrc-group[semantics=\"" +
  1084. group.group.semantics + "\"]:has(source[ssrc=\"" + group.primarySSRC +
  1085. "\"])");
  1086. groupNode.remove();
  1087. });
  1088. });
  1089. ssrcs = this.modifiedSSRCs["remove"];
  1090. this.modifiedSSRCs["remove"] = [];
  1091. if(ssrcs && ssrcs.length)
  1092. ssrcs.forEach(function (ssrcObj) {
  1093. var desc = createDescriptionNode(jingle, ssrcObj.mtype);
  1094. ssrcObj.ssrc.ssrcs.forEach(function (ssrc) {
  1095. var sourceNode = desc.find(">source[ssrc=\"" +ssrc + "\"]");
  1096. if(!sourceNode || !sourceNode.length) {
  1097. //Maybe we have to include cname, msid, etc here?
  1098. desc.append("<source " +
  1099. "xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\" ssrc=\"" +
  1100. ssrc + "\"></source>");
  1101. }
  1102. });
  1103. ssrcObj.ssrc.groups.forEach(function (group) {
  1104. var groupNode = desc.find(">ssrc-group[semantics=\"" +
  1105. group.group.semantics + "\"]:has(source[ssrc=\"" + group.primarySSRC +
  1106. "\"])");
  1107. if(!groupNode || !groupNode.length) {
  1108. desc.append("<ssrc-group semantics=\"" +
  1109. group.group.semantics +
  1110. "\" xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\"><source ssrc=\"" +
  1111. group.group.ssrcs.split(" ").join("\"/><source ssrc=\"") + "\"/>" +
  1112. "</ssrc-group>");
  1113. }
  1114. });
  1115. });
  1116. };
  1117. /**
  1118. * Returns the description node related to the passed content type. If the node
  1119. * doesn't exists it will be created.
  1120. * @param jingle - the jingle packet
  1121. * @param mtype - the content type(audio, video, etc.)
  1122. */
  1123. function createDescriptionNode(jingle, mtype) {
  1124. var content = $(jingle.tree()).find(">jingle>content[name=\"" +
  1125. mtype + "\"]");
  1126. if(!content || !content.length) {
  1127. $(jingle.tree()).find(">jingle").append(
  1128. "<content name=\"" + mtype + "\"></content>");
  1129. content = $(jingle.tree()).find(">jingle>content[name=\"" +
  1130. mtype + "\"]");
  1131. }
  1132. var desc = content.find(">description");
  1133. if(!desc || !desc.length) {
  1134. content.append("<description " +
  1135. "xmlns=\"urn:xmpp:jingle:apps:rtp:1\" media=\"" +
  1136. mtype + "\"></description>");
  1137. desc = content.find(">description");
  1138. }
  1139. return desc;
  1140. }
  1141. module.exports = JingleSessionPC;