You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JingleSessionPC.js 54KB

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