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

JingleSessionPC.js 95KB

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