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

JingleSessionPC.js 96KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547
  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. * Returns the video codec configured as the preferred codec on the peerconnection.
  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. * Updates the codecs on the peerconnection and initiates a renegotiation for the
  971. * new codec config to take effect.
  972. *
  973. * @param {CodecMimeType} preferred the preferred codec.
  974. * @param {CodecMimeType} disabled the codec that needs to be disabled.
  975. */
  976. setVideoCodecs(preferred = null, disabled = null) {
  977. const current = this.peerconnection.getConfiguredVideoCodec();
  978. if (this._assertNotEnded() && preferred !== current) {
  979. logger.info(`${this} Switching video codec from ${current} to ${preferred}`);
  980. this.peerconnection.setVideoCodecs(preferred, disabled);
  981. // Initiate a renegotiate for the codec setting to take effect.
  982. const workFunction = finishedCallback => {
  983. this._renegotiate().then(() => finishedCallback(), error => finishedCallback(error));
  984. };
  985. // Queue and execute
  986. this.modificationQueue.push(workFunction);
  987. }
  988. }
  989. /* eslint-enable max-params */
  990. /**
  991. * Although it states "replace transport" it does accept full Jingle offer
  992. * which should contain new ICE transport details.
  993. * @param jingleOfferElem an element Jingle IQ that contains new offer and
  994. * transport info.
  995. * @param success callback called when we succeed to accept new offer.
  996. * @param failure function(error) called when we fail to accept new offer.
  997. */
  998. replaceTransport(jingleOfferElem, success, failure) {
  999. this.room.eventEmitter.emit(XMPPEvents.ICE_RESTARTING, this);
  1000. // We need to first reject the 'data' section to have the SCTP stack
  1001. // cleaned up to signal the known data channel is now invalid. After
  1002. // that the original offer is set to have the SCTP connection
  1003. // established with the new bridge.
  1004. const originalOffer = jingleOfferElem.clone();
  1005. jingleOfferElem
  1006. .find('>content[name=\'data\']')
  1007. .attr('senders', 'rejected');
  1008. // Remove all remote sources in order to reset the client's state
  1009. // for the remote MediaStreams. When a conference is moved to
  1010. // another bridge it will start streaming with a sequence number
  1011. // that is not in sync with the most recently seen by the client.
  1012. // The symptoms include frozen or black video and lots of "failed to
  1013. // unprotect SRTP packets" in Chrome logs.
  1014. jingleOfferElem
  1015. .find('>content>description>source')
  1016. .remove();
  1017. jingleOfferElem
  1018. .find('>content>description>ssrc-group')
  1019. .remove();
  1020. // On the JVB it's not a real ICE restart and all layers are re-initialized from scratch as Jicofo does
  1021. // the restart by re-allocating new channels. Chrome (or WebRTC stack) needs to have the DTLS transport layer
  1022. // reset to start a new handshake with fresh DTLS transport on the bridge. Make it think that the DTLS
  1023. // fingerprint has changed by setting an all zeros key.
  1024. const newFingerprint = jingleOfferElem.find('>content>transport>fingerprint');
  1025. newFingerprint.attr('hash', 'sha-1');
  1026. newFingerprint.text('00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00');
  1027. // First set an offer with a rejected 'data' section
  1028. this.setOfferAnswerCycle(
  1029. jingleOfferElem,
  1030. () => {
  1031. // Now set the original offer(with the 'data' section)
  1032. this.setOfferAnswerCycle(
  1033. originalOffer,
  1034. () => {
  1035. const localSDP
  1036. = new SDP(this.peerconnection.localDescription.sdp);
  1037. this.sendTransportAccept(localSDP, success, failure);
  1038. this.room.eventEmitter.emit(
  1039. XMPPEvents.ICE_RESTART_SUCCESS,
  1040. this,
  1041. originalOffer);
  1042. },
  1043. failure);
  1044. },
  1045. failure
  1046. );
  1047. }
  1048. /**
  1049. * Sends Jingle 'session-accept' message.
  1050. * @param {function()} success callback called when we receive 'RESULT'
  1051. * packet for the 'session-accept'
  1052. * @param {function(error)} failure called when we receive an error response
  1053. * or when the request has timed out.
  1054. * @private
  1055. */
  1056. sendSessionAccept(success, failure) {
  1057. // NOTE: since we're just reading from it, we don't need to be within
  1058. // the modification queue to access the local description
  1059. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  1060. let accept = $iq({ to: this.remoteJid,
  1061. type: 'set' })
  1062. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  1063. action: 'session-accept',
  1064. initiator: this.initiatorJid,
  1065. responder: this.responderJid,
  1066. sid: this.sid });
  1067. if (this.webrtcIceTcpDisable) {
  1068. localSDP.removeTcpCandidates = true;
  1069. }
  1070. if (this.webrtcIceUdpDisable) {
  1071. localSDP.removeUdpCandidates = true;
  1072. }
  1073. if (this.failICE) {
  1074. localSDP.failICE = true;
  1075. }
  1076. localSDP.toJingle(
  1077. accept,
  1078. this.initiatorJid === this.localJid ? 'initiator' : 'responder',
  1079. null);
  1080. // Calling tree() to print something useful
  1081. accept = accept.tree();
  1082. logger.info('Sending session-accept', accept);
  1083. this.connection.sendIQ(accept,
  1084. success,
  1085. this.newJingleErrorHandler(accept, error => {
  1086. failure(error);
  1087. // 'session-accept' is a critical timeout and we'll
  1088. // have to restart
  1089. this.room.eventEmitter.emit(
  1090. XMPPEvents.SESSION_ACCEPT_TIMEOUT, this);
  1091. }),
  1092. IQ_TIMEOUT);
  1093. // XXX Videobridge needs WebRTC's answer (ICE ufrag and pwd, DTLS
  1094. // fingerprint and setup) ASAP in order to start the connection
  1095. // establishment.
  1096. //
  1097. // FIXME Flushing the connection at this point triggers an issue with
  1098. // BOSH request handling in Prosody on slow connections.
  1099. //
  1100. // The problem is that this request will be quite large and it may take
  1101. // time before it reaches Prosody. In the meantime Strophe may decide
  1102. // to send the next one. And it was observed that a small request with
  1103. // 'transport-info' usually follows this one. It does reach Prosody
  1104. // before the previous one was completely received. 'rid' on the server
  1105. // is increased and Prosody ignores the request with 'session-accept'.
  1106. // It will never reach Jicofo and everything in the request table is
  1107. // lost. Removing the flush does not guarantee it will never happen, but
  1108. // makes it much less likely('transport-info' is bundled with
  1109. // 'session-accept' and any immediate requests).
  1110. //
  1111. // this.connection.flush();
  1112. }
  1113. /**
  1114. * Will send 'content-modify' IQ in order to ask the remote peer to
  1115. * either stop or resume sending video media or to adjust sender's video constraints.
  1116. * @private
  1117. */
  1118. sendContentModify() {
  1119. const maxFrameHeight = this.localRecvMaxFrameHeight;
  1120. const senders = this._localVideoActive ? 'both' : 'none';
  1121. let sessionModify
  1122. = $iq({
  1123. to: this.remoteJid,
  1124. type: 'set'
  1125. })
  1126. .c('jingle', {
  1127. xmlns: 'urn:xmpp:jingle:1',
  1128. action: 'content-modify',
  1129. initiator: this.initiatorJid,
  1130. sid: this.sid
  1131. })
  1132. .c('content', {
  1133. name: 'video',
  1134. senders
  1135. });
  1136. if (typeof maxFrameHeight !== 'undefined') {
  1137. sessionModify = sessionModify
  1138. .c('max-frame-height', { xmlns: 'http://jitsi.org/jitmeet/video' })
  1139. .t(maxFrameHeight);
  1140. }
  1141. logger.info(`${this} sending content-modify, video senders: ${senders}, max frame height: ${maxFrameHeight}`);
  1142. this.connection.sendIQ(
  1143. sessionModify,
  1144. null,
  1145. this.newJingleErrorHandler(sessionModify),
  1146. IQ_TIMEOUT);
  1147. }
  1148. /**
  1149. * Adjust the preference for max video frame height that the local party is willing to receive. Signals
  1150. * the remote party.
  1151. *
  1152. * @param {Number} maxFrameHeight - the new value to set.
  1153. */
  1154. setReceiverVideoConstraint(maxFrameHeight) {
  1155. logger.info(`${this} setReceiverVideoConstraint - max frame height: ${maxFrameHeight}`);
  1156. this.localRecvMaxFrameHeight = maxFrameHeight;
  1157. if (this.isP2P) {
  1158. // Tell the remote peer about our receive constraint. If Jingle session is not yet active the state will
  1159. // be synced after offer/answer.
  1160. if (this.state === JingleSessionState.ACTIVE) {
  1161. this.sendContentModify();
  1162. }
  1163. } else {
  1164. this.rtc.setReceiverVideoConstraint(maxFrameHeight);
  1165. }
  1166. }
  1167. /**
  1168. * Sends Jingle 'transport-accept' message which is a response to
  1169. * 'transport-replace'.
  1170. * @param localSDP the 'SDP' object with local session description
  1171. * @param success callback called when we receive 'RESULT' packet for
  1172. * 'transport-replace'
  1173. * @param failure function(error) called when we receive an error response
  1174. * or when the request has timed out.
  1175. * @private
  1176. */
  1177. sendTransportAccept(localSDP, success, failure) {
  1178. let transportAccept = $iq({ to: this.remoteJid,
  1179. type: 'set' })
  1180. .c('jingle', {
  1181. xmlns: 'urn:xmpp:jingle:1',
  1182. action: 'transport-accept',
  1183. initiator: this.initiatorJid,
  1184. sid: this.sid
  1185. });
  1186. localSDP.media.forEach((medialines, idx) => {
  1187. const mline = SDPUtil.parseMLine(medialines.split('\r\n')[0]);
  1188. transportAccept.c('content',
  1189. {
  1190. creator:
  1191. this.initiatorJid === this.localJid
  1192. ? 'initiator'
  1193. : 'responder',
  1194. name: mline.media
  1195. }
  1196. );
  1197. localSDP.transportToJingle(idx, transportAccept);
  1198. transportAccept.up();
  1199. });
  1200. // Calling tree() to print something useful to the logger
  1201. transportAccept = transportAccept.tree();
  1202. logger.info('Sending transport-accept: ', transportAccept);
  1203. this.connection.sendIQ(transportAccept,
  1204. success,
  1205. this.newJingleErrorHandler(transportAccept, failure),
  1206. IQ_TIMEOUT);
  1207. }
  1208. /**
  1209. * Sends Jingle 'transport-reject' message which is a response to
  1210. * 'transport-replace'.
  1211. * @param success callback called when we receive 'RESULT' packet for
  1212. * 'transport-replace'
  1213. * @param failure function(error) called when we receive an error response
  1214. * or when the request has timed out.
  1215. *
  1216. * FIXME method should be marked as private, but there's some spaghetti that
  1217. * needs to be fixed prior doing that
  1218. */
  1219. sendTransportReject(success, failure) {
  1220. // Send 'transport-reject', so that the focus will
  1221. // know that we've failed
  1222. let transportReject = $iq({ to: this.remoteJid,
  1223. type: 'set' })
  1224. .c('jingle', {
  1225. xmlns: 'urn:xmpp:jingle:1',
  1226. action: 'transport-reject',
  1227. initiator: this.initiatorJid,
  1228. sid: this.sid
  1229. });
  1230. transportReject = transportReject.tree();
  1231. logger.info('Sending \'transport-reject', transportReject);
  1232. this.connection.sendIQ(transportReject,
  1233. success,
  1234. this.newJingleErrorHandler(transportReject, failure),
  1235. IQ_TIMEOUT);
  1236. }
  1237. /**
  1238. * Sets the maximum bitrates on the local video track. Bitrate values from
  1239. * videoQuality settings in config.js will be used for configuring the sender.
  1240. * @returns {Promise<void>} promise that will be resolved when the operation is
  1241. * successful and rejected otherwise.
  1242. */
  1243. setSenderMaxBitrates() {
  1244. if (this._assertNotEnded()) {
  1245. return this.peerconnection.setMaxBitRate();
  1246. }
  1247. return Promise.resolve();
  1248. }
  1249. /**
  1250. * Sets the resolution constraint on the local camera track.
  1251. * @param {number} maxFrameHeight - The user preferred max frame height.
  1252. * @returns {Promise} promise that will be resolved when the operation is
  1253. * successful and rejected otherwise.
  1254. */
  1255. setSenderVideoConstraint(maxFrameHeight) {
  1256. if (this._assertNotEnded()) {
  1257. logger.info(`${this} setSenderVideoConstraint: ${maxFrameHeight}`);
  1258. return this.peerconnection.setSenderVideoConstraint(maxFrameHeight);
  1259. }
  1260. return Promise.resolve();
  1261. }
  1262. /**
  1263. * Sets the degradation preference on the video sender. This setting determines if
  1264. * resolution or framerate will be preferred when bandwidth or cpu is constrained.
  1265. * @returns {Promise<void>} promise that will be resolved when the operation is
  1266. * successful and rejected otherwise.
  1267. */
  1268. setSenderVideoDegradationPreference() {
  1269. if (this._assertNotEnded()) {
  1270. return this.peerconnection.setSenderVideoDegradationPreference();
  1271. }
  1272. return Promise.resolve();
  1273. }
  1274. /**
  1275. * @inheritDoc
  1276. */
  1277. terminate(success, failure, options) {
  1278. if (this.state === JingleSessionState.ENDED) {
  1279. return;
  1280. }
  1281. if (!options || Boolean(options.sendSessionTerminate)) {
  1282. let sessionTerminate
  1283. = $iq({
  1284. to: this.remoteJid,
  1285. type: 'set'
  1286. })
  1287. .c('jingle', {
  1288. xmlns: 'urn:xmpp:jingle:1',
  1289. action: 'session-terminate',
  1290. initiator: this.initiatorJid,
  1291. sid: this.sid
  1292. })
  1293. .c('reason')
  1294. .c((options && options.reason) || 'success')
  1295. .up();
  1296. if (options && options.reasonDescription) {
  1297. sessionTerminate
  1298. .c('text')
  1299. .t(options.reasonDescription)
  1300. .up()
  1301. .up();
  1302. } else {
  1303. sessionTerminate.up();
  1304. }
  1305. this._bridgeSessionId
  1306. && sessionTerminate.c(
  1307. 'bridge-session', {
  1308. xmlns: 'http://jitsi.org/protocol/focus',
  1309. id: this._bridgeSessionId,
  1310. restart: options && options.requestRestart === true
  1311. }).up();
  1312. // Calling tree() to print something useful
  1313. sessionTerminate = sessionTerminate.tree();
  1314. logger.info('Sending session-terminate', sessionTerminate);
  1315. this.connection.sendIQ(
  1316. sessionTerminate,
  1317. success,
  1318. this.newJingleErrorHandler(sessionTerminate, failure),
  1319. IQ_TIMEOUT);
  1320. } else {
  1321. logger.info(`Skipped sending session-terminate for ${this}`);
  1322. }
  1323. // this should result in 'onTerminated' being called by strope.jingle.js
  1324. this.connection.jingle.terminate(this.sid);
  1325. }
  1326. /**
  1327. *
  1328. * @param reasonCondition
  1329. * @param reasonText
  1330. */
  1331. onTerminated(reasonCondition, reasonText) {
  1332. // Do something with reason and reasonCondition when we start to care
  1333. // this.reasonCondition = reasonCondition;
  1334. // this.reasonText = reasonText;
  1335. logger.info(`Session terminated ${this}`, reasonCondition, reasonText);
  1336. this._xmppListeners.forEach(removeListener => removeListener());
  1337. this._xmppListeners = [];
  1338. if (this._removeSenderVideoConstraintsChangeListener) {
  1339. this._removeSenderVideoConstraintsChangeListener();
  1340. }
  1341. this.close();
  1342. }
  1343. /**
  1344. * Handles XMPP connection state changes.
  1345. *
  1346. * @param {XmppConnection.Status} status - The new status.
  1347. */
  1348. onXmppStatusChanged(status) {
  1349. if (status === XmppConnection.Status.CONNECTED && this._cachedOldLocalSdp) {
  1350. logger.info('Sending SSRC update on reconnect');
  1351. this.notifyMySSRCUpdate(
  1352. this._cachedOldLocalSdp,
  1353. this._cachedNewLocalSdp);
  1354. }
  1355. }
  1356. /**
  1357. * Parse the information from the xml sourceAddElem and translate it
  1358. * into sdp lines
  1359. * @param {jquery xml element} sourceAddElem the source-add
  1360. * element from jingle
  1361. * @param {SDP object} currentRemoteSdp the current remote
  1362. * sdp (as of this new source-add)
  1363. * @returns {list} a list of SDP line strings that should
  1364. * be added to the remote SDP
  1365. */
  1366. _parseSsrcInfoFromSourceAdd(sourceAddElem, currentRemoteSdp) {
  1367. const addSsrcInfo = [];
  1368. $(sourceAddElem).each((i1, content) => {
  1369. const name = $(content).attr('name');
  1370. let lines = '';
  1371. $(content)
  1372. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  1373. .each(function() {
  1374. // eslint-disable-next-line no-invalid-this
  1375. const semantics = this.getAttribute('semantics');
  1376. const ssrcs
  1377. = $(this) // eslint-disable-line no-invalid-this
  1378. .find('>source')
  1379. .map(function() {
  1380. // eslint-disable-next-line no-invalid-this
  1381. return this.getAttribute('ssrc');
  1382. })
  1383. .get();
  1384. if (ssrcs.length) {
  1385. lines
  1386. += `a=ssrc-group:${semantics} ${
  1387. ssrcs.join(' ')}\r\n`;
  1388. }
  1389. });
  1390. // handles both >source and >description>source
  1391. const tmp
  1392. = $(content).find(
  1393. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  1394. /* eslint-disable no-invalid-this */
  1395. tmp.each(function() {
  1396. const ssrc = $(this).attr('ssrc');
  1397. if (currentRemoteSdp.containsSSRC(ssrc)) {
  1398. logger.warn(
  1399. `Source-add request for existing SSRC: ${ssrc}`);
  1400. return;
  1401. }
  1402. // eslint-disable-next-line newline-per-chained-call
  1403. $(this).find('>parameter').each(function() {
  1404. lines += `a=ssrc:${ssrc} ${$(this).attr('name')}`;
  1405. if ($(this).attr('value') && $(this).attr('value').length) {
  1406. lines += `:${$(this).attr('value')}`;
  1407. }
  1408. lines += '\r\n';
  1409. });
  1410. });
  1411. /* eslint-enable no-invalid-this */
  1412. currentRemoteSdp.media.forEach((media, i2) => {
  1413. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  1414. return;
  1415. }
  1416. if (!addSsrcInfo[i2]) {
  1417. addSsrcInfo[i2] = '';
  1418. }
  1419. addSsrcInfo[i2] += lines;
  1420. });
  1421. });
  1422. return addSsrcInfo;
  1423. }
  1424. /**
  1425. * Handles a Jingle source-add message for this Jingle session.
  1426. * @param elem An array of Jingle "content" elements.
  1427. */
  1428. addRemoteStream(elem) {
  1429. this._addOrRemoveRemoteStream(true /* add */, elem);
  1430. }
  1431. /**
  1432. * Handles a Jingle source-remove message for this Jingle session.
  1433. * @param elem An array of Jingle "content" elements.
  1434. */
  1435. removeRemoteStream(elem) {
  1436. this._addOrRemoveRemoteStream(false /* remove */, elem);
  1437. }
  1438. /**
  1439. * Handles either Jingle 'source-add' or 'source-remove' message for this
  1440. * Jingle session.
  1441. * @param {boolean} isAdd <tt>true</tt> for 'source-add' or <tt>false</tt>
  1442. * otherwise.
  1443. * @param {Array<Element>} elem an array of Jingle "content" elements.
  1444. * @private
  1445. */
  1446. _addOrRemoveRemoteStream(isAdd, elem) {
  1447. const logPrefix = isAdd ? 'addRemoteStream' : 'removeRemoteStream';
  1448. if (isAdd) {
  1449. this.readSsrcInfo(elem);
  1450. }
  1451. const workFunction = finishedCallback => {
  1452. if (!this.peerconnection.localDescription
  1453. || !this.peerconnection.localDescription.sdp) {
  1454. const errMsg = `${logPrefix} - localDescription not ready yet`;
  1455. logger.error(errMsg);
  1456. finishedCallback(errMsg);
  1457. return;
  1458. }
  1459. logger.log(`Processing ${logPrefix}`);
  1460. logger.log(
  1461. 'ICE connection state: ',
  1462. this.peerconnection.iceConnectionState);
  1463. const oldLocalSdp
  1464. = new SDP(this.peerconnection.localDescription.sdp);
  1465. const sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  1466. const addOrRemoveSsrcInfo
  1467. = isAdd
  1468. ? this._parseSsrcInfoFromSourceAdd(elem, sdp)
  1469. : this._parseSsrcInfoFromSourceRemove(elem, sdp);
  1470. const newRemoteSdp
  1471. = isAdd
  1472. ? this._processRemoteAddSource(addOrRemoveSsrcInfo)
  1473. : this._processRemoteRemoveSource(addOrRemoveSsrcInfo);
  1474. this._renegotiate(newRemoteSdp.raw)
  1475. .then(() => {
  1476. const newLocalSdp
  1477. = new SDP(this.peerconnection.localDescription.sdp);
  1478. logger.log(
  1479. `${logPrefix} - OK, SDPs: `, oldLocalSdp, newLocalSdp);
  1480. this.notifyMySSRCUpdate(oldLocalSdp, newLocalSdp);
  1481. finishedCallback();
  1482. }, error => {
  1483. logger.error(`${logPrefix} failed:`, error);
  1484. finishedCallback(error);
  1485. });
  1486. };
  1487. // Queue and execute
  1488. this.modificationQueue.push(workFunction);
  1489. }
  1490. /**
  1491. * Takes in a jingle offer iq, returns the new sdp offer
  1492. * @param {jquery xml element} offerIq the incoming offer
  1493. * @returns {SDP object} the jingle offer translated to SDP
  1494. */
  1495. _processNewJingleOfferIq(offerIq) {
  1496. const remoteSdp = new SDP('');
  1497. if (this.webrtcIceTcpDisable) {
  1498. remoteSdp.removeTcpCandidates = true;
  1499. }
  1500. if (this.webrtcIceUdpDisable) {
  1501. remoteSdp.removeUdpCandidates = true;
  1502. }
  1503. if (this.failICE) {
  1504. remoteSdp.failICE = true;
  1505. }
  1506. remoteSdp.fromJingle(offerIq);
  1507. this.readSsrcInfo($(offerIq).find('>content'));
  1508. return remoteSdp;
  1509. }
  1510. /**
  1511. * Remove the given ssrc lines from the current remote sdp
  1512. * @param {list} removeSsrcInfo a list of SDP line strings that
  1513. * should be removed from the remote SDP
  1514. * @returns type {SDP Object} the new remote SDP (after removing the lines
  1515. * in removeSsrcInfo
  1516. */
  1517. _processRemoteRemoveSource(removeSsrcInfo) {
  1518. const remoteSdp = browser.usesPlanB()
  1519. ? new SDP(this.peerconnection.remoteDescription.sdp)
  1520. : new SDP(this.peerconnection.peerconnection.remoteDescription.sdp);
  1521. removeSsrcInfo.forEach((lines, idx) => {
  1522. // eslint-disable-next-line no-param-reassign
  1523. lines = lines.split('\r\n');
  1524. lines.pop(); // remove empty last element;
  1525. if (browser.usesPlanB()) {
  1526. lines.forEach(line => {
  1527. remoteSdp.media[idx]
  1528. = remoteSdp.media[idx].replace(`${line}\r\n`, '');
  1529. });
  1530. } else {
  1531. lines.forEach(line => {
  1532. const mid = remoteSdp.media.findIndex(mLine => mLine.includes(line));
  1533. if (mid > -1) {
  1534. remoteSdp.media[mid] = remoteSdp.media[mid].replace(`${line}\r\n`, '');
  1535. // Change the direction to "inactive" only on Firefox. Audio fails on
  1536. // Safari (possibly Chrome in unified plan mode) when we try to re-use inactive
  1537. // m-lines due to a webkit bug.
  1538. // https://bugs.webkit.org/show_bug.cgi?id=211181
  1539. if (browser.isFirefox()) {
  1540. remoteSdp.media[mid] = remoteSdp.media[mid].replace('a=sendonly', 'a=inactive');
  1541. }
  1542. }
  1543. });
  1544. }
  1545. });
  1546. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  1547. return remoteSdp;
  1548. }
  1549. /**
  1550. * Add the given ssrc lines to the current remote sdp
  1551. * @param {list} addSsrcInfo a list of SDP line strings that
  1552. * should be added to the remote SDP
  1553. * @returns type {SDP Object} the new remote SDP (after removing the lines
  1554. * in removeSsrcInfo
  1555. */
  1556. _processRemoteAddSource(addSsrcInfo) {
  1557. const remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
  1558. addSsrcInfo.forEach((lines, idx) => {
  1559. remoteSdp.media[idx] += lines;
  1560. });
  1561. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  1562. return remoteSdp;
  1563. }
  1564. /**
  1565. * Do a new o/a flow using the existing remote description
  1566. * @param {string} [optionalRemoteSdp] optional, raw remote sdp
  1567. * to use. If not provided, the remote sdp from the
  1568. * peerconnection will be used
  1569. * @returns {Promise} promise which resolves when the
  1570. * o/a flow is complete with no arguments or
  1571. * rejects with an error {string}
  1572. */
  1573. _renegotiate(optionalRemoteSdp) {
  1574. if (this.peerconnection.signalingState === 'closed') {
  1575. const error = new Error('Attempted to renegotiate in state closed');
  1576. this.room.eventEmitter.emit(XMPPEvents.RENEGOTIATION_FAILED, error, this);
  1577. return Promise.reject(error);
  1578. }
  1579. const remoteSdp
  1580. = optionalRemoteSdp || this.peerconnection.remoteDescription.sdp;
  1581. if (!remoteSdp) {
  1582. const error = new Error(`Can not renegotiate without remote description, current state: ${this.state}`);
  1583. this.room.eventEmitter.emit(XMPPEvents.RENEGOTIATION_FAILED, error, this);
  1584. return Promise.reject(error);
  1585. }
  1586. const remoteDescription = new RTCSessionDescription({
  1587. type: this.isInitiator ? 'answer' : 'offer',
  1588. sdp: remoteSdp
  1589. });
  1590. const promise = this.isInitiator
  1591. ? this._initiatorRenegotiate(remoteDescription)
  1592. : this._responderRenegotiate(remoteDescription);
  1593. return promise.then(() => {
  1594. // Publish the codec info to the other endpoints in the conference if it has changed
  1595. // as a result of the renegotiation (only on current active session).
  1596. const codec = this.peerconnection.getConfiguredVideoCodec();
  1597. if (this.currentCodec !== codec && this._localVideoActive) {
  1598. this.room.sendCodecInfoPresence(codec);
  1599. this.currentCodec = codec;
  1600. }
  1601. });
  1602. }
  1603. /**
  1604. * Renegotiate cycle implementation for the responder case.
  1605. * @param {object} remoteDescription the SDP object as defined by the WebRTC
  1606. * which will be used as remote description in the cycle.
  1607. * @private
  1608. */
  1609. _responderRenegotiate(remoteDescription) {
  1610. logger.debug('Renegotiate: setting remote description');
  1611. return this.peerconnection.setRemoteDescription(remoteDescription)
  1612. .then(() => {
  1613. logger.debug('Renegotiate: creating answer');
  1614. return this.peerconnection.createAnswer(this.mediaConstraints)
  1615. .then(answer => {
  1616. logger.debug('Renegotiate: setting local description');
  1617. return this.peerconnection.setLocalDescription(answer);
  1618. });
  1619. });
  1620. }
  1621. /**
  1622. * Renegotiate cycle implementation for the initiator's case.
  1623. * @param {object} remoteDescription the SDP object as defined by the WebRTC
  1624. * which will be used as remote description in the cycle.
  1625. * @private
  1626. */
  1627. _initiatorRenegotiate(remoteDescription) {
  1628. logger.debug('Renegotiate: creating offer');
  1629. return this.peerconnection.createOffer(this.mediaConstraints)
  1630. .then(offer => {
  1631. logger.debug('Renegotiate: setting local description');
  1632. return this.peerconnection.setLocalDescription(offer)
  1633. .then(() => {
  1634. logger.debug(
  1635. 'Renegotiate: setting remote description');
  1636. // eslint-disable-next-line max-len
  1637. return this.peerconnection.setRemoteDescription(remoteDescription);
  1638. });
  1639. });
  1640. }
  1641. /**
  1642. * Replaces <tt>oldTrack</tt> with <tt>newTrack</tt> and performs a single
  1643. * offer/answer cycle after both operations are done. Either
  1644. * <tt>oldTrack</tt> or <tt>newTrack</tt> can be null; replacing a valid
  1645. * <tt>oldTrack</tt> with a null <tt>newTrack</tt> effectively just removes
  1646. * <tt>oldTrack</tt>
  1647. * @param {JitsiLocalTrack|null} oldTrack the current track in use to be
  1648. * replaced
  1649. * @param {JitsiLocalTrack|null} newTrack the new track to use
  1650. * @returns {Promise} which resolves once the replacement is complete
  1651. * with no arguments or rejects with an error {string}
  1652. */
  1653. replaceTrack(oldTrack, newTrack) {
  1654. const workFunction = finishedCallback => {
  1655. const oldLocalSdp = this.peerconnection.localDescription.sdp;
  1656. if (browser.usesPlanB()) {
  1657. // NOTE the code below assumes that no more than 1 video track
  1658. // can be added to the peer connection.
  1659. // Transition from camera to desktop share
  1660. // or transition from one camera source to another.
  1661. if (this.peerconnection.options.capScreenshareBitrate
  1662. && oldTrack && newTrack && newTrack.isVideoTrack()) {
  1663. // Clearing current primary SSRC will make
  1664. // the SdpConsistency generate a new one which will result
  1665. // with:
  1666. // 1. source-remove for the old video stream.
  1667. // 2. source-add for the new video stream.
  1668. this.peerconnection.clearRecvonlySsrc();
  1669. }
  1670. // Transition from no video to video (unmute).
  1671. if (!oldTrack && newTrack && newTrack.isVideoTrack()) {
  1672. // Clearing current primary SSRC will make
  1673. // the SdpConsistency generate a new one which will result
  1674. // with:
  1675. // 1. source-remove for the recvonly
  1676. // 2. source-add for the new video stream
  1677. this.peerconnection.clearRecvonlySsrc();
  1678. // Transition from video to no video
  1679. } else if (oldTrack && oldTrack.isVideoTrack() && !newTrack) {
  1680. // Clearing current primary SSRC and generating the recvonly
  1681. // will result in:
  1682. // 1. source-remove for the old video stream
  1683. // 2. source-add for the recvonly stream
  1684. this.peerconnection.clearRecvonlySsrc();
  1685. this.peerconnection.generateRecvonlySsrc();
  1686. }
  1687. }
  1688. this.peerconnection.replaceTrack(oldTrack, newTrack)
  1689. .then(shouldRenegotiate => {
  1690. let promise = Promise.resolve();
  1691. if (shouldRenegotiate
  1692. && (oldTrack || newTrack)
  1693. && this.state === JingleSessionState.ACTIVE) {
  1694. promise = this._renegotiate().then(() => {
  1695. const newLocalSDP = new SDP(this.peerconnection.localDescription.sdp);
  1696. this.notifyMySSRCUpdate(new SDP(oldLocalSdp), newLocalSDP);
  1697. });
  1698. }
  1699. return promise.then(() => {
  1700. if (newTrack && newTrack.isVideoTrack()) {
  1701. // FIXME set all sender parameters in one go?
  1702. // Set the degradation preference on the new video sender.
  1703. return this.peerconnection.setSenderVideoDegradationPreference()
  1704. // Apply the cached video constraints on the new video sender.
  1705. .then(() => this.peerconnection.setSenderVideoConstraint())
  1706. .then(() => this.peerconnection.setMaxBitRate());
  1707. }
  1708. });
  1709. })
  1710. .then(() => finishedCallback(), error => finishedCallback(error));
  1711. };
  1712. return new Promise((resolve, reject) => {
  1713. this.modificationQueue.push(
  1714. workFunction,
  1715. error => {
  1716. if (error) {
  1717. logger.error('Replace track error:', error);
  1718. reject(error);
  1719. } else {
  1720. logger.info('Replace track done!');
  1721. resolve();
  1722. }
  1723. });
  1724. });
  1725. }
  1726. /**
  1727. * Parse the information from the xml sourceRemoveElem and translate it
  1728. * into sdp lines
  1729. * @param {jquery xml element} sourceRemoveElem the source-remove
  1730. * element from jingle
  1731. * @param {SDP object} currentRemoteSdp the current remote
  1732. * sdp (as of this new source-remove)
  1733. * @returns {list} a list of SDP line strings that should
  1734. * be removed from the remote SDP
  1735. */
  1736. _parseSsrcInfoFromSourceRemove(sourceRemoveElem, currentRemoteSdp) {
  1737. const removeSsrcInfo = [];
  1738. $(sourceRemoveElem).each((i1, content) => {
  1739. const name = $(content).attr('name');
  1740. let lines = '';
  1741. $(content)
  1742. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  1743. .each(function() {
  1744. /* eslint-disable no-invalid-this */
  1745. const semantics = this.getAttribute('semantics');
  1746. const ssrcs
  1747. = $(this)
  1748. .find('>source')
  1749. .map(function() {
  1750. return this.getAttribute('ssrc');
  1751. })
  1752. .get();
  1753. if (ssrcs.length) {
  1754. lines
  1755. += `a=ssrc-group:${semantics} ${
  1756. ssrcs.join(' ')}\r\n`;
  1757. }
  1758. /* eslint-enable no-invalid-this */
  1759. });
  1760. const ssrcs = [];
  1761. // handles both >source and >description>source versions
  1762. const tmp
  1763. = $(content).find(
  1764. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  1765. tmp.each(function() {
  1766. // eslint-disable-next-line no-invalid-this
  1767. const ssrc = $(this).attr('ssrc');
  1768. ssrcs.push(ssrc);
  1769. });
  1770. currentRemoteSdp.media.forEach((media, i2) => {
  1771. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  1772. return;
  1773. }
  1774. if (!removeSsrcInfo[i2]) {
  1775. removeSsrcInfo[i2] = '';
  1776. }
  1777. ssrcs.forEach(ssrc => {
  1778. const ssrcLines
  1779. = SDPUtil.findLines(media, `a=ssrc:${ssrc}`);
  1780. if (ssrcLines.length) {
  1781. removeSsrcInfo[i2] += `${ssrcLines.join('\r\n')}\r\n`;
  1782. }
  1783. });
  1784. removeSsrcInfo[i2] += lines;
  1785. });
  1786. });
  1787. return removeSsrcInfo;
  1788. }
  1789. /**
  1790. * Will print an error if there is any difference, between the SSRCs given
  1791. * in the <tt>oldSDP</tt> and the ones currently described in
  1792. * the peerconnection's local description.
  1793. * @param {string} operationName the operation's name which will be printed
  1794. * in the error message.
  1795. * @param {SDP} oldSDP the old local SDP which will be compared with
  1796. * the current one.
  1797. * @return {boolean} <tt>true</tt> if there was any change or <tt>false</tt>
  1798. * otherwise.
  1799. * @private
  1800. */
  1801. _verifyNoSSRCChanged(operationName, oldSDP) {
  1802. const currentLocalSDP
  1803. = new SDP(this.peerconnection.localDescription.sdp);
  1804. let sdpDiff = new SDPDiffer(oldSDP, currentLocalSDP);
  1805. const addedMedia = sdpDiff.getNewMedia();
  1806. if (Object.keys(addedMedia).length) {
  1807. logger.error(
  1808. `${this} - some SSRC were added on ${operationName}`,
  1809. addedMedia);
  1810. return false;
  1811. }
  1812. sdpDiff = new SDPDiffer(currentLocalSDP, oldSDP);
  1813. const removedMedia = sdpDiff.getNewMedia();
  1814. if (Object.keys(removedMedia).length) {
  1815. logger.error(
  1816. `${this} - some SSRCs were removed on ${operationName}`,
  1817. removedMedia);
  1818. return false;
  1819. }
  1820. return true;
  1821. }
  1822. /**
  1823. * Adds local track back to this session, as part of the unmute operation.
  1824. * @param {JitsiLocalTrack} track
  1825. * @return {Promise} a promise that will resolve once the local track is
  1826. * added back to this session and renegotiation succeeds. Will be rejected
  1827. * with a <tt>string</tt> that provides some error details in case something
  1828. * goes wrong.
  1829. */
  1830. addTrackAsUnmute(track) {
  1831. return this._addRemoveTrackAsMuteUnmute(
  1832. false /* add as unmute */, track)
  1833. .then(() => {
  1834. // Apply the video constraints, max bitrates and degradation preference on
  1835. // the video sender if needed.
  1836. if (track.isVideoTrack() && browser.doesVideoMuteByStreamRemove()) {
  1837. return this.setSenderMaxBitrates()
  1838. .then(() => this.setSenderVideoDegradationPreference())
  1839. .then(() => this.setSenderVideoConstraint());
  1840. }
  1841. });
  1842. }
  1843. /**
  1844. * Remove local track as part of the mute operation.
  1845. * @param {JitsiLocalTrack} track the local track to be removed
  1846. * @return {Promise} a promise which will be resolved once the local track
  1847. * is removed from this session and the renegotiation is performed.
  1848. * The promise will be rejected with a <tt>string</tt> that the describes
  1849. * the error if anything goes wrong.
  1850. */
  1851. removeTrackAsMute(track) {
  1852. return this._addRemoveTrackAsMuteUnmute(
  1853. true /* remove as mute */, track);
  1854. }
  1855. /**
  1856. * See {@link addTrackAsUnmute} and {@link removeTrackAsMute}.
  1857. * @param {boolean} isMute <tt>true</tt> for "remove as mute" or
  1858. * <tt>false</tt> for "add as unmute".
  1859. * @param {JitsiLocalTrack} track the track that will be added/removed
  1860. * @private
  1861. */
  1862. _addRemoveTrackAsMuteUnmute(isMute, track) {
  1863. if (!track) {
  1864. return Promise.reject('invalid "track" argument value');
  1865. }
  1866. const operationName = isMute ? 'removeTrackMute' : 'addTrackUnmute';
  1867. const workFunction = finishedCallback => {
  1868. const tpc = this.peerconnection;
  1869. if (!tpc) {
  1870. finishedCallback(
  1871. `Error: tried ${operationName} track with no active peer`
  1872. + 'connection');
  1873. return;
  1874. }
  1875. const oldLocalSDP = tpc.localDescription.sdp;
  1876. const operationPromise
  1877. = isMute
  1878. ? tpc.removeTrackMute(track)
  1879. : tpc.addTrackUnmute(track);
  1880. operationPromise
  1881. .then(shouldRenegotiate => {
  1882. if (shouldRenegotiate && oldLocalSDP && tpc.remoteDescription.sdp) {
  1883. this._renegotiate()
  1884. .then(() => {
  1885. // The results are ignored, as this check failure is not
  1886. // enough to fail the whole operation. It will log
  1887. // an error inside.
  1888. this._verifyNoSSRCChanged(
  1889. operationName, new SDP(oldLocalSDP));
  1890. finishedCallback();
  1891. });
  1892. } else {
  1893. finishedCallback();
  1894. }
  1895. },
  1896. finishedCallback /* will be called with an error */);
  1897. };
  1898. return new Promise((resolve, reject) => {
  1899. this.modificationQueue.push(
  1900. workFunction,
  1901. error => {
  1902. if (error) {
  1903. reject(error);
  1904. } else {
  1905. resolve();
  1906. }
  1907. });
  1908. });
  1909. }
  1910. /**
  1911. * Resumes or suspends media transfer over the underlying peer connection.
  1912. * @param {boolean} audioActive <tt>true</tt> to enable audio media
  1913. * transfer or <tt>false</tt> to suspend audio media transmission.
  1914. * @param {boolean} videoActive <tt>true</tt> to enable video media
  1915. * transfer or <tt>false</tt> to suspend video media transmission.
  1916. * @return {Promise} a <tt>Promise</tt> which will resolve once
  1917. * the operation is done. It will be rejected with an error description as
  1918. * a string in case anything goes wrong.
  1919. */
  1920. setMediaTransferActive(audioActive, videoActive) {
  1921. if (!this.peerconnection) {
  1922. return Promise.reject(
  1923. 'Can not modify transfer active state,'
  1924. + ' before "initialize" is called');
  1925. }
  1926. const logAudioStr = audioActive ? 'audio active' : 'audio inactive';
  1927. const logVideoStr = videoActive ? 'video active' : 'video inactive';
  1928. logger.info(`Queued make ${logVideoStr}, ${logAudioStr} task...`);
  1929. const workFunction = finishedCallback => {
  1930. const isSessionActive = this.state === JingleSessionState.ACTIVE;
  1931. // Because the value is modified on the queue it's impossible to
  1932. // check it's final value reliably prior to submitting the task.
  1933. // The rule here is that the last submitted state counts.
  1934. // Check the values here to avoid unnecessary renegotiation cycle.
  1935. const audioActiveChanged
  1936. = this.peerconnection.setAudioTransferActive(audioActive);
  1937. if (this._localVideoActive !== videoActive) {
  1938. this._localVideoActive = videoActive;
  1939. // Do only for P2P - Jicofo will reply with 'bad-request'
  1940. // We don't want to send 'content-modify', before the initial
  1941. // O/A (state === JingleSessionState.ACTIVE), because that will
  1942. // mess up video media direction in the remote SDP.
  1943. // 'content-modify' when processed only affects the media
  1944. // direction in the local SDP. We're doing that, because setting
  1945. // 'inactive' on video media in remote SDP will mess up our SDP
  1946. // translation chain (simulcast, RTX, video mute etc.).
  1947. if (this.isP2P && isSessionActive) {
  1948. this.sendContentModify();
  1949. }
  1950. }
  1951. const pcVideoActiveChanged
  1952. = this.peerconnection.setVideoTransferActive(
  1953. this._localVideoActive && this._remoteVideoActive);
  1954. // Will do the sRD/sLD cycle to update SDPs and adjust the media
  1955. // direction
  1956. if (isSessionActive
  1957. && (audioActiveChanged || pcVideoActiveChanged)) {
  1958. this._renegotiate()
  1959. .then(
  1960. finishedCallback,
  1961. finishedCallback /* will be called with an error */);
  1962. } else {
  1963. finishedCallback();
  1964. }
  1965. };
  1966. return new Promise((resolve, reject) => {
  1967. this.modificationQueue.push(
  1968. workFunction,
  1969. error => {
  1970. if (error) {
  1971. reject(error);
  1972. } else {
  1973. resolve();
  1974. }
  1975. });
  1976. });
  1977. }
  1978. /**
  1979. * Will put and execute on the queue a session modify task. Currently it
  1980. * only checks the senders attribute of the video content in order to figure
  1981. * out if the remote peer has video in the inactive state (stored locally
  1982. * in {@link _remoteVideoActive} - see field description for more info).
  1983. * @param {jQuery} jingleContents jQuery selector pointing to the jingle
  1984. * element of the session modify IQ.
  1985. * @see {@link _remoteVideoActive}
  1986. * @see {@link _localVideoActive}
  1987. */
  1988. modifyContents(jingleContents) {
  1989. const newVideoSenders
  1990. = JingleSessionPC.parseVideoSenders(jingleContents);
  1991. const newMaxFrameHeight
  1992. = JingleSessionPC.parseMaxFrameHeight(jingleContents);
  1993. // frame height is optional in our content-modify protocol
  1994. if (newMaxFrameHeight) {
  1995. logger.info(`${this} received remote max frame height: ${newMaxFrameHeight}`);
  1996. this.remoteRecvMaxFrameHeight = newMaxFrameHeight;
  1997. this.eventEmitter.emit(
  1998. MediaSessionEvents.REMOTE_VIDEO_CONSTRAINTS_CHANGED, this);
  1999. }
  2000. if (newVideoSenders === null) {
  2001. logger.error(
  2002. `${this} - failed to parse video "senders" attribute in`
  2003. + '"content-modify" action');
  2004. return;
  2005. }
  2006. const workFunction = finishedCallback => {
  2007. if (this._assertNotEnded('content-modify')
  2008. && this._modifyRemoteVideoActive(newVideoSenders)) {
  2009. // Will do the sRD/sLD cycle to update SDPs and adjust
  2010. // the media direction
  2011. this._renegotiate()
  2012. .then(finishedCallback, finishedCallback /* (error) */);
  2013. } else {
  2014. finishedCallback();
  2015. }
  2016. };
  2017. logger.debug(
  2018. `${this} queued "content-modify" task`
  2019. + `(video senders="${newVideoSenders}")`);
  2020. this.modificationQueue.push(
  2021. workFunction,
  2022. error => {
  2023. if (error) {
  2024. logger.error('"content-modify" failed', error);
  2025. }
  2026. });
  2027. }
  2028. /**
  2029. * Processes new value of remote video "senders" Jingle attribute and tries
  2030. * to apply it for {@link _remoteVideoActive}.
  2031. * @param {string} remoteVideoSenders the value of "senders" attribute of
  2032. * Jingle video content element advertised by remote peer.
  2033. * @return {boolean} <tt>true</tt> if the change affected state of
  2034. * the underlying peerconnection and renegotiation is required for
  2035. * the changes to take effect.
  2036. * @private
  2037. */
  2038. _modifyRemoteVideoActive(remoteVideoSenders) {
  2039. const isRemoteVideoActive
  2040. = remoteVideoSenders === 'both'
  2041. || (remoteVideoSenders === 'initiator' && this.isInitiator)
  2042. || (remoteVideoSenders === 'responder' && !this.isInitiator);
  2043. if (isRemoteVideoActive !== this._remoteVideoActive) {
  2044. logger.debug(
  2045. `${this} new remote video active: ${isRemoteVideoActive}`);
  2046. this._remoteVideoActive = isRemoteVideoActive;
  2047. }
  2048. return this.peerconnection.setVideoTransferActive(
  2049. this._localVideoActive && this._remoteVideoActive);
  2050. }
  2051. /**
  2052. * Figures out added/removed ssrcs and send update IQs.
  2053. * @param oldSDP SDP object for old description.
  2054. * @param newSDP SDP object for new description.
  2055. */
  2056. notifyMySSRCUpdate(oldSDP, newSDP) {
  2057. if (this.state !== JingleSessionState.ACTIVE) {
  2058. logger.warn(`Skipping SSRC update in '${this.state} ' state.`);
  2059. return;
  2060. }
  2061. if (!this.connection.connected) {
  2062. // The goal is to compare the oldest SDP with the latest one upon reconnect
  2063. if (!this._cachedOldLocalSdp) {
  2064. this._cachedOldLocalSdp = oldSDP;
  2065. }
  2066. this._cachedNewLocalSdp = newSDP;
  2067. logger.warn('Not sending SSRC update while the signaling is disconnected');
  2068. return;
  2069. }
  2070. this._cachedOldLocalSdp = undefined;
  2071. this._cachedNewLocalSdp = undefined;
  2072. // send source-remove IQ.
  2073. let sdpDiffer = new SDPDiffer(newSDP, oldSDP);
  2074. const remove = $iq({ to: this.remoteJid,
  2075. type: 'set' })
  2076. .c('jingle', {
  2077. xmlns: 'urn:xmpp:jingle:1',
  2078. action: 'source-remove',
  2079. initiator: this.initiatorJid,
  2080. sid: this.sid
  2081. }
  2082. );
  2083. const removedAnySSRCs = sdpDiffer.toJingle(remove);
  2084. if (removedAnySSRCs) {
  2085. logger.info('Sending source-remove', remove.tree());
  2086. this.connection.sendIQ(
  2087. remove, null,
  2088. this.newJingleErrorHandler(remove), IQ_TIMEOUT);
  2089. } else {
  2090. logger.log('removal not necessary');
  2091. }
  2092. // send source-add IQ.
  2093. sdpDiffer = new SDPDiffer(oldSDP, newSDP);
  2094. const add = $iq({ to: this.remoteJid,
  2095. type: 'set' })
  2096. .c('jingle', {
  2097. xmlns: 'urn:xmpp:jingle:1',
  2098. action: 'source-add',
  2099. initiator: this.initiatorJid,
  2100. sid: this.sid
  2101. }
  2102. );
  2103. const containsNewSSRCs = sdpDiffer.toJingle(add);
  2104. if (containsNewSSRCs) {
  2105. logger.info('Sending source-add', add.tree());
  2106. this.connection.sendIQ(
  2107. add, null, this.newJingleErrorHandler(add), IQ_TIMEOUT);
  2108. } else {
  2109. logger.log('addition not necessary');
  2110. }
  2111. }
  2112. /**
  2113. * Method returns function(errorResponse) which is a callback to be passed
  2114. * to Strophe connection.sendIQ method. An 'error' structure is created that
  2115. * is passed as 1st argument to given <tt>failureCb</tt>. The format of this
  2116. * structure is as follows:
  2117. * {
  2118. * code: {XMPP error response code}
  2119. * reason: {the name of XMPP error reason element or 'timeout' if the
  2120. * request has timed out within <tt>IQ_TIMEOUT</tt> milliseconds}
  2121. * source: {request.tree() that provides original request}
  2122. * session: {this JingleSessionPC.toString()}
  2123. * }
  2124. * @param request Strophe IQ instance which is the request to be dumped into
  2125. * the error structure
  2126. * @param failureCb function(error) called when error response was returned
  2127. * or when a timeout has occurred.
  2128. * @returns {function(this:JingleSessionPC)}
  2129. */
  2130. newJingleErrorHandler(request, failureCb) {
  2131. return errResponse => {
  2132. const error = {};
  2133. // Get XMPP error code and condition(reason)
  2134. const errorElSel = $(errResponse).find('error');
  2135. if (errorElSel.length) {
  2136. error.code = errorElSel.attr('code');
  2137. const errorReasonSel = $(errResponse).find('error :first');
  2138. if (errorReasonSel.length) {
  2139. error.reason = errorReasonSel[0].tagName;
  2140. }
  2141. const errorMsgSel = errorElSel.find('>text');
  2142. if (errorMsgSel.length) {
  2143. error.msg = errorMsgSel.text();
  2144. }
  2145. }
  2146. if (!errResponse) {
  2147. error.reason = 'timeout';
  2148. }
  2149. error.session = this.toString();
  2150. if (failureCb) {
  2151. failureCb(error);
  2152. } else if (this.state === JingleSessionState.ENDED
  2153. && error.reason === 'item-not-found') {
  2154. // When remote peer decides to terminate the session, but it
  2155. // still have few messages on the queue for processing,
  2156. // it will first send us 'session-terminate' (we enter ENDED)
  2157. // and then follow with 'item-not-found' for the queued requests
  2158. // We don't want to have that logged on error level.
  2159. logger.debug(`Jingle error: ${JSON.stringify(error)}`);
  2160. } else {
  2161. GlobalOnErrorHandler.callErrorHandler(
  2162. new Error(
  2163. `Jingle error: ${JSON.stringify(error)}`));
  2164. }
  2165. };
  2166. }
  2167. /**
  2168. * Returns the ice connection state for the peer connection.
  2169. * @returns the ice connection state for the peer connection.
  2170. */
  2171. getIceConnectionState() {
  2172. return this.peerconnection.getConnectionState();
  2173. }
  2174. /**
  2175. * Closes the peerconnection.
  2176. */
  2177. close() {
  2178. this.state = JingleSessionState.ENDED;
  2179. this.establishmentDuration = undefined;
  2180. if (this.peerconnection) {
  2181. this.peerconnection.onicecandidate = null;
  2182. this.peerconnection.oniceconnectionstatechange = null;
  2183. this.peerconnection.onnegotiationneeded = null;
  2184. this.peerconnection.onsignalingstatechange = null;
  2185. }
  2186. // Remove any pending tasks from the queue
  2187. this.modificationQueue.clear();
  2188. this.modificationQueue.push(finishCallback => {
  2189. // The signaling layer will remove it's listeners
  2190. this.signalingLayer.setChatRoom(null);
  2191. // do not try to close if already closed.
  2192. this.peerconnection && this.peerconnection.close();
  2193. finishCallback();
  2194. });
  2195. // No more tasks can go in after the close task
  2196. this.modificationQueue.shutdown();
  2197. }
  2198. /**
  2199. * Converts to string with minor summary.
  2200. * @return {string}
  2201. */
  2202. toString() {
  2203. return `JingleSessionPC[p2p=${this.isP2P},`
  2204. + `initiator=${this.isInitiator},sid=${this.sid}]`;
  2205. }
  2206. /**
  2207. * If the A/B test for suspend video is disabled according to the room's
  2208. * configuration, returns undefined. Otherwise returns a boolean which
  2209. * indicates whether the suspend video option should be enabled or disabled.
  2210. * @param {JingleSessionPCOptions} options - The config options.
  2211. */
  2212. _abtestSuspendVideoEnabled({ abTesting }) {
  2213. if (!abTesting || !abTesting.enableSuspendVideoTest) {
  2214. return;
  2215. }
  2216. // We want the two participants in a P2P call to agree on the value of
  2217. // the "suspend" option. We use the JID of the initiator, because it is
  2218. // both randomly selected and agreed upon by both participants.
  2219. const jid = this._getInitiatorJid();
  2220. return integerHash(jid) % 2 === 0;
  2221. }
  2222. }