Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

JingleSessionPC.js 115KB

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