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

JingleSessionPC.js 96KB

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