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

TraceablePeerConnection.js 116KB

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