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 60KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586
  1. /* global $, $iq */
  2. import {getLogger} from "jitsi-meet-logger";
  3. const logger = getLogger(__filename);
  4. var JingleSession = require("./JingleSession");
  5. var TraceablePeerConnection = require("./TraceablePeerConnection");
  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. import RTC from "../RTC/RTC";
  13. var GlobalOnErrorHandler = require("../util/GlobalOnErrorHandler");
  14. var Statistics = require("../statistics/statistics");
  15. import * as JingleSessionState from "./JingleSessionState";
  16. /**
  17. * Constant tells how long we're going to wait for IQ response, before timeout
  18. * error is triggered.
  19. * @type {number}
  20. */
  21. var IQ_TIMEOUT = 10000;
  22. // Jingle stuff
  23. function JingleSessionPC(me, sid, peerjid, connection,
  24. media_constraints, ice_config, service, eventEmitter) {
  25. JingleSession.call(this, me, sid, peerjid, connection,
  26. media_constraints, ice_config, service, eventEmitter);
  27. this.lasticecandidate = false;
  28. this.closed = false;
  29. this.modifyingLocalStreams = false;
  30. /**
  31. * Used to keep state about muted/unmuted video streams
  32. * so we can prevent errant source-add/source-removes
  33. * from happening
  34. */
  35. this.modifiedSSRCs = {};
  36. /**
  37. * The local ICE username fragment for this session.
  38. */
  39. this.localUfrag = null;
  40. /**
  41. * The remote ICE username fragment for this session.
  42. */
  43. this.remoteUfrag = null;
  44. /**
  45. * A map that stores SSRCs of remote streams. And is used only locally
  46. * We store the mapping when jingle is received, and later is used
  47. * onaddstream webrtc event where we have only the ssrc
  48. * FIXME: This map got filled and never cleaned and can grow durring long
  49. * conference
  50. * @type {{}} maps SSRC number to jid
  51. */
  52. this.ssrcOwners = {};
  53. this.webrtcIceUdpDisable = !!this.service.options.webrtcIceUdpDisable;
  54. this.webrtcIceTcpDisable = !!this.service.options.webrtcIceTcpDisable;
  55. /**
  56. * Flag used to enforce ICE failure through the URL parameter for
  57. * the automatic testing purpose.
  58. * @type {boolean}
  59. */
  60. this.failICE = !!this.service.options.failICE;
  61. this.modificationQueue = async.queue(this._processQueueTasks.bind(this), 1);
  62. }
  63. JingleSessionPC.prototype = Object.create(JingleSession.prototype);
  64. JingleSessionPC.prototype.constructor = JingleSessionPC;
  65. JingleSessionPC.prototype.doInitialize = function () {
  66. var self = this;
  67. this.lasticecandidate = false;
  68. // True if reconnect is in progress
  69. this.isreconnect = false;
  70. // Set to true if the connection was ever stable
  71. this.wasstable = false;
  72. this.peerconnection = new TraceablePeerConnection(
  73. this.connection.jingle.ice_config,
  74. RTC.getPCConstraints(),
  75. this);
  76. this.peerconnection.onicecandidate = function (ev) {
  77. if (!ev) {
  78. // There was an incomplete check for ev before which left the last
  79. // line of the function unprotected from a potential throw of an
  80. // exception. Consequently, it may be argued that the check is
  81. // unnecessary. Anyway, I'm leaving it and making the check
  82. // complete.
  83. return;
  84. }
  85. // XXX this is broken, candidate is not parsed.
  86. var candidate = ev.candidate;
  87. if (candidate) {
  88. // Discard candidates of disabled protocols.
  89. var protocol = candidate.protocol;
  90. if (typeof protocol === 'string') {
  91. protocol = protocol.toLowerCase();
  92. if (protocol === 'tcp' || protocol ==='ssltcp') {
  93. if (self.webrtcIceTcpDisable)
  94. return;
  95. } else if (protocol == 'udp') {
  96. if (self.webrtcIceUdpDisable)
  97. return;
  98. }
  99. }
  100. }
  101. self.sendIceCandidate(candidate);
  102. };
  103. this.peerconnection.onaddstream = function (event) {
  104. self.remoteStreamAdded(event.stream);
  105. };
  106. this.peerconnection.onremovestream = function (event) {
  107. self.remoteStreamRemoved(event.stream);
  108. };
  109. // Note there is a change in the spec about closed:
  110. // This value moved into the RTCPeerConnectionState enum in the May 13, 2016
  111. // draft of the specification, as it reflects the state of the
  112. // RTCPeerConnection, not the signaling connection. You now detect a
  113. // closed connection by checking for connectionState to be "closed" instead.
  114. // I suppose at some point this will be moved to onconnectionstatechange
  115. this.peerconnection.onsignalingstatechange = function () {
  116. if (!(self && self.peerconnection)) return;
  117. if (self.peerconnection.signalingState === 'stable') {
  118. self.wasstable = true;
  119. } else if (
  120. (self.peerconnection.signalingState === 'closed'
  121. || self.peerconnection.connectionState === 'closed')
  122. && !self.closed) {
  123. self.room.eventEmitter.emit(XMPPEvents.SUSPEND_DETECTED);
  124. }
  125. };
  126. /**
  127. * The oniceconnectionstatechange event handler contains the code to execute
  128. * when the iceconnectionstatechange event, of type Event, is received by
  129. * this RTCPeerConnection. Such an event is sent when the value of
  130. * RTCPeerConnection.iceConnectionState changes.
  131. */
  132. this.peerconnection.oniceconnectionstatechange = function () {
  133. if (!(self && self.peerconnection)) return;
  134. var now = window.performance.now();
  135. self.room.connectionTimes["ice.state." +
  136. self.peerconnection.iceConnectionState] = now;
  137. logger.log("(TIME) ICE " + self.peerconnection.iceConnectionState +
  138. ":\t", now);
  139. Statistics.analytics.sendEvent(
  140. 'ice.' + self.peerconnection.iceConnectionState, {value: now});
  141. self.room.eventEmitter.emit(
  142. XMPPEvents.ICE_CONNECTION_STATE_CHANGED,
  143. self.peerconnection.iceConnectionState);
  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. if(self.closed)
  153. break;
  154. self.isreconnect = true;
  155. // Informs interested parties that the connection has been interrupted.
  156. if (self.wasstable)
  157. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  158. break;
  159. case 'failed':
  160. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_ICE_FAILED,
  161. self.peerconnection);
  162. break;
  163. }
  164. };
  165. this.peerconnection.onnegotiationneeded = function () {
  166. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  167. };
  168. };
  169. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  170. var self = this;
  171. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  172. if (candidate && !this.lasticecandidate) {
  173. var ice = SDPUtil.iceparams(localSDP.media[candidate.sdpMLineIndex], localSDP.session);
  174. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  175. if (!(ice && jcand)) {
  176. var errorMesssage = "failed to get ice && jcand";
  177. GlobalOnErrorHandler.callErrorHandler(new Error(errorMesssage));
  178. logger.error(errorMesssage);
  179. return;
  180. }
  181. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  182. if (this.usedrip) {
  183. if (this.drip_container.length === 0) {
  184. // start 20ms callout
  185. window.setTimeout(function () {
  186. if (self.drip_container.length === 0) return;
  187. self.sendIceCandidates(self.drip_container);
  188. self.drip_container = [];
  189. }, 20);
  190. }
  191. this.drip_container.push(candidate);
  192. } else {
  193. self.sendIceCandidates([candidate]);
  194. }
  195. } else {
  196. logger.log('sendIceCandidate: last candidate.');
  197. // FIXME: remember to re-think in ICE-restart
  198. this.lasticecandidate = true;
  199. }
  200. };
  201. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  202. logger.log('sendIceCandidates', candidates);
  203. var cand = $iq({to: this.peerjid, type: 'set'})
  204. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  205. action: 'transport-info',
  206. initiator: this.initiator,
  207. sid: this.sid});
  208. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  209. for (var mid = 0; mid < localSDP.media.length; mid++) {
  210. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  211. var mline = SDPUtil.parse_mline(localSDP.media[mid].split('\r\n')[0]);
  212. if (cands.length > 0) {
  213. var ice = SDPUtil.iceparams(localSDP.media[mid], 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. var candidate = SDPUtil.candidateToJingle(cands[i].candidate);
  220. // Mangle ICE candidate if 'failICE' test option is enabled
  221. if (this.service.options.failICE) {
  222. candidate.ip = "1.1.1.1";
  223. }
  224. cand.c('candidate', candidate).up();
  225. }
  226. // add fingerprint
  227. var fingerprint_line = SDPUtil.find_line(localSDP.media[mid], 'a=fingerprint:', localSDP.session);
  228. if (fingerprint_line) {
  229. var tmp = SDPUtil.parse_fingerprint(fingerprint_line);
  230. tmp.required = true;
  231. cand.c(
  232. 'fingerprint',
  233. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  234. .t(tmp.fingerprint);
  235. delete tmp.fingerprint;
  236. cand.attrs(tmp);
  237. cand.up();
  238. }
  239. cand.up(); // transport
  240. cand.up(); // content
  241. }
  242. }
  243. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  244. //logger.log('was this the last candidate', this.lasticecandidate);
  245. this.connection.sendIQ(
  246. cand, null, this.newJingleErrorHandler(cand, function (error) {
  247. GlobalOnErrorHandler.callErrorHandler(
  248. new Error("Jingle error: " + JSON.stringify(error)));
  249. }), IQ_TIMEOUT);
  250. };
  251. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  252. var self = this;
  253. $(contents).each(function (idx, content) {
  254. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  255. ssrcs.each(function () {
  256. var ssrc = this.getAttribute('ssrc');
  257. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  258. function () {
  259. var owner = this.getAttribute('owner');
  260. self.ssrcOwners[ssrc] = owner;
  261. }
  262. );
  263. });
  264. });
  265. };
  266. /**
  267. * Does accept incoming Jingle 'session-initiate' and should send
  268. * 'session-accept' in result.
  269. * @param jingleOffer jQuery selector pointing to the jingle element of
  270. * the offer IQ
  271. * @param success callback called when we accept incoming session successfully
  272. * and receive RESULT packet to 'session-accept' sent.
  273. * @param failure function(error) called if for any reason we fail to accept
  274. * the incoming offer. 'error' argument can be used to log some details
  275. * about the error.
  276. */
  277. JingleSessionPC.prototype.acceptOffer = function(jingleOffer,
  278. success, failure) {
  279. this.state = JingleSessionState.ACTIVE;
  280. this.setOfferCycle(
  281. jingleOffer,
  282. () => {
  283. // setOfferCycle succeeded, now we have self.localSDP up to date
  284. // Let's send an answer !
  285. // FIXME we may not care about RESULT packet for session-accept
  286. // then we should either call 'success' here immediately or
  287. // modify sendSessionAccept method to do that
  288. this.sendSessionAccept(success, failure);
  289. },
  290. failure);
  291. };
  292. /**
  293. * This is a setRemoteDescription/setLocalDescription cycle which starts at
  294. * converting Strophe Jingle IQ into remote offer SDP. Once converted
  295. * setRemoteDescription, createAnswer and setLocalDescription calls follow.
  296. * @param jingleOfferIq jQuery selector pointing to the jingle element of
  297. * the offer IQ
  298. * @param success callback called when sRD/sLD cycle finishes successfully.
  299. * @param failure callback called with an error object as an argument if we fail
  300. * at any point during setRD, createAnswer, setLD.
  301. */
  302. JingleSessionPC.prototype.setOfferCycle = function (jingleOfferIq,
  303. success,
  304. failure) {
  305. let workFunction = (finishedCallback) => {
  306. let newRemoteSdp = this._processNewJingleOfferIq(jingleOfferIq);
  307. this._renegotiate(newRemoteSdp)
  308. .then(() => {
  309. finishedCallback();
  310. }, (error) => {
  311. logger.info("Error renegotiating after setting new remote offer: " + error);
  312. JingleSessionPC.onJingleFatalError(this, error);
  313. finishedCallback(error);
  314. });
  315. };
  316. this.modificationQueue.push(
  317. workFunction,
  318. (error) => {
  319. if (!error) {
  320. success();
  321. } else {
  322. failure(error);
  323. }
  324. }
  325. );
  326. };
  327. /**
  328. * Although it states "replace transport" it does accept full Jingle offer
  329. * which should contain new ICE transport details.
  330. * @param jingleOfferElem an element Jingle IQ that contains new offer and
  331. * transport info.
  332. * @param success callback called when we succeed to accept new offer.
  333. * @param failure function(error) called when we fail to accept new offer.
  334. */
  335. JingleSessionPC.prototype.replaceTransport = function (jingleOfferElem,
  336. success,
  337. failure) {
  338. // We need to first set an offer without the 'data' section to have the SCTP
  339. // stack cleaned up. After that the original offer is set to have the SCTP
  340. // connection established with the new bridge.
  341. this.room.eventEmitter.emit(XMPPEvents.ICE_RESTARTING);
  342. var originalOffer = jingleOfferElem.clone();
  343. jingleOfferElem.find(">content[name='data']").remove();
  344. // First set an offer without the 'data' section
  345. this.setOfferCycle(
  346. jingleOfferElem,
  347. () => {
  348. // Now set the original offer(with the 'data' section)
  349. this.setOfferCycle(
  350. originalOffer,
  351. () => {
  352. // Set local description OK, now localSDP up to date
  353. this.sendTransportAccept(this.localSDP, success, failure);
  354. },
  355. failure);
  356. },
  357. failure
  358. );
  359. };
  360. /**
  361. * Sends Jingle 'session-accept' message.
  362. * @param localSDP the 'SDP' object with local session description
  363. * @param {function()} success callback called when we recive 'RESULT' packet for
  364. * 'session-accept'
  365. * @param {function(error)} failure called when we receive an error response or
  366. * when the request has timed out.
  367. */
  368. JingleSessionPC.prototype.sendSessionAccept = function (success, failure) {
  369. // NOTE: since we're just reading from it, we don't need to be within
  370. // the modification queue to access the local description
  371. let localSDP = new SDP(this.peerconnection.localDescription.sdp);
  372. var accept = $iq({to: this.peerjid,
  373. type: 'set'})
  374. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  375. action: 'session-accept',
  376. initiator: this.initiator,
  377. responder: this.responder,
  378. sid: this.sid });
  379. if (this.webrtcIceTcpDisable) {
  380. localSDP.removeTcpCandidates = true;
  381. }
  382. if (this.webrtcIceUdpDisable) {
  383. localSDP.removeUdpCandidates = true;
  384. }
  385. if (this.failICE) {
  386. localSDP.failICE = true;
  387. }
  388. localSDP.toJingle(
  389. accept,
  390. this.initiator == this.me ? 'initiator' : 'responder',
  391. null);
  392. this.fixJingle(accept);
  393. // Calling tree() to print something useful
  394. accept = accept.tree();
  395. logger.info("Sending session-accept", accept);
  396. var self = this;
  397. this.connection.sendIQ(accept,
  398. success,
  399. this.newJingleErrorHandler(accept, function (error) {
  400. failure(error);
  401. // 'session-accept' is a critical timeout and we'll have to restart
  402. self.room.eventEmitter.emit(XMPPEvents.SESSION_ACCEPT_TIMEOUT);
  403. }),
  404. IQ_TIMEOUT);
  405. // XXX Videobridge needs WebRTC's answer (ICE ufrag and pwd, DTLS
  406. // fingerprint and setup) ASAP in order to start the connection
  407. // establishment.
  408. //
  409. // FIXME Flushing the connection at this point triggers an issue with BOSH
  410. // request handling in Prosody on slow connections.
  411. //
  412. // The problem is that this request will be quite large and it may take time
  413. // before it reaches Prosody. In the meantime Strophe may decide to send
  414. // the next one. And it was observed that a small request with
  415. // 'transport-info' usually follows this one. It does reach Prosody before
  416. // the previous one was completely received. 'rid' on the server is
  417. // increased and Prosody ignores the request with 'session-accept'. It will
  418. // never reach Jicofo and everything in the request table is lost. Removing
  419. // the flush does not guarantee it will never happen, but makes it much less
  420. // likely('transport-info' is bundled with 'session-accept' and any
  421. // immediate requests).
  422. //
  423. // this.connection.flush();
  424. };
  425. /**
  426. * Sends Jingle 'transport-accept' message which is a response to
  427. * 'transport-replace'.
  428. * @param localSDP the 'SDP' object with local session description
  429. * @param success callback called when we receive 'RESULT' packet for
  430. * 'transport-replace'
  431. * @param failure function(error) called when we receive an error response or
  432. * when the request has timed out.
  433. */
  434. JingleSessionPC.prototype.sendTransportAccept = function(localSDP, success,
  435. failure) {
  436. var self = this;
  437. var tAccept = $iq({to: this.peerjid, type: 'set'})
  438. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  439. action: 'transport-accept',
  440. initiator: this.initiator,
  441. sid: this.sid});
  442. localSDP.media.forEach(function(medialines, idx){
  443. var mline = SDPUtil.parse_mline(medialines.split('\r\n')[0]);
  444. tAccept.c('content',
  445. { creator: self.initiator == self.me ? 'initiator' : 'responder',
  446. name: mline.media
  447. }
  448. );
  449. localSDP.transportToJingle(idx, tAccept);
  450. tAccept.up();
  451. });
  452. // Calling tree() to print something useful to the logger
  453. tAccept = tAccept.tree();
  454. console.info("Sending transport-accept: ", tAccept);
  455. self.connection.sendIQ(tAccept,
  456. success,
  457. self.newJingleErrorHandler(tAccept, failure),
  458. IQ_TIMEOUT);
  459. };
  460. /**
  461. * Sends Jingle 'transport-reject' message which is a response to
  462. * 'transport-replace'.
  463. * @param success callback called when we receive 'RESULT' packet for
  464. * 'transport-replace'
  465. * @param failure function(error) called when we receive an error response or
  466. * when the request has timed out.
  467. */
  468. JingleSessionPC.prototype.sendTransportReject = function(success, failure) {
  469. // Send 'transport-reject', so that the focus will
  470. // know that we've failed
  471. var tReject = $iq({to: this.peerjid, type: 'set'})
  472. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  473. action: 'transport-reject',
  474. initiator: this.initiator,
  475. sid: this.sid});
  476. tReject = tReject.tree();
  477. logger.info("Sending 'transport-reject", tReject);
  478. this.connection.sendIQ(tReject,
  479. success,
  480. this.newJingleErrorHandler(tReject, failure),
  481. IQ_TIMEOUT);
  482. };
  483. /**
  484. * @inheritDoc
  485. */
  486. JingleSessionPC.prototype.terminate = function (reason, text,
  487. success, failure) {
  488. this.state = JingleSessionState.ENDED;
  489. var term = $iq({to: this.peerjid,
  490. type: 'set'})
  491. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  492. action: 'session-terminate',
  493. initiator: this.initiator,
  494. sid: this.sid})
  495. .c('reason')
  496. .c(reason || 'success');
  497. if (text) {
  498. term.up().c('text').t(text);
  499. }
  500. // Calling tree() to print something useful
  501. term = term.tree();
  502. logger.info("Sending session-terminate", term);
  503. this.connection.sendIQ(
  504. term, success, this.newJingleErrorHandler(term, failure), IQ_TIMEOUT);
  505. // this should result in 'onTerminated' being called by strope.jingle.js
  506. this.connection.jingle.terminate(this.sid);
  507. };
  508. JingleSessionPC.prototype.onTerminated = function (reasonCondition,
  509. reasonText) {
  510. this.state = 'ended';
  511. // Do something with reason and reasonCondition when we start to care
  512. //this.reasonCondition = reasonCondition;
  513. //this.reasonText = reasonText;
  514. logger.info("Session terminated", this, reasonCondition, reasonText);
  515. this.close();
  516. };
  517. /**
  518. * Parse the information from the xml sourceAddElem and translate it
  519. * into sdp lines
  520. * @param {jquery xml element} sourceAddElem the source-add
  521. * element from jingle
  522. * @param {SDP object} currentRemoteSdp the current remote
  523. * sdp (as of this new source-add)
  524. * @returns {list} a list of SDP line strings that should
  525. * be added to the remote SDP
  526. */
  527. JingleSessionPC.prototype._parseSsrcInfoFromSourceAdd = function (sourceAddElem, currentRemoteSdp) {
  528. let addSsrcInfo = [];
  529. $(sourceAddElem).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 (currentRemoteSdp.containsSSRC(ssrc)) {
  545. logger.warn("Source-add request for existing SSRC: " + ssrc);
  546. return;
  547. }
  548. $(this).find('>parameter').each(function () {
  549. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  550. if ($(this).attr('value') && $(this).attr('value').length)
  551. lines += ':' + $(this).attr('value');
  552. lines += '\r\n';
  553. });
  554. });
  555. currentRemoteSdp.media.forEach(function(media, idx) {
  556. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  557. return;
  558. if (!addSsrcInfo[idx]) {
  559. addSsrcInfo[idx] = '';
  560. }
  561. addSsrcInfo[idx] += lines;
  562. });
  563. });
  564. return addSsrcInfo;
  565. };
  566. /**
  567. * Handles a Jingle source-add message for this Jingle session.
  568. * @param elem An array of Jingle "content" elements.
  569. */
  570. JingleSessionPC.prototype.addRemoteStream = function (elem) {
  571. // FIXME: dirty waiting
  572. if (!this.peerconnection.localDescription) {
  573. logger.warn("addSource - localDescription not ready yet");
  574. setTimeout(() => this.addRemoteStream(elem), 200);
  575. return;
  576. }
  577. logger.log('Processing add remote stream');
  578. logger.log('ICE connection state: ', this.peerconnection.iceConnectionState);
  579. this.readSsrcInfo(elem);
  580. let workFunction = (finishedCallback) => {
  581. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  582. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  583. let addSsrcInfo = this._parseSsrcInfoFromSourceAdd(elem, sdp);
  584. let newRemoteSdp = this._processRemoteAddSource(addSsrcInfo);
  585. this._renegotiate(newRemoteSdp)
  586. .then(() => {
  587. logger.info("Remote source-add processed");
  588. var newSdp = new SDP(this.peerconnection.localDescription.sdp);
  589. logger.log("SDPs", mySdp, newSdp);
  590. this.notifyMySSRCUpdate(mySdp, newSdp);
  591. finishedCallback();
  592. }, (error) => {
  593. logger.info("Error renegotiating after processing remote source-add: " + error);
  594. finishedCallback(error);
  595. });
  596. };
  597. this.modificationQueue.push(workFunction);
  598. };
  599. /**
  600. * Handles a Jingle source-remove message for this Jingle session.
  601. * @param elem An array of Jingle "content" elements.
  602. */
  603. JingleSessionPC.prototype.removeRemoteStream = function (elem) {
  604. // FIXME: dirty waiting
  605. if (!this.peerconnection.localDescription) {
  606. logger.warn("removeSource - localDescription not ready yet");
  607. setTimeout(() => this.removeRemoteStream(elem), 200);
  608. return;
  609. }
  610. logger.log('Remove remote stream');
  611. logger.log('ICE connection state: ', this.peerconnection.iceConnectionState);
  612. let workFunction = (finishedCallback) => {
  613. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  614. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  615. let removeSsrcInfo = this._parseSsrcInfoFromSourceRemove(elem, sdp);
  616. let newRemoteSdp = this._processRemoteRemoveSource(removeSsrcInfo);
  617. this._renegotiate(newRemoteSdp)
  618. .then(() => {
  619. logger.info("Remote source-remove processed");
  620. var newSdp = new SDP(this.peerconnection.localDescription.sdp);
  621. logger.log("SDPs", mySdp, newSdp);
  622. this.notifyMySSRCUpdate(mySdp, newSdp);
  623. finishedCallback();
  624. }, (error) => {
  625. logger.info("Error renegotiating after processing remote source-remove: " + error);
  626. finishedCallback(error);
  627. });
  628. };
  629. this.modificationQueue.push(workFunction);
  630. };
  631. /**
  632. * The 'task' function will be given a callback it MUST call with either:
  633. * 1) No arguments if it was successful or
  634. * 2) An error argument if there was an error
  635. * If the task wants to process the success or failure of the task, it should
  636. * pass a handler to the .push function, e.g.:
  637. * queue.push(task, (err) => {
  638. * if (err) {
  639. * // error handling
  640. * } else {
  641. * // success handling
  642. * }
  643. * });
  644. */
  645. JingleSessionPC.prototype._processQueueTasks = function (task, finishedCallback) {
  646. task(finishedCallback);
  647. };
  648. /**
  649. * Takes in a jingle offer iq, returns the new sdp offer
  650. * @param {jquery xml element} offerIq the incoming offer
  651. * @returns {SDP object} the jingle offer translated to SDP
  652. */
  653. JingleSessionPC.prototype._processNewJingleOfferIq = function(offerIq) {
  654. let remoteSdp = new SDP('');
  655. if (this.webrtcIceTcpDisable) {
  656. remoteSdp.removeTcpCandidates = true;
  657. }
  658. if (this.webrtcIceUdpDisable) {
  659. remoteSdp.removeUdpCandidates = true;
  660. }
  661. if (this.failICE) {
  662. remoteSdp.failICE = true;
  663. }
  664. remoteSdp.fromJingle(offerIq);
  665. this.readSsrcInfo($(offerIq).find(">content"));
  666. return remoteSdp;
  667. };
  668. /**
  669. * Remove the given ssrc lines from the current remote sdp
  670. * @param {list} removeSsrcInfo a list of SDP line strings that
  671. * should be removed from the remote SDP
  672. * @returns type {SDP Object} the new remote SDP (after removing the lines
  673. * in removeSsrcInfo
  674. */
  675. JingleSessionPC.prototype._processRemoteRemoveSource = function (removeSsrcInfo) {
  676. let remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
  677. removeSsrcInfo.forEach(function(lines, idx) {
  678. lines = lines.split('\r\n');
  679. lines.pop(); // remove empty last element;
  680. lines.forEach(function(line) {
  681. remoteSdp.media[idx] = remoteSdp.media[idx].replace(line + '\r\n', '');
  682. });
  683. });
  684. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  685. return remoteSdp;
  686. };
  687. /**
  688. * Add the given ssrc lines to the current remote sdp
  689. * @param {list} addSsrcInfo a list of SDP line strings that
  690. * should be added to the remote SDP
  691. * @returns type {SDP Object} the new remote SDP (after removing the lines
  692. * in removeSsrcInfo
  693. */
  694. JingleSessionPC.prototype._processRemoteAddSource = function (addSsrcInfo) {
  695. let remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
  696. addSsrcInfo.forEach(function(lines, idx) {
  697. remoteSdp.media[idx] += lines;
  698. });
  699. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  700. return remoteSdp;
  701. };
  702. /**
  703. * Do a new o/a flow using the existing remote description
  704. * @param {SDP object} optionalRemoteSdp optional remote sdp
  705. * to use. If not provided, the remote sdp from the
  706. * peerconnection will be used
  707. * @returns {Promise} promise which resolves when the
  708. * o/a flow is complete with no arguments or
  709. * rejects with an error {string}
  710. */
  711. JingleSessionPC.prototype._renegotiate = function(optionalRemoteSdp) {
  712. let media_constraints = this.media_constraints;
  713. let remoteSdp = optionalRemoteSdp || new SDP(this.peerconnection.remoteDescription.sdp);
  714. let remoteDescription = new RTCSessionDescription({
  715. type: "offer",
  716. sdp: remoteSdp.raw
  717. });
  718. //TODO(brian): in the code below there are 2 chunks of code that relate
  719. // to observing changes in local and remove ufrags. since they
  720. // just need to read and observe the SDPs, we should create the
  721. // notion of an SDP observer in TraceablePeerConnection that
  722. // gets notified of all SDP changes. Code like the ufrag
  723. // logic below could listen to that and be separated from
  724. // core flows like this.
  725. return new Promise((resolve, reject) => {
  726. let remoteUfrag = getUfrag(remoteDescription.sdp);
  727. if (remoteUfrag != this.remoteUfrag) {
  728. this.remoteUfrag = remoteUfrag;
  729. this.room.eventEmitter.emit(
  730. XMPPEvents.REMOTE_UFRAG_CHANGED, remoteUfrag);
  731. }
  732. this.peerconnection.setRemoteDescription(
  733. remoteDescription,
  734. () => {
  735. if (this.signalingState === 'closed') {
  736. reject("Attemped to setRemoteDescription in state closed");
  737. }
  738. this.peerconnection.createAnswer(
  739. (answer) => {
  740. let localUfrag = getUfrag(answer.sdp);
  741. if (localUfrag != this.localUfrag) {
  742. this.localUfrag = localUfrag;
  743. this.room.eventEmitter.emit(
  744. XMPPEvents.LOCAL_UFRAG_CHANGED, localUfrag);
  745. }
  746. this.peerconnection.setLocalDescription(
  747. answer,
  748. () => { resolve(); },
  749. (error) => { reject("setLocalDescription failed: " + error); }
  750. );
  751. },
  752. (error) => { reject("createAnswer failed: " + error); },
  753. media_constraints
  754. );
  755. },
  756. (error) => {
  757. reject("setRemoteDescription failed: " + error);
  758. }
  759. );
  760. });
  761. };
  762. /**
  763. * Replaces oldStream with newStream and performs a single offer/answer
  764. * cycle after both operations are done. Either oldStream or newStream
  765. * can be null; replacing a valid 'oldStream' with a null 'newStream'
  766. * effectively just removes 'oldStream'
  767. * @param oldStream the current stream in use to be replaced
  768. * @param newStream the new stream to use
  769. * @returns {Promise} which resolves once the replacement is complete
  770. * with no arguments or rejects with an error {string}
  771. */
  772. JingleSessionPC.prototype.replaceStream = function (oldStream, newStream) {
  773. return new Promise((resolve, reject) => {
  774. let workFunction = (finishedCallback) => {
  775. let oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  776. this.removeStreamFromPeerConnection(oldStream);
  777. this.addStreamToPeerConnection(newStream);
  778. this._renegotiate()
  779. .then(() => {
  780. var newSdp = new SDP(this.peerconnection.localDescription.sdp);
  781. this.notifyMySSRCUpdate(oldSdp, newSdp);
  782. finishedCallback();
  783. }, (error) => {
  784. logger.error("replaceStream renegotiation failed: " + error);
  785. finishedCallback(error);
  786. });
  787. };
  788. this.modificationQueue.push(
  789. workFunction,
  790. (error) => {
  791. if (!error) {
  792. resolve();
  793. } else {
  794. reject(error);
  795. }
  796. }
  797. );
  798. });
  799. };
  800. /**
  801. * Just add the stream to the peerconnection
  802. * @param stream either the low-level webrtc MediaStream or
  803. * a Jitsi mediastream
  804. * NOTE: must be called within a work function being executed
  805. * by the modification queue.
  806. */
  807. JingleSessionPC.prototype.addStreamToPeerConnection = function (stream, ssrcInfo) {
  808. let actualStream = stream && stream.getOriginalStream ? stream.getOriginalStream() : stream;
  809. if (this.peerconnection) {
  810. this.peerconnection.addStream(actualStream, ssrcInfo);
  811. }
  812. };
  813. /**
  814. * Parse the information from the xml sourceRemoveElem and translate it
  815. * into sdp lines
  816. * @param {jquery xml element} sourceRemoveElem the source-remove
  817. * element from jingle
  818. * @param {SDP object} currentRemoteSdp the current remote
  819. * sdp (as of this new source-remove)
  820. * @returns {list} a list of SDP line strings that should
  821. * be removed from the remote SDP
  822. */
  823. JingleSessionPC.prototype._parseSsrcInfoFromSourceRemove = function (sourceRemoveElem, currentRemoteSdp) {
  824. let removeSsrcInfo = [];
  825. $(sourceRemoveElem).each(function (idx, content) {
  826. var name = $(content).attr('name');
  827. var lines = '';
  828. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  829. var semantics = this.getAttribute('semantics');
  830. var ssrcs = $(this).find('>source').map(function () {
  831. return this.getAttribute('ssrc');
  832. }).get();
  833. if (ssrcs.length) {
  834. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  835. }
  836. });
  837. var ssrcs = [];
  838. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  839. tmp.each(function () {
  840. var ssrc = $(this).attr('ssrc');
  841. ssrcs.push(ssrc);
  842. });
  843. currentRemoteSdp.media.forEach(function(media, idx) {
  844. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  845. return;
  846. if (!removeSsrcInfo[idx]) {
  847. removeSsrcInfo[idx] = '';
  848. }
  849. ssrcs.forEach(function(ssrc) {
  850. var ssrcLines = SDPUtil.find_lines(media, 'a=ssrc:' + ssrc);
  851. if (ssrcLines.length) {
  852. removeSsrcInfo[idx] += ssrcLines.join("\r\n")+"\r\n";
  853. }
  854. });
  855. removeSsrcInfo[idx] += lines;
  856. });
  857. });
  858. return removeSsrcInfo;
  859. };
  860. /**
  861. * Adds stream.
  862. * @param stream new stream that will be added.
  863. * @param callback callback executed after successful stream addition.
  864. * @param errorCallback callback executed if stream addition fail.
  865. * @param ssrcInfo object with information about the SSRCs associated with the
  866. * stream.
  867. * @param dontModifySources {boolean} if true _modifySources won't be called.
  868. * Used for streams added before the call start.
  869. * NOTE(brian): there is a decent amount of overlap here with replaceStream that
  870. * could be re-used...however we can't leverage that currently because the
  871. * extra work we do here must be in the work function context and if we
  872. * then called replaceStream we'd be adding another task on the queue
  873. * from within a task which would then deadlock. The 'replaceStream' core
  874. * logic should be moved into a helper function that could be called within
  875. * the 'doReplaceStream' task or the 'doAddStream' task (for example)
  876. */
  877. JingleSessionPC.prototype.addStream = function (stream, callback, errorCallback,
  878. ssrcInfo, dontModifySources) {
  879. let workFunction = (finishedCallback) => {
  880. if (!this.peerconnection) {
  881. finishedCallback("Error: tried adding stream with no active peer connection");
  882. return;
  883. }
  884. this.addStreamToPeerConnection(stream, ssrcInfo);
  885. if (ssrcInfo) {
  886. // available only on video mute/unmute
  887. this.modifiedSSRCs[ssrcInfo.type] =
  888. this.modifiedSSRCs[ssrcInfo.type] || [];
  889. this.modifiedSSRCs[ssrcInfo.type].push(ssrcInfo);
  890. }
  891. if (dontModifySources) {
  892. finishedCallback();
  893. return;
  894. }
  895. let oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  896. this._renegotiate()
  897. .then(() => {
  898. let newSdp = new SDP(this.peerconnection.localDescription.sdp);
  899. logger.log("SDPs", oldSdp, newSdp);
  900. this.notifyMySSRCUpdate(oldSdp, newSdp);
  901. finishedCallback();
  902. }, (error) => {
  903. finishedCallback(error);
  904. });
  905. };
  906. this.modificationQueue.push(
  907. workFunction,
  908. (error) => {
  909. if (!error) {
  910. callback();
  911. } else {
  912. errorCallback(error);
  913. }
  914. }
  915. );
  916. };
  917. /**
  918. * Generate ssrc info object for a stream with the following properties:
  919. * - ssrcs - Array of the ssrcs associated with the stream.
  920. * - groups - Array of the groups associated with the stream.
  921. */
  922. JingleSessionPC.prototype.generateNewStreamSSRCInfo = function () {
  923. return this.peerconnection.generateNewStreamSSRCInfo();
  924. };
  925. /**
  926. * Remove stream handling for firefox
  927. * @param stream: webrtc media stream
  928. */
  929. JingleSessionPC.prototype._handleFirefoxRemoveStream = function (stream) {
  930. if (!stream) { //There is nothing to be changed
  931. return;
  932. }
  933. var sender = null;
  934. // On Firefox we don't replace MediaStreams as this messes up the
  935. // m-lines (which can't be removed in Plan Unified) and brings a lot
  936. // of complications. Instead, we use the RTPSender and remove just
  937. // the track.
  938. var track = null;
  939. if (stream.getAudioTracks() && stream.getAudioTracks().length) {
  940. track = stream.getAudioTracks()[0];
  941. } else if (stream.getVideoTracks() && stream.getVideoTracks().length) {
  942. track = stream.getVideoTracks()[0];
  943. }
  944. if (!track) {
  945. var msg = "Cannot remove tracks: no tracks.";
  946. logger.log(msg);
  947. return;
  948. }
  949. // Find the right sender (for audio or video)
  950. this.peerconnection.peerconnection.getSenders().some(function (s) {
  951. if (s.track === track) {
  952. sender = s;
  953. return true;
  954. }
  955. });
  956. if (sender) {
  957. this.peerconnection.peerconnection.removeTrack(sender);
  958. } else {
  959. logger.log("Cannot remove tracks: no RTPSender.");
  960. }
  961. };
  962. /**
  963. * Just remove the stream from the peerconnection
  964. * @param {JitsiLocalTrack|MediaStream} stream the stream to remove
  965. * NOTE: must be called within a work function being executed
  966. * by the modification queue.
  967. */
  968. JingleSessionPC.prototype.removeStreamFromPeerConnection = function (stream) {
  969. let actualStream
  970. = stream && stream.getOriginalStream
  971. ? stream.getOriginalStream() : stream;
  972. if (!this.peerconnection) {
  973. return;
  974. }
  975. if (RTCBrowserType.getBrowserType() ===
  976. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  977. this._handleFirefoxRemoveStream(actualStream);
  978. } else if (actualStream) {
  979. this.peerconnection.removeStream(actualStream);
  980. }
  981. };
  982. /**
  983. * Remove streams.
  984. * @param stream stream that will be removed.
  985. * @param callback callback executed after successful stream addition.
  986. * @param errorCallback callback executed if stream addition fail.
  987. * @param ssrcInfo object with information about the SSRCs associated with the
  988. * stream.
  989. */
  990. JingleSessionPC.prototype.removeStream = function (stream, callback, errorCallback,
  991. ssrcInfo) {
  992. let workFunction = (finishedCallback) => {
  993. if (!this.peerconnection) {
  994. finishedCallback();
  995. return;
  996. }
  997. if (RTCBrowserType.getBrowserType() ===
  998. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  999. this._handleFirefoxRemoveStream(stream);
  1000. } else if (stream) {
  1001. this.removeStreamFromPeerConnection(stream);
  1002. }
  1003. let oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  1004. this._renegotiate()
  1005. .then(() => {
  1006. let newSdp = new SDP(this.peerconnection.localDescription.sdp);
  1007. if (ssrcInfo) {
  1008. this.modifiedSSRCs[ssrcInfo.type] =
  1009. this.modifiedSSRCs[ssrcInfo.type] || [];
  1010. this.modifiedSSRCs[ssrcInfo.type].push(ssrcInfo);
  1011. }
  1012. logger.log("SDPs", oldSdp, newSdp);
  1013. this.notifyMySSRCUpdate(oldSdp, newSdp);
  1014. finishedCallback();
  1015. }, (error) => {
  1016. finishedCallback(error);
  1017. });
  1018. };
  1019. this.modificationQueue.push(
  1020. workFunction,
  1021. (error) => {
  1022. if (!error) {
  1023. callback();
  1024. } else {
  1025. errorCallback(error);
  1026. }
  1027. }
  1028. );
  1029. };
  1030. /**
  1031. * Figures out added/removed ssrcs and send update IQs.
  1032. * @param old_sdp SDP object for old description.
  1033. * @param new_sdp SDP object for new description.
  1034. */
  1035. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  1036. if (this.state !== JingleSessionState.ACTIVE){
  1037. logger.warn(
  1038. "Skipping SSRC update in \'" + this.state + " \' state.");
  1039. return;
  1040. }
  1041. // send source-remove IQ.
  1042. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  1043. var remove = $iq({to: this.peerjid, type: 'set'})
  1044. .c('jingle', {
  1045. xmlns: 'urn:xmpp:jingle:1',
  1046. action: 'source-remove',
  1047. initiator: this.initiator,
  1048. sid: this.sid
  1049. }
  1050. );
  1051. sdpDiffer.toJingle(remove);
  1052. var removed = this.fixJingle(remove);
  1053. if (removed && remove) {
  1054. logger.info("Sending source-remove", remove.tree());
  1055. this.connection.sendIQ(
  1056. remove, null, this.newJingleErrorHandler(remove, function (error) {
  1057. GlobalOnErrorHandler.callErrorHandler(
  1058. new Error("Jingle error: " + JSON.stringify(error)));
  1059. }), IQ_TIMEOUT);
  1060. } else {
  1061. logger.log('removal not necessary');
  1062. }
  1063. // send source-add IQ.
  1064. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  1065. var add = $iq({to: this.peerjid, type: 'set'})
  1066. .c('jingle', {
  1067. xmlns: 'urn:xmpp:jingle:1',
  1068. action: 'source-add',
  1069. initiator: this.initiator,
  1070. sid: this.sid
  1071. }
  1072. );
  1073. sdpDiffer.toJingle(add);
  1074. var added = this.fixJingle(add);
  1075. if (added && add) {
  1076. logger.info("Sending source-add", add.tree());
  1077. this.connection.sendIQ(
  1078. add, null, this.newJingleErrorHandler(add, function (error) {
  1079. GlobalOnErrorHandler.callErrorHandler(
  1080. new Error("Jingle error: " + JSON.stringify(error)));
  1081. }), IQ_TIMEOUT);
  1082. } else {
  1083. logger.log('addition not necessary');
  1084. }
  1085. };
  1086. /**
  1087. * Method returns function(errorResponse) which is a callback to be passed to
  1088. * Strophe connection.sendIQ method. An 'error' structure is created that is
  1089. * passed as 1st argument to given <tt>failureCb</tt>. The format of this
  1090. * structure is as follows:
  1091. * {
  1092. * code: {XMPP error response code}
  1093. * reason: {the name of XMPP error reason element or 'timeout' if the request
  1094. * has timed out within <tt>IQ_TIMEOUT</tt> milliseconds}
  1095. * source: {request.tree() that provides original request}
  1096. * session: {JingleSessionPC instance on which the error occurred}
  1097. * }
  1098. * @param request Strophe IQ instance which is the request to be dumped into
  1099. * the error structure
  1100. * @param failureCb function(error) called when error response was returned or
  1101. * when a timeout has occurred.
  1102. * @returns {function(this:JingleSessionPC)}
  1103. */
  1104. JingleSessionPC.prototype.newJingleErrorHandler = function(request, failureCb) {
  1105. return function (errResponse) {
  1106. var error = { };
  1107. // Get XMPP error code and condition(reason)
  1108. var errorElSel = $(errResponse).find('error');
  1109. if (errorElSel.length) {
  1110. error.code = errorElSel.attr('code');
  1111. var errorReasonSel = $(errResponse).find('error :first');
  1112. if (errorReasonSel.length)
  1113. error.reason = errorReasonSel[0].tagName;
  1114. }
  1115. if (!errResponse) {
  1116. error.reason = 'timeout';
  1117. }
  1118. error.source = null;
  1119. if (request && "function" == typeof request.tree) {
  1120. error.source = request.tree();
  1121. }
  1122. // Commented to fix JSON.stringify(error) exception for circular
  1123. // dependancies when we print that error.
  1124. // FIXME: Maybe we can include part of the session object
  1125. // error.session = this;
  1126. logger.error("Jingle error", error);
  1127. if (failureCb) {
  1128. failureCb(error);
  1129. }
  1130. }.bind(this);
  1131. };
  1132. JingleSessionPC.onJingleFatalError = function (session, error)
  1133. {
  1134. if (this.room) {
  1135. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED, error);
  1136. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  1137. }
  1138. };
  1139. /**
  1140. * Called when new remote MediaStream is added to the PeerConnection.
  1141. * @param stream the WebRTC MediaStream for remote participant
  1142. */
  1143. JingleSessionPC.prototype.remoteStreamAdded = function (stream) {
  1144. var self = this;
  1145. if (!RTC.isUserStream(stream)) {
  1146. logger.info(
  1147. "Ignored remote 'stream added' event for non-user stream", stream);
  1148. return;
  1149. }
  1150. // Bind 'addtrack'/'removetrack' event handlers
  1151. if (RTCBrowserType.isChrome() || RTCBrowserType.isNWJS()
  1152. || RTCBrowserType.isElectron()) {
  1153. stream.onaddtrack = function (event) {
  1154. self.remoteTrackAdded(event.target, event.track);
  1155. };
  1156. stream.onremovetrack = function (event) {
  1157. self.remoteTrackRemoved(event.target, event.track);
  1158. };
  1159. }
  1160. // Call remoteTrackAdded for each track in the stream
  1161. stream.getAudioTracks().forEach(function (track) {
  1162. self.remoteTrackAdded(stream, track);
  1163. });
  1164. stream.getVideoTracks().forEach(function (track) {
  1165. self.remoteTrackAdded(stream, track);
  1166. });
  1167. };
  1168. /**
  1169. * Called on "track added" and "stream added" PeerConnection events(cause we
  1170. * handle streams on per track basis). Does find the owner and the SSRC for
  1171. * the track and passes that to ChatRoom for further processing.
  1172. * @param stream WebRTC MediaStream instance which is the parent of the track
  1173. * @param track the WebRTC MediaStreamTrack added for remote participant
  1174. */
  1175. JingleSessionPC.prototype.remoteTrackAdded = function (stream, track) {
  1176. logger.info("Remote track added", stream, track);
  1177. var streamId = RTC.getStreamID(stream);
  1178. var mediaType = track.kind;
  1179. // This is our event structure which will be passed by the ChatRoom as
  1180. // XMPPEvents.REMOTE_TRACK_ADDED data
  1181. var jitsiTrackAddedEvent = {
  1182. stream: stream,
  1183. track: track,
  1184. mediaType: track.kind, /* 'audio' or 'video' */
  1185. owner: undefined, /* to be determined below */
  1186. muted: null /* will be set in the ChatRoom */
  1187. };
  1188. try{
  1189. // look up an associated JID for a stream id
  1190. if (!mediaType) {
  1191. logger.error("MediaType undefined", track);
  1192. throw new Error("MediaType undefined for remote track");
  1193. }
  1194. var remoteSDP = new SDP(this.peerconnection.remoteDescription.sdp);
  1195. var medialines = remoteSDP.media.filter(function (mediaLines){
  1196. return mediaLines.startsWith("m=" + mediaType);
  1197. });
  1198. if (!medialines.length) {
  1199. logger.error("No media for type " + mediaType + " found in remote SDP");
  1200. throw new Error("No media for type " + mediaType +
  1201. " found in remote SDP for remote track");
  1202. }
  1203. var ssrclines = SDPUtil.find_lines(medialines[0], 'a=ssrc:');
  1204. ssrclines = ssrclines.filter(function (line) {
  1205. var msid = RTCBrowserType.isTemasysPluginUsed() ? 'mslabel' : 'msid';
  1206. return line.indexOf(msid + ':' + streamId) !== -1;
  1207. });
  1208. var thessrc;
  1209. if (ssrclines.length) {
  1210. thessrc = ssrclines[0].substring(7).split(' ')[0];
  1211. if (!this.ssrcOwners[thessrc]) {
  1212. logger.error("No SSRC owner known for: " + thessrc);
  1213. throw new Error("No SSRC owner known for: " + thessrc +
  1214. " for remote track");
  1215. }
  1216. jitsiTrackAddedEvent.owner = this.ssrcOwners[thessrc];
  1217. logger.log('associated jid', this.ssrcOwners[thessrc], thessrc);
  1218. } else {
  1219. logger.error("No SSRC lines for ", streamId);
  1220. throw new Error("No SSRC lines for streamId " + streamId +
  1221. " for remote track");
  1222. }
  1223. jitsiTrackAddedEvent.ssrc = thessrc;
  1224. this.room.remoteTrackAdded(jitsiTrackAddedEvent);
  1225. } catch (error) {
  1226. GlobalOnErrorHandler.callErrorHandler(error);
  1227. }
  1228. };
  1229. /**
  1230. * Handles remote stream removal.
  1231. * @param stream the WebRTC MediaStream object which is being removed from the
  1232. * PeerConnection
  1233. */
  1234. JingleSessionPC.prototype.remoteStreamRemoved = function (stream) {
  1235. var self = this;
  1236. if (!RTC.isUserStream(stream)) {
  1237. logger.info(
  1238. "Ignored remote 'stream removed' event for non-user stream", stream);
  1239. return;
  1240. }
  1241. // Call remoteTrackRemoved for each track in the stream
  1242. stream.getVideoTracks().forEach(function(track){
  1243. self.remoteTrackRemoved(stream, track);
  1244. });
  1245. stream.getAudioTracks().forEach(function(track) {
  1246. self.remoteTrackRemoved(stream, track);
  1247. });
  1248. };
  1249. /**
  1250. * Handles remote media track removal.
  1251. * @param stream WebRTC MediaStream instance which is the parent of the track
  1252. * @param track the WebRTC MediaStreamTrack which has been removed from
  1253. * the PeerConnection.
  1254. */
  1255. JingleSessionPC.prototype.remoteTrackRemoved = function (stream, track) {
  1256. logger.info("Remote track removed", stream, track);
  1257. var streamId = RTC.getStreamID(stream);
  1258. var trackId = track && track.id;
  1259. try{
  1260. if (!streamId) {
  1261. logger.error("No stream ID for", stream);
  1262. throw new Error("Remote track removal failed - No stream ID");
  1263. }
  1264. if (!trackId) {
  1265. logger.error("No track ID for", track);
  1266. throw new Error("Remote track removal failed - No track ID");
  1267. }
  1268. this.room.eventEmitter.emit(
  1269. XMPPEvents.REMOTE_TRACK_REMOVED, streamId, trackId);
  1270. } catch (error) {
  1271. GlobalOnErrorHandler.callErrorHandler(error);
  1272. }
  1273. };
  1274. /**
  1275. * Returns the ice connection state for the peer connection.
  1276. * @returns the ice connection state for the peer connection.
  1277. */
  1278. JingleSessionPC.prototype.getIceConnectionState = function () {
  1279. return this.peerconnection.iceConnectionState;
  1280. };
  1281. /**
  1282. * Closes the peerconnection.
  1283. */
  1284. JingleSessionPC.prototype.close = function () {
  1285. this.closed = true;
  1286. // do not try to close if already closed.
  1287. this.peerconnection
  1288. && ((this.peerconnection.signalingState
  1289. && this.peerconnection.signalingState !== 'closed')
  1290. || (this.peerconnection.connectionState
  1291. && this.peerconnection.connectionState !== 'closed'))
  1292. && this.peerconnection.close();
  1293. };
  1294. /**
  1295. * Fixes the outgoing jingle packets by removing the nodes related to the
  1296. * muted/unmuted streams, handles removing of muted stream, etc.
  1297. * @param jingle the jingle packet that is going to be sent
  1298. * @returns {boolean} true if the jingle has to be sent and false otherwise.
  1299. */
  1300. JingleSessionPC.prototype.fixJingle = function(jingle) {
  1301. var action = $(jingle.nodeTree).find("jingle").attr("action");
  1302. switch (action) {
  1303. case "source-add":
  1304. case "session-accept":
  1305. this.fixSourceAddJingle(jingle);
  1306. break;
  1307. case "source-remove":
  1308. this.fixSourceRemoveJingle(jingle);
  1309. break;
  1310. default:
  1311. var errmsg = "Unknown jingle action!";
  1312. GlobalOnErrorHandler.callErrorHandler(errmsg);
  1313. logger.error(errmsg);
  1314. return false;
  1315. }
  1316. var sources = $(jingle.tree()).find(">jingle>content>description>source");
  1317. return sources && sources.length > 0;
  1318. };
  1319. /**
  1320. * Fixes the outgoing jingle packets with action source-add by removing the
  1321. * nodes related to the unmuted streams
  1322. * @param jingle the jingle packet that is going to be sent
  1323. * @returns {boolean} true if the jingle has to be sent and false otherwise.
  1324. */
  1325. JingleSessionPC.prototype.fixSourceAddJingle = function (jingle) {
  1326. var ssrcs = this.modifiedSSRCs["unmute"];
  1327. this.modifiedSSRCs["unmute"] = [];
  1328. if(ssrcs && ssrcs.length) {
  1329. ssrcs.forEach(function (ssrcObj) {
  1330. var desc = $(jingle.tree()).find(">jingle>content[name=\"" +
  1331. ssrcObj.mtype + "\"]>description");
  1332. if(!desc || !desc.length)
  1333. return;
  1334. ssrcObj.ssrc.ssrcs.forEach(function (ssrc) {
  1335. var sourceNode = desc.find(">source[ssrc=\"" +
  1336. ssrc + "\"]");
  1337. sourceNode.remove();
  1338. });
  1339. ssrcObj.ssrc.groups.forEach(function (group) {
  1340. var groupNode = desc.find(">ssrc-group[semantics=\"" +
  1341. group.group.semantics + "\"]:has(source[ssrc=\"" +
  1342. group.primarySSRC +
  1343. "\"])");
  1344. groupNode.remove();
  1345. });
  1346. });
  1347. }
  1348. ssrcs = this.modifiedSSRCs["addMuted"];
  1349. this.modifiedSSRCs["addMuted"] = [];
  1350. if(ssrcs && ssrcs.length) {
  1351. ssrcs.forEach(function (ssrcObj) {
  1352. var desc = createDescriptionNode(jingle, ssrcObj.mtype);
  1353. var cname = Math.random().toString(36).substring(2);
  1354. ssrcObj.ssrc.ssrcs.forEach(function (ssrc) {
  1355. var sourceNode = desc.find(">source[ssrc=\"" +ssrc + "\"]");
  1356. sourceNode.remove();
  1357. var sourceXML = "<source " +
  1358. "xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\" ssrc=\"" +
  1359. ssrc + "\">" +
  1360. "<parameter xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\"" +
  1361. " value=\"" + ssrcObj.msid + "\" name=\"msid\"/>" +
  1362. "<parameter xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\"" +
  1363. " value=\"" + cname + "\" name=\"cname\" />" + "</source>";
  1364. desc.append(sourceXML);
  1365. });
  1366. ssrcObj.ssrc.groups.forEach(function (group) {
  1367. var groupNode = desc.find(">ssrc-group[semantics=\"" +
  1368. group.group.semantics + "\"]:has(source[ssrc=\"" + group.primarySSRC +
  1369. "\"])");
  1370. groupNode.remove();
  1371. desc.append("<ssrc-group semantics=\"" +
  1372. group.group.semantics +
  1373. "\" xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\"><source ssrc=\"" +
  1374. group.group.ssrcs.split(" ").join("\"/><source ssrc=\"") + "\"/>" +
  1375. "</ssrc-group>");
  1376. });
  1377. });
  1378. }
  1379. };
  1380. /**
  1381. * Fixes the outgoing jingle packets with action source-remove by removing the
  1382. * nodes related to the muted streams, handles removing of muted stream
  1383. * @param jingle the jingle packet that is going to be sent
  1384. * @returns {boolean} true if the jingle has to be sent and false otherwise.
  1385. */
  1386. JingleSessionPC.prototype.fixSourceRemoveJingle = function(jingle) {
  1387. var ssrcs = this.modifiedSSRCs["mute"];
  1388. this.modifiedSSRCs["mute"] = [];
  1389. if(ssrcs && ssrcs.length)
  1390. ssrcs.forEach(function (ssrcObj) {
  1391. ssrcObj.ssrc.ssrcs.forEach(function (ssrc) {
  1392. var sourceNode = $(jingle.tree()).find(">jingle>content[name=\"" +
  1393. ssrcObj.mtype + "\"]>description>source[ssrc=\"" +
  1394. ssrc + "\"]");
  1395. sourceNode.remove();
  1396. });
  1397. ssrcObj.ssrc.groups.forEach(function (group) {
  1398. var groupNode = $(jingle.tree()).find(">jingle>content[name=\"" +
  1399. ssrcObj.mtype + "\"]>description>ssrc-group[semantics=\"" +
  1400. group.group.semantics + "\"]:has(source[ssrc=\"" + group.primarySSRC +
  1401. "\"])");
  1402. groupNode.remove();
  1403. });
  1404. });
  1405. ssrcs = this.modifiedSSRCs["remove"];
  1406. this.modifiedSSRCs["remove"] = [];
  1407. if(ssrcs && ssrcs.length)
  1408. ssrcs.forEach(function (ssrcObj) {
  1409. var desc = createDescriptionNode(jingle, ssrcObj.mtype);
  1410. ssrcObj.ssrc.ssrcs.forEach(function (ssrc) {
  1411. var sourceNode = desc.find(">source[ssrc=\"" +ssrc + "\"]");
  1412. if(!sourceNode || !sourceNode.length) {
  1413. //Maybe we have to include cname, msid, etc here?
  1414. desc.append("<source " +
  1415. "xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\" ssrc=\"" +
  1416. ssrc + "\"></source>");
  1417. }
  1418. });
  1419. ssrcObj.ssrc.groups.forEach(function (group) {
  1420. var groupNode = desc.find(">ssrc-group[semantics=\"" +
  1421. group.group.semantics + "\"]:has(source[ssrc=\"" + group.primarySSRC +
  1422. "\"])");
  1423. if(!groupNode || !groupNode.length) {
  1424. desc.append("<ssrc-group semantics=\"" +
  1425. group.group.semantics +
  1426. "\" xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\"><source ssrc=\"" +
  1427. group.group.ssrcs.split(" ").join("\"/><source ssrc=\"") + "\"/>" +
  1428. "</ssrc-group>");
  1429. }
  1430. });
  1431. });
  1432. };
  1433. /**
  1434. * Returns the description node related to the passed content type. If the node
  1435. * doesn't exists it will be created.
  1436. * @param jingle - the jingle packet
  1437. * @param mtype - the content type(audio, video, etc.)
  1438. */
  1439. function createDescriptionNode(jingle, mtype) {
  1440. var content = $(jingle.tree()).find(">jingle>content[name=\"" +
  1441. mtype + "\"]");
  1442. if(!content || !content.length) {
  1443. $(jingle.tree()).find(">jingle").append(
  1444. "<content name=\"" + mtype + "\"></content>");
  1445. content = $(jingle.tree()).find(">jingle>content[name=\"" +
  1446. mtype + "\"]");
  1447. }
  1448. var desc = content.find(">description");
  1449. if(!desc || !desc.length) {
  1450. content.append("<description " +
  1451. "xmlns=\"urn:xmpp:jingle:apps:rtp:1\" media=\"" +
  1452. mtype + "\"></description>");
  1453. desc = content.find(">description");
  1454. }
  1455. return desc;
  1456. }
  1457. /**
  1458. * Extracts the ice username fragment from an SDP string.
  1459. */
  1460. function getUfrag(sdp) {
  1461. var ufragLines = sdp.split('\n').filter(function(line) {
  1462. return line.startsWith("a=ice-ufrag:");});
  1463. if (ufragLines.length > 0) {
  1464. return ufragLines[0].substr("a=ice-ufrag:".length);
  1465. }
  1466. }
  1467. module.exports = JingleSessionPC;