You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JingleSessionPC.js 46KB

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