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

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