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

JingleSessionPC.js 117KB

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