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

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