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

JingleSessionPC.js 55KB

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