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

JingleSessionPC.js 51KB

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