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

TraceablePeerConnection.js 109KB

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