modified lib-jitsi-meet dev repo
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JingleSessionPC.js 120KB

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