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 115KB

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