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

JingleSessionPC.js 115KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896
  1. import { getLogger } from '@jitsi/logger';
  2. import $ from 'jquery';
  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. && state === 'stable'
  565. && remoteDescription
  566. && typeof remoteDescription.sdp === 'string') {
  567. logger.info(`${this} onnegotiationneeded fired on ${this.peerconnection}`);
  568. const workFunction = finishedCallback => {
  569. const oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  570. this._renegotiate()
  571. .then(() => this.peerconnection.configureSenderVideoEncodings())
  572. .then(() => {
  573. const newSdp = new SDP(this.peerconnection.localDescription.sdp);
  574. this.notifyMySSRCUpdate(oldSdp, newSdp);
  575. })
  576. .then(() => finishedCallback(), error => finishedCallback(error));
  577. };
  578. this.modificationQueue.push(
  579. workFunction,
  580. error => {
  581. if (error) {
  582. logger.error(`${this} onnegotiationneeded error`, error);
  583. } else {
  584. logger.debug(`${this} onnegotiationneeded executed - OK`);
  585. }
  586. });
  587. }
  588. };
  589. }
  590. /**
  591. * Remote preference for receive video max frame height.
  592. *
  593. * @returns {Number|undefined}
  594. */
  595. getRemoteRecvMaxFrameHeight() {
  596. if (this.isP2P) {
  597. return this.remoteRecvMaxFrameHeight;
  598. }
  599. return undefined;
  600. }
  601. /**
  602. * Remote preference for receive video max frame heights when source-name signaling is enabled.
  603. *
  604. * @returns {Map<string, number>|undefined}
  605. */
  606. getRemoteSourcesRecvMaxFrameHeight() {
  607. if (this.isP2P) {
  608. return this.remoteSourceMaxFrameHeights;
  609. }
  610. return undefined;
  611. }
  612. /**
  613. * Sends given candidate in Jingle 'transport-info' message.
  614. * @param {RTCIceCandidate} candidate the WebRTC ICE candidate instance
  615. * @private
  616. */
  617. sendIceCandidate(candidate) {
  618. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  619. if (candidate && candidate.candidate.length && !this.lasticecandidate) {
  620. const ice = SDPUtil.iceparams(localSDP.media[candidate.sdpMLineIndex], localSDP.session);
  621. const jcand = SDPUtil.candidateToJingle(candidate.candidate);
  622. if (!(ice && jcand)) {
  623. const errorMesssage = 'failed to get ice && jcand';
  624. GlobalOnErrorHandler.callErrorHandler(new Error(errorMesssage));
  625. logger.error(errorMesssage);
  626. return;
  627. }
  628. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  629. if (this.usedrip) {
  630. if (this.dripContainer.length === 0) {
  631. setTimeout(() => {
  632. if (this.dripContainer.length === 0) {
  633. return;
  634. }
  635. this.sendIceCandidates(this.dripContainer);
  636. this.dripContainer = [];
  637. }, ICE_CAND_GATHERING_TIMEOUT);
  638. }
  639. this.dripContainer.push(candidate);
  640. } else {
  641. this.sendIceCandidates([ candidate ]);
  642. }
  643. } else {
  644. logger.log(`${this} sendIceCandidate: last candidate`);
  645. // FIXME: remember to re-think in ICE-restart
  646. this.lasticecandidate = true;
  647. }
  648. }
  649. /**
  650. * Sends given candidates in Jingle 'transport-info' message.
  651. * @param {Array<RTCIceCandidate>} candidates an array of the WebRTC ICE
  652. * candidate instances
  653. * @private
  654. */
  655. sendIceCandidates(candidates) {
  656. if (!this._assertNotEnded('sendIceCandidates')) {
  657. return;
  658. }
  659. logger.log(`${this} sendIceCandidates ${JSON.stringify(candidates)}`);
  660. const cand = $iq({ to: this.remoteJid,
  661. type: 'set' })
  662. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  663. action: 'transport-info',
  664. initiator: this.initiatorJid,
  665. sid: this.sid });
  666. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  667. for (let mid = 0; mid < localSDP.media.length; mid++) {
  668. const cands = candidates.filter(el => el.sdpMLineIndex === mid);
  669. const mline
  670. = SDPUtil.parseMLine(localSDP.media[mid].split('\r\n')[0]);
  671. if (cands.length > 0) {
  672. const ice
  673. = SDPUtil.iceparams(localSDP.media[mid], localSDP.session);
  674. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  675. cand.c('content', {
  676. creator: this.initiatorJid === this.localJid
  677. ? 'initiator' : 'responder',
  678. name: cands[0].sdpMid ? cands[0].sdpMid : mline.media
  679. }).c('transport', ice);
  680. for (let i = 0; i < cands.length; i++) {
  681. const candidate
  682. = SDPUtil.candidateToJingle(cands[i].candidate);
  683. // Mangle ICE candidate if 'failICE' test option is enabled
  684. if (this.failICE) {
  685. candidate.ip = '1.1.1.1';
  686. }
  687. cand.c('candidate', candidate).up();
  688. }
  689. // add fingerprint
  690. const fingerprintLine
  691. = SDPUtil.findLine(
  692. localSDP.media[mid],
  693. 'a=fingerprint:', localSDP.session);
  694. if (fingerprintLine) {
  695. const tmp = SDPUtil.parseFingerprint(fingerprintLine);
  696. tmp.required = true;
  697. cand.c(
  698. 'fingerprint',
  699. { xmlns: 'urn:xmpp:jingle:apps:dtls:0' })
  700. .t(tmp.fingerprint);
  701. delete tmp.fingerprint;
  702. cand.attrs(tmp);
  703. cand.up();
  704. }
  705. cand.up(); // transport
  706. cand.up(); // content
  707. }
  708. }
  709. // might merge last-candidate notification into this, but it is called
  710. // a lot later. See webrtc issue #2340
  711. // logger.log('was this the last candidate', this.lasticecandidate);
  712. this.connection.sendIQ(
  713. cand, null, this.newJingleErrorHandler(cand), IQ_TIMEOUT);
  714. }
  715. /**
  716. * Sends Jingle 'session-info' message which includes custom Jitsi Meet
  717. * 'ice-state' element with the text value 'failed' to let Jicofo know
  718. * that the ICE connection has entered the failed state. It can then
  719. * choose to re-create JVB channels and send 'transport-replace' to
  720. * retry the connection.
  721. */
  722. sendIceFailedNotification() {
  723. const sessionInfo
  724. = $iq({
  725. to: this.remoteJid,
  726. type: 'set' })
  727. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  728. action: 'session-info',
  729. initiator: this.initiatorJid,
  730. sid: this.sid })
  731. .c('ice-state', { xmlns: 'http://jitsi.org/protocol/focus' })
  732. .t('failed')
  733. .up();
  734. this._bridgeSessionId
  735. && sessionInfo.c(
  736. 'bridge-session', {
  737. xmlns: 'http://jitsi.org/protocol/focus',
  738. id: this._bridgeSessionId
  739. });
  740. this.connection.sendIQ2(
  741. sessionInfo, {
  742. /*
  743. * This message will be often sent when there are connectivity
  744. * issues, so make it slightly longer than Prosody's default BOSH
  745. * inactivity timeout of 60 seconds.
  746. */
  747. timeout: 65
  748. })
  749. .catch(this.newJingleErrorHandler(sessionInfo));
  750. }
  751. /**
  752. * {@inheritDoc}
  753. */
  754. addIceCandidates(elem) {
  755. if (this.peerconnection.signalingState === 'closed') {
  756. logger.warn(`${this} Ignored add ICE candidate when in closed state`);
  757. return;
  758. }
  759. const iceCandidates = [];
  760. elem.find('>content>transport>candidate')
  761. .each((idx, candidate) => {
  762. let line = SDPUtil.candidateFromJingle(candidate);
  763. line = line.replace('\r\n', '').replace('a=', '');
  764. // FIXME this code does not care to handle
  765. // non-bundle transport
  766. const rtcCandidate = new RTCIceCandidate({
  767. sdpMLineIndex: 0,
  768. // FF comes up with more complex names like audio-23423,
  769. // Given that it works on both Chrome and FF without
  770. // providing it, let's leave it like this for the time
  771. // being...
  772. // sdpMid: 'audio',
  773. sdpMid: '',
  774. candidate: line
  775. });
  776. iceCandidates.push(rtcCandidate);
  777. });
  778. if (!iceCandidates.length) {
  779. logger.error(`${this} No ICE candidates to add ?`, elem[0] && elem[0].outerHTML);
  780. return;
  781. }
  782. // We want to have this task queued, so that we know it is executed,
  783. // after the initial sRD/sLD offer/answer cycle was done (based on
  784. // the assumption that candidates are spawned after the offer/answer
  785. // and XMPP preserves order).
  786. const workFunction = finishedCallback => {
  787. for (const iceCandidate of iceCandidates) {
  788. this.peerconnection.addIceCandidate(iceCandidate)
  789. .then(
  790. () => logger.debug(`${this} addIceCandidate ok!`),
  791. err => logger.error(`${this} addIceCandidate failed!`, err));
  792. }
  793. finishedCallback();
  794. logger.debug(`${this} ICE candidates task finished`);
  795. };
  796. logger.debug(`${this} Queued add (${iceCandidates.length}) ICE candidates task`);
  797. this.modificationQueue.push(workFunction);
  798. }
  799. /**
  800. *
  801. * @param contents
  802. */
  803. readSsrcInfo(contents) {
  804. const ssrcs = $(contents).find('>description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  805. ssrcs.each((i, ssrcElement) => {
  806. const ssrc = Number(ssrcElement.getAttribute('ssrc'));
  807. if (FeatureFlags.isSourceNameSignalingEnabled()) {
  808. if (ssrcElement.hasAttribute('name')) {
  809. const sourceName = ssrcElement.getAttribute('name');
  810. this._signalingLayer.setTrackSourceName(ssrc, sourceName);
  811. }
  812. }
  813. if (this.isP2P) {
  814. // In P2P all SSRCs are owner by the remote peer
  815. this._signalingLayer.setSSRCOwner(ssrc, Strophe.getResourceFromJid(this.remoteJid));
  816. } else {
  817. $(ssrcElement)
  818. .find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]')
  819. .each((i3, ssrcInfoElement) => {
  820. const owner = ssrcInfoElement.getAttribute('owner');
  821. if (owner?.length) {
  822. if (isNaN(ssrc) || ssrc < 0) {
  823. logger.warn(`${this} Invalid SSRC ${ssrc} value received for ${owner}`);
  824. } else {
  825. this._signalingLayer.setSSRCOwner(ssrc, getEndpointId(owner));
  826. }
  827. }
  828. });
  829. }
  830. });
  831. }
  832. /**
  833. * Makes the underlying TraceablePeerConnection generate new SSRC for
  834. * the recvonly video stream.
  835. * @deprecated
  836. */
  837. generateRecvonlySsrc() {
  838. if (this.peerconnection) {
  839. this.peerconnection.generateRecvonlySsrc();
  840. } else {
  841. logger.error(`${this} Unable to generate recvonly SSRC - no peerconnection`);
  842. }
  843. }
  844. /**
  845. * Returns the video codec configured as the preferred codec on the peerconnection.
  846. */
  847. getConfiguredVideoCodec() {
  848. return this.peerconnection.getConfiguredVideoCodec();
  849. }
  850. /**
  851. * Accepts incoming Jingle 'session-initiate' and should send 'session-accept' in result.
  852. *
  853. * @param jingleOffer jQuery selector pointing to the jingle element of the offer IQ
  854. * @param success callback called when we accept incoming session successfully and receive RESULT packet to
  855. * 'session-accept' sent.
  856. * @param failure function(error) called if for any reason we fail to accept the incoming offer. 'error' argument
  857. * can be used to log some details about the error.
  858. * @param {Array<JitsiLocalTrack>} [localTracks] the optional list of the local tracks that will be added, before
  859. * the offer/answer cycle executes. We allow the localTracks to optionally be passed in so that the addition of the
  860. * local tracks and the processing of the initial offer can all be done atomically. We want to make sure that any
  861. * other operations which originate in the XMPP Jingle messages related with this session to be executed with an
  862. * assumption that the initial offer/answer cycle has been executed already.
  863. */
  864. acceptOffer(jingleOffer, success, failure, localTracks) {
  865. this.setOfferAnswerCycle(
  866. jingleOffer,
  867. () => {
  868. // FIXME we may not care about RESULT packet for session-accept
  869. // then we should either call 'success' here immediately or
  870. // modify sendSessionAccept method to do that
  871. this.sendSessionAccept(() => {
  872. success();
  873. this.room.eventEmitter.emit(XMPPEvents.SESSION_ACCEPT, this);
  874. // The first video track is added to the peerconnection and signaled as part of the session-accept.
  875. // Add secondary video tracks (that were already added to conference) to the peerconnection here.
  876. // This will happen when someone shares a secondary source to a two people call, the other user
  877. // leaves and joins the call again, a new peerconnection is created for p2p/jvb connection. At this
  878. // point, there are 2 video tracks which need to be signaled to the remote peer.
  879. const videoTracks = localTracks.filter(track => track.getType() === MediaType.VIDEO);
  880. videoTracks.length && videoTracks.splice(0, 1);
  881. if (FeatureFlags.isMultiStreamSupportEnabled() && videoTracks.length) {
  882. this.addTracks(videoTracks);
  883. }
  884. },
  885. error => {
  886. failure(error);
  887. this.room.eventEmitter.emit(XMPPEvents.SESSION_ACCEPT_ERROR, this, error);
  888. });
  889. },
  890. failure,
  891. localTracks);
  892. }
  893. /**
  894. * Creates an offer and sends Jingle 'session-initiate' to the remote peer.
  895. *
  896. * @param {Array<JitsiLocalTrack>} localTracks the local tracks that will be added, before the offer/answer cycle
  897. * executes (for the local track addition to be an atomic operation together with the offer/answer).
  898. */
  899. invite(localTracks = []) {
  900. if (!this.isInitiator) {
  901. throw new Error('Trying to invite from the responder session');
  902. }
  903. const workFunction = finishedCallback => {
  904. const addTracks = [];
  905. for (const track of localTracks) {
  906. addTracks.push(this.peerconnection.addTrack(track, this.isInitiator));
  907. }
  908. Promise.all(addTracks)
  909. .then(() => this.peerconnection.createOffer(this.mediaConstraints))
  910. .then(offerSdp => this.peerconnection.setLocalDescription(offerSdp))
  911. .then(() => {
  912. this.peerconnection.processLocalSdpForTransceiverInfo(localTracks);
  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. this.peerconnection.processLocalSdpForTransceiverInfo(localTracks);
  1045. if (this.state === JingleSessionState.PENDING) {
  1046. this.state = JingleSessionState.ACTIVE;
  1047. // #1 Sync up video transfer active/inactive only after the initial O/A cycle. We want to
  1048. // adjust the video media direction only in the local SDP and the Jingle contents direction
  1049. // included in the initial offer/answer is mapped to the remote SDP. Jingle 'content-modify'
  1050. // IQ is processed in a way that it will only modify local SDP when remote peer is no longer
  1051. // interested in receiving video content. Changing media direction in the remote SDP will mess
  1052. // up our SDP translation chain (simulcast, video mute, RTX etc.)
  1053. // #2 Sends the max frame height if it was set, before the session-initiate/accept
  1054. if (this.isP2P
  1055. && (!this._localVideoActive
  1056. || this.localRecvMaxFrameHeight
  1057. || this._sourceReceiverConstraints)) {
  1058. this.sendContentModify();
  1059. }
  1060. }
  1061. // Old local SDP will be available when we're setting answer for the first time, but not when offer
  1062. // and it's fine since we're generating an answer now it will contain all our SSRCs.
  1063. if (oldLocalSdp) {
  1064. const newLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  1065. this.notifyMySSRCUpdate(new SDP(oldLocalSdp), newLocalSdp);
  1066. }
  1067. })
  1068. .then(() => finishedCallback(), error => finishedCallback(error));
  1069. };
  1070. logger.debug(`${this} Queued setOfferAnswerCycle task`);
  1071. this.modificationQueue.push(
  1072. workFunction,
  1073. error => {
  1074. if (error) {
  1075. logger.error(`${this} setOfferAnswerCycle task failed: ${error}`);
  1076. failure(error);
  1077. } else {
  1078. logger.debug(`${this} setOfferAnswerCycle task done`);
  1079. success();
  1080. }
  1081. });
  1082. }
  1083. /**
  1084. * Updates the codecs on the peerconnection and initiates a renegotiation for the
  1085. * new codec config to take effect.
  1086. *
  1087. * @param {CodecMimeType} preferred the preferred codec.
  1088. * @param {CodecMimeType} disabled the codec that needs to be disabled.
  1089. */
  1090. setVideoCodecs(preferred = null, disabled = null) {
  1091. const current = this.peerconnection.getConfiguredVideoCodec();
  1092. if (this._assertNotEnded() && preferred !== current) {
  1093. logger.info(`${this} Switching video codec from ${current} to ${preferred}`);
  1094. this.peerconnection.setVideoCodecs(preferred, disabled);
  1095. // Initiate a renegotiate for the codec setting to take effect.
  1096. const workFunction = finishedCallback => {
  1097. this._renegotiate().then(
  1098. () => {
  1099. logger.debug(`${this} setVideoCodecs task is done`);
  1100. return finishedCallback();
  1101. }, error => {
  1102. logger.error(`${this} setVideoCodecs task failed: ${error}`);
  1103. return finishedCallback(error);
  1104. });
  1105. };
  1106. logger.debug(`${this} Queued setVideoCodecs task`);
  1107. // Queue and execute
  1108. this.modificationQueue.push(workFunction);
  1109. }
  1110. }
  1111. /* eslint-enable max-params */
  1112. /**
  1113. * Although it states "replace transport" it does accept full Jingle offer
  1114. * which should contain new ICE transport details.
  1115. * @param jingleOfferElem an element Jingle IQ that contains new offer and
  1116. * transport info.
  1117. * @param success callback called when we succeed to accept new offer.
  1118. * @param failure function(error) called when we fail to accept new offer.
  1119. */
  1120. replaceTransport(jingleOfferElem, success, failure) {
  1121. if (this.options.enableForcedReload) {
  1122. const sdp = new SDP(this.peerconnection.localDescription.sdp);
  1123. this.sendTransportAccept(sdp, success, failure);
  1124. this.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTARTED, this);
  1125. return;
  1126. }
  1127. this.room.eventEmitter.emit(XMPPEvents.ICE_RESTARTING, this);
  1128. // We need to first reject the 'data' section to have the SCTP stack
  1129. // cleaned up to signal the known data channel is now invalid. After
  1130. // that the original offer is set to have the SCTP connection
  1131. // established with the new bridge.
  1132. const originalOffer = jingleOfferElem.clone();
  1133. jingleOfferElem
  1134. .find('>content[name=\'data\']')
  1135. .attr('senders', 'rejected');
  1136. // Remove all remote sources in order to reset the client's state
  1137. // for the remote MediaStreams. When a conference is moved to
  1138. // another bridge it will start streaming with a sequence number
  1139. // that is not in sync with the most recently seen by the client.
  1140. // The symptoms include frozen or black video and lots of "failed to
  1141. // unprotect SRTP packets" in Chrome logs.
  1142. jingleOfferElem
  1143. .find('>content>description>source')
  1144. .remove();
  1145. jingleOfferElem
  1146. .find('>content>description>ssrc-group')
  1147. .remove();
  1148. // On the JVB it's not a real ICE restart and all layers are re-initialized from scratch as Jicofo does
  1149. // the restart by re-allocating new channels. Chrome (or WebRTC stack) needs to have the DTLS transport layer
  1150. // reset to start a new handshake with fresh DTLS transport on the bridge. Make it think that the DTLS
  1151. // fingerprint has changed by setting an all zeros key.
  1152. const newFingerprint = jingleOfferElem.find('>content>transport>fingerprint');
  1153. newFingerprint.attr('hash', 'sha-1');
  1154. newFingerprint.text('00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00');
  1155. // First set an offer with a rejected 'data' section
  1156. this.setOfferAnswerCycle(
  1157. jingleOfferElem,
  1158. () => {
  1159. // Now set the original offer(with the 'data' section)
  1160. this.setOfferAnswerCycle(
  1161. originalOffer,
  1162. () => {
  1163. const localSDP
  1164. = new SDP(this.peerconnection.localDescription.sdp);
  1165. this.sendTransportAccept(localSDP, success, failure);
  1166. this.room.eventEmitter.emit(
  1167. XMPPEvents.ICE_RESTART_SUCCESS,
  1168. this,
  1169. originalOffer);
  1170. },
  1171. failure);
  1172. },
  1173. failure
  1174. );
  1175. }
  1176. /**
  1177. * Sends Jingle 'session-accept' message.
  1178. * @param {function()} success callback called when we receive 'RESULT'
  1179. * packet for the 'session-accept'
  1180. * @param {function(error)} failure called when we receive an error response
  1181. * or when the request has timed out.
  1182. * @private
  1183. */
  1184. sendSessionAccept(success, failure) {
  1185. // NOTE: since we're just reading from it, we don't need to be within
  1186. // the modification queue to access the local description
  1187. const localSDP = new SDP(this.peerconnection.localDescription.sdp);
  1188. const accept = $iq({ to: this.remoteJid,
  1189. type: 'set' })
  1190. .c('jingle', { xmlns: 'urn:xmpp:jingle:1',
  1191. action: 'session-accept',
  1192. initiator: this.initiatorJid,
  1193. responder: this.responderJid,
  1194. sid: this.sid });
  1195. if (this.webrtcIceTcpDisable) {
  1196. localSDP.removeTcpCandidates = true;
  1197. }
  1198. if (this.webrtcIceUdpDisable) {
  1199. localSDP.removeUdpCandidates = true;
  1200. }
  1201. if (this.failICE) {
  1202. localSDP.failICE = true;
  1203. }
  1204. localSDP.toJingle(
  1205. accept,
  1206. this.initiatorJid === this.localJid ? 'initiator' : 'responder');
  1207. logger.info(`${this} Sending session-accept`);
  1208. logger.debug(accept.tree());
  1209. this.connection.sendIQ(accept,
  1210. success,
  1211. this.newJingleErrorHandler(accept, error => {
  1212. failure(error);
  1213. // 'session-accept' is a critical timeout and we'll
  1214. // have to restart
  1215. this.room.eventEmitter.emit(
  1216. XMPPEvents.SESSION_ACCEPT_TIMEOUT, this);
  1217. }),
  1218. IQ_TIMEOUT);
  1219. // XXX Videobridge needs WebRTC's answer (ICE ufrag and pwd, DTLS
  1220. // fingerprint and setup) ASAP in order to start the connection
  1221. // establishment.
  1222. //
  1223. // FIXME Flushing the connection at this point triggers an issue with
  1224. // BOSH request handling in Prosody on slow connections.
  1225. //
  1226. // The problem is that this request will be quite large and it may take
  1227. // time before it reaches Prosody. In the meantime Strophe may decide
  1228. // to send the next one. And it was observed that a small request with
  1229. // 'transport-info' usually follows this one. It does reach Prosody
  1230. // before the previous one was completely received. 'rid' on the server
  1231. // is increased and Prosody ignores the request with 'session-accept'.
  1232. // It will never reach Jicofo and everything in the request table is
  1233. // lost. Removing the flush does not guarantee it will never happen, but
  1234. // makes it much less likely('transport-info' is bundled with
  1235. // 'session-accept' and any immediate requests).
  1236. //
  1237. // this.connection.flush();
  1238. }
  1239. /**
  1240. * Will send 'content-modify' IQ in order to ask the remote peer to
  1241. * either stop or resume sending video media or to adjust sender's video constraints.
  1242. * @private
  1243. */
  1244. sendContentModify() {
  1245. const maxFrameHeight = this.localRecvMaxFrameHeight;
  1246. const senders = this._localVideoActive ? 'both' : 'none';
  1247. let sessionModify
  1248. = $iq({
  1249. to: this.remoteJid,
  1250. type: 'set'
  1251. })
  1252. .c('jingle', {
  1253. xmlns: 'urn:xmpp:jingle:1',
  1254. action: 'content-modify',
  1255. initiator: this.initiatorJid,
  1256. sid: this.sid
  1257. })
  1258. .c('content', {
  1259. name: MediaType.VIDEO,
  1260. senders
  1261. });
  1262. if (typeof maxFrameHeight !== 'undefined') {
  1263. sessionModify = sessionModify
  1264. .c('max-frame-height', { xmlns: 'http://jitsi.org/jitmeet/video' })
  1265. .t(maxFrameHeight);
  1266. logger.info(`${this} sending content-modify, video senders: ${senders},`
  1267. + ` max frame height: ${maxFrameHeight}`);
  1268. }
  1269. if (typeof this._sourceReceiverConstraints !== 'undefined') {
  1270. this._sourceReceiverConstraints.forEach((maxHeight, sourceName) => {
  1271. sessionModify
  1272. .c('source-frame-height', { xmlns: 'http://jitsi.org/jitmeet/video' })
  1273. .attrs({
  1274. sourceName,
  1275. maxHeight
  1276. });
  1277. sessionModify.up();
  1278. logger.info(`${this} sending content-modify for source-name: ${sourceName}, maxHeight: ${maxHeight}`);
  1279. });
  1280. }
  1281. logger.debug(sessionModify.tree());
  1282. this.connection.sendIQ(
  1283. sessionModify,
  1284. null,
  1285. this.newJingleErrorHandler(sessionModify),
  1286. IQ_TIMEOUT);
  1287. }
  1288. /**
  1289. * Adjust the preference for max video frame height that the local party is willing to receive. Signals
  1290. * the remote party.
  1291. *
  1292. * @param {Number} maxFrameHeight - the new value to set.
  1293. * @param {Map<string, number>} sourceReceiverConstraints - The receiver constraints per source.
  1294. */
  1295. setReceiverVideoConstraint(maxFrameHeight, sourceReceiverConstraints) {
  1296. logger.info(`${this} setReceiverVideoConstraint - max frame height: ${maxFrameHeight}`
  1297. + ` sourceReceiverConstraints: ${sourceReceiverConstraints}`);
  1298. if (FeatureFlags.isSourceNameSignalingEnabled()) {
  1299. this._sourceReceiverConstraints = sourceReceiverConstraints;
  1300. } else {
  1301. this.localRecvMaxFrameHeight = maxFrameHeight;
  1302. }
  1303. if (this.isP2P) {
  1304. // Tell the remote peer about our receive constraint. If Jingle session is not yet active the state will
  1305. // be synced after offer/answer.
  1306. if (this.state === JingleSessionState.ACTIVE) {
  1307. this.sendContentModify();
  1308. }
  1309. }
  1310. }
  1311. /**
  1312. * Sends Jingle 'transport-accept' message which is a response to
  1313. * 'transport-replace'.
  1314. * @param localSDP the 'SDP' object with local session description
  1315. * @param success callback called when we receive 'RESULT' packet for
  1316. * 'transport-replace'
  1317. * @param failure function(error) called when we receive an error response
  1318. * or when the request has timed out.
  1319. * @private
  1320. */
  1321. sendTransportAccept(localSDP, success, failure) {
  1322. const transportAccept = $iq({ to: this.remoteJid,
  1323. type: 'set' })
  1324. .c('jingle', {
  1325. xmlns: 'urn:xmpp:jingle:1',
  1326. action: 'transport-accept',
  1327. initiator: this.initiatorJid,
  1328. sid: this.sid
  1329. });
  1330. localSDP.media.forEach((medialines, idx) => {
  1331. const mline = SDPUtil.parseMLine(medialines.split('\r\n')[0]);
  1332. transportAccept.c('content',
  1333. {
  1334. creator:
  1335. this.initiatorJid === this.localJid
  1336. ? 'initiator'
  1337. : 'responder',
  1338. name: mline.media
  1339. }
  1340. );
  1341. localSDP.transportToJingle(idx, transportAccept);
  1342. transportAccept.up();
  1343. });
  1344. logger.info(`${this} Sending transport-accept`);
  1345. logger.debug(transportAccept.tree());
  1346. this.connection.sendIQ(transportAccept,
  1347. success,
  1348. this.newJingleErrorHandler(transportAccept, failure),
  1349. IQ_TIMEOUT);
  1350. }
  1351. /**
  1352. * Sends Jingle 'transport-reject' message which is a response to
  1353. * 'transport-replace'.
  1354. * @param success callback called when we receive 'RESULT' packet for
  1355. * 'transport-replace'
  1356. * @param failure function(error) called when we receive an error response
  1357. * or when the request has timed out.
  1358. *
  1359. * FIXME method should be marked as private, but there's some spaghetti that
  1360. * needs to be fixed prior doing that
  1361. */
  1362. sendTransportReject(success, failure) {
  1363. // Send 'transport-reject', so that the focus will
  1364. // know that we've failed
  1365. const transportReject = $iq({ to: this.remoteJid,
  1366. type: 'set' })
  1367. .c('jingle', {
  1368. xmlns: 'urn:xmpp:jingle:1',
  1369. action: 'transport-reject',
  1370. initiator: this.initiatorJid,
  1371. sid: this.sid
  1372. });
  1373. logger.info(`${this} Sending 'transport-reject'`);
  1374. logger.debug(transportReject.tree());
  1375. this.connection.sendIQ(transportReject,
  1376. success,
  1377. this.newJingleErrorHandler(transportReject, failure),
  1378. IQ_TIMEOUT);
  1379. }
  1380. /**
  1381. * Sets the resolution constraint on the local camera track.
  1382. * @param {number} maxFrameHeight - The user preferred max frame height.
  1383. * @param {string} sourceName - The source name of the track.
  1384. * @returns {Promise} promise that will be resolved when the operation is
  1385. * successful and rejected otherwise.
  1386. */
  1387. setSenderVideoConstraint(maxFrameHeight, sourceName = null) {
  1388. if (this._assertNotEnded()) {
  1389. logger.info(`${this} setSenderVideoConstraint: ${maxFrameHeight}, sourceName: ${sourceName}`);
  1390. const jitsiLocalTrack = sourceName
  1391. ? this.rtc.getLocalVideoTracks().find(track => track.getSourceName() === sourceName)
  1392. : this.rtc.getLocalVideoTrack();
  1393. return this.peerconnection.setSenderVideoConstraints(maxFrameHeight, jitsiLocalTrack);
  1394. }
  1395. return Promise.resolve();
  1396. }
  1397. /**
  1398. * @inheritDoc
  1399. */
  1400. terminate(success, failure, options) {
  1401. if (this.state === JingleSessionState.ENDED) {
  1402. return;
  1403. }
  1404. if (!options || Boolean(options.sendSessionTerminate)) {
  1405. const sessionTerminate
  1406. = $iq({
  1407. to: this.remoteJid,
  1408. type: 'set'
  1409. })
  1410. .c('jingle', {
  1411. xmlns: 'urn:xmpp:jingle:1',
  1412. action: 'session-terminate',
  1413. initiator: this.initiatorJid,
  1414. sid: this.sid
  1415. })
  1416. .c('reason')
  1417. .c((options && options.reason) || 'success')
  1418. .up();
  1419. if (options && options.reasonDescription) {
  1420. sessionTerminate
  1421. .c('text')
  1422. .t(options.reasonDescription)
  1423. .up()
  1424. .up();
  1425. } else {
  1426. sessionTerminate.up();
  1427. }
  1428. this._bridgeSessionId
  1429. && sessionTerminate.c(
  1430. 'bridge-session', {
  1431. xmlns: 'http://jitsi.org/protocol/focus',
  1432. id: this._bridgeSessionId,
  1433. restart: options && options.requestRestart === true
  1434. }).up();
  1435. logger.info(`${this} Sending session-terminate`);
  1436. logger.debug(sessionTerminate.tree());
  1437. this.connection.sendIQ(
  1438. sessionTerminate,
  1439. success,
  1440. this.newJingleErrorHandler(sessionTerminate, failure),
  1441. IQ_TIMEOUT);
  1442. } else {
  1443. logger.info(`${this} Skipped sending session-terminate`);
  1444. }
  1445. // this should result in 'onTerminated' being called by strope.jingle.js
  1446. this.connection.jingle.terminate(this.sid);
  1447. }
  1448. /**
  1449. *
  1450. * @param reasonCondition
  1451. * @param reasonText
  1452. */
  1453. onTerminated(reasonCondition, reasonText) {
  1454. // Do something with reason and reasonCondition when we start to care
  1455. // this.reasonCondition = reasonCondition;
  1456. // this.reasonText = reasonText;
  1457. logger.info(`${this} Session terminated`, reasonCondition, reasonText);
  1458. this._xmppListeners.forEach(removeListener => removeListener());
  1459. this._xmppListeners = [];
  1460. if (this._removeSenderVideoConstraintsChangeListener) {
  1461. this._removeSenderVideoConstraintsChangeListener();
  1462. }
  1463. this.close();
  1464. }
  1465. /**
  1466. * Handles XMPP connection state changes.
  1467. *
  1468. * @param {XmppConnection.Status} status - The new status.
  1469. */
  1470. onXmppStatusChanged(status) {
  1471. if (status === XmppConnection.Status.CONNECTED && this._cachedOldLocalSdp) {
  1472. logger.info(`${this} Sending SSRC update on reconnect`);
  1473. this.notifyMySSRCUpdate(
  1474. this._cachedOldLocalSdp,
  1475. this._cachedNewLocalSdp);
  1476. }
  1477. }
  1478. /**
  1479. * Parse the information from the xml sourceAddElem and translate it
  1480. * into sdp lines
  1481. * @param {jquery xml element} sourceAddElem the source-add
  1482. * element from jingle
  1483. * @param {SDP object} currentRemoteSdp the current remote
  1484. * sdp (as of this new source-add)
  1485. * @returns {list} a list of SDP line strings that should
  1486. * be added to the remote SDP
  1487. */
  1488. _parseSsrcInfoFromSourceAdd(sourceAddElem, currentRemoteSdp) {
  1489. const addSsrcInfo = [];
  1490. const self = this;
  1491. $(sourceAddElem).each((i1, content) => {
  1492. const name = $(content).attr('name');
  1493. let lines = '';
  1494. $(content)
  1495. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  1496. .each(function() {
  1497. // eslint-disable-next-line no-invalid-this
  1498. const semantics = this.getAttribute('semantics');
  1499. const ssrcs
  1500. = $(this) // eslint-disable-line no-invalid-this
  1501. .find('>source')
  1502. .map(function() {
  1503. // eslint-disable-next-line no-invalid-this
  1504. return this.getAttribute('ssrc');
  1505. })
  1506. .get();
  1507. if (ssrcs.length) {
  1508. lines += `a=ssrc-group:${semantics} ${ssrcs.join(' ')}\r\n`;
  1509. }
  1510. });
  1511. // handles both >source and >description>source
  1512. const tmp
  1513. = $(content).find(
  1514. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  1515. /* eslint-disable no-invalid-this */
  1516. tmp.each(function() {
  1517. const ssrc = $(this).attr('ssrc');
  1518. if (currentRemoteSdp.containsSSRC(ssrc)) {
  1519. // Do not print the warning for unified plan p2p case since ssrcs are never removed from the SDP.
  1520. !(self.usesUnifiedPlan && self.isP2P)
  1521. && logger.warn(`${self} Source-add request for existing SSRC: ${ssrc}`);
  1522. return;
  1523. }
  1524. // eslint-disable-next-line newline-per-chained-call
  1525. $(this).find('>parameter').each(function() {
  1526. lines += `a=ssrc:${ssrc} ${$(this).attr('name')}`;
  1527. if ($(this).attr('value') && $(this).attr('value').length) {
  1528. lines += `:${$(this).attr('value')}`;
  1529. }
  1530. lines += '\r\n';
  1531. });
  1532. });
  1533. let midFound = false;
  1534. /* eslint-enable no-invalid-this */
  1535. currentRemoteSdp.media.forEach((media, i2) => {
  1536. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  1537. return;
  1538. }
  1539. if (!addSsrcInfo[i2]) {
  1540. addSsrcInfo[i2] = '';
  1541. }
  1542. addSsrcInfo[i2] += lines;
  1543. midFound = true;
  1544. });
  1545. // In p2p unified mode with multi-stream enabled, the new sources will have content name that doesn't exist
  1546. // in the current remote description. Add a new m-line for this newly signaled source.
  1547. if (!midFound && this.isP2P && FeatureFlags.isSourceNameSignalingEnabled()) {
  1548. addSsrcInfo[name] = lines;
  1549. }
  1550. });
  1551. return addSsrcInfo;
  1552. }
  1553. /**
  1554. * Handles a Jingle source-add message for this Jingle session.
  1555. * @param elem An array of Jingle "content" elements.
  1556. */
  1557. addRemoteStream(elem) {
  1558. this._addOrRemoveRemoteStream(true /* add */, elem);
  1559. }
  1560. /**
  1561. * Handles a Jingle source-remove message for this Jingle session.
  1562. * @param elem An array of Jingle "content" elements.
  1563. */
  1564. removeRemoteStream(elem) {
  1565. this._addOrRemoveRemoteStream(false /* remove */, elem);
  1566. }
  1567. /**
  1568. * Handles the deletion of SSRCs associated with a remote user from the remote description when the user leaves.
  1569. *
  1570. * @param {string} id Endpoint id of the participant that has left the call.
  1571. * @returns {void}
  1572. */
  1573. removeRemoteStreamsOnLeave(id) {
  1574. const workFunction = finishCallback => {
  1575. const removeSsrcInfo = this.peerconnection.getRemoteSourceInfoByParticipant(id);
  1576. if (removeSsrcInfo.length) {
  1577. const oldLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  1578. const newRemoteSdp = this._processRemoteRemoveSource(removeSsrcInfo);
  1579. this._renegotiate(newRemoteSdp.raw)
  1580. .then(() => {
  1581. const newLocalSDP = new SDP(this.peerconnection.localDescription.sdp);
  1582. this.notifyMySSRCUpdate(oldLocalSdp, newLocalSDP);
  1583. finishCallback();
  1584. })
  1585. .catch(err => finishCallback(err));
  1586. } else {
  1587. finishCallback();
  1588. }
  1589. };
  1590. logger.debug(`${this} Queued removeRemoteStreamsOnLeave task for participant ${id}`);
  1591. this.modificationQueue.push(
  1592. workFunction,
  1593. error => {
  1594. if (error) {
  1595. logger.error(`${this} removeRemoteStreamsOnLeave error:`, error);
  1596. } else {
  1597. logger.info(`${this} removeRemoteStreamsOnLeave done!`);
  1598. }
  1599. });
  1600. }
  1601. /**
  1602. * Handles either Jingle 'source-add' or 'source-remove' message for this
  1603. * Jingle session.
  1604. * @param {boolean} isAdd <tt>true</tt> for 'source-add' or <tt>false</tt>
  1605. * otherwise.
  1606. * @param {Array<Element>} elem an array of Jingle "content" elements.
  1607. * @private
  1608. */
  1609. _addOrRemoveRemoteStream(isAdd, elem) {
  1610. const logPrefix = isAdd ? 'addRemoteStream' : 'removeRemoteStream';
  1611. if (isAdd) {
  1612. this.readSsrcInfo(elem);
  1613. }
  1614. const workFunction = finishedCallback => {
  1615. if (!this.peerconnection.localDescription
  1616. || !this.peerconnection.localDescription.sdp) {
  1617. const errMsg = `${logPrefix} - localDescription not ready yet`;
  1618. logger.error(errMsg);
  1619. finishedCallback(errMsg);
  1620. return;
  1621. }
  1622. logger.log(`${this} Processing ${logPrefix}`);
  1623. const oldLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  1624. const sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  1625. const addOrRemoveSsrcInfo
  1626. = isAdd
  1627. ? this._parseSsrcInfoFromSourceAdd(elem, sdp)
  1628. : this._parseSsrcInfoFromSourceRemove(elem, sdp);
  1629. const newRemoteSdp
  1630. = isAdd
  1631. ? this._processRemoteAddSource(addOrRemoveSsrcInfo)
  1632. : this._processRemoteRemoveSource(addOrRemoveSsrcInfo);
  1633. const remoteDescription = new RTCSessionDescription({
  1634. type: 'offer',
  1635. sdp: newRemoteSdp.raw
  1636. });
  1637. // Always initiate a sRD->cA->sLD cycle when a remote source is added or removed irrespective of whether
  1638. // the local endpoint is an initiator or responder. Fixes bugs on Chromium where decoders are not created
  1639. // when sLD->cO->sRD cycle is initiated for p2p cases when remote sources are received.
  1640. this._responderRenegotiate(remoteDescription).then(() => {
  1641. const newLocalSdp = new SDP(this.peerconnection.localDescription.sdp);
  1642. logger.log(`${this} ${logPrefix} - OK`);
  1643. this.notifyMySSRCUpdate(oldLocalSdp, newLocalSdp);
  1644. finishedCallback();
  1645. }, error => {
  1646. logger.error(`${this} ${logPrefix} failed:`, error);
  1647. finishedCallback(error);
  1648. });
  1649. };
  1650. logger.debug(`${this} Queued ${logPrefix} task`);
  1651. // Queue and execute
  1652. this.modificationQueue.push(workFunction);
  1653. }
  1654. /**
  1655. * Takes in a jingle offer iq, returns the new sdp offer
  1656. * @param {jquery xml element} offerIq the incoming offer
  1657. * @returns {SDP object} the jingle offer translated to SDP
  1658. */
  1659. _processNewJingleOfferIq(offerIq) {
  1660. const remoteSdp = new SDP('');
  1661. if (this.webrtcIceTcpDisable) {
  1662. remoteSdp.removeTcpCandidates = true;
  1663. }
  1664. if (this.webrtcIceUdpDisable) {
  1665. remoteSdp.removeUdpCandidates = true;
  1666. }
  1667. if (this.failICE) {
  1668. remoteSdp.failICE = true;
  1669. }
  1670. remoteSdp.fromJingle(offerIq);
  1671. this.readSsrcInfo($(offerIq).find('>content'));
  1672. return remoteSdp;
  1673. }
  1674. /**
  1675. * Remove the given ssrc lines from the current remote sdp
  1676. * @param {list} removeSsrcInfo a list of SDP line strings that
  1677. * should be removed from the remote SDP
  1678. * @returns type {SDP Object} the new remote SDP (after removing the lines
  1679. * in removeSsrcInfo
  1680. */
  1681. _processRemoteRemoveSource(removeSsrcInfo) {
  1682. const remoteSdp = this.usesUnifiedPlan
  1683. ? new SDP(this.peerconnection.peerconnection.remoteDescription.sdp)
  1684. : new SDP(this.peerconnection.remoteDescription.sdp);
  1685. removeSsrcInfo.forEach((lines, idx) => {
  1686. // eslint-disable-next-line no-param-reassign
  1687. lines = lines.split('\r\n');
  1688. lines.pop(); // remove empty last element;
  1689. if (this.usesUnifiedPlan) {
  1690. let mid;
  1691. lines.forEach(line => {
  1692. mid = remoteSdp.media.findIndex(mLine => mLine.includes(line));
  1693. if (mid > -1) {
  1694. remoteSdp.media[mid] = remoteSdp.media[mid].replace(`${line}\r\n`, '');
  1695. if (this.isP2P) {
  1696. const mediaType = SDPUtil.parseMLine(remoteSdp.media[mid].split('\r\n')[0])?.media;
  1697. const desiredDirection = this.peerconnection.getDesiredMediaDirection(mediaType, false);
  1698. [ MediaDirection.SENDRECV, MediaDirection.SENDONLY ].forEach(direction => {
  1699. remoteSdp.media[mid] = remoteSdp.media[mid]
  1700. .replace(`a=${direction}`, `a=${desiredDirection}`);
  1701. });
  1702. } else {
  1703. // Jvb connections will have direction set to 'sendonly' for the remote sources.
  1704. remoteSdp.media[mid] = remoteSdp.media[mid]
  1705. .replace(`a=${MediaDirection.SENDONLY}`, `a=${MediaDirection.INACTIVE}`);
  1706. }
  1707. }
  1708. });
  1709. // Reject the m-line so that the browser removes the associated transceiver from the list of available
  1710. // transceivers. This will prevent the client from trying to re-use these inactive transceivers when
  1711. // additional video sources are added to the peerconnection.
  1712. if (mid > -1 && !this.isP2P && FeatureFlags.isMultiStreamSupportEnabled()) {
  1713. const { media, port } = SDPUtil.parseMLine(remoteSdp.media[mid].split('\r\n')[0]);
  1714. remoteSdp.media[mid] = remoteSdp.media[mid].replace(`m=${media} ${port}`, `m=${media} 0`);
  1715. }
  1716. } else {
  1717. lines.forEach(line => {
  1718. remoteSdp.media[idx] = remoteSdp.media[idx].replace(`${line}\r\n`, '');
  1719. });
  1720. }
  1721. });
  1722. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  1723. return remoteSdp;
  1724. }
  1725. /**
  1726. * Add the given ssrc lines to the current remote sdp
  1727. * @param {list} addSsrcInfo a list of SDP line strings that
  1728. * should be added to the remote SDP
  1729. * @returns type {SDP Object} the new remote SDP (after removing the lines
  1730. * in removeSsrcInfo
  1731. */
  1732. _processRemoteAddSource(addSsrcInfo) {
  1733. let remoteSdp = new SDP(this.peerconnection.remoteDescription.sdp);
  1734. // Add a new m-line in the remote description if the source info for a secondary video source is recceived from
  1735. // the remote p2p peer when multi-stream support is enabled.
  1736. if (addSsrcInfo.length > remoteSdp.media.length
  1737. && FeatureFlags.isSourceNameSignalingEnabled()
  1738. && this.isP2P
  1739. && this.usesUnifiedPlan) {
  1740. remoteSdp.addMlineForNewLocalSource(MediaType.VIDEO);
  1741. remoteSdp = new SDP(remoteSdp.raw);
  1742. }
  1743. addSsrcInfo.forEach((lines, idx) => {
  1744. remoteSdp.media[idx] += lines;
  1745. // Make sure to change the direction to 'sendrecv/sendonly' only for p2p connections. For jvb connections,
  1746. // a new m-line is added for the new remote sources.
  1747. if (this.isP2P && this.usesUnifiedPlan) {
  1748. const mediaType = SDPUtil.parseMLine(remoteSdp.media[idx].split('\r\n')[0])?.media;
  1749. const desiredDirection = this.peerconnection.getDesiredMediaDirection(mediaType, true);
  1750. [ MediaDirection.RECVONLY, MediaDirection.INACTIVE ].forEach(direction => {
  1751. remoteSdp.media[idx] = remoteSdp.media[idx]
  1752. .replace(`a=${direction}`, `a=${desiredDirection}`);
  1753. });
  1754. }
  1755. });
  1756. remoteSdp.raw = remoteSdp.session + remoteSdp.media.join('');
  1757. return remoteSdp;
  1758. }
  1759. /**
  1760. * Do a new o/a flow using the existing remote description
  1761. * @param {string} [optionalRemoteSdp] optional, raw remote sdp
  1762. * to use. If not provided, the remote sdp from the
  1763. * peerconnection will be used
  1764. * @returns {Promise} promise which resolves when the
  1765. * o/a flow is complete with no arguments or
  1766. * rejects with an error {string}
  1767. */
  1768. _renegotiate(optionalRemoteSdp) {
  1769. if (this.peerconnection.signalingState === 'closed') {
  1770. const error = new Error('Attempted to renegotiate in state closed');
  1771. this.room.eventEmitter.emit(XMPPEvents.RENEGOTIATION_FAILED, error, this);
  1772. return Promise.reject(error);
  1773. }
  1774. const remoteSdp
  1775. = optionalRemoteSdp || this.peerconnection.remoteDescription.sdp;
  1776. if (!remoteSdp) {
  1777. const error = new Error(`Can not renegotiate without remote description, current state: ${this.state}`);
  1778. this.room.eventEmitter.emit(XMPPEvents.RENEGOTIATION_FAILED, error, this);
  1779. return Promise.reject(error);
  1780. }
  1781. const remoteDescription = new RTCSessionDescription({
  1782. type: this.isInitiator ? 'answer' : 'offer',
  1783. sdp: remoteSdp
  1784. });
  1785. if (this.isInitiator) {
  1786. return this._initiatorRenegotiate(remoteDescription);
  1787. }
  1788. return this._responderRenegotiate(remoteDescription);
  1789. }
  1790. /**
  1791. * Renegotiate cycle implementation for the responder case.
  1792. * @param {object} remoteDescription the SDP object as defined by the WebRTC
  1793. * which will be used as remote description in the cycle.
  1794. * @private
  1795. */
  1796. _responderRenegotiate(remoteDescription) {
  1797. logger.debug(`${this} Renegotiate: setting remote description`);
  1798. return this.peerconnection.setRemoteDescription(remoteDescription)
  1799. .then(() => {
  1800. logger.debug(`${this} Renegotiate: creating answer`);
  1801. return this.peerconnection.createAnswer(this.mediaConstraints)
  1802. .then(answer => {
  1803. logger.debug(`${this} Renegotiate: setting local description`);
  1804. return this.peerconnection.setLocalDescription(answer);
  1805. });
  1806. });
  1807. }
  1808. /**
  1809. * Renegotiate cycle implementation for the initiator's case.
  1810. * @param {object} remoteDescription the SDP object as defined by the WebRTC
  1811. * which will be used as remote description in the cycle.
  1812. * @private
  1813. */
  1814. _initiatorRenegotiate(remoteDescription) {
  1815. logger.debug(`${this} Renegotiate: creating offer`);
  1816. return this.peerconnection.createOffer(this.mediaConstraints)
  1817. .then(offer => {
  1818. logger.debug(`${this} Renegotiate: setting local description`);
  1819. return this.peerconnection.setLocalDescription(offer)
  1820. .then(() => {
  1821. logger.debug(`${this} Renegotiate: setting remote description`);
  1822. // eslint-disable-next-line max-len
  1823. return this.peerconnection.setRemoteDescription(remoteDescription);
  1824. });
  1825. });
  1826. }
  1827. /**
  1828. * Adds a new track to the peerconnection. This method needs to be called only when a secondary JitsiLocalTrack is
  1829. * being added to the peerconnection for the first time.
  1830. *
  1831. * @param {Array<JitsiLocalTrack>} localTracks - Tracks to be added to the peer connection.
  1832. * @returns {Promise<void>} that resolves when the track is successfully added to the peerconnection, rejected
  1833. * otherwise.
  1834. */
  1835. addTracks(localTracks = null) {
  1836. if (!FeatureFlags.isMultiStreamSupportEnabled()
  1837. || !localTracks?.length
  1838. || localTracks.find(track => track.getType() !== MediaType.VIDEO)) {
  1839. return Promise.reject(new Error('Multiple tracks of the given media type are not supported'));
  1840. }
  1841. const replaceTracks = [];
  1842. const workFunction = finishedCallback => {
  1843. const oldLocalSDP = new SDP(this.peerconnection.localDescription.sdp);
  1844. const remoteSdp = new SDP(this.peerconnection.peerconnection.remoteDescription.sdp);
  1845. const recvOnlyTransceiver = this.peerconnection.peerconnection.getTransceivers()
  1846. .find(t => t.receiver.track.kind === MediaType.VIDEO
  1847. && t.direction === MediaDirection.RECVONLY
  1848. && t.currentDirection === MediaDirection.RECVONLY);
  1849. // Add transceivers by adding a new mline in the remote description for each track. Do not create a new
  1850. // m-line if a recv-only transceiver exists in the p2p case. The new track will be attached to the
  1851. // existing one in that case.
  1852. for (const track of localTracks) {
  1853. if (!this.isP2P || !recvOnlyTransceiver) {
  1854. remoteSdp.addMlineForNewLocalSource(track.getType());
  1855. }
  1856. }
  1857. const remoteDescription = new RTCSessionDescription({
  1858. type: 'offer',
  1859. sdp: remoteSdp.raw
  1860. });
  1861. // Always initiate a responder renegotiate since the new m-line is added to remote SDP.
  1862. this._responderRenegotiate(remoteDescription)
  1863. .then(() => {
  1864. // Replace the tracks on the newly generated transceivers.
  1865. for (const track of localTracks) {
  1866. replaceTracks.push(this.peerconnection.replaceTrack(null, track));
  1867. }
  1868. return Promise.all(replaceTracks);
  1869. })
  1870. // Trigger a renegotiation here since renegotiations are suppressed at TPC.replaceTrack for screenshare
  1871. // tracks. This is done here so that presence for screenshare tracks is sent before signaling.
  1872. .then(() => this._renegotiate())
  1873. .then(() => {
  1874. const newLocalSDP = new SDP(this.peerconnection.localDescription.sdp);
  1875. // Signal the new sources to the peer.
  1876. this.notifyMySSRCUpdate(oldLocalSDP, newLocalSDP);
  1877. finishedCallback();
  1878. })
  1879. .catch(error => finishedCallback(error));
  1880. };
  1881. return new Promise((resolve, reject) => {
  1882. logger.debug(`${this} Queued renegotiation after addTrack`);
  1883. this.modificationQueue.push(
  1884. workFunction,
  1885. error => {
  1886. if (error) {
  1887. logger.error(`${this} renegotiation after addTrack error`, error);
  1888. reject(error);
  1889. } else {
  1890. logger.debug(`${this} renegotiation after addTrack executed - OK`);
  1891. resolve();
  1892. }
  1893. });
  1894. });
  1895. }
  1896. /**
  1897. * Replaces <tt>oldTrack</tt> with <tt>newTrack</tt> and performs a single
  1898. * offer/answer cycle after both operations are done. Either
  1899. * <tt>oldTrack</tt> or <tt>newTrack</tt> can be null; replacing a valid
  1900. * <tt>oldTrack</tt> with a null <tt>newTrack</tt> effectively just removes
  1901. * <tt>oldTrack</tt>
  1902. * @param {JitsiLocalTrack|null} oldTrack the current track in use to be
  1903. * replaced
  1904. * @param {JitsiLocalTrack|null} newTrack the new track to use
  1905. * @returns {Promise} which resolves once the replacement is complete
  1906. * with no arguments or rejects with an error {string}
  1907. */
  1908. replaceTrack(oldTrack, newTrack) {
  1909. const workFunction = finishedCallback => {
  1910. logger.debug(`${this} replaceTrack worker started. oldTrack = ${oldTrack}, newTrack = ${newTrack}`);
  1911. const oldLocalSdp = this.peerconnection.localDescription.sdp;
  1912. if (!this.usesUnifiedPlan) {
  1913. // NOTE the code below assumes that no more than 1 video track
  1914. // can be added to the peer connection.
  1915. // Transition from camera to desktop share
  1916. // or transition from one camera source to another.
  1917. if (this.peerconnection.options.capScreenshareBitrate
  1918. && 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 old video stream.
  1923. // 2. source-add for the new video stream.
  1924. this.peerconnection.clearRecvonlySsrc();
  1925. }
  1926. // Transition from no video to video (unmute).
  1927. if (!oldTrack && newTrack && newTrack.isVideoTrack()) {
  1928. // Clearing current primary SSRC will make
  1929. // the SdpConsistency generate a new one which will result
  1930. // with:
  1931. // 1. source-remove for the recvonly
  1932. // 2. source-add for the new video stream
  1933. this.peerconnection.clearRecvonlySsrc();
  1934. // Transition from video to no video
  1935. } else if (oldTrack && oldTrack.isVideoTrack() && !newTrack) {
  1936. // Clearing current primary SSRC and generating the recvonly
  1937. // will result in:
  1938. // 1. source-remove for the old video stream
  1939. // 2. source-add for the recvonly stream
  1940. this.peerconnection.clearRecvonlySsrc();
  1941. this.peerconnection.generateRecvonlySsrc();
  1942. }
  1943. }
  1944. this.peerconnection.replaceTrack(oldTrack, newTrack)
  1945. .then(shouldRenegotiate => {
  1946. let promise = Promise.resolve();
  1947. logger.debug(`${this} TPC.replaceTrack finished. shouldRenegotiate = ${
  1948. shouldRenegotiate}, JingleSessionState = ${this.state}`);
  1949. if (shouldRenegotiate
  1950. && (oldTrack || newTrack)
  1951. && this.state === JingleSessionState.ACTIVE) {
  1952. promise = this._renegotiate().then(() => {
  1953. const newLocalSDP = new SDP(this.peerconnection.localDescription.sdp);
  1954. this.notifyMySSRCUpdate(new SDP(oldLocalSdp), newLocalSDP);
  1955. });
  1956. }
  1957. return promise.then(() => {
  1958. // Set the source name of the new track.
  1959. if (FeatureFlags.isSourceNameSignalingEnabled()
  1960. && oldTrack
  1961. && newTrack
  1962. && oldTrack.isVideoTrack()) {
  1963. newTrack.setSourceName(oldTrack.getSourceName());
  1964. }
  1965. if (newTrack?.isVideoTrack()) {
  1966. logger.debug(`${this} replaceTrack worker: configuring video stream`);
  1967. // Configure the video encodings after the track is replaced.
  1968. return this.peerconnection.configureSenderVideoEncodings(newTrack);
  1969. }
  1970. });
  1971. })
  1972. .then(() => finishedCallback(), error => finishedCallback(error));
  1973. };
  1974. return new Promise((resolve, reject) => {
  1975. logger.debug(`${this} Queued replaceTrack task. Old track = ${oldTrack}, new track = ${newTrack}`);
  1976. this.modificationQueue.push(
  1977. workFunction,
  1978. error => {
  1979. if (error) {
  1980. logger.error(`${this} Replace track error:`, error);
  1981. reject(error);
  1982. } else {
  1983. logger.info(`${this} Replace track done!`);
  1984. resolve();
  1985. }
  1986. });
  1987. });
  1988. }
  1989. /**
  1990. * Parse the information from the xml sourceRemoveElem and translate it
  1991. * into sdp lines
  1992. * @param {jquery xml element} sourceRemoveElem the source-remove
  1993. * element from jingle
  1994. * @param {SDP object} currentRemoteSdp the current remote
  1995. * sdp (as of this new source-remove)
  1996. * @returns {list} a list of SDP line strings that should
  1997. * be removed from the remote SDP
  1998. */
  1999. _parseSsrcInfoFromSourceRemove(sourceRemoveElem, currentRemoteSdp) {
  2000. const removeSsrcInfo = [];
  2001. $(sourceRemoveElem).each((i1, content) => {
  2002. const name = $(content).attr('name');
  2003. let lines = '';
  2004. $(content)
  2005. .find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]')
  2006. .each(function() {
  2007. /* eslint-disable no-invalid-this */
  2008. const semantics = this.getAttribute('semantics');
  2009. const ssrcs
  2010. = $(this)
  2011. .find('>source')
  2012. .map(function() {
  2013. return this.getAttribute('ssrc');
  2014. })
  2015. .get();
  2016. if (ssrcs.length) {
  2017. lines
  2018. += `a=ssrc-group:${semantics} ${
  2019. ssrcs.join(' ')}\r\n`;
  2020. }
  2021. /* eslint-enable no-invalid-this */
  2022. });
  2023. const ssrcs = [];
  2024. // handles both >source and >description>source versions
  2025. const tmp
  2026. = $(content).find(
  2027. 'source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  2028. tmp.each(function() {
  2029. // eslint-disable-next-line no-invalid-this
  2030. const ssrc = $(this).attr('ssrc');
  2031. ssrcs.push(ssrc);
  2032. });
  2033. currentRemoteSdp.media.forEach((media, i2) => {
  2034. if (!SDPUtil.findLine(media, `a=mid:${name}`)) {
  2035. return;
  2036. }
  2037. if (!removeSsrcInfo[i2]) {
  2038. removeSsrcInfo[i2] = '';
  2039. }
  2040. ssrcs.forEach(ssrc => {
  2041. const ssrcLines
  2042. = SDPUtil.findLines(media, `a=ssrc:${ssrc}`);
  2043. if (ssrcLines.length) {
  2044. removeSsrcInfo[i2] += `${ssrcLines.join('\r\n')}\r\n`;
  2045. }
  2046. });
  2047. removeSsrcInfo[i2] += lines;
  2048. });
  2049. });
  2050. return removeSsrcInfo;
  2051. }
  2052. /**
  2053. * Will print an error if there is any difference, between the SSRCs given
  2054. * in the <tt>oldSDP</tt> and the ones currently described in
  2055. * the peerconnection's local description.
  2056. * @param {string} operationName the operation's name which will be printed
  2057. * in the error message.
  2058. * @param {SDP} oldSDP the old local SDP which will be compared with
  2059. * the current one.
  2060. * @return {boolean} <tt>true</tt> if there was any change or <tt>false</tt>
  2061. * otherwise.
  2062. * @private
  2063. */
  2064. _verifyNoSSRCChanged(operationName, oldSDP) {
  2065. const currentLocalSDP
  2066. = new SDP(this.peerconnection.localDescription.sdp);
  2067. let sdpDiff = new SDPDiffer(oldSDP, currentLocalSDP);
  2068. const addedMedia = sdpDiff.getNewMedia();
  2069. if (Object.keys(addedMedia).length) {
  2070. logger.error(`${this} - some SSRC were added on ${operationName}`, addedMedia);
  2071. return false;
  2072. }
  2073. sdpDiff = new SDPDiffer(currentLocalSDP, oldSDP);
  2074. const removedMedia = sdpDiff.getNewMedia();
  2075. if (Object.keys(removedMedia).length) {
  2076. logger.error(`${this} - some SSRCs were removed on ${operationName}`, removedMedia);
  2077. return false;
  2078. }
  2079. return true;
  2080. }
  2081. /**
  2082. * Adds local track back to the peerconnection associated with this session.
  2083. * @param {JitsiLocalTrack} track
  2084. * @return {Promise} a promise that will resolve once the local track is added back to this session and
  2085. * renegotiation succeeds (if its warranted). Will be rejected with a <tt>string</tt> that provides some error
  2086. * details in case something goes wrong.
  2087. */
  2088. addTrackToPc(track) {
  2089. return this._addRemoveTrack(false /* add */, track)
  2090. .then(() => {
  2091. // Configure the video encodings after the track is unmuted. If the user joins the call muted and
  2092. // unmutes it the first time, all the parameters need to be configured.
  2093. if (track.isVideoTrack()) {
  2094. return this.peerconnection.configureSenderVideoEncodings(track);
  2095. }
  2096. });
  2097. }
  2098. /**
  2099. * Remove local track as part of the mute operation.
  2100. * @param {JitsiLocalTrack} track the local track to be removed
  2101. * @return {Promise} a promise which will be resolved once the local track
  2102. * is removed from this session and the renegotiation is performed.
  2103. * The promise will be rejected with a <tt>string</tt> that the describes
  2104. * the error if anything goes wrong.
  2105. */
  2106. removeTrackFromPc(track) {
  2107. return this._addRemoveTrack(true /* remove */, track);
  2108. }
  2109. /**
  2110. * See {@link addTrackToPc} and {@link removeTrackFromPc}.
  2111. * @param {boolean} isRemove <tt>true</tt> for "remove" operation or <tt>false</tt> for "add" operation.
  2112. * @param {JitsiLocalTrack} track the track that will be added/removed
  2113. * @private
  2114. */
  2115. _addRemoveTrack(isRemove, track) {
  2116. if (!track) {
  2117. return Promise.reject('invalid "track" argument value');
  2118. }
  2119. const operationName = isRemove ? 'removeTrack' : 'addTrack';
  2120. const workFunction = finishedCallback => {
  2121. const tpc = this.peerconnection;
  2122. if (!tpc) {
  2123. finishedCallback(`Error: tried ${operationName} track with no active peer connection`);
  2124. return;
  2125. }
  2126. const oldLocalSDP = tpc.localDescription.sdp;
  2127. const operationPromise
  2128. = isRemove
  2129. ? tpc.removeTrackFromPc(track)
  2130. : tpc.addTrackToPc(track);
  2131. operationPromise
  2132. .then(shouldRenegotiate => {
  2133. if (shouldRenegotiate && oldLocalSDP && tpc.remoteDescription.sdp) {
  2134. this._renegotiate()
  2135. .then(() => {
  2136. // The results are ignored, as this check failure is not enough to fail the whole
  2137. // operation. It will log an error inside for plan-b.
  2138. !this.usesUnifiedPlan && this._verifyNoSSRCChanged(operationName, new SDP(oldLocalSDP));
  2139. const newLocalSdp = tpc.localDescription.sdp;
  2140. // Signal the ssrc if an unmute operation results in a new ssrc being generated.
  2141. this.notifyMySSRCUpdate(new SDP(oldLocalSDP), new SDP(newLocalSdp));
  2142. finishedCallback();
  2143. });
  2144. } else {
  2145. finishedCallback();
  2146. }
  2147. },
  2148. finishedCallback /* will be called with an error */);
  2149. };
  2150. logger.debug(`${this} Queued ${operationName} task`);
  2151. return new Promise((resolve, reject) => {
  2152. this.modificationQueue.push(
  2153. workFunction,
  2154. error => {
  2155. if (error) {
  2156. logger.error(`${this} ${operationName} failed`);
  2157. reject(error);
  2158. } else {
  2159. logger.debug(`${this} ${operationName} done`);
  2160. resolve();
  2161. }
  2162. });
  2163. });
  2164. }
  2165. /**
  2166. * Resumes or suspends media transfer over the underlying peer connection.
  2167. * @param {boolean} audioActive <tt>true</tt> to enable audio media
  2168. * transfer or <tt>false</tt> to suspend audio media transmission.
  2169. * @param {boolean} videoActive <tt>true</tt> to enable video media
  2170. * transfer or <tt>false</tt> to suspend video media transmission.
  2171. * @return {Promise} a <tt>Promise</tt> which will resolve once
  2172. * the operation is done. It will be rejected with an error description as
  2173. * a string in case anything goes wrong.
  2174. */
  2175. setMediaTransferActive(audioActive, videoActive) {
  2176. if (!this.peerconnection) {
  2177. return Promise.reject(
  2178. 'Can not modify transfer active state,'
  2179. + ' before "initialize" is called');
  2180. }
  2181. const logAudioStr = audioActive ? 'audio active' : 'audio inactive';
  2182. const logVideoStr = videoActive ? 'video active' : 'video inactive';
  2183. logger.info(`${this} Queued make ${logVideoStr}, ${logAudioStr} task`);
  2184. const workFunction = finishedCallback => {
  2185. const isSessionActive = this.state === JingleSessionState.ACTIVE;
  2186. // Because the value is modified on the queue it's impossible to
  2187. // check it's final value reliably prior to submitting the task.
  2188. // The rule here is that the last submitted state counts.
  2189. // Check the values here to avoid unnecessary renegotiation cycle.
  2190. const audioActiveChanged
  2191. = this.peerconnection.setAudioTransferActive(audioActive);
  2192. if (this._localVideoActive !== videoActive) {
  2193. this._localVideoActive = videoActive;
  2194. // Do only for P2P - Jicofo will reply with 'bad-request'
  2195. // We don't want to send 'content-modify', before the initial
  2196. // O/A (state === JingleSessionState.ACTIVE), because that will
  2197. // mess up video media direction in the remote SDP.
  2198. // 'content-modify' when processed only affects the media
  2199. // direction in the local SDP. We're doing that, because setting
  2200. // 'inactive' on video media in remote SDP will mess up our SDP
  2201. // translation chain (simulcast, RTX, video mute etc.).
  2202. if (this.isP2P && isSessionActive) {
  2203. this.sendContentModify();
  2204. }
  2205. }
  2206. const pcVideoActiveChanged
  2207. = this.peerconnection.setVideoTransferActive(
  2208. this._localVideoActive && this._remoteVideoActive);
  2209. // Will do the sRD/sLD cycle to update SDPs and adjust the media
  2210. // direction
  2211. if (isSessionActive
  2212. && (audioActiveChanged || pcVideoActiveChanged)) {
  2213. this._renegotiate()
  2214. .then(
  2215. finishedCallback,
  2216. finishedCallback /* will be called with an error */);
  2217. } else {
  2218. finishedCallback();
  2219. }
  2220. };
  2221. return new Promise((resolve, reject) => {
  2222. this.modificationQueue.push(
  2223. workFunction,
  2224. error => {
  2225. if (error) {
  2226. logger.error(`${this} Make ${logVideoStr}, ${logAudioStr} task failed!`);
  2227. reject(error);
  2228. } else {
  2229. logger.debug(`${this} Make ${logVideoStr}, ${logAudioStr} task done!`);
  2230. resolve();
  2231. }
  2232. });
  2233. });
  2234. }
  2235. /**
  2236. * Will put and execute on the queue a session modify task. Currently it
  2237. * only checks the senders attribute of the video content in order to figure
  2238. * out if the remote peer has video in the inactive state (stored locally
  2239. * in {@link _remoteVideoActive} - see field description for more info).
  2240. * @param {jQuery} jingleContents jQuery selector pointing to the jingle
  2241. * element of the session modify IQ.
  2242. * @see {@link _remoteVideoActive}
  2243. * @see {@link _localVideoActive}
  2244. */
  2245. modifyContents(jingleContents) {
  2246. const newVideoSenders = JingleSessionPC.parseVideoSenders(jingleContents);
  2247. const newMaxFrameHeight = JingleSessionPC.parseMaxFrameHeight(jingleContents);
  2248. const sourceMaxFrameHeights = JingleSessionPC.parseSourceMaxFrameHeight(jingleContents);
  2249. // frame height is optional in our content-modify protocol
  2250. if (newMaxFrameHeight) {
  2251. logger.info(`${this} received remote max frame height: ${newMaxFrameHeight}`);
  2252. this.remoteRecvMaxFrameHeight = newMaxFrameHeight;
  2253. this.eventEmitter.emit(MediaSessionEvents.REMOTE_VIDEO_CONSTRAINTS_CHANGED, this);
  2254. }
  2255. if (sourceMaxFrameHeights) {
  2256. this.remoteSourceMaxFrameHeights = sourceMaxFrameHeights;
  2257. this.eventEmitter.emit(MediaSessionEvents.REMOTE_SOURCE_CONSTRAINTS_CHANGED, this, sourceMaxFrameHeights);
  2258. }
  2259. if (newVideoSenders === null) {
  2260. logger.error(`${this} - failed to parse video "senders" attribute in "content-modify" action`);
  2261. return;
  2262. }
  2263. const workFunction = finishedCallback => {
  2264. if (this._assertNotEnded() && this._modifyRemoteVideoActive(newVideoSenders)) {
  2265. // Will do the sRD/sLD cycle to update SDPs and adjust the media direction.
  2266. this._renegotiate()
  2267. .then(finishedCallback, finishedCallback /* (error) */);
  2268. } else {
  2269. finishedCallback();
  2270. }
  2271. };
  2272. logger.debug(`${this} queued "content-modify" task(video senders="${newVideoSenders}")`);
  2273. this.modificationQueue.push(
  2274. workFunction,
  2275. error => {
  2276. if (error) {
  2277. logger.error(`${this} "content-modify" failed`, error);
  2278. } else {
  2279. logger.debug(`${this} "content-modify" task(video senders="${newVideoSenders}") done`);
  2280. }
  2281. });
  2282. }
  2283. /**
  2284. * Processes new value of remote video "senders" Jingle attribute and tries
  2285. * to apply it for {@link _remoteVideoActive}.
  2286. * @param {string} remoteVideoSenders the value of "senders" attribute of
  2287. * Jingle video content element advertised by remote peer.
  2288. * @return {boolean} <tt>true</tt> if the change affected state of
  2289. * the underlying peerconnection and renegotiation is required for
  2290. * the changes to take effect.
  2291. * @private
  2292. */
  2293. _modifyRemoteVideoActive(remoteVideoSenders) {
  2294. const isRemoteVideoActive
  2295. = remoteVideoSenders === 'both'
  2296. || (remoteVideoSenders === 'initiator' && this.isInitiator)
  2297. || (remoteVideoSenders === 'responder' && !this.isInitiator);
  2298. if (isRemoteVideoActive !== this._remoteVideoActive) {
  2299. logger.debug(`${this} new remote video active: ${isRemoteVideoActive}`);
  2300. this._remoteVideoActive = isRemoteVideoActive;
  2301. }
  2302. return this.peerconnection.setVideoTransferActive(this._localVideoActive && this._remoteVideoActive);
  2303. }
  2304. /**
  2305. * Figures out added/removed ssrcs and send update IQs.
  2306. * @param oldSDP SDP object for old description.
  2307. * @param newSDP SDP object for new description.
  2308. */
  2309. notifyMySSRCUpdate(oldSDP, newSDP) {
  2310. if (this.state !== JingleSessionState.ACTIVE) {
  2311. logger.warn(`${this} Skipping SSRC update in '${this.state} ' state.`);
  2312. return;
  2313. }
  2314. if (!this.connection.connected) {
  2315. // The goal is to compare the oldest SDP with the latest one upon reconnect
  2316. if (!this._cachedOldLocalSdp) {
  2317. this._cachedOldLocalSdp = oldSDP;
  2318. }
  2319. this._cachedNewLocalSdp = newSDP;
  2320. logger.warn(`${this} Not sending SSRC update while the signaling is disconnected`);
  2321. return;
  2322. }
  2323. this._cachedOldLocalSdp = undefined;
  2324. this._cachedNewLocalSdp = undefined;
  2325. const getSignaledSourceInfo = sdpDiffer => {
  2326. const newMedia = sdpDiffer.getNewMedia();
  2327. let ssrcs = [];
  2328. let mediaType = null;
  2329. // It is assumed that sources are signaled one at a time.
  2330. Object.keys(newMedia).forEach(mediaIndex => {
  2331. const signaledSsrcs = Object.keys(newMedia[mediaIndex].ssrcs);
  2332. mediaType = newMedia[mediaIndex].mid;
  2333. if (signaledSsrcs?.length) {
  2334. ssrcs = ssrcs.concat(signaledSsrcs);
  2335. }
  2336. });
  2337. return {
  2338. mediaType,
  2339. ssrcs
  2340. };
  2341. };
  2342. // send source-remove IQ.
  2343. let sdpDiffer = new SDPDiffer(newSDP, oldSDP);
  2344. const remove = $iq({ to: this.remoteJid,
  2345. type: 'set' })
  2346. .c('jingle', {
  2347. xmlns: 'urn:xmpp:jingle:1',
  2348. action: 'source-remove',
  2349. initiator: this.initiatorJid,
  2350. sid: this.sid
  2351. }
  2352. );
  2353. sdpDiffer.toJingle(remove);
  2354. // context a common object for one run of ssrc update (source-add and source-remove) so we can match them if we
  2355. // need to
  2356. const ctx = {};
  2357. const removedSsrcInfo = getSignaledSourceInfo(sdpDiffer);
  2358. if (removedSsrcInfo.ssrcs.length) {
  2359. // Log only the SSRCs instead of the full IQ.
  2360. logger.info(`${this} Sending source-remove for ${removedSsrcInfo.mediaType}`
  2361. + ` ssrcs=${removedSsrcInfo.ssrcs}`);
  2362. this.connection.sendIQ(
  2363. remove,
  2364. () => {
  2365. this.room.eventEmitter.emit(XMPPEvents.SOURCE_REMOVE, this, ctx);
  2366. },
  2367. this.newJingleErrorHandler(remove, error => {
  2368. this.room.eventEmitter.emit(XMPPEvents.SOURCE_REMOVE_ERROR, this, error, ctx);
  2369. }),
  2370. IQ_TIMEOUT);
  2371. }
  2372. // send source-add IQ.
  2373. sdpDiffer = new SDPDiffer(oldSDP, newSDP);
  2374. const add = $iq({ to: this.remoteJid,
  2375. type: 'set' })
  2376. .c('jingle', {
  2377. xmlns: 'urn:xmpp:jingle:1',
  2378. action: 'source-add',
  2379. initiator: this.initiatorJid,
  2380. sid: this.sid
  2381. }
  2382. );
  2383. sdpDiffer.toJingle(add);
  2384. const addedSsrcInfo = getSignaledSourceInfo(sdpDiffer);
  2385. if (addedSsrcInfo.ssrcs.length) {
  2386. // Log only the SSRCs instead of the full IQ.
  2387. logger.info(`${this} Sending source-add for ${addedSsrcInfo.mediaType} ssrcs=${addedSsrcInfo.ssrcs}`);
  2388. this.connection.sendIQ(
  2389. add,
  2390. () => {
  2391. this.room.eventEmitter.emit(XMPPEvents.SOURCE_ADD, this, ctx);
  2392. },
  2393. this.newJingleErrorHandler(add, error => {
  2394. this.room.eventEmitter.emit(XMPPEvents.SOURCE_ADD_ERROR, this, error, addedSsrcInfo.mediaType, ctx);
  2395. }),
  2396. IQ_TIMEOUT);
  2397. }
  2398. }
  2399. /**
  2400. * Method returns function(errorResponse) which is a callback to be passed
  2401. * to Strophe connection.sendIQ method. An 'error' structure is created that
  2402. * is passed as 1st argument to given <tt>failureCb</tt>. The format of this
  2403. * structure is as follows:
  2404. * {
  2405. * code: {XMPP error response code}
  2406. * reason: {the name of XMPP error reason element or 'timeout' if the
  2407. * request has timed out within <tt>IQ_TIMEOUT</tt> milliseconds}
  2408. * source: {request.tree() that provides original request}
  2409. * session: {this JingleSessionPC.toString()}
  2410. * }
  2411. * @param request Strophe IQ instance which is the request to be dumped into
  2412. * the error structure
  2413. * @param failureCb function(error) called when error response was returned
  2414. * or when a timeout has occurred.
  2415. * @returns {function(this:JingleSessionPC)}
  2416. */
  2417. newJingleErrorHandler(request, failureCb) {
  2418. return errResponse => {
  2419. const error = {};
  2420. // Get XMPP error code and condition(reason)
  2421. const errorElSel = $(errResponse).find('error');
  2422. if (errorElSel.length) {
  2423. error.code = errorElSel.attr('code');
  2424. const errorReasonSel = $(errResponse).find('error :first');
  2425. if (errorReasonSel.length) {
  2426. error.reason = errorReasonSel[0].tagName;
  2427. }
  2428. const errorMsgSel = errorElSel.find('>text');
  2429. if (errorMsgSel.length) {
  2430. error.msg = errorMsgSel.text();
  2431. }
  2432. }
  2433. if (!errResponse) {
  2434. error.reason = 'timeout';
  2435. }
  2436. error.session = this.toString();
  2437. if (failureCb) {
  2438. failureCb(error);
  2439. } else if (this.state === JingleSessionState.ENDED
  2440. && error.reason === 'item-not-found') {
  2441. // When remote peer decides to terminate the session, but it
  2442. // still have few messages on the queue for processing,
  2443. // it will first send us 'session-terminate' (we enter ENDED)
  2444. // and then follow with 'item-not-found' for the queued requests
  2445. // We don't want to have that logged on error level.
  2446. logger.debug(`${this} Jingle error: ${JSON.stringify(error)}`);
  2447. } else {
  2448. GlobalOnErrorHandler.callErrorHandler(
  2449. new Error(
  2450. `Jingle error: ${JSON.stringify(error)}`));
  2451. }
  2452. };
  2453. }
  2454. /**
  2455. * Returns the ice connection state for the peer connection.
  2456. * @returns the ice connection state for the peer connection.
  2457. */
  2458. getIceConnectionState() {
  2459. return this.peerconnection.getConnectionState();
  2460. }
  2461. /**
  2462. * Closes the peerconnection.
  2463. */
  2464. close() {
  2465. this.state = JingleSessionState.ENDED;
  2466. this.establishmentDuration = undefined;
  2467. if (this.peerconnection) {
  2468. this.peerconnection.onicecandidate = null;
  2469. this.peerconnection.oniceconnectionstatechange = null;
  2470. this.peerconnection.onnegotiationneeded = null;
  2471. this.peerconnection.onsignalingstatechange = null;
  2472. }
  2473. logger.debug(`${this} Clearing modificationQueue`);
  2474. // Remove any pending tasks from the queue
  2475. this.modificationQueue.clear();
  2476. logger.debug(`${this} Queued PC close task`);
  2477. this.modificationQueue.push(finishCallback => {
  2478. // do not try to close if already closed.
  2479. this.peerconnection && this.peerconnection.close();
  2480. finishCallback();
  2481. logger.debug(`${this} PC close task done!`);
  2482. });
  2483. logger.debug(`${this} Shutdown modificationQueue!`);
  2484. // No more tasks can go in after the close task
  2485. this.modificationQueue.shutdown();
  2486. }
  2487. /**
  2488. * Converts to string with minor summary.
  2489. * @return {string}
  2490. */
  2491. toString() {
  2492. return `JingleSessionPC[session=${this.isP2P ? 'P2P' : 'JVB'},initiator=${this.isInitiator},sid=${this.sid}]`;
  2493. }
  2494. /**
  2495. * If the A/B test for suspend video is disabled according to the room's
  2496. * configuration, returns undefined. Otherwise returns a boolean which
  2497. * indicates whether the suspend video option should be enabled or disabled.
  2498. * @param {JingleSessionPCOptions} options - The config options.
  2499. */
  2500. _abtestSuspendVideoEnabled({ abTesting }) {
  2501. if (!abTesting || !abTesting.enableSuspendVideoTest) {
  2502. return;
  2503. }
  2504. // We want the two participants in a P2P call to agree on the value of
  2505. // the "suspend" option. We use the JID of the initiator, because it is
  2506. // both randomly selected and agreed upon by both participants.
  2507. const jid = this._getInitiatorJid();
  2508. return integerHash(jid) % 2 === 0;
  2509. }
  2510. }