Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

JingleSessionPC.js 119KB

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