Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

JingleSessionPC.js 90KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397
  1. /* global __filename, $ */
  2. import {
  3. ICE_DURATION,
  4. ICE_STATE_CHANGED
  5. } from '../../service/statistics/AnalyticsEvents';
  6. import { getLogger } from 'jitsi-meet-logger';
  7. import { $iq, Strophe } from 'strophe.js';
  8. import { integerHash } from '../util/StringUtils';
  9. import browser from './../browser';
  10. import JingleSession from './JingleSession';
  11. import * as JingleSessionState from './JingleSessionState';
  12. import SDP from './SDP';
  13. import SDPDiffer from './SDPDiffer';
  14. import SDPUtil from './SDPUtil';
  15. import SignalingLayerImpl from './SignalingLayerImpl';
  16. import RTCEvents from '../../service/RTC/RTCEvents';
  17. import Statistics from '../statistics/statistics';
  18. import XMPPEvents from '../../service/xmpp/XMPPEvents';
  19. import AsyncQueue from '../util/AsyncQueue';
  20. import GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  21. import XmppConnection from './XmppConnection';
  22. const logger = getLogger(__filename);
  23. /**
  24. * Constant tells how long we're going to wait for IQ response, before timeout
  25. * error is triggered.
  26. * @type {number}
  27. */
  28. const IQ_TIMEOUT = 10000;
  29. /*
  30. * The default number of samples (per stat) to keep when webrtc stats gathering
  31. * is enabled in TraceablePeerConnection.
  32. */
  33. const DEFAULT_MAX_STATS = 300;
  34. /**
  35. * @typedef {Object} JingleSessionPCOptions
  36. * @property {Object} abTesting - A/B testing related options (ask George).
  37. * @property {boolean} abTesting.enableSuspendVideoTest - enables the suspend
  38. * video test ?(ask George).
  39. * @property {boolean} disableH264 - Described in the config.js[1].
  40. * @property {boolean} disableRtx - Described in the config.js[1].
  41. * @property {boolean} disableSimulcast - Described in the config.js[1].
  42. * @property {boolean} enableLayerSuspension - Described in the config.js[1].
  43. * @property {boolean} failICE - it's an option used in the tests. Set to
  44. * <tt>true</tt> to block any real candidates and make the ICE fail.
  45. * @property {boolean} gatherStats - Described in the config.js[1].
  46. * @property {object} p2p - Peer to peer related options (FIXME those could be
  47. * fetched from config.p2p on the upper level).
  48. * @property {boolean} p2p.disableH264 - Described in the config.js[1].
  49. * @property {boolean} p2p.preferH264 - Described in the config.js[1].
  50. * @property {boolean} preferH264 - Described in the config.js[1].
  51. * @property {Object} testing - Testing and/or experimental options.
  52. * @property {boolean} testing.enableFirefoxSimulcast - Described in the
  53. * config.js[1].
  54. * @property {boolean} webrtcIceUdpDisable - Described in the config.js[1].
  55. * @property {boolean} webrtcIceTcpDisable - Described in the config.js[1].
  56. *
  57. * [1]: https://github.com/jitsi/jitsi-meet/blob/master/config.js
  58. */
  59. /**
  60. *
  61. */
  62. export default class JingleSessionPC extends JingleSession {
  63. /**
  64. * Parses 'senders' attribute of the video content.
  65. * @param {jQuery} jingleContents
  66. * @return {string|null} one of the values of content "senders" attribute
  67. * defined by Jingle. If there is no "senders" attribute or if the value is
  68. * invalid then <tt>null</tt> will be returned.
  69. * @private
  70. */
  71. static parseVideoSenders(jingleContents) {
  72. const videoContents = jingleContents.find('>content[name="video"]');
  73. if (videoContents.length) {
  74. const senders = videoContents[0].getAttribute('senders');
  75. if (senders === 'both'
  76. || senders === 'initiator'
  77. || senders === 'responder'
  78. || senders === 'none') {
  79. return senders;
  80. }
  81. }
  82. return null;
  83. }
  84. /* eslint-disable max-params */
  85. /**
  86. * Creates new <tt>JingleSessionPC</tt>
  87. * @param {string} sid the Jingle Session ID - random string which
  88. * identifies the session
  89. * @param {string} localJid our JID
  90. * @param {string} remoteJid remote peer JID
  91. * @param {XmppConnection} connection - The XMPP connection instance.
  92. * @param mediaConstraints the media constraints object passed to
  93. * createOffer/Answer, as defined by the WebRTC standard
  94. * @param iceConfig the ICE servers config object as defined by the WebRTC
  95. * standard.
  96. * @param {boolean} isP2P indicates whether this instance is
  97. * meant to be used in a direct, peer to peer connection or <tt>false</tt>
  98. * if it's a JVB connection.
  99. * @param {boolean} isInitiator indicates if it will be the side which
  100. * initiates the session.
  101. * @constructor
  102. *
  103. * @implements {SignalingLayer}
  104. */
  105. constructor(
  106. sid,
  107. localJid,
  108. remoteJid,
  109. connection,
  110. mediaConstraints,
  111. iceConfig,
  112. isP2P,
  113. isInitiator) {
  114. super(
  115. sid,
  116. localJid,
  117. remoteJid, connection, mediaConstraints, iceConfig, isInitiator);
  118. /**
  119. * The bridge session's identifier. One Jingle session can during
  120. * it's lifetime participate in multiple bridge sessions managed by
  121. * Jicofo. A new bridge session is started whenever Jicofo sends
  122. * 'session-initiate' or 'transport-replace'.
  123. *
  124. * @type {?string}
  125. * @private
  126. */
  127. this._bridgeSessionId = null;
  128. /**
  129. * The oldest SDP passed to {@link notifyMySSRCUpdate} while the XMPP connection was offline that will be
  130. * used to update Jicofo once the XMPP connection goes back online.
  131. * @type {SDP|undefined}
  132. * @private
  133. */
  134. this._cachedOldLocalSdp = undefined;
  135. /**
  136. * The latest SDP passed to {@link notifyMySSRCUpdate} while the XMPP connection was offline that will be
  137. * used to update Jicofo once the XMPP connection goes back online.
  138. * @type {SDP|undefined}
  139. * @private
  140. */
  141. this._cachedNewLocalSdp = undefined;
  142. /**
  143. * Stores result of {@link window.performance.now()} at the time when
  144. * ICE enters 'checking' state.
  145. * @type {number|null} null if no value has been stored yet
  146. * @private
  147. */
  148. this._iceCheckingStartedTimestamp = null;
  149. /**
  150. * Stores result of {@link window.performance.now()} at the time when
  151. * first ICE candidate is spawned by the peerconnection to mark when
  152. * ICE gathering started. That's, because ICE gathering state changed
  153. * events are not supported by most of the browsers, so we try something
  154. * that will work everywhere. It may not be as accurate, but given that
  155. * 'host' candidate usually comes first, the delay should be minimal.
  156. * @type {number|null} null if no value has been stored yet
  157. * @private
  158. */
  159. this._gatheringStartedTimestamp = null;
  160. /**
  161. * Indicates whether or not this session is willing to send/receive
  162. * video media. When set to <tt>false</tt> the underlying peer
  163. * connection will disable local video transfer and the remote peer will
  164. * be will be asked to stop sending video via 'content-modify' IQ
  165. * (the senders attribute of video contents will be adjusted
  166. * accordingly). Note that this notification is sent only in P2P
  167. * session, because Jicofo does not support it yet. Obviously when
  168. * the value is changed from <tt>false</tt> to <tt>true</tt> another
  169. * notification will be sent to resume video transfer on the remote
  170. * side.
  171. * @type {boolean}
  172. * @private
  173. */
  174. this._localVideoActive = true;
  175. /**
  176. * Indicates whether or not the remote peer has video transfer active.
  177. * When set to <tt>true</tt> it means that remote peer is neither
  178. * sending nor willing to receive video. In such case we'll ask
  179. * our peerconnection to stop sending video by calling
  180. * {@link TraceablePeerConnection.setVideoTransferActive} with
  181. * <tt>false</tt>.
  182. * @type {boolean}
  183. * @private
  184. */
  185. this._remoteVideoActive = true;
  186. /**
  187. * Marks that ICE gathering duration has been reported already. That
  188. * prevents reporting it again, after eventual 'transport-replace' (JVB
  189. * conference migration/ICE restart).
  190. * @type {boolean}
  191. * @private
  192. */
  193. this._gatheringReported = false;
  194. this.lasticecandidate = false;
  195. this.closed = false;
  196. /**
  197. * Indicates whether or not this <tt>JingleSessionPC</tt> is used in
  198. * a peer to peer type of session.
  199. * @type {boolean} <tt>true</tt> if it's a peer to peer
  200. * session or <tt>false</tt> if it's a JVB session
  201. */
  202. this.isP2P = isP2P;
  203. /**
  204. * The signaling layer implementation.
  205. * @type {SignalingLayerImpl}
  206. */
  207. this.signalingLayer = new SignalingLayerImpl();
  208. /**
  209. * The queue used to serialize operations done on the peerconnection.
  210. *
  211. * @type {AsyncQueue}
  212. */
  213. this.modificationQueue = new AsyncQueue();
  214. /**
  215. * Flag used to guarantee that the connection established event is
  216. * triggered just once.
  217. * @type {boolean}
  218. */
  219. this.wasConnected = false;
  220. /**
  221. * Keeps track of how long (in ms) it took from ICE start to ICE
  222. * connect.
  223. *
  224. * @type {number}
  225. */
  226. this.establishmentDuration = undefined;
  227. this._xmppListeners = [];
  228. this._xmppListeners.push(
  229. connection.addEventListener(
  230. XmppConnection.Events.CONN_STATUS_CHANGED,
  231. this.onXmppStatusChanged.bind(this))
  232. );
  233. }
  234. /* eslint-enable max-params */
  235. /**
  236. * Checks whether or not this session instance is still operational.
  237. * @private
  238. * @returns {boolean} {@code true} if operation or {@code false} otherwise.
  239. */
  240. _assertNotEnded() {
  241. return this.state !== JingleSessionState.ENDED;
  242. }
  243. /**
  244. * @inheritDoc
  245. * @param {JingleSessionPCOptions} options - a set of config options.
  246. */
  247. doInitialize(options) {
  248. this.failICE = Boolean(options.failICE);
  249. this.lasticecandidate = false;
  250. this.options = options;
  251. /**
  252. * {@code true} if reconnect is in progress.
  253. * @type {boolean}
  254. */
  255. this.isReconnect = false;
  256. /**
  257. * Set to {@code true} if the connection was ever stable
  258. * @type {boolean}
  259. */
  260. this.wasstable = false;
  261. this.webrtcIceUdpDisable = Boolean(options.webrtcIceUdpDisable);
  262. this.webrtcIceTcpDisable = Boolean(options.webrtcIceTcpDisable);
  263. const pcOptions = { disableRtx: options.disableRtx };
  264. if (options.gatherStats) {
  265. pcOptions.maxstats = DEFAULT_MAX_STATS;
  266. }
  267. pcOptions.capScreenshareBitrate = false;
  268. if (this.isP2P) {
  269. // simulcast needs to be disabled for P2P (121) calls
  270. pcOptions.disableSimulcast = true;
  271. pcOptions.disableH264 = options.p2p && options.p2p.disableH264;
  272. pcOptions.preferH264 = options.p2p && options.p2p.preferH264;
  273. const abtestSuspendVideo = this._abtestSuspendVideoEnabled(options);
  274. if (typeof abtestSuspendVideo !== 'undefined') {
  275. pcOptions.abtestSuspendVideo = abtestSuspendVideo;
  276. }
  277. } else {
  278. // H264 does not support simulcast, so it needs to be disabled.
  279. pcOptions.disableSimulcast
  280. = options.disableSimulcast
  281. || (options.preferH264 && !options.disableH264);
  282. pcOptions.preferH264 = options.preferH264;
  283. pcOptions.enableFirefoxSimulcast
  284. = options.testing && options.testing.enableFirefoxSimulcast;
  285. pcOptions.enableLayerSuspension = options.enableLayerSuspension;
  286. // disable simulcast for screenshare and set the max bitrate to
  287. // 500Kbps if the testing flag is present in config.js.
  288. if (options.testing
  289. && options.testing.capScreenshareBitrate
  290. && typeof options.testing.capScreenshareBitrate === 'number') {
  291. pcOptions.capScreenshareBitrate
  292. = Math.random()
  293. < options.testing.capScreenshareBitrate;
  294. // add the capScreenshareBitrate to the permanent properties so
  295. // that it's included with every event that we send to the
  296. // analytics backend.
  297. Statistics.analytics.addPermanentProperties({ capScreenshareBitrate: pcOptions.capScreenshareBitrate });
  298. }
  299. }
  300. if (options.startSilent) {
  301. pcOptions.startSilent = true;
  302. }
  303. this.peerconnection
  304. = this.rtc.createPeerConnection(
  305. this.signalingLayer,
  306. this.iceConfig,
  307. this.isP2P,
  308. pcOptions);
  309. this.peerconnection.onicecandidate = ev => {
  310. if (!ev) {
  311. // There was an incomplete check for ev before which left
  312. // the last line of the function unprotected from a potential
  313. // throw of an exception. Consequently, it may be argued that
  314. // the check is unnecessary. Anyway, I'm leaving it and making
  315. // the check complete.
  316. return;
  317. }
  318. // XXX this is broken, candidate is not parsed.
  319. const candidate = ev.candidate;
  320. const now = window.performance.now();
  321. if (candidate) {
  322. if (this._gatheringStartedTimestamp === null) {
  323. this._gatheringStartedTimestamp = now;
  324. }
  325. // Discard candidates of disabled protocols.
  326. let protocol = candidate.protocol;
  327. if (typeof protocol === 'string') {
  328. protocol = protocol.toLowerCase();
  329. if (protocol === 'tcp' || protocol === 'ssltcp') {
  330. if (this.webrtcIceTcpDisable) {
  331. return;
  332. }
  333. } else if (protocol === 'udp') {
  334. if (this.webrtcIceUdpDisable) {
  335. return;
  336. }
  337. }
  338. }
  339. } else if (!this._gatheringReported) {
  340. // End of gathering
  341. Statistics.sendAnalytics(
  342. ICE_DURATION,
  343. {
  344. phase: 'gathering',
  345. value: now - this._gatheringStartedTimestamp,
  346. p2p: this.isP2P,
  347. initiator: this.isInitiator
  348. });
  349. this._gatheringReported = true;
  350. }
  351. this.sendIceCandidate(candidate);
  352. };
  353. // Note there is a change in the spec about closed:
  354. // This value moved into the RTCPeerConnectionState enum in
  355. // the May 13, 2016 draft of the specification, as it reflects the state
  356. // of the RTCPeerConnection, not the signaling connection. You now
  357. // detect a closed connection by checking for connectionState to be
  358. // "closed" instead.
  359. // I suppose at some point this will be moved to onconnectionstatechange
  360. this.peerconnection.onsignalingstatechange = () => {
  361. if (this.peerconnection.signalingState === 'stable') {
  362. this.wasstable = true;
  363. } else if (this.peerconnection.signalingState === 'closed'
  364. || this.peerconnection.connectionState === 'closed') {
  365. this.room.eventEmitter.emit(XMPPEvents.SUSPEND_DETECTED, this);
  366. }
  367. };
  368. /**
  369. * The oniceconnectionstatechange event handler contains the code to
  370. * execute when the iceconnectionstatechange event, of type Event,
  371. * is received by this RTCPeerConnection. Such an event is sent when
  372. * the value of RTCPeerConnection.iceConnectionState changes.
  373. */
  374. this.peerconnection.oniceconnectionstatechange = () => {
  375. const now = window.performance.now();
  376. if (!this.isP2P) {
  377. this.room.connectionTimes[
  378. `ice.state.${this.peerconnection.iceConnectionState}`]
  379. = now;
  380. }
  381. logger.log(
  382. `(TIME) ICE ${this.peerconnection.iceConnectionState}`
  383. + ` P2P? ${this.isP2P}:\t`,
  384. now);
  385. Statistics.sendAnalytics(
  386. ICE_STATE_CHANGED,
  387. {
  388. p2p: this.isP2P,
  389. state: this.peerconnection.iceConnectionState,
  390. 'signaling_state': this.peerconnection.signalingState,
  391. reconnect: this.isReconnect,
  392. value: now
  393. });
  394. this.room.eventEmitter.emit(
  395. XMPPEvents.ICE_CONNECTION_STATE_CHANGED,
  396. this,
  397. this.peerconnection.iceConnectionState);
  398. switch (this.peerconnection.iceConnectionState) {
  399. case 'checking':
  400. this._iceCheckingStartedTimestamp = now;
  401. break;
  402. case 'connected':
  403. // Informs interested parties that the connection has been
  404. // restored.
  405. if (this.peerconnection.signalingState === 'stable') {
  406. if (this.isReconnect) {
  407. this.room.eventEmitter.emit(
  408. XMPPEvents.CONNECTION_RESTORED, this);
  409. }
  410. }
  411. if (!this.wasConnected && this.wasstable) {
  412. Statistics.sendAnalytics(
  413. ICE_DURATION,
  414. {
  415. phase: 'checking',
  416. value: now - this._iceCheckingStartedTimestamp,
  417. p2p: this.isP2P,
  418. initiator: this.isInitiator
  419. });
  420. // Switch between ICE gathering and ICE checking whichever
  421. // started first (scenarios are different for initiator
  422. // vs responder)
  423. const iceStarted
  424. = Math.min(
  425. this._iceCheckingStartedTimestamp,
  426. this._gatheringStartedTimestamp);
  427. this.establishmentDuration = now - iceStarted;
  428. Statistics.sendAnalytics(
  429. ICE_DURATION,
  430. {
  431. phase: 'establishment',
  432. value: this.establishmentDuration,
  433. p2p: this.isP2P,
  434. initiator: this.isInitiator
  435. });
  436. this.wasConnected = true;
  437. this.room.eventEmitter.emit(
  438. XMPPEvents.CONNECTION_ESTABLISHED, this);
  439. }
  440. this.isReconnect = false;
  441. break;
  442. case 'disconnected':
  443. this.isReconnect = true;
  444. // Informs interested parties that the connection has been
  445. // interrupted.
  446. if (this.wasstable) {
  447. this.room.eventEmitter.emit(
  448. XMPPEvents.CONNECTION_INTERRUPTED, this);
  449. }
  450. break;
  451. case 'failed':
  452. this.room.eventEmitter.emit(
  453. XMPPEvents.CONNECTION_ICE_FAILED, this);
  454. break;
  455. }
  456. };
  457. /**
  458. * The negotiationneeded event is fired whenever we shake the media on the
  459. * RTCPeerConnection object.
  460. */
  461. this.peerconnection.onnegotiationneeded = () => {
  462. const state = this.peerconnection.signalingState;
  463. const remoteDescription = this.peerconnection.remoteDescription;
  464. this.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, this);
  465. if (browser.usesUnifiedPlan() && state.toString() === 'stable'
  466. && remoteDescription && typeof remoteDescription.sdp === 'string') {
  467. logger.debug(`onnegotiationneeded fired on ${this.peerconnection} in state: ${state}`);
  468. const workFunction = finishedCallback => {
  469. const oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  470. this._renegotiate()
  471. .then(() => {
  472. const newSdp = new SDP(this.peerconnection.localDescription.sdp);
  473. this.notifyMySSRCUpdate(oldSdp, newSdp);
  474. finishedCallback();
  475. })
  476. .catch(() => {
  477. finishedCallback();
  478. });
  479. };
  480. this.modificationQueue.push(
  481. workFunction,
  482. error => {
  483. if (error) {
  484. logger.error('onnegotiationneeded error', error);
  485. } else {
  486. logger.debug('onnegotiationneeded executed - OK');
  487. }
  488. });
  489. }
  490. };
  491. // The signaling layer will bind it's listeners at this point
  492. this.signalingLayer.setChatRoom(this.room);
  493. if (!this.isP2P && options.enableLayerSuspension) {
  494. // If this is the bridge session, we'll listen for
  495. // IS_SELECTED_CHANGED events and notify the peer connection
  496. this.rtc.addListener(RTCEvents.IS_SELECTED_CHANGED,
  497. isSelected => {
  498. this.peerconnection.setIsSelected(isSelected);
  499. logger.info('Doing local O/A due to '
  500. + 'IS_SELECTED_CHANGED event');
  501. this.modificationQueue.push(finishedCallback => {
  502. this._renegotiate()
  503. .then(finishedCallback)
  504. .catch(finishedCallback);
  505. });
  506. }
  507. );
  508. }
  509. }
  510. /**
  511. * Sends given candidate in Jingle 'transport-info' message.
  512. * @param {RTCIceCandidate} candidate the WebRTC ICE candidate instance
  513. * @private
  514. */
  515. sendIceCandidate(candidate) {
  516. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  517. if (candidate && candidate.candidate.length && !this.lasticecandidate) {
  518. const ice
  519. = SDPUtil.iceparams(
  520. localSDP.media[candidate.sdpMLineIndex], localSDP.session);
  521. const jcand = SDPUtil.candidateToJingle(candidate.candidate);
  522. if (!(ice && jcand)) {
  523. const errorMesssage = 'failed to get ice && jcand';
  524. GlobalOnErrorHandler.callErrorHandler(new Error(errorMesssage));
  525. logger.error(errorMesssage);
  526. return;
  527. }
  528. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  529. if (this.usedrip) {
  530. if (this.dripContainer.length === 0) {
  531. // start 20ms callout
  532. setTimeout(() => {
  533. if (this.dripContainer.length === 0) {
  534. return;
  535. }
  536. this.sendIceCandidates(this.dripContainer);
  537. this.dripContainer = [];
  538. }, 20);
  539. }
  540. this.dripContainer.push(candidate);
  541. } else {
  542. this.sendIceCandidates([ candidate ]);
  543. }
  544. } else {
  545. logger.log('sendIceCandidate: last candidate.');
  546. // FIXME: remember to re-think in ICE-restart
  547. this.lasticecandidate = true;
  548. }
  549. }
  550. /**
  551. * Sends given candidates in Jingle 'transport-info' message.
  552. * @param {Array<RTCIceCandidate>} candidates an array of the WebRTC ICE
  553. * candidate instances
  554. * @private
  555. */
  556. sendIceCandidates(candidates) {
  557. if (!this._assertNotEnded('sendIceCandidates')) {
  558. return;
  559. }
  560. logger.log('sendIceCandidates', candidates);
  561. const cand = $iq({ to: this.remoteJid,
  562. type: 'set' })
  563. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  564. action: 'transport-info',
  565. initiator: this.initiatorJid,
  566. sid: this.sid });
  567. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  568. for (let mid = 0; mid < localSDP.media.length; mid++) {
  569. const cands = candidates.filter(el => el.sdpMLineIndex === mid);
  570. const mline
  571. = SDPUtil.parseMLine(localSDP.media[mid].split('\r\n')[0]);
  572. if (cands.length > 0) {
  573. const ice
  574. = SDPUtil.iceparams(localSDP.media[mid], localSDP.session);
  575. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  576. cand.c('content', {
  577. creator: this.initiatorJid === this.localJid
  578. ? 'initiator' : 'responder',
  579. name: cands[0].sdpMid ? cands[0].sdpMid : mline.media
  580. }).c('transport', ice);
  581. for (let i = 0; i < cands.length; i++) {
  582. const candidate
  583. = SDPUtil.candidateToJingle(cands[i].candidate);
  584. // Mangle ICE candidate if 'failICE' test option is enabled
  585. if (this.failICE) {
  586. candidate.ip = '1.1.1.1';
  587. }
  588. cand.c('candidate', candidate).up();
  589. }
  590. // add fingerprint
  591. const fingerprintLine
  592. = SDPUtil.findLine(
  593. localSDP.media[mid],
  594. 'a=fingerprint:', localSDP.session);
  595. if (fingerprintLine) {
  596. const tmp = SDPUtil.parseFingerprint(fingerprintLine);
  597. tmp.required = true;
  598. cand.c(
  599. 'fingerprint',
  600. { xmlns: 'urn:xmpp:jingle:apps:dtls:0' })
  601. .t(tmp.fingerprint);
  602. delete tmp.fingerprint;
  603. cand.attrs(tmp);
  604. cand.up();
  605. }
  606. cand.up(); // transport
  607. cand.up(); // content
  608. }
  609. }
  610. // might merge last-candidate notification into this, but it is called
  611. // a lot later. See webrtc issue #2340
  612. // logger.log('was this the last candidate', this.lasticecandidate);
  613. this.connection.sendIQ(
  614. cand, null, this.newJingleErrorHandler(cand), IQ_TIMEOUT);
  615. }
  616. /**
  617. * Sends Jingle 'session-info' message which includes custom Jitsi Meet
  618. * 'ice-state' element with the text value 'failed' to let Jicofo know
  619. * that the ICE connection has entered the failed state. It can then
  620. * choose to re-create JVB channels and send 'transport-replace' to
  621. * retry the connection.
  622. */
  623. sendIceFailedNotification() {
  624. const sessionInfo
  625. = $iq({
  626. to: this.remoteJid,
  627. type: 'set' })
  628. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  629. action: 'session-info',
  630. initiator: this.initiatorJid,
  631. sid: this.sid })
  632. .c('ice-state', { xmlns: 'http://jitsi.org/protocol/focus' })
  633. .t('failed')
  634. .up();
  635. this._bridgeSessionId
  636. && sessionInfo.c(
  637. 'bridge-session', {
  638. xmlns: 'http://jitsi.org/protocol/focus',
  639. id: this._bridgeSessionId
  640. });
  641. this.connection.sendIQ(
  642. sessionInfo,
  643. null,
  644. this.newJingleErrorHandler(sessionInfo),
  645. /*
  646. * This message will be often sent when there are connectivity
  647. * issues, so make it slightly longer than Prosody's default BOSH
  648. * inactivity timeout of 60 seconds.
  649. */ 65);
  650. }
  651. /**
  652. * {@inheritDoc}
  653. */
  654. addIceCandidates(elem) {
  655. if (this.peerconnection.signalingState === 'closed') {
  656. logger.warn('Ignored add ICE candidate when in closed state');
  657. return;
  658. }
  659. const iceCandidates = [];
  660. elem.find('>content>transport>candidate')
  661. .each((idx, candidate) => {
  662. let line = SDPUtil.candidateFromJingle(candidate);
  663. line = line.replace('\r\n', '').replace('a=', '');
  664. // FIXME this code does not care to handle
  665. // non-bundle transport
  666. const rtcCandidate = new RTCIceCandidate({
  667. sdpMLineIndex: 0,
  668. // FF comes up with more complex names like audio-23423,
  669. // Given that it works on both Chrome and FF without
  670. // providing it, let's leave it like this for the time
  671. // being...
  672. // sdpMid: 'audio',
  673. sdpMid: '',
  674. candidate: line
  675. });
  676. iceCandidates.push(rtcCandidate);
  677. });
  678. if (!iceCandidates.length) {
  679. logger.error(
  680. 'No ICE candidates to add ?', elem[0] && elem[0].outerHTML);
  681. return;
  682. }
  683. // We want to have this task queued, so that we know it is executed,
  684. // after the initial sRD/sLD offer/answer cycle was done (based on
  685. // the assumption that candidates are spawned after the offer/answer
  686. // and XMPP preserves order).
  687. const workFunction = finishedCallback => {
  688. for (const iceCandidate of iceCandidates) {
  689. this.peerconnection.addIceCandidate(iceCandidate)
  690. .then(
  691. () => logger.debug('addIceCandidate ok!'),
  692. err => logger.error('addIceCandidate failed!', err));
  693. }
  694. finishedCallback();
  695. };
  696. logger.debug(
  697. `Queued add (${iceCandidates.length}) ICE candidates task...`);
  698. this.modificationQueue.push(workFunction);
  699. }
  700. /**
  701. *
  702. * @param contents
  703. */
  704. readSsrcInfo(contents) {
  705. const ssrcs
  706. = $(contents).find(
  707. '>description>'
  708. + 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  709. ssrcs.each((i, ssrcElement) => {
  710. const ssrc = Number(ssrcElement.getAttribute('ssrc'));
  711. if (this.isP2P) {
  712. // In P2P all SSRCs are owner by the remote peer
  713. this.signalingLayer.setSSRCOwner(
  714. ssrc, Strophe.getResourceFromJid(this.remoteJid));
  715. } else {
  716. $(ssrcElement)
  717. .find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]')
  718. .each((i3, ssrcInfoElement) => {
  719. const owner = ssrcInfoElement.getAttribute('owner');
  720. if (owner && owner.length) {
  721. if (isNaN(ssrc) || ssrc < 0) {
  722. logger.warn(
  723. `Invalid SSRC ${ssrc} value received`
  724. + ` for ${owner}`);
  725. } else {
  726. this.signalingLayer.setSSRCOwner(
  727. ssrc,
  728. Strophe.getResourceFromJid(owner));
  729. }
  730. }
  731. });
  732. }
  733. });
  734. }
  735. /**
  736. * Makes the underlying TraceablePeerConnection generate new SSRC for
  737. * the recvonly video stream.
  738. * @deprecated
  739. */
  740. generateRecvonlySsrc() {
  741. if (this.peerconnection) {
  742. this.peerconnection.generateRecvonlySsrc();
  743. } else {
  744. logger.error(
  745. 'Unable to generate recvonly SSRC - no peerconnection');
  746. }
  747. }
  748. /* eslint-disable max-params */
  749. /**
  750. * Accepts incoming Jingle 'session-initiate' and should send
  751. * 'session-accept' in result.
  752. * @param jingleOffer jQuery selector pointing to the jingle element of
  753. * the offer IQ
  754. * @param success callback called when we accept incoming session
  755. * successfully and receive RESULT packet to 'session-accept' sent.
  756. * @param failure function(error) called if for any reason we fail to accept
  757. * the incoming offer. 'error' argument can be used to log some details
  758. * about the error.
  759. * @param {Array<JitsiLocalTrack>} [localTracks] the optional list of
  760. * the local tracks that will be added, before the offer/answer cycle
  761. * executes. We allow the localTracks to optionally be passed in so that
  762. * the addition of the local tracks and the processing of the initial offer
  763. * can all be done atomically. We want to make sure that any other
  764. * operations which originate in the XMPP Jingle messages related with
  765. * this session to be executed with an assumption that the initial
  766. * offer/answer cycle has been executed already.
  767. */
  768. acceptOffer(jingleOffer, success, failure, localTracks) {
  769. this.setOfferAnswerCycle(
  770. jingleOffer,
  771. () => {
  772. // FIXME we may not care about RESULT packet for session-accept
  773. // then we should either call 'success' here immediately or
  774. // modify sendSessionAccept method to do that
  775. this.sendSessionAccept(success, failure);
  776. },
  777. failure,
  778. localTracks);
  779. }
  780. /* eslint-enable max-params */
  781. /**
  782. * Creates an offer and sends Jingle 'session-initiate' to the remote peer.
  783. * @param {Array<JitsiLocalTrack>} localTracks the local tracks that will be
  784. * added, before the offer/answer cycle executes (for the local track
  785. * addition to be an atomic operation together with the offer/answer).
  786. */
  787. invite(localTracks) {
  788. if (!this.isInitiator) {
  789. throw new Error('Trying to invite from the responder session');
  790. }
  791. const workFunction = finishedCallback => {
  792. for (const localTrack of localTracks) {
  793. this.peerconnection.addTrack(localTrack, true /* isInitiator */);
  794. }
  795. this.peerconnection.createOffer(this.mediaConstraints)
  796. .then(offerSdp => {
  797. this.peerconnection.setLocalDescription(offerSdp)
  798. .then(() => {
  799. // NOTE that the offer is obtained from
  800. // the localDescription getter as it needs to go
  801. // though the transformation chain.
  802. this.sendSessionInitiate(
  803. this.peerconnection.localDescription.sdp);
  804. finishedCallback();
  805. }, error => {
  806. logger.error(
  807. 'Failed to set local SDP', error, offerSdp);
  808. finishedCallback(error);
  809. });
  810. }, error => {
  811. logger.error(
  812. 'Failed to create an offer',
  813. error,
  814. this.mediaConstraints);
  815. finishedCallback(error);
  816. });
  817. };
  818. this.modificationQueue.push(
  819. workFunction,
  820. error => {
  821. if (error) {
  822. logger.error('invite error', error);
  823. } else {
  824. logger.debug('invite executed - OK');
  825. }
  826. });
  827. }
  828. /**
  829. * Sends 'session-initiate' to the remote peer.
  830. *
  831. * NOTE this method is synchronous and we're not waiting for the RESULT
  832. * response which would delay the startup process.
  833. *
  834. * @param {string} offerSdp - The local session description which will be
  835. * used to generate an offer.
  836. * @private
  837. */
  838. sendSessionInitiate(offerSdp) {
  839. let init = $iq({
  840. to: this.remoteJid,
  841. type: 'set'
  842. }).c('jingle', {
  843. xmlns: 'urn:xmpp:jingle:1',
  844. action: 'session-initiate',
  845. initiator: this.initiatorJid,
  846. sid: this.sid
  847. });
  848. new SDP(offerSdp).toJingle(
  849. init,
  850. this.isInitiator ? 'initiator' : 'responder');
  851. init = init.tree();
  852. logger.info('Session-initiate: ', init);
  853. this.connection.sendIQ(init,
  854. () => {
  855. logger.info('Got RESULT for "session-initiate"');
  856. },
  857. error => {
  858. logger.error('"session-initiate" error', error);
  859. },
  860. IQ_TIMEOUT);
  861. }
  862. /**
  863. * Sets the answer received from the remote peer.
  864. * @param jingleAnswer
  865. */
  866. setAnswer(jingleAnswer) {
  867. if (!this.isInitiator) {
  868. throw new Error('Trying to set an answer on the responder session');
  869. }
  870. this.setOfferAnswerCycle(
  871. jingleAnswer,
  872. () => {
  873. logger.info('setAnswer - succeeded');
  874. },
  875. error => {
  876. logger.error('setAnswer failed: ', error);
  877. });
  878. }
  879. /* eslint-disable max-params */
  880. /**
  881. * This is a setRemoteDescription/setLocalDescription cycle which starts at
  882. * converting Strophe Jingle IQ into remote offer SDP. Once converted
  883. * setRemoteDescription, createAnswer and setLocalDescription calls follow.
  884. * @param jingleOfferAnswerIq jQuery selector pointing to the jingle element
  885. * of the offer (or answer) IQ
  886. * @param success callback called when sRD/sLD cycle finishes successfully.
  887. * @param failure callback called with an error object as an argument if we
  888. * fail at any point during setRD, createAnswer, setLD.
  889. * @param {Array<JitsiLocalTrack>} [localTracks] the optional list of
  890. * the local tracks that will be added, before the offer/answer cycle
  891. * executes (for the local track addition to be an atomic operation together
  892. * with the offer/answer).
  893. */
  894. setOfferAnswerCycle(jingleOfferAnswerIq, success, failure, localTracks) {
  895. const workFunction = finishedCallback => {
  896. if (localTracks) {
  897. for (const track of localTracks) {
  898. this.peerconnection.addTrack(track);
  899. }
  900. }
  901. const newRemoteSdp
  902. = this._processNewJingleOfferIq(jingleOfferAnswerIq);
  903. const oldLocalSdp
  904. = this.peerconnection.localDescription.sdp;
  905. const bridgeSession
  906. = $(jingleOfferAnswerIq)
  907. .find('>bridge-session['
  908. + 'xmlns="http://jitsi.org/protocol/focus"]');
  909. const bridgeSessionId = bridgeSession.attr('id');
  910. if (bridgeSessionId !== this._bridgeSessionId) {
  911. this._bridgeSessionId = bridgeSessionId;
  912. }
  913. this._renegotiate(newRemoteSdp.raw)
  914. .then(() => {
  915. if (this.state === JingleSessionState.PENDING) {
  916. this.state = JingleSessionState.ACTIVE;
  917. // Sync up video transfer active/inactive only after
  918. // the initial O/A cycle. We want to adjust the video
  919. // media direction only in the local SDP and the Jingle
  920. // contents direction included in the initial
  921. // offer/answer is mapped to the remote SDP. Jingle
  922. // 'content-modify' IQ is processed in a way that it
  923. // will only modify local SDP when remote peer is no
  924. // longer interested in receiving video content.
  925. // Changing media direction in the remote SDP will mess
  926. // up our SDP translation chain (simulcast, video mute,
  927. // RTX etc.)
  928. if (this.isP2P && !this._localVideoActive) {
  929. this.sendContentModify(this._localVideoActive);
  930. }
  931. }
  932. // Old local SDP will be available when we're setting answer
  933. // for the first time, but not when offer and it's fine
  934. // since we're generating an answer now it will contain all
  935. // our SSRCs
  936. if (oldLocalSdp) {
  937. const newLocalSdp
  938. = new SDP(this.peerconnection.localDescription.sdp);
  939. this.notifyMySSRCUpdate(
  940. new SDP(oldLocalSdp), newLocalSdp);
  941. }
  942. finishedCallback();
  943. }, error => {
  944. logger.error(
  945. `Error renegotiating after setting new remote ${
  946. this.isInitiator ? 'answer: ' : 'offer: '}${error}`,
  947. newRemoteSdp);
  948. finishedCallback(error);
  949. });
  950. };
  951. this.modificationQueue.push(
  952. workFunction,
  953. error => {
  954. error ? failure(error) : success();
  955. });
  956. }
  957. /* eslint-enable max-params */
  958. /**
  959. * Although it states "replace transport" it does accept full Jingle offer
  960. * which should contain new ICE transport details.
  961. * @param jingleOfferElem an element Jingle IQ that contains new offer and
  962. * transport info.
  963. * @param success callback called when we succeed to accept new offer.
  964. * @param failure function(error) called when we fail to accept new offer.
  965. */
  966. replaceTransport(jingleOfferElem, success, failure) {
  967. this.room.eventEmitter.emit(XMPPEvents.ICE_RESTARTING, this);
  968. // We need to first reject the 'data' section to have the SCTP stack
  969. // cleaned up to signal the known data channel is now invalid. After
  970. // that the original offer is set to have the SCTP connection
  971. // established with the new bridge.
  972. const originalOffer = jingleOfferElem.clone();
  973. jingleOfferElem
  974. .find('>content[name=\'data\']')
  975. .attr('senders', 'rejected');
  976. // Remove all remote sources in order to reset the client's state
  977. // for the remote MediaStreams. When a conference is moved to
  978. // another bridge it will start streaming with a sequence number
  979. // that is not in sync with the most recently seen by the client.
  980. // The symptoms include frozen or black video and lots of "failed to
  981. // unprotect SRTP packets" in Chrome logs.
  982. jingleOfferElem
  983. .find('>content>description>source')
  984. .remove();
  985. jingleOfferElem
  986. .find('>content>description>ssrc-group')
  987. .remove();
  988. // On the JVB it's not a real ICE restart and all layers are re-initialized from scratch as Jicofo does
  989. // the restart by re-allocating new channels. Chrome (or WebRTC stack) needs to have the DTLS transport layer
  990. // reset to start a new handshake with fresh DTLS transport on the bridge. Make it think that the DTLS
  991. // fingerprint has changed by setting an all zeros key.
  992. const newFingerprint = jingleOfferElem.find('>content>transport>fingerprint');
  993. newFingerprint.attr('hash', 'sha-1');
  994. newFingerprint.text('00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00');
  995. // First set an offer with a rejected 'data' section
  996. this.setOfferAnswerCycle(
  997. jingleOfferElem,
  998. () => {
  999. // Now set the original offer(with the 'data' section)
  1000. this.setOfferAnswerCycle(
  1001. originalOffer,
  1002. () => {
  1003. const localSDP
  1004. = new SDP(this.peerconnection.localDescription.sdp);
  1005. this.sendTransportAccept(localSDP, success, failure);
  1006. this.room.eventEmitter.emit(
  1007. XMPPEvents.ICE_RESTART_SUCCESS,
  1008. this,
  1009. originalOffer);
  1010. },
  1011. failure);
  1012. },
  1013. failure
  1014. );
  1015. }
  1016. /**
  1017. * Sends Jingle 'session-accept' message.
  1018. * @param {function()} success callback called when we receive 'RESULT'
  1019. * packet for the 'session-accept'
  1020. * @param {function(error)} failure called when we receive an error response
  1021. * or when the request has timed out.
  1022. * @private
  1023. */
  1024. sendSessionAccept(success, failure) {
  1025. // NOTE: since we're just reading from it, we don't need to be within
  1026. // the modification queue to access the local description
  1027. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  1028. let accept = $iq({ to: this.remoteJid,
  1029. type: 'set' })
  1030. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  1031. action: 'session-accept',
  1032. initiator: this.initiatorJid,
  1033. responder: this.responderJid,
  1034. sid: this.sid });
  1035. if (this.webrtcIceTcpDisable) {
  1036. localSDP.removeTcpCandidates = true;
  1037. }
  1038. if (this.webrtcIceUdpDisable) {
  1039. localSDP.removeUdpCandidates = true;
  1040. }
  1041. if (this.failICE) {
  1042. localSDP.failICE = true;
  1043. }
  1044. localSDP.toJingle(
  1045. accept,
  1046. this.initiatorJid === this.localJid ? 'initiator' : 'responder',
  1047. null);
  1048. // Calling tree() to print something useful
  1049. accept = accept.tree();
  1050. logger.info('Sending session-accept', accept);
  1051. this.connection.sendIQ(accept,
  1052. success,
  1053. this.newJingleErrorHandler(accept, error => {
  1054. failure(error);
  1055. // 'session-accept' is a critical timeout and we'll
  1056. // have to restart
  1057. this.room.eventEmitter.emit(
  1058. XMPPEvents.SESSION_ACCEPT_TIMEOUT, this);
  1059. }),
  1060. IQ_TIMEOUT);
  1061. // XXX Videobridge needs WebRTC's answer (ICE ufrag and pwd, DTLS
  1062. // fingerprint and setup) ASAP in order to start the connection
  1063. // establishment.
  1064. //
  1065. // FIXME Flushing the connection at this point triggers an issue with
  1066. // BOSH request handling in Prosody on slow connections.
  1067. //
  1068. // The problem is that this request will be quite large and it may take
  1069. // time before it reaches Prosody. In the meantime Strophe may decide
  1070. // to send the next one. And it was observed that a small request with
  1071. // 'transport-info' usually follows this one. It does reach Prosody
  1072. // before the previous one was completely received. 'rid' on the server
  1073. // is increased and Prosody ignores the request with 'session-accept'.
  1074. // It will never reach Jicofo and everything in the request table is
  1075. // lost. Removing the flush does not guarantee it will never happen, but
  1076. // makes it much less likely('transport-info' is bundled with
  1077. // 'session-accept' and any immediate requests).
  1078. //
  1079. // this.connection.flush();
  1080. }
  1081. /**
  1082. * Will send 'content-modify' IQ in order to ask the remote peer to
  1083. * either stop or resume sending video media.
  1084. * @param {boolean} videoTransferActive <tt>false</tt> to let the other peer
  1085. * know that we're not sending nor interested in receiving video contents.
  1086. * When set to <tt>true</tt> remote peer will be asked to resume video
  1087. * transfer.
  1088. * @private
  1089. */
  1090. sendContentModify(videoTransferActive) {
  1091. const newSendersValue = videoTransferActive ? 'both' : 'none';
  1092. const sessionModify
  1093. = $iq({
  1094. to: this.remoteJid,
  1095. type: 'set'
  1096. })
  1097. .c('jingle', {
  1098. xmlns: 'urn:xmpp:jingle:1',
  1099. action: 'content-modify',
  1100. initiator: this.initiatorJid,
  1101. sid: this.sid
  1102. })
  1103. .c('content', {
  1104. name: 'video',
  1105. senders: newSendersValue
  1106. });
  1107. logger.info(
  1108. `Sending content-modify, video senders: ${newSendersValue}`);
  1109. this.connection.sendIQ(
  1110. sessionModify,
  1111. null,
  1112. this.newJingleErrorHandler(sessionModify),
  1113. IQ_TIMEOUT);
  1114. }
  1115. /**
  1116. * Sends Jingle 'transport-accept' message which is a response to
  1117. * 'transport-replace'.
  1118. * @param localSDP the 'SDP' object with local session description
  1119. * @param success callback called when we receive 'RESULT' packet for
  1120. * 'transport-replace'
  1121. * @param failure function(error) called when we receive an error response
  1122. * or when the request has timed out.
  1123. * @private
  1124. */
  1125. sendTransportAccept(localSDP, success, failure) {
  1126. let transportAccept = $iq({ to: this.remoteJid,
  1127. type: 'set' })
  1128. .c('jingle', {
  1129. xmlns: 'urn:xmpp:jingle:1',
  1130. action: 'transport-accept',
  1131. initiator: this.initiatorJid,
  1132. sid: this.sid
  1133. });
  1134. localSDP.media.forEach((medialines, idx) => {
  1135. const mline = SDPUtil.parseMLine(medialines.split('\r\n')[0]);
  1136. transportAccept.c('content',
  1137. {
  1138. creator:
  1139. this.initiatorJid === this.localJid
  1140. ? 'initiator'
  1141. : 'responder',
  1142. name: mline.media
  1143. }
  1144. );
  1145. localSDP.transportToJingle(idx, transportAccept);
  1146. transportAccept.up();
  1147. });
  1148. // Calling tree() to print something useful to the logger
  1149. transportAccept = transportAccept.tree();
  1150. logger.info('Sending transport-accept: ', transportAccept);
  1151. this.connection.sendIQ(transportAccept,
  1152. success,
  1153. this.newJingleErrorHandler(transportAccept, failure),
  1154. IQ_TIMEOUT);
  1155. }
  1156. /**
  1157. * Sends Jingle 'transport-reject' message which is a response to
  1158. * 'transport-replace'.
  1159. * @param success callback called when we receive 'RESULT' packet for
  1160. * 'transport-replace'
  1161. * @param failure function(error) called when we receive an error response
  1162. * or when the request has timed out.
  1163. *
  1164. * FIXME method should be marked as private, but there's some spaghetti that
  1165. * needs to be fixed prior doing that
  1166. */
  1167. sendTransportReject(success, failure) {
  1168. // Send 'transport-reject', so that the focus will
  1169. // know that we've failed
  1170. let transportReject = $iq({ to: this.remoteJid,
  1171. type: 'set' })
  1172. .c('jingle', {
  1173. xmlns: 'urn:xmpp:jingle:1',
  1174. action: 'transport-reject',
  1175. initiator: this.initiatorJid,
  1176. sid: this.sid
  1177. });
  1178. transportReject = transportReject.tree();
  1179. logger.info('Sending \'transport-reject', transportReject);
  1180. this.connection.sendIQ(transportReject,
  1181. success,
  1182. this.newJingleErrorHandler(transportReject, failure),
  1183. IQ_TIMEOUT);
  1184. }
  1185. /**
  1186. * @inheritDoc
  1187. */
  1188. terminate(success, failure, options) {
  1189. if (this.state === JingleSessionState.ENDED) {
  1190. return;
  1191. }
  1192. if (!options || Boolean(options.sendSessionTerminate)) {
  1193. let sessionTerminate
  1194. = $iq({
  1195. to: this.remoteJid,
  1196. type: 'set'
  1197. })
  1198. .c('jingle', {
  1199. xmlns: 'urn:xmpp:jingle:1',
  1200. action: 'session-terminate',
  1201. initiator: this.initiatorJid,
  1202. sid: this.sid
  1203. })
  1204. .c('reason')
  1205. .c((options && options.reason) || 'success');
  1206. if (options && options.reasonDescription) {
  1207. sessionTerminate.up()
  1208. .c('text')
  1209. .t(options.reasonDescription);
  1210. }
  1211. // Calling tree() to print something useful
  1212. sessionTerminate = sessionTerminate.tree();
  1213. logger.info('Sending session-terminate', sessionTerminate);
  1214. this.connection.sendIQ(
  1215. sessionTerminate,
  1216. success,
  1217. this.newJingleErrorHandler(sessionTerminate, failure),
  1218. IQ_TIMEOUT);
  1219. } else {
  1220. logger.info(`Skipped sending session-terminate for ${this}`);
  1221. }
  1222. // this should result in 'onTerminated' being called by strope.jingle.js
  1223. this.connection.jingle.terminate(this.sid);
  1224. }
  1225. /**
  1226. *
  1227. * @param reasonCondition
  1228. * @param reasonText
  1229. */
  1230. onTerminated(reasonCondition, reasonText) {
  1231. // Do something with reason and reasonCondition when we start to care
  1232. // this.reasonCondition = reasonCondition;
  1233. // this.reasonText = reasonText;
  1234. logger.info(`Session terminated ${this}`, reasonCondition, reasonText);
  1235. this._xmppListeners.forEach(removeListener => removeListener());
  1236. this._xmppListeners = [];
  1237. this.close();
  1238. }
  1239. /**
  1240. * Handles XMPP connection state changes.
  1241. *
  1242. * @param {XmppConnection.Status} status - The new status.
  1243. */
  1244. onXmppStatusChanged(status) {
  1245. if (status === XmppConnection.Status.CONNECTED && this._cachedOldLocalSdp) {
  1246. logger.info('Sending SSRC update on reconnect');
  1247. this.notifyMySSRCUpdate(
  1248. this._cachedOldLocalSdp,
  1249. this._cachedNewLocalSdp);
  1250. }
  1251. }
  1252. /**
  1253. * Parse the information from the xml sourceAddElem and translate it
  1254. * into sdp lines
  1255. * @param {jquery xml element} sourceAddElem the source-add
  1256. * element from jingle
  1257. * @param {SDP object} currentRemoteSdp the current remote
  1258. * sdp (as of this new source-add)
  1259. * @returns {list} a list of SDP line strings that should
  1260. * be added to the remote SDP
  1261. */
  1262. _parseSsrcInfoFromSourceAdd(sourceAddElem, currentRemoteSdp) {
  1263. const addSsrcInfo = [];
  1264. $(sourceAddElem).each((i1, content) => {
  1265. const name = $(content).attr('name');
  1266. let lines = '';
  1267. $(content)
  1268. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  1269. .each(function() {
  1270. // eslint-disable-next-line no-invalid-this
  1271. const semantics = this.getAttribute('semantics');
  1272. const ssrcs
  1273. = $(this) // eslint-disable-line no-invalid-this
  1274. .find('>source')
  1275. .map(function() {
  1276. // eslint-disable-next-line no-invalid-this
  1277. return this.getAttribute('ssrc');
  1278. })
  1279. .get();
  1280. if (ssrcs.length) {
  1281. lines
  1282. += `a=ssrc-group:${semantics} ${
  1283. ssrcs.join(' ')}\r\n`;
  1284. }
  1285. });
  1286. // handles both >source and >description>source
  1287. const tmp
  1288. = $(content).find(
  1289. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  1290. /* eslint-disable no-invalid-this */
  1291. tmp.each(function() {
  1292. const ssrc = $(this).attr('ssrc');
  1293. if (currentRemoteSdp.containsSSRC(ssrc)) {
  1294. logger.warn(
  1295. `Source-add request for existing SSRC: ${ssrc}`);
  1296. return;
  1297. }
  1298. // eslint-disable-next-line newline-per-chained-call
  1299. $(this).find('>parameter').each(function() {
  1300. lines += `a=ssrc:${ssrc} ${$(this).attr('name')}`;
  1301. if ($(this).attr('value') && $(this).attr('value').length) {
  1302. lines += `:${$(this).attr('value')}`;
  1303. }
  1304. lines += '\r\n';
  1305. });
  1306. });
  1307. /* eslint-enable no-invalid-this */
  1308. currentRemoteSdp.media.forEach((media, i2) => {
  1309. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  1310. return;
  1311. }
  1312. if (!addSsrcInfo[i2]) {
  1313. addSsrcInfo[i2] = '';
  1314. }
  1315. addSsrcInfo[i2] += lines;
  1316. });
  1317. });
  1318. return addSsrcInfo;
  1319. }
  1320. /**
  1321. * Handles a Jingle source-add message for this Jingle session.
  1322. * @param elem An array of Jingle "content" elements.
  1323. */
  1324. addRemoteStream(elem) {
  1325. this._addOrRemoveRemoteStream(true /* add */, elem);
  1326. }
  1327. /**
  1328. * Handles a Jingle source-remove message for this Jingle session.
  1329. * @param elem An array of Jingle "content" elements.
  1330. */
  1331. removeRemoteStream(elem) {
  1332. this._addOrRemoveRemoteStream(false /* remove */, elem);
  1333. }
  1334. /**
  1335. * Handles either Jingle 'source-add' or 'source-remove' message for this
  1336. * Jingle session.
  1337. * @param {boolean} isAdd <tt>true</tt> for 'source-add' or <tt>false</tt>
  1338. * otherwise.
  1339. * @param {Array<Element>} elem an array of Jingle "content" elements.
  1340. * @private
  1341. */
  1342. _addOrRemoveRemoteStream(isAdd, elem) {
  1343. const logPrefix = isAdd ? 'addRemoteStream' : 'removeRemoteStream';
  1344. if (isAdd) {
  1345. this.readSsrcInfo(elem);
  1346. }
  1347. const workFunction = finishedCallback => {
  1348. if (!this.peerconnection.localDescription
  1349. || !this.peerconnection.localDescription.sdp) {
  1350. const errMsg = `${logPrefix} - localDescription not ready yet`;
  1351. logger.error(errMsg);
  1352. finishedCallback(errMsg);
  1353. return;
  1354. }
  1355. logger.log(`Processing ${logPrefix}`);
  1356. logger.log(
  1357. 'ICE connection state: ',
  1358. this.peerconnection.iceConnectionState);
  1359. const oldLocalSdp
  1360. = new SDP(this.peerconnection.localDescription.sdp);
  1361. const sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  1362. const addOrRemoveSsrcInfo
  1363. = isAdd
  1364. ? this._parseSsrcInfoFromSourceAdd(elem, sdp)
  1365. : this._parseSsrcInfoFromSourceRemove(elem, sdp);
  1366. const newRemoteSdp
  1367. = isAdd
  1368. ? this._processRemoteAddSource(addOrRemoveSsrcInfo)
  1369. : this._processRemoteRemoveSource(addOrRemoveSsrcInfo);
  1370. this._renegotiate(newRemoteSdp.raw)
  1371. .then(() => {
  1372. const newLocalSdp
  1373. = new SDP(this.peerconnection.localDescription.sdp);
  1374. logger.log(
  1375. `${logPrefix} - OK, SDPs: `, oldLocalSdp, newLocalSdp);
  1376. this.notifyMySSRCUpdate(oldLocalSdp, newLocalSdp);
  1377. finishedCallback();
  1378. }, error => {
  1379. logger.error(`${logPrefix} failed:`, error);
  1380. finishedCallback(error);
  1381. });
  1382. };
  1383. // Queue and execute
  1384. this.modificationQueue.push(workFunction);
  1385. }
  1386. /**
  1387. * Takes in a jingle offer iq, returns the new sdp offer
  1388. * @param {jquery xml element} offerIq the incoming offer
  1389. * @returns {SDP object} the jingle offer translated to SDP
  1390. */
  1391. _processNewJingleOfferIq(offerIq) {
  1392. const remoteSdp = new SDP('');
  1393. if (this.webrtcIceTcpDisable) {
  1394. remoteSdp.removeTcpCandidates = true;
  1395. }
  1396. if (this.webrtcIceUdpDisable) {
  1397. remoteSdp.removeUdpCandidates = true;
  1398. }
  1399. if (this.failICE) {
  1400. remoteSdp.failICE = true;
  1401. }
  1402. remoteSdp.fromJingle(offerIq);
  1403. this.readSsrcInfo($(offerIq).find('>content'));
  1404. return remoteSdp;
  1405. }
  1406. /**
  1407. * Remove the given ssrc lines from the current remote sdp
  1408. * @param {list} removeSsrcInfo a list of SDP line strings that
  1409. * should be removed from the remote SDP
  1410. * @returns type {SDP Object} the new remote SDP (after removing the lines
  1411. * in removeSsrcInfo
  1412. */
  1413. _processRemoteRemoveSource(removeSsrcInfo) {
  1414. const remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
  1415. removeSsrcInfo.forEach((lines, idx) => {
  1416. // eslint-disable-next-line no-param-reassign
  1417. lines = lines.split('\r\n');
  1418. lines.pop(); // remove empty last element;
  1419. lines.forEach(line => {
  1420. remoteSdp.media[idx]
  1421. = remoteSdp.media[idx].replace(`${line}\r\n`, '');
  1422. });
  1423. });
  1424. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  1425. return remoteSdp;
  1426. }
  1427. /**
  1428. * Add the given ssrc lines to the current remote sdp
  1429. * @param {list} addSsrcInfo a list of SDP line strings that
  1430. * should be added to the remote SDP
  1431. * @returns type {SDP Object} the new remote SDP (after removing the lines
  1432. * in removeSsrcInfo
  1433. */
  1434. _processRemoteAddSource(addSsrcInfo) {
  1435. const remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
  1436. addSsrcInfo.forEach((lines, idx) => {
  1437. remoteSdp.media[idx] += lines;
  1438. });
  1439. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  1440. return remoteSdp;
  1441. }
  1442. /**
  1443. * Do a new o/a flow using the existing remote description
  1444. * @param {string} [optionalRemoteSdp] optional, raw remote sdp
  1445. * to use. If not provided, the remote sdp from the
  1446. * peerconnection will be used
  1447. * @returns {Promise} promise which resolves when the
  1448. * o/a flow is complete with no arguments or
  1449. * rejects with an error {string}
  1450. */
  1451. _renegotiate(optionalRemoteSdp) {
  1452. if (this.peerconnection.signalingState === 'closed') {
  1453. const error = new Error('Attempted to renegotiate in state closed');
  1454. this.room.eventEmitter.emit(XMPPEvents.RENEGOTIATION_FAILED, error, this);
  1455. return Promise.reject(error);
  1456. }
  1457. const remoteSdp
  1458. = optionalRemoteSdp || this.peerconnection.remoteDescription.sdp;
  1459. if (!remoteSdp) {
  1460. const error = new Error(`Can not renegotiate without remote description, current state: ${this.state}`);
  1461. this.room.eventEmitter.emit(XMPPEvents.RENEGOTIATION_FAILED, error, this);
  1462. return Promise.reject(error);
  1463. }
  1464. const remoteDescription = new RTCSessionDescription({
  1465. type: this.isInitiator ? 'answer' : 'offer',
  1466. sdp: remoteSdp
  1467. });
  1468. if (this.isInitiator) {
  1469. return this._initiatorRenegotiate(remoteDescription);
  1470. }
  1471. return this._responderRenegotiate(remoteDescription);
  1472. }
  1473. /**
  1474. * Renegotiate cycle implementation for the responder case.
  1475. * @param {object} remoteDescription the SDP object as defined by the WebRTC
  1476. * which will be used as remote description in the cycle.
  1477. * @private
  1478. */
  1479. _responderRenegotiate(remoteDescription) {
  1480. logger.debug('Renegotiate: setting remote description');
  1481. return this.peerconnection.setRemoteDescription(remoteDescription)
  1482. .then(() => {
  1483. logger.debug('Renegotiate: creating answer');
  1484. return this.peerconnection.createAnswer(this.mediaConstraints)
  1485. .then(answer => {
  1486. logger.debug('Renegotiate: setting local description');
  1487. return this.peerconnection.setLocalDescription(answer);
  1488. });
  1489. });
  1490. }
  1491. /**
  1492. * Renegotiate cycle implementation for the initiator's case.
  1493. * @param {object} remoteDescription the SDP object as defined by the WebRTC
  1494. * which will be used as remote description in the cycle.
  1495. * @private
  1496. */
  1497. _initiatorRenegotiate(remoteDescription) {
  1498. if (this.peerconnection.signalingState === 'have-local-offer') {
  1499. // Skip createOffer and setLocalDescription or FF will fail
  1500. logger.debug(
  1501. 'Renegotiate: setting remote description');
  1502. /* eslint-disable arrow-body-style */
  1503. return this.peerconnection.setRemoteDescription(remoteDescription)
  1504. .then(() => {
  1505. // In case when the answer is being set for the first time,
  1506. // full sRD/sLD cycle is required to have the local
  1507. // description updated and SSRCs synchronized correctly.
  1508. // Otherwise SSRCs for streams added after invite, but
  1509. // before the answer was accepted will not be detected.
  1510. // The reason for that is that renegotiate can not be called
  1511. // when adding tracks and they will not be reflected in
  1512. // the local SDP.
  1513. return this._initiatorRenegotiate(remoteDescription);
  1514. });
  1515. /* eslint-enable arrow-body-style */
  1516. }
  1517. logger.debug('Renegotiate: creating offer');
  1518. return this.peerconnection.createOffer(this.mediaConstraints)
  1519. .then(offer => {
  1520. logger.debug('Renegotiate: setting local description');
  1521. return this.peerconnection.setLocalDescription(offer)
  1522. .then(() => {
  1523. logger.debug(
  1524. 'Renegotiate: setting remote description');
  1525. // eslint-disable-next-line max-len
  1526. return this.peerconnection.setRemoteDescription(remoteDescription);
  1527. });
  1528. });
  1529. }
  1530. /**
  1531. * Replaces <tt>oldTrack</tt> with <tt>newTrack</tt> and performs a single
  1532. * offer/answer cycle after both operations are done. Either
  1533. * <tt>oldTrack</tt> or <tt>newTrack</tt> can be null; replacing a valid
  1534. * <tt>oldTrack</tt> with a null <tt>newTrack</tt> effectively just removes
  1535. * <tt>oldTrack</tt>
  1536. * @param {JitsiLocalTrack|null} oldTrack the current track in use to be
  1537. * replaced
  1538. * @param {JitsiLocalTrack|null} newTrack the new track to use
  1539. * @returns {Promise} which resolves once the replacement is complete
  1540. * with no arguments or rejects with an error {string}
  1541. */
  1542. replaceTrack(oldTrack, newTrack) {
  1543. const workFunction = finishedCallback => {
  1544. const oldLocalSdp = this.peerconnection.localDescription.sdp;
  1545. if (browser.usesPlanB()) {
  1546. // NOTE the code below assumes that no more than 1 video track
  1547. // can be added to the peer connection.
  1548. // Transition from camera to desktop share
  1549. // or transition from one camera source to another.
  1550. if (this.peerconnection.options.capScreenshareBitrate
  1551. && oldTrack && newTrack && newTrack.isVideoTrack()) {
  1552. // Clearing current primary SSRC will make
  1553. // the SdpConsistency generate a new one which will result
  1554. // with:
  1555. // 1. source-remove for the old video stream.
  1556. // 2. source-add for the new video stream.
  1557. this.peerconnection.clearRecvonlySsrc();
  1558. }
  1559. // Transition from no video to video (unmute).
  1560. if (!oldTrack && newTrack && newTrack.isVideoTrack()) {
  1561. // Clearing current primary SSRC will make
  1562. // the SdpConsistency generate a new one which will result
  1563. // with:
  1564. // 1. source-remove for the recvonly
  1565. // 2. source-add for the new video stream
  1566. this.peerconnection.clearRecvonlySsrc();
  1567. // Transition from video to no video
  1568. } else if (oldTrack && oldTrack.isVideoTrack() && !newTrack) {
  1569. // Clearing current primary SSRC and generating the recvonly
  1570. // will result in:
  1571. // 1. source-remove for the old video stream
  1572. // 2. source-add for the recvonly stream
  1573. this.peerconnection.clearRecvonlySsrc();
  1574. this.peerconnection.generateRecvonlySsrc();
  1575. }
  1576. }
  1577. this.peerconnection.replaceTrack(oldTrack, newTrack)
  1578. .then(shouldRenegotiate => {
  1579. let promise = Promise.resolve();
  1580. if (shouldRenegotiate
  1581. && (oldTrack || newTrack)
  1582. && this.state === JingleSessionState.ACTIVE) {
  1583. promise = this._renegotiate().then(() => {
  1584. const newLocalSDP = new SDP(this.peerconnection.localDescription.sdp);
  1585. this.notifyMySSRCUpdate(new SDP(oldLocalSdp), newLocalSDP);
  1586. },
  1587. finishedCallback /* will be called with en error */);
  1588. }
  1589. // Wait for the renegotation to be done if needed (plan-b) before adjusting
  1590. // the max bitrates on the video sender.
  1591. promise.then(() => {
  1592. // configure max bitrate only when media is routed
  1593. // through JVB. For p2p case, browser takes care of
  1594. // adjusting the uplink based on the feedback it
  1595. // gets from the peer.
  1596. if (newTrack && !this.isP2P) {
  1597. this.peerconnection.setMaxBitRate(newTrack);
  1598. }
  1599. finishedCallback();
  1600. }, finishedCallback /* will be called with en error */);
  1601. })
  1602. .catch(err => {
  1603. finishedCallback(err);
  1604. });
  1605. };
  1606. return new Promise((resolve, reject) => {
  1607. this.modificationQueue.push(
  1608. workFunction,
  1609. error => {
  1610. if (error) {
  1611. logger.error('Replace track error:', error);
  1612. reject(error);
  1613. } else {
  1614. logger.info('Replace track done!');
  1615. resolve();
  1616. }
  1617. });
  1618. });
  1619. }
  1620. /**
  1621. * Parse the information from the xml sourceRemoveElem and translate it
  1622. * into sdp lines
  1623. * @param {jquery xml element} sourceRemoveElem the source-remove
  1624. * element from jingle
  1625. * @param {SDP object} currentRemoteSdp the current remote
  1626. * sdp (as of this new source-remove)
  1627. * @returns {list} a list of SDP line strings that should
  1628. * be removed from the remote SDP
  1629. */
  1630. _parseSsrcInfoFromSourceRemove(sourceRemoveElem, currentRemoteSdp) {
  1631. const removeSsrcInfo = [];
  1632. $(sourceRemoveElem).each((i1, content) => {
  1633. const name = $(content).attr('name');
  1634. let lines = '';
  1635. $(content)
  1636. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  1637. .each(function() {
  1638. /* eslint-disable no-invalid-this */
  1639. const semantics = this.getAttribute('semantics');
  1640. const ssrcs
  1641. = $(this)
  1642. .find('>source')
  1643. .map(function() {
  1644. return this.getAttribute('ssrc');
  1645. })
  1646. .get();
  1647. if (ssrcs.length) {
  1648. lines
  1649. += `a=ssrc-group:${semantics} ${
  1650. ssrcs.join(' ')}\r\n`;
  1651. }
  1652. /* eslint-enable no-invalid-this */
  1653. });
  1654. const ssrcs = [];
  1655. // handles both >source and >description>source versions
  1656. const tmp
  1657. = $(content).find(
  1658. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  1659. tmp.each(function() {
  1660. // eslint-disable-next-line no-invalid-this
  1661. const ssrc = $(this).attr('ssrc');
  1662. ssrcs.push(ssrc);
  1663. });
  1664. currentRemoteSdp.media.forEach((media, i2) => {
  1665. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  1666. return;
  1667. }
  1668. if (!removeSsrcInfo[i2]) {
  1669. removeSsrcInfo[i2] = '';
  1670. }
  1671. ssrcs.forEach(ssrc => {
  1672. const ssrcLines
  1673. = SDPUtil.findLines(media, `a=ssrc:${ssrc}`);
  1674. if (ssrcLines.length) {
  1675. removeSsrcInfo[i2] += `${ssrcLines.join('\r\n')}\r\n`;
  1676. }
  1677. });
  1678. removeSsrcInfo[i2] += lines;
  1679. });
  1680. });
  1681. return removeSsrcInfo;
  1682. }
  1683. /**
  1684. * Will print an error if there is any difference, between the SSRCs given
  1685. * in the <tt>oldSDP</tt> and the ones currently described in
  1686. * the peerconnection's local description.
  1687. * @param {string} operationName the operation's name which will be printed
  1688. * in the error message.
  1689. * @param {SDP} oldSDP the old local SDP which will be compared with
  1690. * the current one.
  1691. * @return {boolean} <tt>true</tt> if there was any change or <tt>false</tt>
  1692. * otherwise.
  1693. * @private
  1694. */
  1695. _verifyNoSSRCChanged(operationName, oldSDP) {
  1696. const currentLocalSDP
  1697. = new SDP(this.peerconnection.localDescription.sdp);
  1698. let sdpDiff = new SDPDiffer(oldSDP, currentLocalSDP);
  1699. const addedMedia = sdpDiff.getNewMedia();
  1700. if (Object.keys(addedMedia).length) {
  1701. logger.error(
  1702. `${this} - some SSRC were added on ${operationName}`,
  1703. addedMedia);
  1704. return false;
  1705. }
  1706. sdpDiff = new SDPDiffer(currentLocalSDP, oldSDP);
  1707. const removedMedia = sdpDiff.getNewMedia();
  1708. if (Object.keys(removedMedia).length) {
  1709. logger.error(
  1710. `${this} - some SSRCs were removed on ${operationName}`,
  1711. removedMedia);
  1712. return false;
  1713. }
  1714. return true;
  1715. }
  1716. /**
  1717. * Adds local track back to this session, as part of the unmute operation.
  1718. * @param {JitsiLocalTrack} track
  1719. * @return {Promise} a promise that will resolve once the local track is
  1720. * added back to this session and renegotiation succeeds. Will be rejected
  1721. * with a <tt>string</tt> that provides some error details in case something
  1722. * goes wrong.
  1723. */
  1724. addTrackAsUnmute(track) {
  1725. return this._addRemoveTrackAsMuteUnmute(
  1726. false /* add as unmute */, track);
  1727. }
  1728. /**
  1729. * Remove local track as part of the mute operation.
  1730. * @param {JitsiLocalTrack} track the local track to be removed
  1731. * @return {Promise} a promise which will be resolved once the local track
  1732. * is removed from this session and the renegotiation is performed.
  1733. * The promise will be rejected with a <tt>string</tt> that the describes
  1734. * the error if anything goes wrong.
  1735. */
  1736. removeTrackAsMute(track) {
  1737. return this._addRemoveTrackAsMuteUnmute(
  1738. true /* remove as mute */, track);
  1739. }
  1740. /**
  1741. * See {@link addTrackAsUnmute} and {@link removeTrackAsMute}.
  1742. * @param {boolean} isMute <tt>true</tt> for "remove as mute" or
  1743. * <tt>false</tt> for "add as unmute".
  1744. * @param {JitsiLocalTrack} track the track that will be added/removed
  1745. * @private
  1746. */
  1747. _addRemoveTrackAsMuteUnmute(isMute, track) {
  1748. if (!track) {
  1749. return Promise.reject('invalid "track" argument value');
  1750. }
  1751. const operationName = isMute ? 'removeTrackMute' : 'addTrackUnmute';
  1752. const workFunction = finishedCallback => {
  1753. const tpc = this.peerconnection;
  1754. if (!tpc) {
  1755. finishedCallback(
  1756. `Error: tried ${operationName} track with no active peer`
  1757. + 'connection');
  1758. return;
  1759. }
  1760. const oldLocalSDP = tpc.localDescription.sdp;
  1761. const tpcOperation
  1762. = isMute
  1763. ? tpc.removeTrackMute.bind(tpc, track)
  1764. : tpc.addTrackUnmute.bind(tpc, track);
  1765. if (!tpcOperation()) {
  1766. finishedCallback(`${operationName} failed!`);
  1767. // Do not renegotiate when browser is running in Unified-plan mode.
  1768. } else if (!oldLocalSDP || !tpc.remoteDescription.sdp || browser.usesUnifiedPlan()) {
  1769. finishedCallback();
  1770. } else {
  1771. this._renegotiate()
  1772. .then(() => {
  1773. // The results are ignored, as this check failure is not
  1774. // enough to fail the whole operation. It will log
  1775. // an error inside.
  1776. this._verifyNoSSRCChanged(
  1777. operationName, new SDP(oldLocalSDP));
  1778. finishedCallback();
  1779. },
  1780. finishedCallback /* will be called with an error */);
  1781. }
  1782. };
  1783. return new Promise((resolve, reject) => {
  1784. this.modificationQueue.push(
  1785. workFunction,
  1786. error => {
  1787. if (error) {
  1788. reject(error);
  1789. } else {
  1790. resolve();
  1791. }
  1792. });
  1793. });
  1794. }
  1795. /**
  1796. * Resumes or suspends media transfer over the underlying peer connection.
  1797. * @param {boolean} audioActive <tt>true</tt> to enable audio media
  1798. * transfer or <tt>false</tt> to suspend audio media transmission.
  1799. * @param {boolean} videoActive <tt>true</tt> to enable video media
  1800. * transfer or <tt>false</tt> to suspend video media transmission.
  1801. * @return {Promise} a <tt>Promise</tt> which will resolve once
  1802. * the operation is done. It will be rejected with an error description as
  1803. * a string in case anything goes wrong.
  1804. */
  1805. setMediaTransferActive(audioActive, videoActive) {
  1806. if (!this.peerconnection) {
  1807. return Promise.reject(
  1808. 'Can not modify transfer active state,'
  1809. + ' before "initialize" is called');
  1810. }
  1811. const logAudioStr = audioActive ? 'audio active' : 'audio inactive';
  1812. const logVideoStr = videoActive ? 'video active' : 'video inactive';
  1813. logger.info(`Queued make ${logVideoStr}, ${logAudioStr} task...`);
  1814. const workFunction = finishedCallback => {
  1815. const isSessionActive = this.state === JingleSessionState.ACTIVE;
  1816. // Because the value is modified on the queue it's impossible to
  1817. // check it's final value reliably prior to submitting the task.
  1818. // The rule here is that the last submitted state counts.
  1819. // Check the values here to avoid unnecessary renegotiation cycle.
  1820. const audioActiveChanged
  1821. = this.peerconnection.setAudioTransferActive(audioActive);
  1822. if (this._localVideoActive !== videoActive) {
  1823. this._localVideoActive = videoActive;
  1824. // Do only for P2P - Jicofo will reply with 'bad-request'
  1825. // We don't want to send 'content-modify', before the initial
  1826. // O/A (state === JingleSessionState.ACTIVE), because that will
  1827. // mess up video media direction in the remote SDP.
  1828. // 'content-modify' when processed only affects the media
  1829. // direction in the local SDP. We're doing that, because setting
  1830. // 'inactive' on video media in remote SDP will mess up our SDP
  1831. // translation chain (simulcast, RTX, video mute etc.).
  1832. if (this.isP2P && isSessionActive) {
  1833. this.sendContentModify(videoActive);
  1834. }
  1835. }
  1836. const pcVideoActiveChanged
  1837. = this.peerconnection.setVideoTransferActive(
  1838. this._localVideoActive && this._remoteVideoActive);
  1839. // Will do the sRD/sLD cycle to update SDPs and adjust the media
  1840. // direction
  1841. if (isSessionActive
  1842. && (audioActiveChanged || pcVideoActiveChanged)) {
  1843. this._renegotiate()
  1844. .then(
  1845. finishedCallback,
  1846. finishedCallback /* will be called with an error */);
  1847. } else {
  1848. finishedCallback();
  1849. }
  1850. };
  1851. return new Promise((resolve, reject) => {
  1852. this.modificationQueue.push(
  1853. workFunction,
  1854. error => {
  1855. if (error) {
  1856. reject(error);
  1857. } else {
  1858. resolve();
  1859. }
  1860. });
  1861. });
  1862. }
  1863. /**
  1864. * Will put and execute on the queue a session modify task. Currently it
  1865. * only checks the senders attribute of the video content in order to figure
  1866. * out if the remote peer has video in the inactive state (stored locally
  1867. * in {@link _remoteVideoActive} - see field description for more info).
  1868. * @param {jQuery} jingleContents jQuery selector pointing to the jingle
  1869. * element of the session modify IQ.
  1870. * @see {@link _remoteVideoActive}
  1871. * @see {@link _localVideoActive}
  1872. */
  1873. modifyContents(jingleContents) {
  1874. const newVideoSenders
  1875. = JingleSessionPC.parseVideoSenders(jingleContents);
  1876. if (newVideoSenders === null) {
  1877. logger.error(
  1878. `${this} - failed to parse video "senders" attribute in`
  1879. + '"content-modify" action');
  1880. return;
  1881. }
  1882. const workFunction = finishedCallback => {
  1883. if (this._assertNotEnded('content-modify')
  1884. && this._modifyRemoteVideoActive(newVideoSenders)) {
  1885. // Will do the sRD/sLD cycle to update SDPs and adjust
  1886. // the media direction
  1887. this._renegotiate()
  1888. .then(finishedCallback, finishedCallback /* (error) */);
  1889. } else {
  1890. finishedCallback();
  1891. }
  1892. };
  1893. logger.debug(
  1894. `${this} queued "content-modify" task`
  1895. + `(video senders="${newVideoSenders}")`);
  1896. this.modificationQueue.push(
  1897. workFunction,
  1898. error => {
  1899. if (error) {
  1900. logger.error('"content-modify" failed', error);
  1901. }
  1902. });
  1903. }
  1904. /**
  1905. * Processes new value of remote video "senders" Jingle attribute and tries
  1906. * to apply it for {@link _remoteVideoActive}.
  1907. * @param {string} remoteVideoSenders the value of "senders" attribute of
  1908. * Jingle video content element advertised by remote peer.
  1909. * @return {boolean} <tt>true</tt> if the change affected state of
  1910. * the underlying peerconnection and renegotiation is required for
  1911. * the changes to take effect.
  1912. * @private
  1913. */
  1914. _modifyRemoteVideoActive(remoteVideoSenders) {
  1915. const isRemoteVideoActive
  1916. = remoteVideoSenders === 'both'
  1917. || (remoteVideoSenders === 'initiator' && this.isInitiator)
  1918. || (remoteVideoSenders === 'responder' && !this.isInitiator);
  1919. if (isRemoteVideoActive !== this._remoteVideoActive) {
  1920. logger.debug(
  1921. `${this} new remote video active: ${isRemoteVideoActive}`);
  1922. this._remoteVideoActive = isRemoteVideoActive;
  1923. }
  1924. return this.peerconnection.setVideoTransferActive(
  1925. this._localVideoActive && this._remoteVideoActive);
  1926. }
  1927. /**
  1928. * Figures out added/removed ssrcs and send update IQs.
  1929. * @param oldSDP SDP object for old description.
  1930. * @param newSDP SDP object for new description.
  1931. */
  1932. notifyMySSRCUpdate(oldSDP, newSDP) {
  1933. if (this.state !== JingleSessionState.ACTIVE) {
  1934. logger.warn(`Skipping SSRC update in '${this.state} ' state.`);
  1935. return;
  1936. }
  1937. if (!this.connection.connected) {
  1938. // The goal is to compare the oldest SDP with the latest one upon reconnect
  1939. if (!this._cachedOldLocalSdp) {
  1940. this._cachedOldLocalSdp = oldSDP;
  1941. }
  1942. this._cachedNewLocalSdp = newSDP;
  1943. logger.warn('Not sending SSRC update while the signaling is disconnected');
  1944. return;
  1945. }
  1946. this._cachedOldLocalSdp = undefined;
  1947. this._cachedNewLocalSdp = undefined;
  1948. // send source-remove IQ.
  1949. let sdpDiffer = new SDPDiffer(newSDP, oldSDP);
  1950. const remove = $iq({ to: this.remoteJid,
  1951. type: 'set' })
  1952. .c('jingle', {
  1953. xmlns: 'urn:xmpp:jingle:1',
  1954. action: 'source-remove',
  1955. initiator: this.initiatorJid,
  1956. sid: this.sid
  1957. }
  1958. );
  1959. const removedAnySSRCs = sdpDiffer.toJingle(remove);
  1960. if (removedAnySSRCs) {
  1961. logger.info('Sending source-remove', remove.tree());
  1962. this.connection.sendIQ(
  1963. remove, null,
  1964. this.newJingleErrorHandler(remove), IQ_TIMEOUT);
  1965. } else {
  1966. logger.log('removal not necessary');
  1967. }
  1968. // send source-add IQ.
  1969. sdpDiffer = new SDPDiffer(oldSDP, newSDP);
  1970. const add = $iq({ to: this.remoteJid,
  1971. type: 'set' })
  1972. .c('jingle', {
  1973. xmlns: 'urn:xmpp:jingle:1',
  1974. action: 'source-add',
  1975. initiator: this.initiatorJid,
  1976. sid: this.sid
  1977. }
  1978. );
  1979. const containsNewSSRCs = sdpDiffer.toJingle(add);
  1980. if (containsNewSSRCs) {
  1981. logger.info('Sending source-add', add.tree());
  1982. this.connection.sendIQ(
  1983. add, null, this.newJingleErrorHandler(add), IQ_TIMEOUT);
  1984. } else {
  1985. logger.log('addition not necessary');
  1986. }
  1987. }
  1988. /**
  1989. * Method returns function(errorResponse) which is a callback to be passed
  1990. * to Strophe connection.sendIQ method. An 'error' structure is created that
  1991. * is passed as 1st argument to given <tt>failureCb</tt>. The format of this
  1992. * structure is as follows:
  1993. * {
  1994. * code: {XMPP error response code}
  1995. * reason: {the name of XMPP error reason element or 'timeout' if the
  1996. * request has timed out within <tt>IQ_TIMEOUT</tt> milliseconds}
  1997. * source: {request.tree() that provides original request}
  1998. * session: {this JingleSessionPC.toString()}
  1999. * }
  2000. * @param request Strophe IQ instance which is the request to be dumped into
  2001. * the error structure
  2002. * @param failureCb function(error) called when error response was returned
  2003. * or when a timeout has occurred.
  2004. * @returns {function(this:JingleSessionPC)}
  2005. */
  2006. newJingleErrorHandler(request, failureCb) {
  2007. return errResponse => {
  2008. const error = {};
  2009. // Get XMPP error code and condition(reason)
  2010. const errorElSel = $(errResponse).find('error');
  2011. if (errorElSel.length) {
  2012. error.code = errorElSel.attr('code');
  2013. const errorReasonSel = $(errResponse).find('error :first');
  2014. if (errorReasonSel.length) {
  2015. error.reason = errorReasonSel[0].tagName;
  2016. }
  2017. const errorMsgSel = errorElSel.find('>text');
  2018. if (errorMsgSel.length) {
  2019. error.msg = errorMsgSel.text();
  2020. }
  2021. }
  2022. if (!errResponse) {
  2023. error.reason = 'timeout';
  2024. }
  2025. error.session = this.toString();
  2026. if (failureCb) {
  2027. failureCb(error);
  2028. } else if (this.state === JingleSessionState.ENDED
  2029. && error.reason === 'item-not-found') {
  2030. // When remote peer decides to terminate the session, but it
  2031. // still have few messages on the queue for processing,
  2032. // it will first send us 'session-terminate' (we enter ENDED)
  2033. // and then follow with 'item-not-found' for the queued requests
  2034. // We don't want to have that logged on error level.
  2035. logger.debug(`Jingle error: ${JSON.stringify(error)}`);
  2036. } else {
  2037. GlobalOnErrorHandler.callErrorHandler(
  2038. new Error(
  2039. `Jingle error: ${JSON.stringify(error)}`));
  2040. }
  2041. };
  2042. }
  2043. /**
  2044. * Returns the ice connection state for the peer connection.
  2045. * @returns the ice connection state for the peer connection.
  2046. */
  2047. getIceConnectionState() {
  2048. return this.peerconnection.iceConnectionState;
  2049. }
  2050. /**
  2051. * Closes the peerconnection.
  2052. */
  2053. close() {
  2054. this.state = JingleSessionState.ENDED;
  2055. this.establishmentDuration = undefined;
  2056. if (this.peerconnection) {
  2057. this.peerconnection.onicecandidate = null;
  2058. this.peerconnection.oniceconnectionstatechange = null;
  2059. this.peerconnection.onnegotiationneeded = null;
  2060. this.peerconnection.onsignalingstatechange = null;
  2061. }
  2062. // Remove any pending tasks from the queue
  2063. this.modificationQueue.clear();
  2064. this.modificationQueue.push(finishCallback => {
  2065. // The signaling layer will remove it's listeners
  2066. this.signalingLayer.setChatRoom(null);
  2067. // do not try to close if already closed.
  2068. this.peerconnection && this.peerconnection.close();
  2069. finishCallback();
  2070. });
  2071. // No more tasks can go in after the close task
  2072. this.modificationQueue.shutdown();
  2073. }
  2074. /**
  2075. * Converts to string with minor summary.
  2076. * @return {string}
  2077. */
  2078. toString() {
  2079. return `JingleSessionPC[p2p=${this.isP2P},`
  2080. + `initiator=${this.isInitiator},sid=${this.sid}]`;
  2081. }
  2082. /**
  2083. * If the A/B test for suspend video is disabled according to the room's
  2084. * configuration, returns undefined. Otherwise returns a boolean which
  2085. * indicates whether the suspend video option should be enabled or disabled.
  2086. * @param {JingleSessionPCOptions} options - The config options.
  2087. */
  2088. _abtestSuspendVideoEnabled({ abTesting }) {
  2089. if (!abTesting || !abTesting.enableSuspendVideoTest) {
  2090. return;
  2091. }
  2092. // We want the two participants in a P2P call to agree on the value of
  2093. // the "suspend" option. We use the JID of the initiator, because it is
  2094. // both randomly selected and agreed upon by both participants.
  2095. const jid = this._getInitiatorJid();
  2096. return integerHash(jid) % 2 === 0;
  2097. }
  2098. }