modified lib-jitsi-meet dev repo
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JingleSessionPC.js 119KB

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