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

TraceablePeerConnection.js 116KB

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