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 112KB

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