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

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