您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JingleSessionPC.js 57KB

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