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

JingleSessionPC.js 60KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584
  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, stopStream) {
  969. let actualStream = stream && stream.getOriginalStream ? stream.getOriginalStream() : stream;
  970. if (!this.peerconnection) {
  971. return;
  972. }
  973. if (RTCBrowserType.getBrowserType() ===
  974. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  975. this._handleFirefoxRemoveStream(actualStream);
  976. } else if (stream) {
  977. this.peerconnection.removeStream(actualStream, stopStream);
  978. }
  979. };
  980. /**
  981. * Remove streams.
  982. * @param stream stream that will be removed.
  983. * @param callback callback executed after successful stream addition.
  984. * @param errorCallback callback executed if stream addition fail.
  985. * @param ssrcInfo object with information about the SSRCs associated with the
  986. * stream.
  987. */
  988. JingleSessionPC.prototype.removeStream = function (stream, callback, errorCallback,
  989. ssrcInfo) {
  990. let workFunction = (finishedCallback) => {
  991. if (!this.peerconnection) {
  992. finishedCallback();
  993. return;
  994. }
  995. if (RTCBrowserType.getBrowserType() ===
  996. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  997. this._handleFirefoxRemoveStream(stream);
  998. } else if (stream) {
  999. this.removeStreamFromPeerConnection(stream, false);
  1000. }
  1001. let oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  1002. this._renegotiate()
  1003. .then(() => {
  1004. let newSdp = new SDP(this.peerconnection.localDescription.sdp);
  1005. if (ssrcInfo) {
  1006. this.modifiedSSRCs[ssrcInfo.type] =
  1007. this.modifiedSSRCs[ssrcInfo.type] || [];
  1008. this.modifiedSSRCs[ssrcInfo.type].push(ssrcInfo);
  1009. }
  1010. logger.log("SDPs", oldSdp, newSdp);
  1011. this.notifyMySSRCUpdate(oldSdp, newSdp);
  1012. finishedCallback();
  1013. }, (error) => {
  1014. finishedCallback(error);
  1015. });
  1016. };
  1017. this.modificationQueue.push(
  1018. workFunction,
  1019. (error) => {
  1020. if (!error) {
  1021. callback();
  1022. } else {
  1023. errorCallback(error);
  1024. }
  1025. }
  1026. );
  1027. };
  1028. /**
  1029. * Figures out added/removed ssrcs and send update IQs.
  1030. * @param old_sdp SDP object for old description.
  1031. * @param new_sdp SDP object for new description.
  1032. */
  1033. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  1034. if (this.state !== JingleSessionState.ACTIVE){
  1035. logger.warn(
  1036. "Skipping SSRC update in \'" + this.state + " \' state.");
  1037. return;
  1038. }
  1039. // send source-remove IQ.
  1040. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  1041. var remove = $iq({to: this.peerjid, type: 'set'})
  1042. .c('jingle', {
  1043. xmlns: 'urn:xmpp:jingle:1',
  1044. action: 'source-remove',
  1045. initiator: this.initiator,
  1046. sid: this.sid
  1047. }
  1048. );
  1049. sdpDiffer.toJingle(remove);
  1050. var removed = this.fixJingle(remove);
  1051. if (removed && remove) {
  1052. logger.info("Sending source-remove", remove.tree());
  1053. this.connection.sendIQ(
  1054. remove, null, this.newJingleErrorHandler(remove, function (error) {
  1055. GlobalOnErrorHandler.callErrorHandler(
  1056. new Error("Jingle error: " + JSON.stringify(error)));
  1057. }), IQ_TIMEOUT);
  1058. } else {
  1059. logger.log('removal not necessary');
  1060. }
  1061. // send source-add IQ.
  1062. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  1063. var add = $iq({to: this.peerjid, type: 'set'})
  1064. .c('jingle', {
  1065. xmlns: 'urn:xmpp:jingle:1',
  1066. action: 'source-add',
  1067. initiator: this.initiator,
  1068. sid: this.sid
  1069. }
  1070. );
  1071. sdpDiffer.toJingle(add);
  1072. var added = this.fixJingle(add);
  1073. if (added && add) {
  1074. logger.info("Sending source-add", add.tree());
  1075. this.connection.sendIQ(
  1076. add, null, this.newJingleErrorHandler(add, function (error) {
  1077. GlobalOnErrorHandler.callErrorHandler(
  1078. new Error("Jingle error: " + JSON.stringify(error)));
  1079. }), IQ_TIMEOUT);
  1080. } else {
  1081. logger.log('addition not necessary');
  1082. }
  1083. };
  1084. /**
  1085. * Method returns function(errorResponse) which is a callback to be passed to
  1086. * Strophe connection.sendIQ method. An 'error' structure is created that is
  1087. * passed as 1st argument to given <tt>failureCb</tt>. The format of this
  1088. * structure is as follows:
  1089. * {
  1090. * code: {XMPP error response code}
  1091. * reason: {the name of XMPP error reason element or 'timeout' if the request
  1092. * has timed out within <tt>IQ_TIMEOUT</tt> milliseconds}
  1093. * source: {request.tree() that provides original request}
  1094. * session: {JingleSessionPC instance on which the error occurred}
  1095. * }
  1096. * @param request Strophe IQ instance which is the request to be dumped into
  1097. * the error structure
  1098. * @param failureCb function(error) called when error response was returned or
  1099. * when a timeout has occurred.
  1100. * @returns {function(this:JingleSessionPC)}
  1101. */
  1102. JingleSessionPC.prototype.newJingleErrorHandler = function(request, failureCb) {
  1103. return function (errResponse) {
  1104. var error = { };
  1105. // Get XMPP error code and condition(reason)
  1106. var errorElSel = $(errResponse).find('error');
  1107. if (errorElSel.length) {
  1108. error.code = errorElSel.attr('code');
  1109. var errorReasonSel = $(errResponse).find('error :first');
  1110. if (errorReasonSel.length)
  1111. error.reason = errorReasonSel[0].tagName;
  1112. }
  1113. if (!errResponse) {
  1114. error.reason = 'timeout';
  1115. }
  1116. error.source = null;
  1117. if (request && "function" == typeof request.tree) {
  1118. error.source = request.tree();
  1119. }
  1120. // Commented to fix JSON.stringify(error) exception for circular
  1121. // dependancies when we print that error.
  1122. // FIXME: Maybe we can include part of the session object
  1123. // error.session = this;
  1124. logger.error("Jingle error", error);
  1125. if (failureCb) {
  1126. failureCb(error);
  1127. }
  1128. }.bind(this);
  1129. };
  1130. JingleSessionPC.onJingleFatalError = function (session, error)
  1131. {
  1132. if (this.room) {
  1133. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED, error);
  1134. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  1135. }
  1136. };
  1137. /**
  1138. * Called when new remote MediaStream is added to the PeerConnection.
  1139. * @param stream the WebRTC MediaStream for remote participant
  1140. */
  1141. JingleSessionPC.prototype.remoteStreamAdded = function (stream) {
  1142. var self = this;
  1143. if (!RTC.isUserStream(stream)) {
  1144. logger.info(
  1145. "Ignored remote 'stream added' event for non-user stream", stream);
  1146. return;
  1147. }
  1148. // Bind 'addtrack'/'removetrack' event handlers
  1149. if (RTCBrowserType.isChrome() || RTCBrowserType.isNWJS()
  1150. || RTCBrowserType.isElectron()) {
  1151. stream.onaddtrack = function (event) {
  1152. self.remoteTrackAdded(event.target, event.track);
  1153. };
  1154. stream.onremovetrack = function (event) {
  1155. self.remoteTrackRemoved(event.target, event.track);
  1156. };
  1157. }
  1158. // Call remoteTrackAdded for each track in the stream
  1159. stream.getAudioTracks().forEach(function (track) {
  1160. self.remoteTrackAdded(stream, track);
  1161. });
  1162. stream.getVideoTracks().forEach(function (track) {
  1163. self.remoteTrackAdded(stream, track);
  1164. });
  1165. };
  1166. /**
  1167. * Called on "track added" and "stream added" PeerConnection events(cause we
  1168. * handle streams on per track basis). Does find the owner and the SSRC for
  1169. * the track and passes that to ChatRoom for further processing.
  1170. * @param stream WebRTC MediaStream instance which is the parent of the track
  1171. * @param track the WebRTC MediaStreamTrack added for remote participant
  1172. */
  1173. JingleSessionPC.prototype.remoteTrackAdded = function (stream, track) {
  1174. logger.info("Remote track added", stream, track);
  1175. var streamId = RTC.getStreamID(stream);
  1176. var mediaType = track.kind;
  1177. // This is our event structure which will be passed by the ChatRoom as
  1178. // XMPPEvents.REMOTE_TRACK_ADDED data
  1179. var jitsiTrackAddedEvent = {
  1180. stream: stream,
  1181. track: track,
  1182. mediaType: track.kind, /* 'audio' or 'video' */
  1183. owner: undefined, /* to be determined below */
  1184. muted: null /* will be set in the ChatRoom */
  1185. };
  1186. try{
  1187. // look up an associated JID for a stream id
  1188. if (!mediaType) {
  1189. logger.error("MediaType undefined", track);
  1190. throw new Error("MediaType undefined for remote track");
  1191. }
  1192. var remoteSDP = new SDP(this.peerconnection.remoteDescription.sdp);
  1193. var medialines = remoteSDP.media.filter(function (mediaLines){
  1194. return mediaLines.startsWith("m=" + mediaType);
  1195. });
  1196. if (!medialines.length) {
  1197. logger.error("No media for type " + mediaType + " found in remote SDP");
  1198. throw new Error("No media for type " + mediaType +
  1199. " found in remote SDP for remote track");
  1200. }
  1201. var ssrclines = SDPUtil.find_lines(medialines[0], 'a=ssrc:');
  1202. ssrclines = ssrclines.filter(function (line) {
  1203. var msid = RTCBrowserType.isTemasysPluginUsed() ? 'mslabel' : 'msid';
  1204. return line.indexOf(msid + ':' + streamId) !== -1;
  1205. });
  1206. var thessrc;
  1207. if (ssrclines.length) {
  1208. thessrc = ssrclines[0].substring(7).split(' ')[0];
  1209. if (!this.ssrcOwners[thessrc]) {
  1210. logger.error("No SSRC owner known for: " + thessrc);
  1211. throw new Error("No SSRC owner known for: " + thessrc +
  1212. " for remote track");
  1213. }
  1214. jitsiTrackAddedEvent.owner = this.ssrcOwners[thessrc];
  1215. logger.log('associated jid', this.ssrcOwners[thessrc], thessrc);
  1216. } else {
  1217. logger.error("No SSRC lines for ", streamId);
  1218. throw new Error("No SSRC lines for streamId " + streamId +
  1219. " for remote track");
  1220. }
  1221. jitsiTrackAddedEvent.ssrc = thessrc;
  1222. this.room.remoteTrackAdded(jitsiTrackAddedEvent);
  1223. } catch (error) {
  1224. GlobalOnErrorHandler.callErrorHandler(error);
  1225. }
  1226. };
  1227. /**
  1228. * Handles remote stream removal.
  1229. * @param stream the WebRTC MediaStream object which is being removed from the
  1230. * PeerConnection
  1231. */
  1232. JingleSessionPC.prototype.remoteStreamRemoved = function (stream) {
  1233. var self = this;
  1234. if (!RTC.isUserStream(stream)) {
  1235. logger.info(
  1236. "Ignored remote 'stream removed' event for non-user stream", stream);
  1237. return;
  1238. }
  1239. // Call remoteTrackRemoved for each track in the stream
  1240. stream.getVideoTracks().forEach(function(track){
  1241. self.remoteTrackRemoved(stream, track);
  1242. });
  1243. stream.getAudioTracks().forEach(function(track) {
  1244. self.remoteTrackRemoved(stream, track);
  1245. });
  1246. };
  1247. /**
  1248. * Handles remote media track removal.
  1249. * @param stream WebRTC MediaStream instance which is the parent of the track
  1250. * @param track the WebRTC MediaStreamTrack which has been removed from
  1251. * the PeerConnection.
  1252. */
  1253. JingleSessionPC.prototype.remoteTrackRemoved = function (stream, track) {
  1254. logger.info("Remote track removed", stream, track);
  1255. var streamId = RTC.getStreamID(stream);
  1256. var trackId = track && track.id;
  1257. try{
  1258. if (!streamId) {
  1259. logger.error("No stream ID for", stream);
  1260. throw new Error("Remote track removal failed - No stream ID");
  1261. }
  1262. if (!trackId) {
  1263. logger.error("No track ID for", track);
  1264. throw new Error("Remote track removal failed - No track ID");
  1265. }
  1266. this.room.eventEmitter.emit(
  1267. XMPPEvents.REMOTE_TRACK_REMOVED, streamId, trackId);
  1268. } catch (error) {
  1269. GlobalOnErrorHandler.callErrorHandler(error);
  1270. }
  1271. };
  1272. /**
  1273. * Returns the ice connection state for the peer connection.
  1274. * @returns the ice connection state for the peer connection.
  1275. */
  1276. JingleSessionPC.prototype.getIceConnectionState = function () {
  1277. return this.peerconnection.iceConnectionState;
  1278. };
  1279. /**
  1280. * Closes the peerconnection.
  1281. */
  1282. JingleSessionPC.prototype.close = function () {
  1283. this.closed = true;
  1284. // do not try to close if already closed.
  1285. this.peerconnection
  1286. && ((this.peerconnection.signalingState
  1287. && this.peerconnection.signalingState !== 'closed')
  1288. || (this.peerconnection.connectionState
  1289. && this.peerconnection.connectionState !== 'closed'))
  1290. && this.peerconnection.close();
  1291. };
  1292. /**
  1293. * Fixes the outgoing jingle packets by removing the nodes related to the
  1294. * muted/unmuted streams, handles removing of muted stream, etc.
  1295. * @param jingle the jingle packet that is going to be sent
  1296. * @returns {boolean} true if the jingle has to be sent and false otherwise.
  1297. */
  1298. JingleSessionPC.prototype.fixJingle = function(jingle) {
  1299. var action = $(jingle.nodeTree).find("jingle").attr("action");
  1300. switch (action) {
  1301. case "source-add":
  1302. case "session-accept":
  1303. this.fixSourceAddJingle(jingle);
  1304. break;
  1305. case "source-remove":
  1306. this.fixSourceRemoveJingle(jingle);
  1307. break;
  1308. default:
  1309. var errmsg = "Unknown jingle action!";
  1310. GlobalOnErrorHandler.callErrorHandler(errmsg);
  1311. logger.error(errmsg);
  1312. return false;
  1313. }
  1314. var sources = $(jingle.tree()).find(">jingle>content>description>source");
  1315. return sources && sources.length > 0;
  1316. };
  1317. /**
  1318. * Fixes the outgoing jingle packets with action source-add by removing the
  1319. * nodes related to the unmuted streams
  1320. * @param jingle the jingle packet that is going to be sent
  1321. * @returns {boolean} true if the jingle has to be sent and false otherwise.
  1322. */
  1323. JingleSessionPC.prototype.fixSourceAddJingle = function (jingle) {
  1324. var ssrcs = this.modifiedSSRCs["unmute"];
  1325. this.modifiedSSRCs["unmute"] = [];
  1326. if(ssrcs && ssrcs.length) {
  1327. ssrcs.forEach(function (ssrcObj) {
  1328. var desc = $(jingle.tree()).find(">jingle>content[name=\"" +
  1329. ssrcObj.mtype + "\"]>description");
  1330. if(!desc || !desc.length)
  1331. return;
  1332. ssrcObj.ssrc.ssrcs.forEach(function (ssrc) {
  1333. var sourceNode = desc.find(">source[ssrc=\"" +
  1334. ssrc + "\"]");
  1335. sourceNode.remove();
  1336. });
  1337. ssrcObj.ssrc.groups.forEach(function (group) {
  1338. var groupNode = desc.find(">ssrc-group[semantics=\"" +
  1339. group.group.semantics + "\"]:has(source[ssrc=\"" +
  1340. group.primarySSRC +
  1341. "\"])");
  1342. groupNode.remove();
  1343. });
  1344. });
  1345. }
  1346. ssrcs = this.modifiedSSRCs["addMuted"];
  1347. this.modifiedSSRCs["addMuted"] = [];
  1348. if(ssrcs && ssrcs.length) {
  1349. ssrcs.forEach(function (ssrcObj) {
  1350. var desc = createDescriptionNode(jingle, ssrcObj.mtype);
  1351. var cname = Math.random().toString(36).substring(2);
  1352. ssrcObj.ssrc.ssrcs.forEach(function (ssrc) {
  1353. var sourceNode = desc.find(">source[ssrc=\"" +ssrc + "\"]");
  1354. sourceNode.remove();
  1355. var sourceXML = "<source " +
  1356. "xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\" ssrc=\"" +
  1357. ssrc + "\">" +
  1358. "<parameter xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\"" +
  1359. " value=\"" + ssrcObj.msid + "\" name=\"msid\"/>" +
  1360. "<parameter xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\"" +
  1361. " value=\"" + cname + "\" name=\"cname\" />" + "</source>";
  1362. desc.append(sourceXML);
  1363. });
  1364. ssrcObj.ssrc.groups.forEach(function (group) {
  1365. var groupNode = desc.find(">ssrc-group[semantics=\"" +
  1366. group.group.semantics + "\"]:has(source[ssrc=\"" + group.primarySSRC +
  1367. "\"])");
  1368. groupNode.remove();
  1369. desc.append("<ssrc-group semantics=\"" +
  1370. group.group.semantics +
  1371. "\" xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\"><source ssrc=\"" +
  1372. group.group.ssrcs.split(" ").join("\"/><source ssrc=\"") + "\"/>" +
  1373. "</ssrc-group>");
  1374. });
  1375. });
  1376. }
  1377. };
  1378. /**
  1379. * Fixes the outgoing jingle packets with action source-remove by removing the
  1380. * nodes related to the muted streams, handles removing of muted stream
  1381. * @param jingle the jingle packet that is going to be sent
  1382. * @returns {boolean} true if the jingle has to be sent and false otherwise.
  1383. */
  1384. JingleSessionPC.prototype.fixSourceRemoveJingle = function(jingle) {
  1385. var ssrcs = this.modifiedSSRCs["mute"];
  1386. this.modifiedSSRCs["mute"] = [];
  1387. if(ssrcs && ssrcs.length)
  1388. ssrcs.forEach(function (ssrcObj) {
  1389. ssrcObj.ssrc.ssrcs.forEach(function (ssrc) {
  1390. var sourceNode = $(jingle.tree()).find(">jingle>content[name=\"" +
  1391. ssrcObj.mtype + "\"]>description>source[ssrc=\"" +
  1392. ssrc + "\"]");
  1393. sourceNode.remove();
  1394. });
  1395. ssrcObj.ssrc.groups.forEach(function (group) {
  1396. var groupNode = $(jingle.tree()).find(">jingle>content[name=\"" +
  1397. ssrcObj.mtype + "\"]>description>ssrc-group[semantics=\"" +
  1398. group.group.semantics + "\"]:has(source[ssrc=\"" + group.primarySSRC +
  1399. "\"])");
  1400. groupNode.remove();
  1401. });
  1402. });
  1403. ssrcs = this.modifiedSSRCs["remove"];
  1404. this.modifiedSSRCs["remove"] = [];
  1405. if(ssrcs && ssrcs.length)
  1406. ssrcs.forEach(function (ssrcObj) {
  1407. var desc = createDescriptionNode(jingle, ssrcObj.mtype);
  1408. ssrcObj.ssrc.ssrcs.forEach(function (ssrc) {
  1409. var sourceNode = desc.find(">source[ssrc=\"" +ssrc + "\"]");
  1410. if(!sourceNode || !sourceNode.length) {
  1411. //Maybe we have to include cname, msid, etc here?
  1412. desc.append("<source " +
  1413. "xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\" ssrc=\"" +
  1414. ssrc + "\"></source>");
  1415. }
  1416. });
  1417. ssrcObj.ssrc.groups.forEach(function (group) {
  1418. var groupNode = desc.find(">ssrc-group[semantics=\"" +
  1419. group.group.semantics + "\"]:has(source[ssrc=\"" + group.primarySSRC +
  1420. "\"])");
  1421. if(!groupNode || !groupNode.length) {
  1422. desc.append("<ssrc-group semantics=\"" +
  1423. group.group.semantics +
  1424. "\" xmlns=\"urn:xmpp:jingle:apps:rtp:ssma:0\"><source ssrc=\"" +
  1425. group.group.ssrcs.split(" ").join("\"/><source ssrc=\"") + "\"/>" +
  1426. "</ssrc-group>");
  1427. }
  1428. });
  1429. });
  1430. };
  1431. /**
  1432. * Returns the description node related to the passed content type. If the node
  1433. * doesn't exists it will be created.
  1434. * @param jingle - the jingle packet
  1435. * @param mtype - the content type(audio, video, etc.)
  1436. */
  1437. function createDescriptionNode(jingle, mtype) {
  1438. var content = $(jingle.tree()).find(">jingle>content[name=\"" +
  1439. mtype + "\"]");
  1440. if(!content || !content.length) {
  1441. $(jingle.tree()).find(">jingle").append(
  1442. "<content name=\"" + mtype + "\"></content>");
  1443. content = $(jingle.tree()).find(">jingle>content[name=\"" +
  1444. mtype + "\"]");
  1445. }
  1446. var desc = content.find(">description");
  1447. if(!desc || !desc.length) {
  1448. content.append("<description " +
  1449. "xmlns=\"urn:xmpp:jingle:apps:rtp:1\" media=\"" +
  1450. mtype + "\"></description>");
  1451. desc = content.find(">description");
  1452. }
  1453. return desc;
  1454. }
  1455. /**
  1456. * Extracts the ice username fragment from an SDP string.
  1457. */
  1458. function getUfrag(sdp) {
  1459. var ufragLines = sdp.split('\n').filter(function(line) {
  1460. return line.startsWith("a=ice-ufrag:");});
  1461. if (ufragLines.length > 0) {
  1462. return ufragLines[0].substr("a=ice-ufrag:".length);
  1463. }
  1464. }
  1465. module.exports = JingleSessionPC;