Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

JingleSessionPC.js 47KB

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