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

JingleSessionPC.js 57KB

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