modified lib-jitsi-meet dev repo
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

TraceablePeerConnection.js 82KB

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