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

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