Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

JingleSessionPC.js 63KB

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