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

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