Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

TraceablePeerConnection.js 114KB

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