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

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