Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

JingleSessionPC.js 119KB

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