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

JingleSessionPC.js 115KB

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