modified lib-jitsi-meet dev repo
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

JingleSessionPC.js 112KB

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