Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

TraceablePeerConnection.js 119KB

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