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

JingleSessionPC.js 114KB

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