Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

JingleSessionPC.js 57KB

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