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 61KB

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