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

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