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

TraceablePeerConnection.js 97KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677
  1. import { getLogger } from '@jitsi/logger';
  2. import { Interop } from '@jitsi/sdp-interop';
  3. import transform from 'sdp-transform';
  4. import { CodecMimeType } from '../../service/RTC/CodecMimeType';
  5. import { MediaDirection } from '../../service/RTC/MediaDirection';
  6. import { MediaType } from '../../service/RTC/MediaType';
  7. import RTCEvents from '../../service/RTC/RTCEvents';
  8. import * as SignalingEvents from '../../service/RTC/SignalingEvents';
  9. import { getSourceIndexFromSourceName } from '../../service/RTC/SignalingLayer';
  10. import { VIDEO_QUALITY_LEVELS } from '../../service/RTC/StandardVideoSettings';
  11. import { VideoType } from '../../service/RTC/VideoType';
  12. import { SS_DEFAULT_FRAME_RATE } from '../RTC/ScreenObtainer';
  13. import browser from '../browser';
  14. import FeatureFlags from '../flags/FeatureFlags';
  15. import LocalSdpMunger from '../sdp/LocalSdpMunger';
  16. import RtxModifier from '../sdp/RtxModifier';
  17. import SDP from '../sdp/SDP';
  18. import SDPUtil from '../sdp/SDPUtil';
  19. import SdpSimulcast from '../sdp/SdpSimulcast';
  20. import { SdpTransformWrap } from '../sdp/SdpTransformUtil';
  21. import JitsiRemoteTrack from './JitsiRemoteTrack';
  22. import RTC from './RTC';
  23. import { TPCUtils } from './TPCUtils';
  24. // FIXME SDP tools should end up in some kind of util module
  25. const logger = getLogger(__filename);
  26. const DEGRADATION_PREFERENCE_CAMERA = 'maintain-framerate';
  27. const DEGRADATION_PREFERENCE_DESKTOP = 'maintain-resolution';
  28. const DD_HEADER_EXT_URI
  29. = 'https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension';
  30. const DD_HEADER_EXT_ID = 11;
  31. /* eslint-disable max-params */
  32. /**
  33. * Creates new instance of 'TraceablePeerConnection'.
  34. *
  35. * @param {RTC} rtc the instance of <tt>RTC</tt> service
  36. * @param {number} id the peer connection id assigned by the parent RTC module.
  37. * @param {SignalingLayer} signalingLayer the signaling layer instance
  38. * @param {object} pcConfig The {@code RTCConfiguration} to use for the WebRTC peer connection.
  39. * @param {object} constraints WebRTC 'PeerConnection' constraints
  40. * @param {boolean} isP2P indicates whether or not the new instance will be used in a peer to peer connection.
  41. * @param {object} options <tt>TracablePeerConnection</tt> config options.
  42. * @param {Object} options.audioQuality - Quality settings to applied on the outbound audio stream.
  43. * @param {boolean} options.capScreenshareBitrate if set to true, lower layers will be disabled for screenshare.
  44. * @param {Array<CodecMimeType>} options.codecSettings - codec settings to be applied for video streams.
  45. * @param {boolean} options.disableSimulcast if set to 'true' will disable the simulcast.
  46. * @param {boolean} options.disableRtx if set to 'true' will disable the RTX.
  47. * @param {boolean} options.enableInsertableStreams set to true when the insertable streams constraints is to be
  48. * enabled on the PeerConnection.
  49. * @param {boolean} options.forceTurnRelay If set to true, the browser will generate only Relay ICE candidates.
  50. * @param {boolean} options.startSilent If set to 'true' no audio will be sent or received.
  51. * @param {Object} options.videoQuality - Quality settings to applied on the outbound video streams.
  52. *
  53. * FIXME: initially the purpose of TraceablePeerConnection was to be able to
  54. * debug the peer connection. Since many other responsibilities have been added
  55. * it would make sense to extract a separate class from it and come up with
  56. * a more suitable name.
  57. *
  58. * @constructor
  59. */
  60. export default function TraceablePeerConnection(
  61. rtc,
  62. id,
  63. signalingLayer,
  64. pcConfig,
  65. constraints,
  66. isP2P,
  67. options) {
  68. /**
  69. * Indicates whether or not this peer connection instance is actively
  70. * sending/receiving audio media. When set to <tt>false</tt> the SDP audio
  71. * media direction will be adjusted to 'inactive' in order to suspend
  72. * the transmission.
  73. * @type {boolean}
  74. * @private
  75. */
  76. this.audioTransferActive = !(options.startSilent === true);
  77. /**
  78. * The DTMF sender instance used to send DTMF tones.
  79. *
  80. * @type {RTCDTMFSender|undefined}
  81. * @private
  82. */
  83. this._dtmfSender = undefined;
  84. /**
  85. * @typedef {Object} TouchToneRequest
  86. * @property {string} tones - The DTMF tones string as defined by
  87. * {@code RTCDTMFSender.insertDTMF}, 'tones' argument.
  88. * @property {number} duration - The amount of time in milliseconds that
  89. * each DTMF should last.
  90. * @property {string} interToneGap - The length of time in miliseconds to
  91. * wait between tones.
  92. */
  93. /**
  94. * TouchToneRequests which are waiting to be played. This queue is filled
  95. * if there are touch tones currently being played.
  96. *
  97. * @type {Array<TouchToneRequest>}
  98. * @private
  99. */
  100. this._dtmfTonesQueue = [];
  101. /**
  102. * Indicates whether or not this peer connection instance is actively
  103. * sending/receiving video media. When set to <tt>false</tt> the SDP video
  104. * media direction will be adjusted to 'inactive' in order to suspend
  105. * the transmission.
  106. * @type {boolean}
  107. * @private
  108. */
  109. this.videoTransferActive = true;
  110. /**
  111. * The parent instance of RTC service which created this
  112. * <tt>TracablePeerConnection</tt>.
  113. * @type {RTC}
  114. */
  115. this.rtc = rtc;
  116. /**
  117. * The peer connection identifier assigned by the RTC module.
  118. * @type {number}
  119. */
  120. this.id = id;
  121. /**
  122. * Indicates whether or not this instance is used in a peer to peer
  123. * connection.
  124. * @type {boolean}
  125. */
  126. this.isP2P = isP2P;
  127. /**
  128. * The map holds remote tracks associated with this peer connection. It maps user's JID to media type and a set of
  129. * remote tracks.
  130. * @type {Map<string, Map<MediaType, Set<JitsiRemoteTrack>>>}
  131. */
  132. this.remoteTracks = new Map();
  133. /**
  134. * A map which stores local tracks mapped by {@link JitsiLocalTrack.rtcId}
  135. * @type {Map<number, JitsiLocalTrack>}
  136. */
  137. this.localTracks = new Map();
  138. /**
  139. * Keeps tracks of the WebRTC <tt>MediaStream</tt>s that have been added to
  140. * the underlying WebRTC PeerConnection.
  141. * @type {Array}
  142. * @private
  143. */
  144. this._addedStreams = [];
  145. /**
  146. * @typedef {Object} TPCGroupInfo
  147. * @property {string} semantics the SSRC groups semantics
  148. * @property {Array<number>} ssrcs group's SSRCs in order where the first
  149. * one is group's primary SSRC, the second one is secondary (RTX) and so
  150. * on...
  151. */
  152. /**
  153. * @typedef {Object} TPCSSRCInfo
  154. * @property {Array<number>} ssrcs an array which holds all track's SSRCs
  155. * @property {Array<TPCGroupInfo>} groups an array stores all track's SSRC
  156. * groups
  157. */
  158. /**
  159. * Holds the info about local track's SSRCs mapped per their
  160. * {@link JitsiLocalTrack.rtcId}
  161. * @type {Map<number, TPCSSRCInfo>}
  162. */
  163. this.localSSRCs = new Map();
  164. /**
  165. * The set of remote SSRCs seen so far.
  166. * Distinguishes new SSRCs from those that have been remapped.
  167. * @type {Set<number>}
  168. */
  169. this.remoteSSRCs = new Set();
  170. /**
  171. * Mapping of source-names and their associated SSRCs that have been signaled by the JVB.
  172. * @type {Map<string, number>}
  173. */
  174. this.remoteSources = new Map();
  175. /**
  176. * The local ICE username fragment for this session.
  177. */
  178. this.localUfrag = null;
  179. /**
  180. * The remote ICE username fragment for this session.
  181. */
  182. this.remoteUfrag = null;
  183. /**
  184. * The DTLS transport object for the PeerConnection.
  185. * Note: this assume only one shared transport exists because we bundled
  186. * all streams on the same underlying transport.
  187. */
  188. this._dtlsTransport = null;
  189. /**
  190. * The signaling layer which operates this peer connection.
  191. * @type {SignalingLayer}
  192. */
  193. this.signalingLayer = signalingLayer;
  194. // SignalingLayer listeners
  195. this._peerVideoTypeChanged = this._peerVideoTypeChanged.bind(this);
  196. this.signalingLayer.on(SignalingEvents.PEER_VIDEO_TYPE_CHANGED, this._peerVideoTypeChanged);
  197. this._peerMutedChanged = this._peerMutedChanged.bind(this);
  198. this.signalingLayer.on(SignalingEvents.PEER_MUTED_CHANGED, this._peerMutedChanged);
  199. this.options = options;
  200. // Setup SignalingLayer listeners for source-name based events.
  201. this.signalingLayer.on(SignalingEvents.SOURCE_MUTED_CHANGED,
  202. (sourceName, isMuted) => this._sourceMutedChanged(sourceName, isMuted));
  203. this.signalingLayer.on(SignalingEvents.SOURCE_VIDEO_TYPE_CHANGED,
  204. (sourceName, videoType) => this._sourceVideoTypeChanged(sourceName, videoType));
  205. // Make sure constraints is properly formatted in order to provide information about whether or not this
  206. // connection is P2P to rtcstats.
  207. const safeConstraints = constraints || {};
  208. safeConstraints.optional = safeConstraints.optional || [];
  209. // The `optional` parameter needs to be of type array, otherwise chrome will throw an error.
  210. // Firefox and Safari just ignore it.
  211. if (Array.isArray(safeConstraints.optional)) {
  212. safeConstraints.optional.push({ rtcStatsSFUP2P: this.isP2P });
  213. } else {
  214. logger.warn('Optional param is not an array, rtcstats p2p data is omitted.');
  215. }
  216. this.peerconnection = new RTCPeerConnection(pcConfig, safeConstraints);
  217. this.tpcUtils = new TPCUtils(this);
  218. this.updateLog = [];
  219. this.stats = {};
  220. this.statsinterval = null;
  221. /**
  222. * Flag used to indicate if low fps screenshare is desired.
  223. */
  224. this._capScreenshareBitrate = this.options.capScreenshareBitrate;
  225. /**
  226. * Codec preferences set for the peerconnection through config.js.
  227. */
  228. this.codecSettings = this.options.codecSettings;
  229. /**
  230. * Flag used to indicate if RTCRtpTransceiver#setCodecPreferences is to be used instead of SDP
  231. * munging for codec selection.
  232. */
  233. browser.supportsCodecPreferences()
  234. && logger.info('Using RTCRtpTransceiver#setCodecPreferences for codec selection');
  235. /**
  236. * Indicates whether an audio track has ever been added to the peer connection.
  237. */
  238. this._hasHadAudioTrack = false;
  239. /**
  240. * Indicates whether a video track has ever been added to the peer connection.
  241. */
  242. this._hasHadVideoTrack = false;
  243. /**
  244. * @type {number} The max number of stats to keep in this.stats. Limit to
  245. * 300 values, i.e. 5 minutes; set to 0 to disable
  246. */
  247. this.maxstats = options.maxstats;
  248. this.interop = new Interop();
  249. this.simulcast = new SdpSimulcast();
  250. /**
  251. * Munges local SDP provided to the Jingle Session in order to prevent from
  252. * sending SSRC updates on attach/detach and mute/unmute (for video).
  253. * @type {LocalSdpMunger}
  254. */
  255. this.localSdpMunger = new LocalSdpMunger(this, this.rtc.getLocalEndpointId());
  256. /**
  257. * TracablePeerConnection uses RTC's eventEmitter
  258. * @type {EventEmitter}
  259. */
  260. this.eventEmitter = rtc.eventEmitter;
  261. this.rtxModifier = new RtxModifier();
  262. /**
  263. * The height constraints to be applied on the sender per local video source (source name as the key).
  264. * @type {Map<string, number>}
  265. */
  266. this._senderMaxHeights = new Map();
  267. /**
  268. * Flag indicating bridge support for AV1 codec. On the bridge connection, it is supported only when support for
  269. * Dependency Descriptor header extensions is offered by Jicofo. H.264 simulcast is also possible when these
  270. * header extensions are negotiated.
  271. */
  272. this._supportsDDHeaderExt = false;
  273. /**
  274. * Holds the RTCRtpTransceiver mids that the local tracks are attached to, mapped per their
  275. * {@link JitsiLocalTrack.rtcId}.
  276. * @type {Map<string, string>}
  277. */
  278. this._localTrackTransceiverMids = new Map();
  279. // override as desired
  280. this.trace = (what, info) => {
  281. logger.trace(what, info);
  282. this.updateLog.push({
  283. time: new Date(),
  284. type: what,
  285. value: info || ''
  286. });
  287. };
  288. this.onicecandidate = null;
  289. this.peerconnection.onicecandidate = event => {
  290. this.trace(
  291. 'onicecandidate',
  292. JSON.stringify(event.candidate, null, ' '));
  293. if (this.onicecandidate !== null) {
  294. this.onicecandidate(event);
  295. }
  296. };
  297. this.onTrack = evt => {
  298. const stream = evt.streams[0];
  299. this._remoteTrackAdded(stream, evt.track, evt.transceiver);
  300. stream.addEventListener('removetrack', e => {
  301. this._remoteTrackRemoved(stream, e.track);
  302. });
  303. };
  304. this.peerconnection.addEventListener('track', this.onTrack);
  305. this.onsignalingstatechange = null;
  306. this.peerconnection.onsignalingstatechange = event => {
  307. this.trace('onsignalingstatechange', this.signalingState);
  308. if (this.onsignalingstatechange !== null) {
  309. this.onsignalingstatechange(event);
  310. }
  311. };
  312. this.oniceconnectionstatechange = null;
  313. this.peerconnection.oniceconnectionstatechange = event => {
  314. this.trace('oniceconnectionstatechange', this.iceConnectionState);
  315. if (this.oniceconnectionstatechange !== null) {
  316. this.oniceconnectionstatechange(event);
  317. }
  318. };
  319. this.onnegotiationneeded = null;
  320. this.peerconnection.onnegotiationneeded = event => {
  321. this.trace('onnegotiationneeded');
  322. if (this.onnegotiationneeded !== null) {
  323. this.onnegotiationneeded(event);
  324. }
  325. };
  326. this.onconnectionstatechange = null;
  327. this.peerconnection.onconnectionstatechange = event => {
  328. this.trace('onconnectionstatechange', this.connectionState);
  329. if (this.onconnectionstatechange !== null) {
  330. this.onconnectionstatechange(event);
  331. }
  332. };
  333. this.ondatachannel = null;
  334. this.peerconnection.ondatachannel = event => {
  335. this.trace('ondatachannel');
  336. if (this.ondatachannel !== null) {
  337. this.ondatachannel(event);
  338. }
  339. };
  340. if (this.maxstats) {
  341. this.statsinterval = window.setInterval(() => {
  342. this.getStats().then(stats => {
  343. if (typeof stats?.result === 'function') {
  344. const results = stats.result();
  345. for (let i = 0; i < results.length; ++i) {
  346. const res = results[i];
  347. res.names().forEach(name => {
  348. this._processStat(res, name, res.stat(name));
  349. });
  350. }
  351. } else {
  352. stats.forEach(r => this._processStat(r, '', r));
  353. }
  354. });
  355. }, 1000);
  356. }
  357. this._lastVideoSenderUpdatePromise = Promise.resolve();
  358. logger.info(`Create new ${this}`);
  359. }
  360. /* eslint-enable max-params */
  361. /**
  362. * Process stat and adds it to the array of stats we store.
  363. * @param report the current stats report.
  364. * @param name the name of the report, if available
  365. * @param statValue the value to add.
  366. * @private
  367. */
  368. TraceablePeerConnection.prototype._processStat
  369. = function(report, name, statValue) {
  370. const id = `${report.id}-${name}`;
  371. let s = this.stats[id];
  372. const now = new Date();
  373. if (!s) {
  374. this.stats[id] = s = {
  375. startTime: now,
  376. endTime: now,
  377. values: [],
  378. times: []
  379. };
  380. }
  381. s.values.push(statValue);
  382. s.times.push(now.getTime());
  383. if (s.values.length > this.maxstats) {
  384. s.values.shift();
  385. s.times.shift();
  386. }
  387. s.endTime = now;
  388. };
  389. /**
  390. * Returns a string representation of a SessionDescription object.
  391. */
  392. const dumpSDP = function(description) {
  393. if (typeof description === 'undefined' || description === null) {
  394. return '';
  395. }
  396. return `type: ${description.type}\r\n${description.sdp}`;
  397. };
  398. /**
  399. * Forwards the {@link peerconnection.iceConnectionState} state except that it
  400. * will convert "completed" into "connected" where both mean that the ICE has
  401. * succeeded and is up and running. We never see "completed" state for
  402. * the JVB connection, but it started appearing for the P2P one. This method
  403. * allows to adapt old logic to this new situation.
  404. * @return {string}
  405. */
  406. TraceablePeerConnection.prototype.getConnectionState = function() {
  407. const state = this.peerconnection.iceConnectionState;
  408. if (state === 'completed') {
  409. return 'connected';
  410. }
  411. return state;
  412. };
  413. /**
  414. * Obtains the media direction for given {@link MediaType} that needs to be set on a p2p peerconnection's remote SDP
  415. * after a source-add or source-remove action. The method takes into account whether or not there are any
  416. * local tracks for the given media type.
  417. * @param {MediaType} mediaType
  418. * @param {boolean} isAddOperation whether the direction is to be calculated after a source-add action.
  419. * @return {string} one of the SDP direction constants ('sendrecv, 'recvonly' etc.) which should be used when setting
  420. * local description on the peerconnection.
  421. * @private
  422. */
  423. TraceablePeerConnection.prototype.getDesiredMediaDirection = function(mediaType, isAddOperation = false) {
  424. const hasLocalSource = this.hasAnyTracksOfType(mediaType);
  425. if (isAddOperation) {
  426. return hasLocalSource ? MediaDirection.SENDRECV : MediaDirection.SENDONLY;
  427. }
  428. return hasLocalSource ? MediaDirection.RECVONLY : MediaDirection.INACTIVE;
  429. };
  430. /**
  431. * Returns the list of RTCRtpReceivers created for the source of the given media type associated with
  432. * the set of remote endpoints specified.
  433. * @param {Array<string>} endpoints list of the endpoints
  434. * @param {string} mediaType 'audio' or 'video'
  435. * @returns {Array<RTCRtpReceiver>} list of receivers created by the peerconnection.
  436. */
  437. TraceablePeerConnection.prototype._getReceiversByEndpointIds = function(endpoints, mediaType) {
  438. let remoteTracks = [];
  439. let receivers = [];
  440. for (const endpoint of endpoints) {
  441. remoteTracks = remoteTracks.concat(this.getRemoteTracks(endpoint, mediaType));
  442. }
  443. // Get the ids of the MediaStreamTracks associated with each of these remote tracks.
  444. const remoteTrackIds = remoteTracks.map(remote => remote.track?.id);
  445. receivers = this.peerconnection.getReceivers()
  446. .filter(receiver => receiver.track
  447. && receiver.track.kind === mediaType
  448. && remoteTrackIds.find(trackId => trackId === receiver.track.id));
  449. return receivers;
  450. };
  451. /**
  452. * Tells whether or not this TPC instance has spatial scalability enabled.
  453. * @return {boolean} <tt>true</tt> if spatial scalability is enabled and active or
  454. * <tt>false</tt> if it's turned off.
  455. */
  456. TraceablePeerConnection.prototype.isSpatialScalabilityOn = function() {
  457. const h264SimulcastEnabled = this.tpcUtils.codecSettings[CodecMimeType.H264].scalabilityModeEnabled
  458. && this._supportsDDHeaderExt;
  459. return !this.options.disableSimulcast
  460. && (this.codecSettings.codecList[0] !== CodecMimeType.H264 || h264SimulcastEnabled);
  461. };
  462. /**
  463. * Handles {@link SignalingEvents.PEER_VIDEO_TYPE_CHANGED}
  464. * @param {string} endpointId the video owner's ID (MUC nickname)
  465. * @param {VideoType} videoType the new value
  466. * @private
  467. */
  468. TraceablePeerConnection.prototype._peerVideoTypeChanged = function(endpointId, videoType) {
  469. // Check if endpointId has a value to avoid action on random track
  470. if (!endpointId) {
  471. logger.error(`${this} No endpointID on peerVideoTypeChanged`);
  472. return;
  473. }
  474. const videoTrack = this.getRemoteTracks(endpointId, MediaType.VIDEO);
  475. if (videoTrack.length) {
  476. // NOTE 1 track per media type is assumed
  477. videoTrack[0]._setVideoType(videoType);
  478. }
  479. };
  480. /**
  481. * Handles remote track mute / unmute events.
  482. * @param {string} endpointId the track owner's identifier (MUC nickname)
  483. * @param {MediaType} mediaType "audio" or "video"
  484. * @param {boolean} isMuted the new mute state
  485. * @private
  486. */
  487. TraceablePeerConnection.prototype._peerMutedChanged = function(endpointId, mediaType, isMuted) {
  488. // Check if endpointId is a value to avoid doing action on all remote tracks
  489. if (!endpointId) {
  490. logger.error(`${this} On peerMuteChanged - no endpoint ID`);
  491. return;
  492. }
  493. const track = this.getRemoteTracks(endpointId, mediaType);
  494. if (track.length) {
  495. // NOTE 1 track per media type is assumed
  496. track[0].setMute(isMuted);
  497. }
  498. };
  499. /**
  500. * Handles remote source mute and unmute changed events.
  501. *
  502. * @param {string} sourceName - The name of the remote source.
  503. * @param {boolean} isMuted - The new mute state.
  504. */
  505. TraceablePeerConnection.prototype._sourceMutedChanged = function(sourceName, isMuted) {
  506. const track = this.getRemoteTracks().find(t => t.getSourceName() === sourceName);
  507. if (!track) {
  508. if (FeatureFlags.isSsrcRewritingSupported()) {
  509. logger.debug(`Remote track not found for source=${sourceName}, mute update failed!`);
  510. }
  511. return;
  512. }
  513. track.setMute(isMuted);
  514. };
  515. /**
  516. * Handles remote source videoType changed events.
  517. *
  518. * @param {string} sourceName - The name of the remote source.
  519. * @param {boolean} isMuted - The new value.
  520. */
  521. TraceablePeerConnection.prototype._sourceVideoTypeChanged = function(sourceName, videoType) {
  522. const track = this.getRemoteTracks().find(t => t.getSourceName() === sourceName);
  523. if (!track) {
  524. return;
  525. }
  526. track._setVideoType(videoType);
  527. };
  528. /**
  529. * Obtains audio levels of the remote audio tracks by getting the source information on the RTCRtpReceivers.
  530. * The information relevant to the ssrc is updated each time a RTP packet constaining the ssrc is received.
  531. * @param {Array<string>} speakerList list of endpoint ids for which audio levels are to be gathered.
  532. * @returns {Object} containing ssrc and audio level information as a key-value pair.
  533. */
  534. TraceablePeerConnection.prototype.getAudioLevels = function(speakerList = []) {
  535. const audioLevels = {};
  536. const audioReceivers = speakerList.length
  537. ? this._getReceiversByEndpointIds(speakerList, MediaType.AUDIO)
  538. : this.peerconnection.getReceivers()
  539. .filter(receiver => receiver.track && receiver.track.kind === MediaType.AUDIO && receiver.track.enabled);
  540. audioReceivers.forEach(remote => {
  541. const ssrc = remote.getSynchronizationSources();
  542. if (ssrc && ssrc.length) {
  543. // As per spec, this audiolevel is a value between 0..1 (linear), where 1.0
  544. // represents 0 dBov, 0 represents silence, and 0.5 represents approximately
  545. // 6 dBSPL change in the sound pressure level from 0 dBov.
  546. // https://www.w3.org/TR/webrtc/#dom-rtcrtpcontributingsource-audiolevel
  547. audioLevels[ssrc[0].source] = ssrc[0].audioLevel;
  548. }
  549. });
  550. return audioLevels;
  551. };
  552. /**
  553. * Checks if the browser is currently doing true simulcast where in three different media streams are being sent to the
  554. * bridge. Currently this happens always for VP8 and only if simulcast is enabled for VP9/AV1/H264.
  555. * @returns {boolean}
  556. */
  557. TraceablePeerConnection.prototype.doesTrueSimulcast = function() {
  558. const currentCodec = this.getConfiguredVideoCodec();
  559. return this.isSpatialScalabilityOn() && this.tpcUtils.isRunningInSimulcastMode(currentCodec);
  560. };
  561. /**
  562. * Returns the SSRCs associated with a given local video track.
  563. *
  564. * @param {JitsiLocalTrack} localTrack
  565. * @returns
  566. */
  567. TraceablePeerConnection.prototype.getLocalVideoSSRCs = function(localTrack) {
  568. const ssrcs = [];
  569. if (!localTrack || !localTrack.isVideoTrack()) {
  570. return ssrcs;
  571. }
  572. const ssrcGroup = this.isSpatialScalabilityOn() ? 'SIM' : 'FID';
  573. return this.localSSRCs.get(localTrack.rtcId)?.groups?.find(group => group.semantics === ssrcGroup)?.ssrcs || ssrcs;
  574. };
  575. /**
  576. * Obtains local tracks for given {@link MediaType}. If the <tt>mediaType</tt>
  577. * argument is omitted the list of all local tracks will be returned.
  578. * @param {MediaType} [mediaType]
  579. * @return {Array<JitsiLocalTrack>}
  580. */
  581. TraceablePeerConnection.prototype.getLocalTracks = function(mediaType) {
  582. let tracks = Array.from(this.localTracks.values());
  583. if (mediaType !== undefined) {
  584. tracks = tracks.filter(track => track.getType() === mediaType);
  585. }
  586. return tracks;
  587. };
  588. /**
  589. * Retrieves the local video tracks.
  590. *
  591. * @returns {Array<JitsiLocalTrack>} - local video tracks.
  592. */
  593. TraceablePeerConnection.prototype.getLocalVideoTracks = function() {
  594. return this.getLocalTracks(MediaType.VIDEO);
  595. };
  596. /**
  597. * Checks whether or not this {@link TraceablePeerConnection} instance contains any local tracks for given
  598. * <tt>mediaType</tt>.
  599. *
  600. * @param {MediaType} mediaType - The media type.
  601. * @return {boolean}
  602. */
  603. TraceablePeerConnection.prototype.hasAnyTracksOfType = function(mediaType) {
  604. if (!mediaType) {
  605. throw new Error('"mediaType" is required');
  606. }
  607. return this.getLocalTracks(mediaType).length > 0;
  608. };
  609. /**
  610. * Obtains all remote tracks currently known to this PeerConnection instance.
  611. *
  612. * @param {string} [endpointId] - The track owner's identifier (MUC nickname)
  613. * @param {MediaType} [mediaType] - The remote tracks will be filtered by their media type if this argument is
  614. * specified.
  615. * @return {Array<JitsiRemoteTrack>}
  616. */
  617. TraceablePeerConnection.prototype.getRemoteTracks = function(endpointId, mediaType) {
  618. let remoteTracks = [];
  619. const endpoints = endpointId ? [ endpointId ] : this.remoteTracks.keys();
  620. for (const endpoint of endpoints) {
  621. const endpointTracksByMediaType = this.remoteTracks.get(endpoint);
  622. if (endpointTracksByMediaType) {
  623. for (const trackMediaType of endpointTracksByMediaType.keys()) {
  624. // per media type filtering
  625. if (!mediaType || mediaType === trackMediaType) {
  626. remoteTracks = remoteTracks.concat(Array.from(endpointTracksByMediaType.get(trackMediaType)));
  627. }
  628. }
  629. }
  630. }
  631. return remoteTracks;
  632. };
  633. /**
  634. * Parses the remote description and returns the sdp lines of the sources associated with a remote participant.
  635. *
  636. * @param {string} id Endpoint id of the remote participant.
  637. * @returns {Array<string>} The sdp lines that have the ssrc information.
  638. */
  639. TraceablePeerConnection.prototype.getRemoteSourceInfoByParticipant = function(id) {
  640. const removeSsrcInfo = [];
  641. const remoteTracks = this.getRemoteTracks(id);
  642. if (!remoteTracks?.length) {
  643. return removeSsrcInfo;
  644. }
  645. const primarySsrcs = remoteTracks.map(track => track.getSSRC());
  646. const sdp = new SDP(this.remoteDescription.sdp);
  647. primarySsrcs.forEach((ssrc, idx) => {
  648. for (const media of sdp.media) {
  649. let lines = '';
  650. let ssrcLines = SDPUtil.findLines(media, `a=ssrc:${ssrc}`);
  651. if (ssrcLines.length) {
  652. if (!removeSsrcInfo[idx]) {
  653. removeSsrcInfo[idx] = '';
  654. }
  655. // Check if there are any FID groups present for the primary ssrc.
  656. const fidLines = SDPUtil.findLines(media, `a=ssrc-group:FID ${ssrc}`);
  657. if (fidLines.length) {
  658. const secondarySsrc = fidLines[0].split(' ')[2];
  659. lines += `${fidLines[0]}\r\n`;
  660. ssrcLines = ssrcLines.concat(SDPUtil.findLines(media, `a=ssrc:${secondarySsrc}`));
  661. }
  662. removeSsrcInfo[idx] += `${ssrcLines.join('\r\n')}\r\n`;
  663. removeSsrcInfo[idx] += lines;
  664. }
  665. }
  666. });
  667. return removeSsrcInfo;
  668. };
  669. /**
  670. * Returns the target bitrates configured for the local video source.
  671. *
  672. * @returns {Object}
  673. */
  674. TraceablePeerConnection.prototype.getTargetVideoBitrates = function() {
  675. const currentCodec = this.getConfiguredVideoCodec();
  676. return this.tpcUtils.codecSettings[currentCodec].maxBitratesVideo;
  677. };
  678. /**
  679. * Tries to find {@link JitsiTrack} for given SSRC number. It will search both
  680. * local and remote tracks bound to this instance.
  681. * @param {number} ssrc
  682. * @return {JitsiTrack|null}
  683. */
  684. TraceablePeerConnection.prototype.getTrackBySSRC = function(ssrc) {
  685. if (typeof ssrc !== 'number') {
  686. throw new Error(`SSRC ${ssrc} is not a number`);
  687. }
  688. for (const localTrack of this.localTracks.values()) {
  689. if (this.getLocalSSRC(localTrack) === ssrc) {
  690. return localTrack;
  691. }
  692. }
  693. for (const remoteTrack of this.getRemoteTracks()) {
  694. if (remoteTrack.getSSRC() === ssrc) {
  695. return remoteTrack;
  696. }
  697. }
  698. return null;
  699. };
  700. /**
  701. * Tries to find SSRC number for given {@link JitsiTrack} id. It will search
  702. * both local and remote tracks bound to this instance.
  703. * @param {string} id
  704. * @return {number|null}
  705. */
  706. TraceablePeerConnection.prototype.getSsrcByTrackId = function(id) {
  707. const findTrackById = track => track.getTrack().id === id;
  708. const localTrack = this.getLocalTracks().find(findTrackById);
  709. if (localTrack) {
  710. return this.getLocalSSRC(localTrack);
  711. }
  712. const remoteTrack = this.getRemoteTracks().find(findTrackById);
  713. if (remoteTrack) {
  714. return remoteTrack.getSSRC();
  715. }
  716. return null;
  717. };
  718. /**
  719. * Called on "track added" and "stream added" PeerConnection events (because we
  720. * handle streams on per track basis). Finds the owner and the SSRC for
  721. * the track and passes that to ChatRoom for further processing.
  722. * @param {MediaStream} stream the WebRTC MediaStream instance which is
  723. * the parent of the track
  724. * @param {MediaStreamTrack} track the WebRTC MediaStreamTrack added for remote
  725. * participant.
  726. * @param {RTCRtpTransceiver} transceiver the WebRTC transceiver that is created
  727. * for the remote participant in unified plan.
  728. */
  729. TraceablePeerConnection.prototype._remoteTrackAdded = function(stream, track, transceiver = null) {
  730. const streamId = stream.id;
  731. const mediaType = track.kind;
  732. // Do not create remote tracks for 'mixed' JVB SSRCs (used by JVB for RTCP termination).
  733. if (!this.isP2P && !RTC.isUserStreamById(streamId)) {
  734. return;
  735. }
  736. logger.info(`${this} Received track event for remote stream[id=${streamId},type=${mediaType}]`);
  737. // look up an associated JID for a stream id
  738. if (!mediaType) {
  739. logger.error(`MediaType undefined for remote track, stream id: ${streamId}, track creation failed!`);
  740. return;
  741. }
  742. const remoteSDP = new SDP(this.peerconnection.remoteDescription.sdp);
  743. let mediaLine;
  744. // Find the matching mline using 'mid' or the 'msid' attr of the stream.
  745. if (transceiver?.mid) {
  746. const mid = transceiver.mid;
  747. mediaLine = remoteSDP.media.find(mls => SDPUtil.findLine(mls, `a=mid:${mid}`));
  748. } else {
  749. mediaLine = remoteSDP.media.find(mls => {
  750. const msid = SDPUtil.findLine(mls, 'a=msid:');
  751. return typeof msid === 'string' && streamId === msid.substring(7).split(' ')[0];
  752. });
  753. }
  754. if (!mediaLine) {
  755. logger.error(`Matching media line not found in remote SDP for remote stream[id=${streamId},type=${mediaType}],`
  756. + 'track creation failed!');
  757. return;
  758. }
  759. let ssrcLines = SDPUtil.findLines(mediaLine, 'a=ssrc:');
  760. ssrcLines = ssrcLines.filter(line => line.indexOf(`msid:${streamId}`) !== -1);
  761. if (!ssrcLines.length) {
  762. logger.error(`No SSRC lines found in remote SDP for remote stream[msid=${streamId},type=${mediaType}]`
  763. + 'track creation failed!');
  764. return;
  765. }
  766. // FIXME the length of ssrcLines[0] not verified, but it will fail
  767. // with global error handler anyway
  768. const ssrcStr = ssrcLines[0].substring(7).split(' ')[0];
  769. const trackSsrc = Number(ssrcStr);
  770. const ownerEndpointId = this.signalingLayer.getSSRCOwner(trackSsrc);
  771. if (isNaN(trackSsrc) || trackSsrc < 0) {
  772. logger.error(`Invalid SSRC for remote stream[ssrc=${trackSsrc},id=${streamId},type=${mediaType}]`
  773. + 'track creation failed!');
  774. return;
  775. }
  776. if (!ownerEndpointId) {
  777. logger.error(`No SSRC owner known for remote stream[ssrc=${trackSsrc},id=${streamId},type=${mediaType}]`
  778. + 'track creation failed!');
  779. return;
  780. }
  781. const sourceName = this.signalingLayer.getTrackSourceName(trackSsrc);
  782. const peerMediaInfo = this.signalingLayer.getPeerMediaInfo(ownerEndpointId, mediaType, sourceName);
  783. // Assume default presence state for remote source. Presence can be received after source signaling. This shouldn't
  784. // prevent the endpoint from creating a remote track for the source.
  785. let muted = true;
  786. let videoType = mediaType === MediaType.VIDEO ? VideoType.CAMERA : undefined; // 'camera' by default
  787. if (peerMediaInfo) {
  788. muted = peerMediaInfo.muted;
  789. videoType = peerMediaInfo.videoType; // can be undefined
  790. } else {
  791. logger.info(`${this}: no source-info available for ${ownerEndpointId}:${sourceName}, assuming default state`);
  792. }
  793. this._createRemoteTrack(ownerEndpointId, stream, track, mediaType, videoType, trackSsrc, muted, sourceName);
  794. };
  795. // FIXME cleanup params
  796. /* eslint-disable max-params */
  797. /**
  798. * Initializes a new JitsiRemoteTrack instance with the data provided by
  799. * the signaling layer and SDP.
  800. *
  801. * @param {string} ownerEndpointId the owner's endpoint ID (MUC nickname)
  802. * @param {MediaStream} stream the WebRTC stream instance
  803. * @param {MediaStreamTrack} track the WebRTC track instance
  804. * @param {MediaType} mediaType the track's type of the media
  805. * @param {VideoType} [videoType] the track's type of the video (if applicable)
  806. * @param {number} ssrc the track's main SSRC number
  807. * @param {boolean} muted the initial muted status
  808. * @param {String} sourceName the track's source name
  809. */
  810. TraceablePeerConnection.prototype._createRemoteTrack = function(
  811. ownerEndpointId,
  812. stream,
  813. track,
  814. mediaType,
  815. videoType,
  816. ssrc,
  817. muted,
  818. sourceName) {
  819. logger.info(`${this} creating remote track[endpoint=${ownerEndpointId},ssrc=${ssrc},`
  820. + `type=${mediaType},sourceName=${sourceName}]`);
  821. let remoteTracksMap = this.remoteTracks.get(ownerEndpointId);
  822. if (!remoteTracksMap) {
  823. remoteTracksMap = new Map();
  824. remoteTracksMap.set(MediaType.AUDIO, new Set());
  825. remoteTracksMap.set(MediaType.VIDEO, new Set());
  826. this.remoteTracks.set(ownerEndpointId, remoteTracksMap);
  827. }
  828. const userTracksByMediaType = remoteTracksMap.get(mediaType);
  829. if (userTracksByMediaType?.size
  830. && Array.from(userTracksByMediaType).find(jitsiTrack => jitsiTrack.getTrack() === track)) {
  831. // Ignore duplicated event which can originate either from 'onStreamAdded' or 'onTrackAdded'.
  832. logger.info(`${this} ignored duplicated track event for track[endpoint=${ownerEndpointId},type=${mediaType}]`);
  833. return;
  834. }
  835. const remoteTrack
  836. = new JitsiRemoteTrack(
  837. this.rtc,
  838. this.rtc.conference,
  839. ownerEndpointId,
  840. stream,
  841. track,
  842. mediaType,
  843. videoType,
  844. ssrc,
  845. muted,
  846. this.isP2P,
  847. sourceName);
  848. userTracksByMediaType.add(remoteTrack);
  849. this.eventEmitter.emit(RTCEvents.REMOTE_TRACK_ADDED, remoteTrack, this);
  850. };
  851. /**
  852. * Handles remote media track removal.
  853. *
  854. * @param {MediaStream} stream - WebRTC MediaStream instance which is the parent of the track.
  855. * @param {MediaStreamTrack} track - WebRTC MediaStreamTrack which has been removed from the PeerConnection.
  856. * @returns {void}
  857. */
  858. TraceablePeerConnection.prototype._remoteTrackRemoved = function(stream, track) {
  859. const streamId = stream.id;
  860. const trackId = track?.id;
  861. // Ignore stream removed events for JVB "mixed" sources (used for RTCP termination).
  862. if (!RTC.isUserStreamById(streamId)) {
  863. return;
  864. }
  865. if (!streamId) {
  866. logger.error(`${this} remote track removal failed - no stream ID`);
  867. return;
  868. }
  869. if (!trackId) {
  870. logger.error(`${this} remote track removal failed - no track ID`);
  871. return;
  872. }
  873. const toBeRemoved = this.getRemoteTracks().find(
  874. remoteTrack => remoteTrack.getStreamId() === streamId && remoteTrack.getTrackId() === trackId);
  875. if (!toBeRemoved) {
  876. logger.error(`${this} remote track removal failed - track not found`);
  877. return;
  878. }
  879. this._removeRemoteTrack(toBeRemoved);
  880. };
  881. /**
  882. * Removes all JitsiRemoteTracks associated with given MUC nickname (resource part of the JID).
  883. *
  884. * @param {string} owner - The resource part of the MUC JID.
  885. * @returns {JitsiRemoteTrack[]} - The array of removed tracks.
  886. */
  887. TraceablePeerConnection.prototype.removeRemoteTracks = function(owner) {
  888. let removedTracks = [];
  889. const remoteTracksByMedia = this.remoteTracks.get(owner);
  890. if (remoteTracksByMedia) {
  891. removedTracks = removedTracks.concat(Array.from(remoteTracksByMedia.get(MediaType.AUDIO)));
  892. removedTracks = removedTracks.concat(Array.from(remoteTracksByMedia.get(MediaType.VIDEO)));
  893. this.remoteTracks.delete(owner);
  894. }
  895. logger.debug(`${this} removed remote tracks[endpoint=${owner},count=${removedTracks.length}`);
  896. return removedTracks;
  897. };
  898. /**
  899. * Removes and disposes given <tt>JitsiRemoteTrack</tt> instance. Emits {@link RTCEvents.REMOTE_TRACK_REMOVED}.
  900. *
  901. * @param {JitsiRemoteTrack} toBeRemoved - The remote track to be removed.
  902. * @returns {void}
  903. */
  904. TraceablePeerConnection.prototype._removeRemoteTrack = function(toBeRemoved) {
  905. logger.info(`${this} Removing remote track stream[id=${toBeRemoved.getStreamId()},`
  906. + `trackId=${toBeRemoved.getTrackId()}]`);
  907. toBeRemoved.dispose();
  908. const participantId = toBeRemoved.getParticipantId();
  909. if (!participantId && FeatureFlags.isSsrcRewritingSupported()) {
  910. return;
  911. }
  912. const userTracksByMediaType = this.remoteTracks.get(participantId);
  913. if (!userTracksByMediaType) {
  914. logger.error(`${this} removeRemoteTrack: no remote tracks map for endpoint=${participantId}`);
  915. } else if (!userTracksByMediaType.get(toBeRemoved.getType())?.delete(toBeRemoved)) {
  916. logger.error(`${this} Failed to remove ${toBeRemoved} - type mapping messed up ?`);
  917. }
  918. this.eventEmitter.emit(RTCEvents.REMOTE_TRACK_REMOVED, toBeRemoved);
  919. };
  920. /**
  921. * Returns a map with keys msid/mediaType and <tt>TrackSSRCInfo</tt> values.
  922. * @param {RTCSessionDescription} desc the local description.
  923. * @return {Map<string,TrackSSRCInfo>}
  924. */
  925. TraceablePeerConnection.prototype._extractSSRCMap = function(desc) {
  926. /**
  927. * Track SSRC infos mapped by stream ID (msid) or mediaType (unified-plan)
  928. * @type {Map<string,TrackSSRCInfo>}
  929. */
  930. const ssrcMap = new Map();
  931. /**
  932. * Groups mapped by primary SSRC number
  933. * @type {Map<number,Array<SSRCGroupInfo>>}
  934. */
  935. const groupsMap = new Map();
  936. if (typeof desc !== 'object' || desc === null
  937. || typeof desc.sdp !== 'string') {
  938. logger.warn('An empty description was passed as an argument');
  939. return ssrcMap;
  940. }
  941. const session = transform.parse(desc.sdp);
  942. if (!Array.isArray(session.media)) {
  943. return ssrcMap;
  944. }
  945. let media = session.media;
  946. media = media.filter(mline => mline.direction === MediaDirection.SENDONLY
  947. || mline.direction === MediaDirection.SENDRECV);
  948. let index = 0;
  949. for (const mLine of media) {
  950. if (!Array.isArray(mLine.ssrcs)) {
  951. continue; // eslint-disable-line no-continue
  952. }
  953. if (Array.isArray(mLine.ssrcGroups)) {
  954. for (const group of mLine.ssrcGroups) {
  955. if (typeof group.semantics !== 'undefined' && typeof group.ssrcs !== 'undefined') {
  956. // Parse SSRCs and store as numbers
  957. const groupSSRCs = group.ssrcs.split(' ').map(ssrcStr => parseInt(ssrcStr, 10));
  958. const primarySSRC = groupSSRCs[0];
  959. // Note that group.semantics is already present
  960. group.ssrcs = groupSSRCs;
  961. // eslint-disable-next-line max-depth
  962. if (!groupsMap.has(primarySSRC)) {
  963. groupsMap.set(primarySSRC, []);
  964. }
  965. groupsMap.get(primarySSRC).push(group);
  966. }
  967. }
  968. const simGroup = mLine.ssrcGroups.find(group => group.semantics === 'SIM');
  969. // Add a SIM group if its missing in the description (happens on Firefox).
  970. if (!simGroup) {
  971. const groupSsrcs = mLine.ssrcGroups.map(group => group.ssrcs[0]);
  972. groupsMap.get(groupSsrcs[0]).push({
  973. semantics: 'SIM',
  974. ssrcs: groupSsrcs
  975. });
  976. }
  977. }
  978. let ssrcs = mLine.ssrcs;
  979. // Filter the ssrcs with 'cname' attribute.
  980. ssrcs = ssrcs.filter(s => s.attribute === 'cname');
  981. for (const ssrc of ssrcs) {
  982. // Use the mediaType as key for the source map for unified plan clients since msids are not part of
  983. // the standard and the unified plan SDPs do not have a proper msid attribute for the sources.
  984. // Also the ssrcs for sources do not change for Unified plan clients since RTCRtpSender#replaceTrack is
  985. // used for switching the tracks so it is safe to use the mediaType as the key for the TrackSSRCInfo map.
  986. const key = `${mLine.type}-${index}`;
  987. const ssrcNumber = ssrc.id;
  988. let ssrcInfo = ssrcMap.get(key);
  989. if (!ssrcInfo) {
  990. ssrcInfo = {
  991. ssrcs: [],
  992. groups: [],
  993. msid: key
  994. };
  995. ssrcMap.set(key, ssrcInfo);
  996. }
  997. ssrcInfo.ssrcs.push(ssrcNumber);
  998. if (groupsMap.has(ssrcNumber)) {
  999. const ssrcGroups = groupsMap.get(ssrcNumber);
  1000. for (const group of ssrcGroups) {
  1001. ssrcInfo.groups.push(group);
  1002. }
  1003. }
  1004. }
  1005. // Currently multi-stream is supported for video only.
  1006. mLine.type === MediaType.VIDEO && index++;
  1007. }
  1008. return ssrcMap;
  1009. };
  1010. /**
  1011. *
  1012. * @param {JitsiLocalTrack} localTrack
  1013. */
  1014. TraceablePeerConnection.prototype.getLocalSSRC = function(localTrack) {
  1015. const ssrcInfo = this._getSSRC(localTrack.rtcId);
  1016. return ssrcInfo && ssrcInfo.ssrcs[0];
  1017. };
  1018. /**
  1019. * When doing unified plan simulcast, we'll have a set of ssrcs but no ssrc-groups on Firefox. Unfortunately, Jicofo
  1020. * will complain if it sees ssrcs with matching msids but no ssrc-group, so a ssrc-group line is injected to make
  1021. * Jicofo happy.
  1022. *
  1023. * @param desc A session description object (with 'type' and 'sdp' fields)
  1024. * @return A session description object with its sdp field modified to contain an inject ssrc-group for simulcast.
  1025. */
  1026. TraceablePeerConnection.prototype._injectSsrcGroupForUnifiedSimulcast = function(desc) {
  1027. const sdp = transform.parse(desc.sdp);
  1028. const video = sdp.media.find(mline => mline.type === 'video');
  1029. // Check if the browser supports RTX, add only the primary ssrcs to the SIM group if that is the case.
  1030. video.ssrcGroups = video.ssrcGroups || [];
  1031. const fidGroups = video.ssrcGroups.filter(group => group.semantics === 'FID');
  1032. if (video.simulcast || video.simulcast_03) {
  1033. const ssrcs = [];
  1034. if (fidGroups && fidGroups.length) {
  1035. fidGroups.forEach(group => {
  1036. ssrcs.push(group.ssrcs.split(' ')[0]);
  1037. });
  1038. } else {
  1039. video.ssrcs.forEach(ssrc => {
  1040. if (ssrc.attribute === 'msid') {
  1041. ssrcs.push(ssrc.id);
  1042. }
  1043. });
  1044. }
  1045. if (video.ssrcGroups.find(group => group.semantics === 'SIM')) {
  1046. // Group already exists, no need to do anything
  1047. return desc;
  1048. }
  1049. // Add a SIM group for every 3 FID groups.
  1050. for (let i = 0; i < ssrcs.length; i += 3) {
  1051. const simSsrcs = ssrcs.slice(i, i + 3);
  1052. video.ssrcGroups.push({
  1053. semantics: 'SIM',
  1054. ssrcs: simSsrcs.join(' ')
  1055. });
  1056. }
  1057. }
  1058. return new RTCSessionDescription({
  1059. type: desc.type,
  1060. sdp: transform.write(sdp)
  1061. });
  1062. };
  1063. /* eslint-disable-next-line vars-on-top */
  1064. const getters = {
  1065. signalingState() {
  1066. return this.peerconnection.signalingState;
  1067. },
  1068. iceConnectionState() {
  1069. return this.peerconnection.iceConnectionState;
  1070. },
  1071. connectionState() {
  1072. return this.peerconnection.connectionState;
  1073. },
  1074. localDescription() {
  1075. let desc = this.peerconnection.localDescription;
  1076. if (!desc) {
  1077. logger.debug(`${this} getLocalDescription no localDescription found`);
  1078. return {};
  1079. }
  1080. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  1081. // For a jvb connection, transform the SDP to Plan B first.
  1082. if (!this.isP2P) {
  1083. desc = this.interop.toPlanB(desc);
  1084. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  1085. desc = this._injectSsrcGroupForUnifiedSimulcast(desc);
  1086. this.trace('getLocalDescription::postTransform (inject ssrc group)', dumpSDP(desc));
  1087. }
  1088. // See the method's doc for more info about this transformation.
  1089. desc = this.localSdpMunger.transformStreamIdentifiers(desc);
  1090. return desc;
  1091. },
  1092. remoteDescription() {
  1093. let desc = this.peerconnection.remoteDescription;
  1094. if (!desc) {
  1095. logger.debug(`${this} getRemoteDescription no remoteDescription found`);
  1096. return {};
  1097. }
  1098. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  1099. if (this.isP2P) {
  1100. // Adjust the media direction for p2p based on whether a local source has been added.
  1101. desc = this._adjustRemoteMediaDirection(desc);
  1102. } else {
  1103. // If this is a jvb connection, transform the SDP to Plan B first.
  1104. desc = this.interop.toPlanB(desc);
  1105. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  1106. }
  1107. return desc;
  1108. }
  1109. };
  1110. Object.keys(getters).forEach(prop => {
  1111. Object.defineProperty(
  1112. TraceablePeerConnection.prototype,
  1113. prop, {
  1114. get: getters[prop]
  1115. }
  1116. );
  1117. });
  1118. TraceablePeerConnection.prototype._getSSRC = function(rtcId) {
  1119. return this.localSSRCs.get(rtcId);
  1120. };
  1121. /**
  1122. * Checks if low fps screensharing is in progress.
  1123. *
  1124. * @private
  1125. * @returns {boolean} Returns true if 5 fps screensharing is in progress, false otherwise.
  1126. */
  1127. TraceablePeerConnection.prototype.isSharingLowFpsScreen = function() {
  1128. return this._isSharingScreen() && this._capScreenshareBitrate;
  1129. };
  1130. /**
  1131. * Checks if screensharing is in progress.
  1132. *
  1133. * @returns {boolean} Returns true if a desktop track has been added to the peerconnection, false otherwise.
  1134. */
  1135. TraceablePeerConnection.prototype._isSharingScreen = function() {
  1136. const tracks = this.getLocalVideoTracks();
  1137. return Boolean(tracks.find(track => track.videoType === VideoType.DESKTOP));
  1138. };
  1139. /**
  1140. * Munges the order of the codecs in the SDP passed based on the preference
  1141. * set through config.js settings. All instances of the specified codec are
  1142. * moved up to the top of the list when it is preferred. The specified codec
  1143. * is deleted from the list if the configuration specifies that the codec be
  1144. * disabled.
  1145. * @param {RTCSessionDescription} description that needs to be munged.
  1146. * @returns {RTCSessionDescription} the munged description.
  1147. */
  1148. TraceablePeerConnection.prototype._mungeCodecOrder = function(description) {
  1149. if (!this.codecSettings) {
  1150. return description;
  1151. }
  1152. const parsedSdp = transform.parse(description.sdp);
  1153. const mLines = parsedSdp.media.filter(m => m.type === this.codecSettings.mediaType);
  1154. if (!mLines.length) {
  1155. return description;
  1156. }
  1157. for (const mLine of mLines) {
  1158. const currentCodecs = this.getConfiguredVideoCodecs(description);
  1159. for (const codec of currentCodecs) {
  1160. if (this.isP2P) {
  1161. // Strip the high profile H264 codecs on mobile clients as they deliver better quality at the expense
  1162. // of higher load.
  1163. if (codec === CodecMimeType.H264 && browser.isMobileDevice()) {
  1164. SDPUtil.stripCodec(mLine, codec, true /* high profile */);
  1165. }
  1166. // There are multiple VP9 payload types generated by the browser, more payload types are added if the
  1167. // endpoint doesn't have a local video source. Therefore, strip all the high profile codec variants for
  1168. // VP9 so that only one payload type for VP9 is negotiated between the peers.
  1169. if (codec === CodecMimeType.VP9) {
  1170. SDPUtil.stripCodec(mLine, codec, true /* high profile */);
  1171. }
  1172. // Do not negotiate ULPFEC and RED either.
  1173. if (codec === CodecMimeType.ULPFEC || codec === CodecMimeType.RED) {
  1174. SDPUtil.stripCodec(mLine, codec, false);
  1175. }
  1176. }
  1177. }
  1178. // Reorder the codecs based on the preferred settings.
  1179. for (const codec of this.codecSettings.codecList.slice().reverse()) {
  1180. SDPUtil.preferCodec(mLine, codec);
  1181. }
  1182. }
  1183. return new RTCSessionDescription({
  1184. type: description.type,
  1185. sdp: transform.write(parsedSdp)
  1186. });
  1187. };
  1188. /**
  1189. * Checks if the AV1 Dependency descriptors are negotiated on the bridge peerconnection and disables them when the
  1190. * codec selected is VP8 or VP9.
  1191. *
  1192. * @param {RTCSessionDescription} description that needs to be munged.
  1193. * @returns {RTCSessionDescription} the munged description.
  1194. */
  1195. TraceablePeerConnection.prototype._updateAv1DdHeaders = function(description) {
  1196. if (!browser.supportsScalabilityModeAPI()) {
  1197. return description;
  1198. }
  1199. const parsedSdp = transform.parse(description.sdp);
  1200. const mLines = parsedSdp.media.filter(m => m.type === MediaType.VIDEO);
  1201. if (!mLines.length) {
  1202. return description;
  1203. }
  1204. mLines.forEach((mLine, idx) => {
  1205. const senderMids = Array.from(this._localTrackTransceiverMids.values());
  1206. const isSender = senderMids.length
  1207. ? senderMids.find(mid => mLine.mid.toString() === mid.toString())
  1208. : idx === 0;
  1209. const payload = mLine.payloads.split(' ')[0];
  1210. let { codec } = mLine.rtp.find(rtp => rtp.payload === Number(payload));
  1211. codec = codec.toLowerCase();
  1212. if (isSender && mLine.ext?.length) {
  1213. const headerIndex = mLine.ext.findIndex(ext => ext.uri === DD_HEADER_EXT_URI);
  1214. const shouldNegotiateHeaderExts = codec === CodecMimeType.AV1 || codec === CodecMimeType.H264;
  1215. if (!this._supportsDDHeaderExt && headerIndex >= 0) {
  1216. this._supportsDDHeaderExt = true;
  1217. }
  1218. if (this._supportsDDHeaderExt && shouldNegotiateHeaderExts && headerIndex < 0) {
  1219. mLine.ext.push({
  1220. value: DD_HEADER_EXT_ID,
  1221. uri: DD_HEADER_EXT_URI
  1222. });
  1223. } else if (!shouldNegotiateHeaderExts && headerIndex >= 0) {
  1224. mLine.ext.splice(headerIndex, 1);
  1225. }
  1226. }
  1227. });
  1228. return new RTCSessionDescription({
  1229. type: description.type,
  1230. sdp: transform.write(parsedSdp)
  1231. });
  1232. };
  1233. /**
  1234. * Add {@link JitsiLocalTrack} to this TPC.
  1235. * @param {JitsiLocalTrack} track
  1236. * @param {boolean} isInitiator indicates if the endpoint is the offerer.
  1237. * @returns {Promise<void>} - resolved when done.
  1238. */
  1239. TraceablePeerConnection.prototype.addTrack = function(track, isInitiator = false) {
  1240. const rtcId = track.rtcId;
  1241. logger.info(`${this} adding ${track}`);
  1242. if (this.localTracks.has(rtcId)) {
  1243. return Promise.reject(new Error(`${track} is already in ${this}`));
  1244. }
  1245. this.localTracks.set(rtcId, track);
  1246. const webrtcStream = track.getOriginalStream();
  1247. try {
  1248. this.tpcUtils.addTrack(track, isInitiator);
  1249. if (track) {
  1250. if (track.isAudioTrack()) {
  1251. this._hasHadAudioTrack = true;
  1252. } else {
  1253. this._hasHadVideoTrack = true;
  1254. }
  1255. }
  1256. } catch (error) {
  1257. logger.error(`${this} Adding track=${track} failed: ${error?.message}`);
  1258. return Promise.reject(error);
  1259. }
  1260. let promiseChain = Promise.resolve();
  1261. // On Firefox, the encodings have to be configured on the sender only after the transceiver is created.
  1262. if (browser.isFirefox()) {
  1263. promiseChain = promiseChain.then(() => webrtcStream && this.tpcUtils.setEncodings(track));
  1264. }
  1265. return promiseChain;
  1266. };
  1267. /**
  1268. * Adds local track to the RTCPeerConnection.
  1269. *
  1270. * @param {JitsiLocalTrack} track the track to be added to the pc.
  1271. * @return {Promise<boolean>} Promise that resolves to true if the underlying PeerConnection's state has changed and
  1272. * renegotiation is required, false if no renegotiation is needed or Promise is rejected when something goes wrong.
  1273. */
  1274. TraceablePeerConnection.prototype.addTrackToPc = function(track) {
  1275. logger.info(`${this} Adding track=${track} to PC`);
  1276. if (!this._assertTrackBelongs('addTrackToPc', track)) {
  1277. // Abort
  1278. return Promise.reject('Track not found on the peerconnection');
  1279. }
  1280. const webRtcStream = track.getOriginalStream();
  1281. if (!webRtcStream) {
  1282. logger.error(`${this} Unable to add track=${track} to PC - no WebRTC stream`);
  1283. return Promise.reject('Stream not found');
  1284. }
  1285. return this.tpcUtils.replaceTrack(null, track).then(() => {
  1286. if (track) {
  1287. if (track.isAudioTrack()) {
  1288. this._hasHadAudioTrack = true;
  1289. } else {
  1290. this._hasHadVideoTrack = true;
  1291. }
  1292. }
  1293. return false;
  1294. });
  1295. };
  1296. /**
  1297. * This method when called will check if given <tt>localTrack</tt> belongs to
  1298. * this TPC (that it has been previously added using {@link addTrack}). If the
  1299. * track does not belong an error message will be logged.
  1300. * @param {string} methodName the method name that will be logged in an error
  1301. * message
  1302. * @param {JitsiLocalTrack} localTrack
  1303. * @return {boolean} <tt>true</tt> if given local track belongs to this TPC or
  1304. * <tt>false</tt> otherwise.
  1305. * @private
  1306. */
  1307. TraceablePeerConnection.prototype._assertTrackBelongs = function(
  1308. methodName,
  1309. localTrack) {
  1310. const doesBelong = this.localTracks.has(localTrack?.rtcId);
  1311. if (!doesBelong) {
  1312. logger.error(`${this} ${methodName}: track=${localTrack} does not belong to pc`);
  1313. }
  1314. return doesBelong;
  1315. };
  1316. /**
  1317. * Returns the codec that is configured on the client as the preferred video codec.
  1318. * This takes into account the current order of codecs in the local description sdp.
  1319. *
  1320. * @returns {CodecMimeType} The codec that is set as the preferred codec to receive
  1321. * video in the local SDP.
  1322. */
  1323. TraceablePeerConnection.prototype.getConfiguredVideoCodec = function() {
  1324. const sdp = this.peerconnection.remoteDescription?.sdp;
  1325. const defaultCodec = CodecMimeType.VP8;
  1326. if (!sdp) {
  1327. return defaultCodec;
  1328. }
  1329. const parsedSdp = transform.parse(sdp);
  1330. const mLine = parsedSdp.media.find(m => m.type === MediaType.VIDEO);
  1331. const payload = mLine.payloads.split(' ')[0];
  1332. const { codec } = mLine.rtp.find(rtp => rtp.payload === Number(payload));
  1333. if (codec) {
  1334. return Object.values(CodecMimeType).find(value => value === codec.toLowerCase());
  1335. }
  1336. return defaultCodec;
  1337. };
  1338. /**
  1339. * Returns the codecs in the current order of preference as configured on the peerconnection.
  1340. *
  1341. * @param {RTCSessionDescription} - The local description to be used.
  1342. * @returns {Array}
  1343. */
  1344. TraceablePeerConnection.prototype.getConfiguredVideoCodecs = function(description) {
  1345. const currentSdp = description?.sdp ?? this.peerconnection.localDescription?.sdp;
  1346. if (!currentSdp) {
  1347. return [];
  1348. }
  1349. const parsedSdp = transform.parse(currentSdp);
  1350. const mLine = parsedSdp.media.find(m => m.type === MediaType.VIDEO);
  1351. const codecs = new Set(mLine.rtp
  1352. .filter(pt => pt.codec.toLowerCase() !== 'rtx')
  1353. .map(pt => pt.codec.toLowerCase()));
  1354. return Array.from(codecs);
  1355. };
  1356. /**
  1357. * Checks if the client has negotiated not to receive video encoded using the given codec, i.e., the codec has been
  1358. * removed from the local description.
  1359. */
  1360. TraceablePeerConnection.prototype.isVideoCodecDisabled = function(codec) {
  1361. const sdp = this.peerconnection.localDescription?.sdp;
  1362. if (!sdp) {
  1363. return false;
  1364. }
  1365. const parsedSdp = transform.parse(sdp);
  1366. const mLine = parsedSdp.media.find(m => m.type === MediaType.VIDEO);
  1367. return !mLine.rtp.find(r => r.codec === codec);
  1368. };
  1369. /**
  1370. * Enables or disables simulcast for screenshare based on the frame rate requested for desktop track capture.
  1371. *
  1372. * @param {number} maxFps framerate to be used for desktop track capture.
  1373. */
  1374. TraceablePeerConnection.prototype.setDesktopSharingFrameRate = function(maxFps) {
  1375. const lowFps = maxFps <= SS_DEFAULT_FRAME_RATE;
  1376. this._capScreenshareBitrate = this.isSpatialScalabilityOn() && lowFps;
  1377. };
  1378. /**
  1379. * Sets the codec preference on the peerconnection. The codec preference goes into effect when
  1380. * the next renegotiation happens.
  1381. *
  1382. * @param {CodecMimeType} preferredCodec the preferred codec.
  1383. * @param {CodecMimeType} disabledCodec the codec that needs to be disabled.
  1384. * @returns {void}
  1385. */
  1386. TraceablePeerConnection.prototype.setVideoCodecs = function(codecList) {
  1387. if (!this.codecSettings || !codecList?.length) {
  1388. return;
  1389. }
  1390. this.codecSettings.codecList = codecList;
  1391. };
  1392. /**
  1393. * Tells if the given WebRTC <tt>MediaStream</tt> has been added to
  1394. * the underlying WebRTC PeerConnection.
  1395. * @param {MediaStream} mediaStream
  1396. * @returns {boolean}
  1397. */
  1398. TraceablePeerConnection.prototype.isMediaStreamInPc = function(mediaStream) {
  1399. return this._addedStreams.indexOf(mediaStream) > -1;
  1400. };
  1401. /**
  1402. * Remove local track from this TPC.
  1403. * @param {JitsiLocalTrack} localTrack the track to be removed from this TPC.
  1404. *
  1405. * FIXME It should probably remove a boolean just like {@link removeTrackFromPc}
  1406. * The same applies to addTrack.
  1407. */
  1408. TraceablePeerConnection.prototype.removeTrack = function(localTrack) {
  1409. const webRtcStream = localTrack.getOriginalStream();
  1410. this.trace(
  1411. 'removeStream',
  1412. localTrack.rtcId, webRtcStream ? webRtcStream.id : undefined);
  1413. if (!this._assertTrackBelongs('removeStream', localTrack)) {
  1414. // Abort - nothing to be done here
  1415. return;
  1416. }
  1417. this.localTracks.delete(localTrack.rtcId);
  1418. this.localSSRCs.delete(localTrack.rtcId);
  1419. if (webRtcStream) {
  1420. this.peerconnection.removeStream(webRtcStream);
  1421. }
  1422. };
  1423. /**
  1424. * Returns the sender corresponding to the given media type.
  1425. * @param {MEDIA_TYPE} mediaType - The media type 'audio' or 'video' to be used for the search.
  1426. * @returns {RTPSender|undefined} - The found sender or undefined if no sender
  1427. * was found.
  1428. */
  1429. TraceablePeerConnection.prototype.findSenderByKind = function(mediaType) {
  1430. if (this.peerconnection.getSenders) {
  1431. return this.peerconnection.getSenders().find(s => s.track && s.track.kind === mediaType);
  1432. }
  1433. };
  1434. /**
  1435. * Returns the receiver corresponding to the given MediaStreamTrack.
  1436. *
  1437. * @param {MediaSreamTrack} track - The media stream track used for the search.
  1438. * @returns {RTCRtpReceiver|undefined} - The found receiver or undefined if no receiver
  1439. * was found.
  1440. */
  1441. TraceablePeerConnection.prototype.findReceiverForTrack = function(track) {
  1442. return this.peerconnection.getReceivers().find(r => r.track === track);
  1443. };
  1444. /**
  1445. * Returns the sender corresponding to the given MediaStreamTrack.
  1446. *
  1447. * @param {MediaSreamTrack} track - The media stream track used for the search.
  1448. * @returns {RTCRtpSender|undefined} - The found sender or undefined if no sender
  1449. * was found.
  1450. */
  1451. TraceablePeerConnection.prototype.findSenderForTrack = function(track) {
  1452. if (this.peerconnection.getSenders) {
  1453. return this.peerconnection.getSenders().find(s => s.track === track);
  1454. }
  1455. };
  1456. /**
  1457. * Processes the local description SDP and caches the mids of the mlines associated with the given tracks.
  1458. *
  1459. * @param {Array<JitsiLocalTrack>} localTracks - local tracks that are added to the peerconnection.
  1460. * @returns {void}
  1461. */
  1462. TraceablePeerConnection.prototype.processLocalSdpForTransceiverInfo = function(localTracks) {
  1463. const localSdp = this.peerconnection.localDescription?.sdp;
  1464. if (!localSdp) {
  1465. return;
  1466. }
  1467. [ MediaType.AUDIO, MediaType.VIDEO ].forEach(mediaType => {
  1468. const tracks = localTracks.filter(t => t.getType() === mediaType);
  1469. const parsedSdp = transform.parse(localSdp);
  1470. const mLines = parsedSdp.media.filter(mline => mline.type === mediaType);
  1471. tracks.forEach((track, idx) => {
  1472. if (!this._localTrackTransceiverMids.has(track.rtcId)) {
  1473. this._localTrackTransceiverMids.set(track.rtcId, mLines[idx].mid.toString());
  1474. }
  1475. });
  1476. });
  1477. };
  1478. /**
  1479. * Replaces <tt>oldTrack</tt> with <tt>newTrack</tt> from the peer connection.
  1480. * Either <tt>oldTrack</tt> or <tt>newTrack</tt> can be null; replacing a valid
  1481. * <tt>oldTrack</tt> with a null <tt>newTrack</tt> effectively just removes
  1482. * <tt>oldTrack</tt>
  1483. *
  1484. * @param {JitsiLocalTrack|null} oldTrack - The current track in use to be replaced on the pc.
  1485. * @param {JitsiLocalTrack|null} newTrack - The new track to be used.
  1486. *
  1487. * @returns {Promise<boolean>} - If the promise resolves with true, renegotiation will be needed.
  1488. * Otherwise no renegotiation is needed.
  1489. */
  1490. TraceablePeerConnection.prototype.replaceTrack = function(oldTrack, newTrack) {
  1491. if (!(oldTrack || newTrack)) {
  1492. logger.info(`${this} replaceTrack called with no new track and no old track`);
  1493. return Promise.resolve();
  1494. }
  1495. logger.debug(`${this} TPC.replaceTrack old=${oldTrack}, new=${newTrack}`);
  1496. return this.tpcUtils.replaceTrack(oldTrack, newTrack)
  1497. .then(transceiver => {
  1498. if (oldTrack) {
  1499. this.localTracks.delete(oldTrack.rtcId);
  1500. this._localTrackTransceiverMids.delete(oldTrack.rtcId);
  1501. }
  1502. if (newTrack) {
  1503. if (newTrack.isAudioTrack()) {
  1504. this._hasHadAudioTrack = true;
  1505. } else {
  1506. this._hasHadVideoTrack = true;
  1507. }
  1508. this._localTrackTransceiverMids.set(newTrack.rtcId, transceiver?.mid?.toString());
  1509. this.localTracks.set(newTrack.rtcId, newTrack);
  1510. }
  1511. // Update the local SSRC cache for the case when one track gets replaced with another and no
  1512. // renegotiation is triggered as a result of this.
  1513. if (oldTrack && newTrack) {
  1514. const oldTrackSSRC = this.localSSRCs.get(oldTrack.rtcId);
  1515. if (oldTrackSSRC) {
  1516. this.localSSRCs.delete(oldTrack.rtcId);
  1517. this.localSSRCs.set(newTrack.rtcId, oldTrackSSRC);
  1518. }
  1519. }
  1520. if (transceiver) {
  1521. // In the scenario where we remove the oldTrack (oldTrack is not null and newTrack is null) on FF
  1522. // if we change the direction to RECVONLY, create answer will generate SDP with only 1 receive
  1523. // only ssrc instead of keeping all 6 ssrcs that we currently have. Stopping the screen sharing
  1524. // and then starting it again will trigger 2 rounds of source-remove and source-add replacing
  1525. // the 6 ssrcs for the screen sharing with 1 receive only ssrc and then removing the receive
  1526. // only ssrc and adding the same 6 ssrcs. On the remote participant's side the same ssrcs will
  1527. // be reused on a new m-line and if the remote participant is FF due to
  1528. // https://bugzilla.mozilla.org/show_bug.cgi?id=1768729 the video stream won't be rendered.
  1529. // That's why we need keep the direction to SENDRECV for FF.
  1530. //
  1531. // NOTE: If we return back to the approach of not removing the track for FF and instead using the
  1532. // enabled property for mute or stopping screensharing we may need to change the direction to
  1533. // RECVONLY if FF still sends the media even though the enabled flag is set to false.
  1534. transceiver.direction
  1535. = newTrack || browser.isFirefox() ? MediaDirection.SENDRECV : MediaDirection.RECVONLY;
  1536. }
  1537. // Avoid configuring the encodings on Chromium/Safari until simulcast is configured
  1538. // for the newly added track using SDP munging which happens during the renegotiation.
  1539. const configureEncodingsPromise = browser.usesSdpMungingForSimulcast() || !newTrack
  1540. ? Promise.resolve()
  1541. : this.tpcUtils.setEncodings(newTrack);
  1542. return configureEncodingsPromise.then(() => this.isP2P);
  1543. });
  1544. };
  1545. /**
  1546. * Removes local track from the RTCPeerConnection.
  1547. *
  1548. * @param {JitsiLocalTrack} localTrack the local track to be removed.
  1549. * @return {Promise<boolean>} Promise that resolves to true if the underlying PeerConnection's state has changed and
  1550. * renegotiation is required, false if no renegotiation is needed or Promise is rejected when something goes wrong.
  1551. */
  1552. TraceablePeerConnection.prototype.removeTrackFromPc = function(localTrack) {
  1553. const webRtcStream = localTrack.getOriginalStream();
  1554. this.trace('removeTrack', localTrack.rtcId, webRtcStream ? webRtcStream.id : null);
  1555. if (!this._assertTrackBelongs('removeTrack', localTrack)) {
  1556. // Abort - nothing to be done here
  1557. return Promise.reject('Track not found in the peerconnection');
  1558. }
  1559. return this.tpcUtils.replaceTrack(localTrack, null).then(() => false);
  1560. };
  1561. TraceablePeerConnection.prototype.createDataChannel = function(label, opts) {
  1562. this.trace('createDataChannel', label, opts);
  1563. return this.peerconnection.createDataChannel(label, opts);
  1564. };
  1565. /**
  1566. * Adjusts the media direction on the remote description based on availability of local and remote sources in a p2p
  1567. * media connection.
  1568. *
  1569. * @param {RTCSessionDescription} remoteDescription the WebRTC session description instance for the remote description.
  1570. * @returns the transformed remoteDescription.
  1571. * @private
  1572. */
  1573. TraceablePeerConnection.prototype._adjustRemoteMediaDirection = function(remoteDescription) {
  1574. const transformer = new SdpTransformWrap(remoteDescription.sdp);
  1575. [ MediaType.AUDIO, MediaType.VIDEO ].forEach(mediaType => {
  1576. const media = transformer.selectMedia(mediaType);
  1577. const localSources = this.getLocalTracks(mediaType).length;
  1578. const remoteSources = this.getRemoteTracks(null, mediaType).length;
  1579. media.forEach((mLine, idx) => {
  1580. if (localSources && localSources === remoteSources) {
  1581. mLine.direction = MediaDirection.SENDRECV;
  1582. } else if (!localSources && !remoteSources) {
  1583. mLine.direction = MediaDirection.INACTIVE;
  1584. } else if (!localSources) {
  1585. mLine.direction = MediaDirection.SENDONLY;
  1586. } else if (!remoteSources) {
  1587. mLine.direction = MediaDirection.RECVONLY;
  1588. // When there are 2 local sources and 1 remote source, the first m-line should be set to 'sendrecv' while
  1589. // the second one needs to be set to 'recvonly'.
  1590. } else if (localSources > remoteSources) {
  1591. mLine.direction = idx ? MediaDirection.RECVONLY : MediaDirection.SENDRECV;
  1592. // When there are 2 remote sources and 1 local source, the first m-line should be set to 'sendrecv' while
  1593. // the second one needs to be set to 'sendonly'.
  1594. } else {
  1595. mLine.direction = idx ? MediaDirection.SENDONLY : MediaDirection.SENDRECV;
  1596. }
  1597. });
  1598. });
  1599. return new RTCSessionDescription({
  1600. type: remoteDescription.type,
  1601. sdp: transformer.toRawSDP()
  1602. });
  1603. };
  1604. /**
  1605. * Munges the stereo flag as well as the opusMaxAverageBitrate in the SDP, based
  1606. * on values set through config.js, if present.
  1607. *
  1608. * @param {RTCSessionDescription} description that needs to be munged.
  1609. * @returns {RTCSessionDescription} the munged description.
  1610. */
  1611. TraceablePeerConnection.prototype._mungeOpus = function(description) {
  1612. const { audioQuality } = this.options;
  1613. if (!audioQuality?.enableOpusDtx && !audioQuality?.stereo && !audioQuality?.opusMaxAverageBitrate) {
  1614. return description;
  1615. }
  1616. const parsedSdp = transform.parse(description.sdp);
  1617. const mLines = parsedSdp.media;
  1618. for (const mLine of mLines) {
  1619. if (mLine.type === 'audio') {
  1620. const { payload } = mLine.rtp.find(protocol => protocol.codec === CodecMimeType.OPUS);
  1621. if (!payload) {
  1622. // eslint-disable-next-line no-continue
  1623. continue;
  1624. }
  1625. let fmtpOpus = mLine.fmtp.find(protocol => protocol.payload === payload);
  1626. if (!fmtpOpus) {
  1627. fmtpOpus = {
  1628. payload,
  1629. config: ''
  1630. };
  1631. }
  1632. const fmtpConfig = transform.parseParams(fmtpOpus.config);
  1633. let sdpChanged = false;
  1634. if (audioQuality?.stereo) {
  1635. fmtpConfig.stereo = 1;
  1636. sdpChanged = true;
  1637. }
  1638. if (audioQuality?.opusMaxAverageBitrate) {
  1639. fmtpConfig.maxaveragebitrate = audioQuality.opusMaxAverageBitrate;
  1640. sdpChanged = true;
  1641. }
  1642. // On Firefox, the OpusDtx enablement has no effect
  1643. if (!browser.isFirefox() && audioQuality?.enableOpusDtx) {
  1644. fmtpConfig.usedtx = 1;
  1645. sdpChanged = true;
  1646. }
  1647. if (!sdpChanged) {
  1648. // eslint-disable-next-line no-continue
  1649. continue;
  1650. }
  1651. let mungedConfig = '';
  1652. for (const key of Object.keys(fmtpConfig)) {
  1653. mungedConfig += `${key}=${fmtpConfig[key]}; `;
  1654. }
  1655. fmtpOpus.config = mungedConfig.trim();
  1656. }
  1657. }
  1658. return new RTCSessionDescription({
  1659. type: description.type,
  1660. sdp: transform.write(parsedSdp)
  1661. });
  1662. };
  1663. /**
  1664. * Munges the SDP to set all directions to inactive and drop all ssrc and ssrc-groups.
  1665. *
  1666. * @param {RTCSessionDescription} description that needs to be munged.
  1667. * @returns {RTCSessionDescription} the munged description.
  1668. */
  1669. TraceablePeerConnection.prototype._mungeInactive = function(description) {
  1670. const parsedSdp = transform.parse(description.sdp);
  1671. const mLines = parsedSdp.media;
  1672. for (const mLine of mLines) {
  1673. mLine.direction = MediaDirection.INACTIVE;
  1674. mLine.ssrcs = undefined;
  1675. mLine.ssrcGroups = undefined;
  1676. }
  1677. return new RTCSessionDescription({
  1678. type: description.type,
  1679. sdp: transform.write(parsedSdp)
  1680. });
  1681. };
  1682. /**
  1683. * Sets up the _dtlsTransport object and initializes callbacks for it.
  1684. */
  1685. TraceablePeerConnection.prototype._initializeDtlsTransport = function() {
  1686. // We are assuming here that we only have one bundled transport here
  1687. if (!this.peerconnection.getSenders || this._dtlsTransport) {
  1688. return;
  1689. }
  1690. const senders = this.peerconnection.getSenders();
  1691. if (senders.length !== 0 && senders[0].transport) {
  1692. this._dtlsTransport = senders[0].transport;
  1693. this._dtlsTransport.onerror = error => {
  1694. logger.error(`${this} DtlsTransport error: ${error}`);
  1695. };
  1696. this._dtlsTransport.onstatechange = () => {
  1697. this.trace('dtlsTransport.onstatechange', this._dtlsTransport.state);
  1698. };
  1699. }
  1700. };
  1701. /**
  1702. * Sets the max bitrates on the video m-lines when VP9/AV1 is the selected codec.
  1703. *
  1704. * @param {RTCSessionDescription} description - The local description that needs to be munged.
  1705. * @param {boolean} isLocalSdp - Whether the max bitrate (via b=AS line in SDP) is set on local SDP.
  1706. * @returns RTCSessionDescription
  1707. */
  1708. TraceablePeerConnection.prototype._setMaxBitrates = function(description, isLocalSdp = false) {
  1709. if (!this.codecSettings) {
  1710. return description;
  1711. }
  1712. const parsedSdp = transform.parse(description.sdp);
  1713. // Find all the m-lines associated with the local sources.
  1714. const direction = isLocalSdp ? MediaDirection.RECVONLY : MediaDirection.SENDONLY;
  1715. const mLines = parsedSdp.media.filter(m => m.type === MediaType.VIDEO && m.direction !== direction);
  1716. const currentCodec = this.codecSettings.codecList[0];
  1717. const codecScalabilityModeSettings = this.tpcUtils.codecSettings[currentCodec];
  1718. for (const mLine of mLines) {
  1719. const isDoingVp9KSvc = currentCodec === CodecMimeType.VP9
  1720. && !codecScalabilityModeSettings.scalabilityModeEnabled;
  1721. const localTrack = this.getLocalVideoTracks()
  1722. .find(track => this._localTrackTransceiverMids.get(track.rtcId) === mLine.mid.toString());
  1723. if ((isDoingVp9KSvc || this.tpcUtils._isRunningInFullSvcMode(currentCodec)) && localTrack) {
  1724. let maxBitrate;
  1725. if (localTrack.getVideoType() === VideoType.DESKTOP) {
  1726. maxBitrate = codecScalabilityModeSettings.maxBitratesVideo.ssHigh;
  1727. } else {
  1728. const { level } = VIDEO_QUALITY_LEVELS.find(lvl => lvl.height <= localTrack.getCaptureResolution());
  1729. maxBitrate = codecScalabilityModeSettings.maxBitratesVideo[level];
  1730. }
  1731. const limit = Math.floor(maxBitrate / 1000);
  1732. // Use only the highest spatial layer bitrates for now as there is no API available yet for configuring
  1733. // the bitrates on the individual SVC layers.
  1734. mLine.bandwidth = [ {
  1735. type: 'AS',
  1736. limit
  1737. } ];
  1738. } else {
  1739. // Clear the bandwidth limit in SDP when VP9 is no longer the preferred codec.
  1740. // This is needed on react native clients as react-native-webrtc returns the
  1741. // SDP that the application passed instead of returning the SDP off the native side.
  1742. // This line automatically gets cleared on web on every renegotiation.
  1743. mLine.bandwidth = undefined;
  1744. }
  1745. }
  1746. return new RTCSessionDescription({
  1747. type: description.type,
  1748. sdp: transform.write(parsedSdp)
  1749. });
  1750. };
  1751. /**
  1752. * Configures the stream encodings depending on the video type and the bitrates configured.
  1753. *
  1754. * @param {JitsiLocalTrack} - The local track for which the sender encodings have to configured.
  1755. * @returns {Promise} promise that will be resolved when the operation is successful and rejected otherwise.
  1756. */
  1757. TraceablePeerConnection.prototype.configureSenderVideoEncodings = function(localVideoTrack = null) {
  1758. // If media is suspended on the jvb peerconnection, make sure that media stays disabled. The default 'active' state
  1759. // for the encodings after the source is added to the peerconnection is 'true', so it needs to be explicitly
  1760. // disabled after the source is added.
  1761. if (!this.isP2P && !(this.videoTransferActive && this.audioTransferActive)) {
  1762. return this.tpcUtils.setMediaTransferActive(false);
  1763. }
  1764. if (localVideoTrack) {
  1765. return this.setSenderVideoConstraints(
  1766. this._senderMaxHeights.get(localVideoTrack.getSourceName()),
  1767. localVideoTrack);
  1768. }
  1769. const promises = [];
  1770. for (const track of this.getLocalVideoTracks()) {
  1771. promises.push(this.setSenderVideoConstraints(this._senderMaxHeights.get(track.getSourceName()), track));
  1772. }
  1773. return Promise.allSettled(promises);
  1774. };
  1775. TraceablePeerConnection.prototype.setLocalDescription = function(description) {
  1776. let localDescription = description;
  1777. this.trace('setLocalDescription::preTransform', dumpSDP(localDescription));
  1778. // Munge stereo flag and opusMaxAverageBitrate based on config.js
  1779. localDescription = this._mungeOpus(localDescription);
  1780. // Munge the order of the codecs based on the preferences set through config.js.
  1781. localDescription = this._mungeCodecOrder(localDescription);
  1782. localDescription = this._setMaxBitrates(localDescription, true);
  1783. localDescription = this._updateAv1DdHeaders(localDescription);
  1784. this.trace('setLocalDescription::postTransform', dumpSDP(localDescription));
  1785. return new Promise((resolve, reject) => {
  1786. this.peerconnection.setLocalDescription(localDescription)
  1787. .then(() => {
  1788. this.trace('setLocalDescriptionOnSuccess');
  1789. const localUfrag = SDPUtil.getUfrag(localDescription.sdp);
  1790. if (localUfrag !== this.localUfrag) {
  1791. this.localUfrag = localUfrag;
  1792. this.eventEmitter.emit(RTCEvents.LOCAL_UFRAG_CHANGED, this, localUfrag);
  1793. }
  1794. this._initializeDtlsTransport();
  1795. resolve();
  1796. }, err => {
  1797. this.trace('setLocalDescriptionOnFailure', err);
  1798. this.eventEmitter.emit(RTCEvents.SET_LOCAL_DESCRIPTION_FAILED, err, this);
  1799. reject(err);
  1800. });
  1801. });
  1802. };
  1803. TraceablePeerConnection.prototype.setRemoteDescription = function(description) {
  1804. let remoteDescription = description;
  1805. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  1806. // Munge stereo flag and opusMaxAverageBitrate based on config.js
  1807. remoteDescription = this._mungeOpus(remoteDescription);
  1808. if (!this.isP2P) {
  1809. const currentDescription = this.peerconnection.remoteDescription;
  1810. remoteDescription = this.interop.toUnifiedPlan(remoteDescription, currentDescription);
  1811. this.trace('setRemoteDescription::postTransform (Unified)', dumpSDP(remoteDescription));
  1812. }
  1813. if (this.isSpatialScalabilityOn()) {
  1814. remoteDescription = this.tpcUtils.insertUnifiedPlanSimulcastReceive(remoteDescription);
  1815. this.trace('setRemoteDescription::postTransform (sim receive)', dumpSDP(remoteDescription));
  1816. }
  1817. remoteDescription = this.tpcUtils.ensureCorrectOrderOfSsrcs(remoteDescription);
  1818. this.trace('setRemoteDescription::postTransform (correct ssrc order)', dumpSDP(remoteDescription));
  1819. // Munge the order of the codecs based on the preferences set through config.js.
  1820. remoteDescription = this._mungeCodecOrder(remoteDescription);
  1821. remoteDescription = this._setMaxBitrates(remoteDescription);
  1822. remoteDescription = this._updateAv1DdHeaders(remoteDescription);
  1823. this.trace('setRemoteDescription::postTransform (munge codec order)', dumpSDP(remoteDescription));
  1824. return new Promise((resolve, reject) => {
  1825. this.peerconnection.setRemoteDescription(remoteDescription)
  1826. .then(() => {
  1827. this.trace('setRemoteDescriptionOnSuccess');
  1828. const remoteUfrag = SDPUtil.getUfrag(remoteDescription.sdp);
  1829. if (remoteUfrag !== this.remoteUfrag) {
  1830. this.remoteUfrag = remoteUfrag;
  1831. this.eventEmitter.emit(RTCEvents.REMOTE_UFRAG_CHANGED, this, remoteUfrag);
  1832. }
  1833. this._initializeDtlsTransport();
  1834. resolve();
  1835. }, err => {
  1836. this.trace('setRemoteDescriptionOnFailure', err);
  1837. this.eventEmitter.emit(RTCEvents.SET_REMOTE_DESCRIPTION_FAILED, err, this);
  1838. reject(err);
  1839. });
  1840. });
  1841. };
  1842. /**
  1843. * Changes the resolution of the video stream that is sent to the peer based on the resolution requested by the peer
  1844. * and user preference, sets the degradation preference on the sender based on the video type, configures the maximum
  1845. * bitrates on the send stream.
  1846. *
  1847. * @param {number} frameHeight - The max frame height to be imposed on the outgoing video stream.
  1848. * @param {JitsiLocalTrack} - The local track for which the sender constraints have to be applied.
  1849. * @returns {Promise} promise that will be resolved when the operation is successful and rejected otherwise.
  1850. */
  1851. TraceablePeerConnection.prototype.setSenderVideoConstraints = function(frameHeight, localVideoTrack) {
  1852. if (frameHeight < 0 || isNaN(frameHeight)) {
  1853. throw new Error(`Invalid frameHeight: ${frameHeight}`);
  1854. }
  1855. if (!localVideoTrack) {
  1856. throw new Error('Local video track is missing');
  1857. }
  1858. const sourceName = localVideoTrack.getSourceName();
  1859. // Ignore sender constraints if the media on the peerconnection is suspended (jvb conn when p2p is currently active)
  1860. // or if the video track is muted.
  1861. if ((!this.isP2P && !this.videoTransferActive) || localVideoTrack.isMuted()) {
  1862. this._senderMaxHeights.set(sourceName, frameHeight);
  1863. return Promise.resolve();
  1864. }
  1865. const configuredResolution = this.tpcUtils.getConfiguredEncodeResolution(
  1866. localVideoTrack,
  1867. this.getConfiguredVideoCodec());
  1868. // Ignore sender constraints if the client is already sending video of the requested resolution. Note that for
  1869. // screensharing sources, the max resolution will be the height of the window being captured irrespective of the
  1870. // height being requested by the peer.
  1871. if ((localVideoTrack.getVideoType() === VideoType.CAMERA && configuredResolution === frameHeight)
  1872. || (localVideoTrack.getVideoType() === VideoType.DESKTOP
  1873. && frameHeight > 0
  1874. && configuredResolution === localVideoTrack.getCaptureResolution())) {
  1875. return Promise.resolve();
  1876. }
  1877. this._senderMaxHeights.set(sourceName, frameHeight);
  1878. return this._updateVideoSenderParameters(
  1879. () => this._updateVideoSenderEncodings(frameHeight, localVideoTrack));
  1880. };
  1881. /**
  1882. * Returns a wrapped-up promise so that the setParameters() call on the RTCRtpSender for video sources are chained.
  1883. * This is needed on Chrome as it resets the transaction id after executing setParameters() and can affect the next on
  1884. * the fly updates if they are not chained.
  1885. * https://chromium.googlesource.com/external/webrtc/+/master/pc/rtp_sender.cc#340
  1886. * @param {Function} nextFunction - The function to be called when the last video sender update promise is settled.
  1887. * @returns {Promise}
  1888. */
  1889. TraceablePeerConnection.prototype._updateVideoSenderParameters = function(nextFunction) {
  1890. const nextPromise = this._lastVideoSenderUpdatePromise
  1891. .finally(nextFunction);
  1892. this._lastVideoSenderUpdatePromise = nextPromise;
  1893. return nextPromise;
  1894. };
  1895. /**
  1896. * Configures the video stream with resolution / degradation / maximum bitrates
  1897. *
  1898. * @param {number} frameHeight - The max frame height to be imposed on the outgoing video stream.
  1899. * @param {JitsiLocalTrack} - The local track for which the sender constraints have to be applied.
  1900. * @returns {Promise} promise that will be resolved when the operation is successful and rejected otherwise.
  1901. */
  1902. TraceablePeerConnection.prototype._updateVideoSenderEncodings = function(frameHeight, localVideoTrack) {
  1903. const videoSender = this.findSenderForTrack(localVideoTrack.getTrack());
  1904. if (!videoSender) {
  1905. return Promise.resolve();
  1906. }
  1907. const parameters = videoSender.getParameters();
  1908. if (!parameters?.encodings?.length) {
  1909. return Promise.resolve();
  1910. }
  1911. const isSharingLowFpsScreen = localVideoTrack.getVideoType() === VideoType.DESKTOP && this._capScreenshareBitrate;
  1912. // Set the degradation preference.
  1913. const preference = isSharingLowFpsScreen
  1914. ? DEGRADATION_PREFERENCE_DESKTOP // Prefer resolution for low fps share.
  1915. : DEGRADATION_PREFERENCE_CAMERA; // Prefer frame-rate for high fps share and camera.
  1916. parameters.degradationPreference = preference;
  1917. logger.info(`${this} Setting degradation preference [preference=${preference},track=${localVideoTrack}`);
  1918. // Calculate the encodings active state based on the resolution requested by the bridge.
  1919. const codec = this.getConfiguredVideoCodec();
  1920. const maxBitrates = this.tpcUtils.calculateEncodingsBitrates(localVideoTrack, codec, frameHeight);
  1921. const encodingsActiveState = this.tpcUtils.calculateEncodingsActiveState(localVideoTrack, codec, frameHeight);
  1922. const scaleFactor = this.tpcUtils.calculateEncodingsScaleFactor(localVideoTrack, codec, frameHeight);
  1923. const scalabilityModes = this.tpcUtils.calculateEncodingsScalabilityMode(localVideoTrack, codec, frameHeight);
  1924. for (const encoding in parameters.encodings) {
  1925. if (parameters.encodings.hasOwnProperty(encoding)) {
  1926. parameters.encodings[encoding].active = encodingsActiveState[encoding];
  1927. // Firefox doesn't follow the spec and lets application specify the degradation preference on the
  1928. // encodings.
  1929. browser.isFirefox() && (parameters.encodings[encoding].degradationPreference = preference);
  1930. // Do not configure 'scaleResolutionDownBy' and 'maxBitrate' for encoders running in legacy K-SVC mode
  1931. // since the browser sends only the lowest resolution layer when those are configured.
  1932. if (codec !== CodecMimeType.VP9
  1933. || !this.isSpatialScalabilityOn()
  1934. || (browser.supportsScalabilityModeAPI()
  1935. && this.tpcUtils.codecSettings[codec].scalabilityModeEnabled)) {
  1936. parameters.encodings[encoding].scaleResolutionDownBy = scaleFactor[encoding];
  1937. parameters.encodings[encoding].maxBitrate = maxBitrates[encoding];
  1938. }
  1939. // Configure scalability mode when its supported and enabled.
  1940. if (scalabilityModes) {
  1941. parameters.encodings[encoding].scalabilityMode = scalabilityModes[encoding];
  1942. }
  1943. }
  1944. }
  1945. logger.info(`${this} setting max height=${frameHeight},encodings=${JSON.stringify(parameters.encodings)}`);
  1946. return videoSender.setParameters(parameters).then(() => {
  1947. localVideoTrack.maxEnabledResolution = frameHeight;
  1948. this.eventEmitter.emit(RTCEvents.LOCAL_TRACK_MAX_ENABLED_RESOLUTION_CHANGED, localVideoTrack);
  1949. });
  1950. };
  1951. /**
  1952. * Enables/disables outgoing video media transmission on this peer connection. When disabled the stream encoding's
  1953. * active state is enabled or disabled to send or stop the media.
  1954. * @param {boolean} active <tt>true</tt> to enable video media transmission or <tt>false</tt> to disable. If the value
  1955. * is not a boolean the call will have no effect.
  1956. * @return {Promise} A promise that is resolved when the change is succesful, rejected otherwise.
  1957. * @public
  1958. */
  1959. TraceablePeerConnection.prototype.setVideoTransferActive = function(active) {
  1960. logger.debug(`${this} video transfer active: ${active}`);
  1961. const changed = this.videoTransferActive !== active;
  1962. this.videoTransferActive = active;
  1963. if (changed) {
  1964. return this.tpcUtils.setMediaTransferActive(active, MediaType.VIDEO);
  1965. }
  1966. return Promise.resolve();
  1967. };
  1968. /**
  1969. * Sends DTMF tones if possible.
  1970. *
  1971. * @param {string} tones - The DTMF tones string as defined by {@code RTCDTMFSender.insertDTMF}, 'tones' argument.
  1972. * @param {number} duration - The amount of time in milliseconds that each DTMF should last. It's 200ms by default.
  1973. * @param {number} interToneGap - The length of time in miliseconds to wait between tones. It's 200ms by default.
  1974. *
  1975. * @returns {void}
  1976. */
  1977. TraceablePeerConnection.prototype.sendTones = function(tones, duration = 200, interToneGap = 200) {
  1978. if (!this._dtmfSender) {
  1979. if (this.peerconnection.getSenders) {
  1980. const rtpSender = this.peerconnection.getSenders().find(s => s.dtmf);
  1981. this._dtmfSender = rtpSender && rtpSender.dtmf;
  1982. this._dtmfSender && logger.info(`${this} initialized DTMFSender using getSenders`);
  1983. }
  1984. if (!this._dtmfSender) {
  1985. const localAudioTrack = Array.from(this.localTracks.values()).find(t => t.isAudioTrack());
  1986. if (this.peerconnection.createDTMFSender && localAudioTrack) {
  1987. this._dtmfSender = this.peerconnection.createDTMFSender(localAudioTrack.getTrack());
  1988. }
  1989. this._dtmfSender && logger.info(`${this} initialized DTMFSender using deprecated createDTMFSender`);
  1990. }
  1991. if (this._dtmfSender) {
  1992. this._dtmfSender.ontonechange = this._onToneChange.bind(this);
  1993. }
  1994. }
  1995. if (this._dtmfSender) {
  1996. if (this._dtmfSender.toneBuffer) {
  1997. this._dtmfTonesQueue.push({
  1998. tones,
  1999. duration,
  2000. interToneGap
  2001. });
  2002. return;
  2003. }
  2004. this._dtmfSender.insertDTMF(tones, duration, interToneGap);
  2005. } else {
  2006. logger.warn(`${this} sendTones - failed to select DTMFSender`);
  2007. }
  2008. };
  2009. /**
  2010. * Callback ivoked by {@code this._dtmfSender} when it has finished playing
  2011. * a single tone.
  2012. *
  2013. * @param {Object} event - The tonechange event which indicates what characters
  2014. * are left to be played for the current tone.
  2015. * @private
  2016. * @returns {void}
  2017. */
  2018. TraceablePeerConnection.prototype._onToneChange = function(event) {
  2019. // An empty event.tone indicates the current tones have finished playing.
  2020. // Automatically start playing any queued tones on finish.
  2021. if (this._dtmfSender && event.tone === '' && this._dtmfTonesQueue.length) {
  2022. const { tones, duration, interToneGap } = this._dtmfTonesQueue.shift();
  2023. this._dtmfSender.insertDTMF(tones, duration, interToneGap);
  2024. }
  2025. };
  2026. /**
  2027. * Closes underlying WebRTC PeerConnection instance and removes all remote
  2028. * tracks by emitting {@link RTCEvents.REMOTE_TRACK_REMOVED} for each one of
  2029. * them.
  2030. */
  2031. TraceablePeerConnection.prototype.close = function() {
  2032. this.trace('stop');
  2033. // Off SignalingEvents
  2034. this.signalingLayer.off(SignalingEvents.PEER_MUTED_CHANGED, this._peerMutedChanged);
  2035. this.signalingLayer.off(SignalingEvents.PEER_VIDEO_TYPE_CHANGED, this._peerVideoTypeChanged);
  2036. this.peerconnection.removeEventListener('track', this.onTrack);
  2037. for (const peerTracks of this.remoteTracks.values()) {
  2038. for (const remoteTracks of peerTracks.values()) {
  2039. for (const remoteTrack of remoteTracks) {
  2040. this._removeRemoteTrack(remoteTrack);
  2041. }
  2042. }
  2043. }
  2044. this.remoteTracks.clear();
  2045. this._addedStreams = [];
  2046. this._dtmfSender = null;
  2047. this._dtmfTonesQueue = [];
  2048. if (!this.rtc._removePeerConnection(this)) {
  2049. logger.error(`${this} RTC._removePeerConnection returned false`);
  2050. }
  2051. if (this.statsinterval !== null) {
  2052. window.clearInterval(this.statsinterval);
  2053. this.statsinterval = null;
  2054. }
  2055. logger.info(`${this} Closing peerconnection`);
  2056. this.peerconnection.close();
  2057. };
  2058. TraceablePeerConnection.prototype.createAnswer = function(constraints) {
  2059. return this._createOfferOrAnswer(false /* answer */, constraints);
  2060. };
  2061. TraceablePeerConnection.prototype.createOffer = function(constraints) {
  2062. return this._createOfferOrAnswer(true /* offer */, constraints);
  2063. };
  2064. TraceablePeerConnection.prototype._createOfferOrAnswer = function(
  2065. isOffer,
  2066. constraints) {
  2067. const logName = isOffer ? 'Offer' : 'Answer';
  2068. this.trace(`create${logName}`, JSON.stringify(constraints, null, ' '));
  2069. const handleSuccess = (resultSdp, resolveFn, rejectFn) => {
  2070. try {
  2071. this.trace(
  2072. `create${logName}OnSuccess::preTransform`, dumpSDP(resultSdp));
  2073. // Munge local description to add 3 SSRCs for video tracks when spatial scalability is enabled.
  2074. if (this.isSpatialScalabilityOn() && browser.usesSdpMungingForSimulcast()) {
  2075. // eslint-disable-next-line no-param-reassign
  2076. resultSdp = this.simulcast.mungeLocalDescription(resultSdp);
  2077. this.trace(`create${logName} OnSuccess::postTransform (simulcast)`, dumpSDP(resultSdp));
  2078. }
  2079. if (!this.options.disableRtx && browser.usesSdpMungingForSimulcast()) {
  2080. // eslint-disable-next-line no-param-reassign
  2081. resultSdp = new RTCSessionDescription({
  2082. type: resultSdp.type,
  2083. sdp: this.rtxModifier.modifyRtxSsrcs(resultSdp.sdp)
  2084. });
  2085. this.trace(
  2086. `create${logName}`
  2087. + 'OnSuccess::postTransform (rtx modifier)',
  2088. dumpSDP(resultSdp));
  2089. }
  2090. const ssrcMap = this._extractSSRCMap(resultSdp);
  2091. this._processLocalSSRCsMap(ssrcMap);
  2092. resolveFn(resultSdp);
  2093. } catch (e) {
  2094. this.trace(`create${logName}OnError`, e);
  2095. this.trace(`create${logName}OnError`, dumpSDP(resultSdp));
  2096. logger.error(`${this} create${logName}OnError`, e, dumpSDP(resultSdp));
  2097. rejectFn(e);
  2098. }
  2099. };
  2100. const handleFailure = (err, rejectFn) => {
  2101. this.trace(`create${logName}OnFailure`, err);
  2102. const eventType
  2103. = isOffer
  2104. ? RTCEvents.CREATE_OFFER_FAILED
  2105. : RTCEvents.CREATE_ANSWER_FAILED;
  2106. this.eventEmitter.emit(eventType, err, this);
  2107. rejectFn(err);
  2108. };
  2109. // Set the codec preference before creating an offer or answer so that the generated SDP will have
  2110. // the correct preference order.
  2111. if (browser.supportsCodecPreferences() && this.codecSettings) {
  2112. const { codecList, mediaType } = this.codecSettings;
  2113. const transceivers = this.peerconnection.getTransceivers()
  2114. .filter(t => t.receiver && t.receiver?.track?.kind === mediaType);
  2115. let capabilities = RTCRtpReceiver.getCapabilities(mediaType)?.codecs;
  2116. if (transceivers.length && capabilities) {
  2117. // Rearrange the codec list as per the preference order.
  2118. for (const codec of codecList.slice().reverse()) {
  2119. // Move the desired codecs (all variations of it as well) to the beginning of the list
  2120. /* eslint-disable-next-line arrow-body-style */
  2121. capabilities.sort(caps => {
  2122. return caps.mimeType.toLowerCase() === `${mediaType}/${codec}` ? -1 : 1;
  2123. });
  2124. }
  2125. // Disable ulpfec and RED on the p2p peerconnection.
  2126. if (this.isP2P && mediaType === MediaType.VIDEO) {
  2127. capabilities = capabilities
  2128. .filter(caps => caps.mimeType.toLowerCase() !== `${MediaType.VIDEO}/${CodecMimeType.ULPFEC}`
  2129. && caps.mimeType.toLowerCase() !== `${MediaType.VIDEO}/${CodecMimeType.RED}`);
  2130. }
  2131. // Apply codec preference to all the transceivers associated with the given media type.
  2132. for (const transceiver of transceivers) {
  2133. transceiver.setCodecPreferences(capabilities);
  2134. }
  2135. }
  2136. }
  2137. return new Promise((resolve, reject) => {
  2138. let oaPromise;
  2139. if (isOffer) {
  2140. oaPromise = this.peerconnection.createOffer(constraints);
  2141. } else {
  2142. oaPromise = this.peerconnection.createAnswer(constraints);
  2143. }
  2144. oaPromise
  2145. .then(
  2146. sdp => handleSuccess(sdp, resolve, reject),
  2147. error => handleFailure(error, reject));
  2148. });
  2149. };
  2150. /**
  2151. * Extract primary SSRC from given {@link TrackSSRCInfo} object.
  2152. * @param {TrackSSRCInfo} ssrcObj
  2153. * @return {number|null} the primary SSRC or <tt>null</tt>
  2154. */
  2155. TraceablePeerConnection.prototype._extractPrimarySSRC = function(ssrcObj) {
  2156. if (ssrcObj && ssrcObj.groups && ssrcObj.groups.length) {
  2157. return ssrcObj.groups[0].ssrcs[0];
  2158. } else if (ssrcObj && ssrcObj.ssrcs && ssrcObj.ssrcs.length) {
  2159. return ssrcObj.ssrcs[0];
  2160. }
  2161. return null;
  2162. };
  2163. /**
  2164. * Goes over the SSRC map extracted from the latest local description and tries
  2165. * to match them with the local tracks (by MSID). Will update the values
  2166. * currently stored in the {@link TraceablePeerConnection.localSSRCs} map.
  2167. * @param {Map<string,TrackSSRCInfo>} ssrcMap
  2168. * @private
  2169. */
  2170. TraceablePeerConnection.prototype._processLocalSSRCsMap = function(ssrcMap) {
  2171. for (const track of this.localTracks.values()) {
  2172. const sourceName = track.getSourceName();
  2173. const sourceIndex = getSourceIndexFromSourceName(sourceName);
  2174. const sourceIdentifier = `${track.getType()}-${sourceIndex}`;
  2175. if (ssrcMap.has(sourceIdentifier)) {
  2176. const newSSRC = ssrcMap.get(sourceIdentifier);
  2177. if (!newSSRC) {
  2178. logger.error(`${this} No SSRC found for stream=${sourceIdentifier}`);
  2179. return;
  2180. }
  2181. const oldSSRC = this.localSSRCs.get(track.rtcId);
  2182. const newSSRCNum = this._extractPrimarySSRC(newSSRC);
  2183. const oldSSRCNum = this._extractPrimarySSRC(oldSSRC);
  2184. // eslint-disable-next-line no-negated-condition
  2185. if (newSSRCNum !== oldSSRCNum) {
  2186. oldSSRCNum && logger.error(`${this} Overwriting SSRC for track=${track}] with ssrc=${newSSRC}`);
  2187. this.localSSRCs.set(track.rtcId, newSSRC);
  2188. this.eventEmitter.emit(RTCEvents.LOCAL_TRACK_SSRC_UPDATED, track, newSSRCNum);
  2189. }
  2190. } else if (!track.isVideoTrack() && !track.isMuted()) {
  2191. // It is normal to find no SSRCs for a muted video track in
  2192. // the local SDP as the recv-only SSRC is no longer munged in.
  2193. // So log the warning only if it's not a muted video track.
  2194. logger.warn(`${this} No SSRCs found in the local SDP for track=${track}, stream=${sourceIdentifier}`);
  2195. }
  2196. }
  2197. };
  2198. /**
  2199. * Track the SSRCs seen so far.
  2200. * @param {number} ssrc - SSRC.
  2201. * @return {boolean} - Whether this is a new SSRC.
  2202. */
  2203. TraceablePeerConnection.prototype.addRemoteSsrc = function(ssrc) {
  2204. const existing = this.remoteSSRCs.has(ssrc);
  2205. if (!existing) {
  2206. this.remoteSSRCs.add(ssrc);
  2207. }
  2208. return !existing;
  2209. };
  2210. TraceablePeerConnection.prototype.addIceCandidate = function(candidate) {
  2211. this.trace('addIceCandidate', JSON.stringify({
  2212. candidate: candidate.candidate,
  2213. sdpMid: candidate.sdpMid,
  2214. sdpMLineIndex: candidate.sdpMLineIndex,
  2215. usernameFragment: candidate.usernameFragment
  2216. }, null, ' '));
  2217. return this.peerconnection.addIceCandidate(candidate);
  2218. };
  2219. /**
  2220. * Obtains call-related stats from the peer connection.
  2221. *
  2222. * @returns {Promise<Object>} Promise which resolves with data providing statistics about
  2223. * the peerconnection.
  2224. */
  2225. TraceablePeerConnection.prototype.getStats = function() {
  2226. return this.peerconnection.getStats();
  2227. };
  2228. /**
  2229. * Creates a text representation of this <tt>TraceablePeerConnection</tt>
  2230. * instance.
  2231. * @return {string}
  2232. */
  2233. TraceablePeerConnection.prototype.toString = function() {
  2234. return `TPC[id=${this.id},type=${this.isP2P ? 'P2P' : 'JVB'}]`;
  2235. };