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

TraceablePeerConnection.js 111KB

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