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

TraceablePeerConnection.js 84KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553
  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.isChromiumBased() || browser.isEdge()) {
  507. stream.onaddtrack = event => {
  508. this._remoteTrackAdded(stream, event.track);
  509. };
  510. stream.onremovetrack = event => {
  511. this._remoteTrackRemoved(stream, event.track);
  512. };
  513. }
  514. // Call remoteTrackAdded for each track in the stream
  515. const streamAudioTracks = stream.getAudioTracks();
  516. for (const audioTrack of streamAudioTracks) {
  517. this._remoteTrackAdded(stream, audioTrack);
  518. }
  519. const streamVideoTracks = stream.getVideoTracks();
  520. for (const videoTrack of streamVideoTracks) {
  521. this._remoteTrackAdded(stream, videoTrack);
  522. }
  523. };
  524. /**
  525. * Called on "track added" and "stream added" PeerConnection events (because we
  526. * handle streams on per track basis). Finds the owner and the SSRC for
  527. * the track and passes that to ChatRoom for further processing.
  528. * @param {MediaStream} stream the WebRTC MediaStream instance which is
  529. * the parent of the track
  530. * @param {MediaStreamTrack} track the WebRTC MediaStreamTrack added for remote
  531. * participant
  532. */
  533. TraceablePeerConnection.prototype._remoteTrackAdded = function(stream, track) {
  534. const streamId = RTC.getStreamID(stream);
  535. const mediaType = track.kind;
  536. logger.info(`${this} remote track added:`, streamId, mediaType);
  537. // look up an associated JID for a stream id
  538. if (!mediaType) {
  539. GlobalOnErrorHandler.callErrorHandler(
  540. new Error(
  541. `MediaType undefined for remote track, stream id: ${streamId}`
  542. ));
  543. // Abort
  544. return;
  545. }
  546. const remoteSDP = new SDP(this.remoteDescription.sdp);
  547. const mediaLines
  548. = remoteSDP.media.filter(mls => mls.startsWith(`m=${mediaType}`));
  549. if (!mediaLines.length) {
  550. GlobalOnErrorHandler.callErrorHandler(
  551. new Error(
  552. `No media lines for type ${
  553. mediaType} found in remote SDP for remote track: ${
  554. streamId}`));
  555. // Abort
  556. return;
  557. }
  558. let ssrcLines = SDPUtil.findLines(mediaLines[0], 'a=ssrc:');
  559. ssrcLines
  560. = ssrcLines.filter(line => line.indexOf(`msid:${streamId}`) !== -1);
  561. if (!ssrcLines.length) {
  562. GlobalOnErrorHandler.callErrorHandler(
  563. new Error(
  564. `No SSRC lines for streamId ${
  565. streamId} for remote track, media type: ${mediaType}`));
  566. // Abort
  567. return;
  568. }
  569. // FIXME the length of ssrcLines[0] not verified, but it will fail
  570. // with global error handler anyway
  571. const ssrcStr = ssrcLines[0].substring(7).split(' ')[0];
  572. const trackSsrc = Number(ssrcStr);
  573. const ownerEndpointId = this.signalingLayer.getSSRCOwner(trackSsrc);
  574. if (isNaN(trackSsrc) || trackSsrc < 0) {
  575. GlobalOnErrorHandler.callErrorHandler(
  576. new Error(
  577. `Invalid SSRC: ${ssrcStr} for remote track, msid: ${
  578. streamId} media type: ${mediaType}`));
  579. // Abort
  580. return;
  581. } else if (!ownerEndpointId) {
  582. GlobalOnErrorHandler.callErrorHandler(
  583. new Error(
  584. `No SSRC owner known for: ${
  585. trackSsrc} for remote track, msid: ${
  586. streamId} media type: ${mediaType}`));
  587. // Abort
  588. return;
  589. }
  590. logger.log(`${this} associated ssrc`, ownerEndpointId, trackSsrc);
  591. const peerMediaInfo
  592. = this.signalingLayer.getPeerMediaInfo(ownerEndpointId, mediaType);
  593. if (!peerMediaInfo) {
  594. GlobalOnErrorHandler.callErrorHandler(
  595. new Error(
  596. `${this}: no peer media info available for ${
  597. ownerEndpointId}`));
  598. return;
  599. }
  600. const muted = peerMediaInfo.muted;
  601. const videoType = peerMediaInfo.videoType; // can be undefined
  602. this._createRemoteTrack(
  603. ownerEndpointId, stream, track, mediaType, videoType, trackSsrc, muted);
  604. };
  605. // FIXME cleanup params
  606. /* eslint-disable max-params */
  607. /**
  608. * Initializes a new JitsiRemoteTrack instance with the data provided by
  609. * the signaling layer and SDP.
  610. *
  611. * @param {string} ownerEndpointId the owner's endpoint ID (MUC nickname)
  612. * @param {MediaStream} stream the WebRTC stream instance
  613. * @param {MediaStreamTrack} track the WebRTC track instance
  614. * @param {MediaType} mediaType the track's type of the media
  615. * @param {VideoType} [videoType] the track's type of the video (if applicable)
  616. * @param {number} ssrc the track's main SSRC number
  617. * @param {boolean} muted the initial muted status
  618. */
  619. TraceablePeerConnection.prototype._createRemoteTrack = function(
  620. ownerEndpointId,
  621. stream,
  622. track,
  623. mediaType,
  624. videoType,
  625. ssrc,
  626. muted) {
  627. let remoteTracksMap = this.remoteTracks.get(ownerEndpointId);
  628. if (!remoteTracksMap) {
  629. remoteTracksMap = new Map();
  630. this.remoteTracks.set(ownerEndpointId, remoteTracksMap);
  631. }
  632. const existingTrack = remoteTracksMap.get(mediaType);
  633. if (existingTrack && existingTrack.getTrack() === track) {
  634. // Ignore duplicated event which can originate either from
  635. // 'onStreamAdded' or 'onTrackAdded'.
  636. logger.info(
  637. `${this} ignored duplicated remote track added event for: `
  638. + `${ownerEndpointId}, ${mediaType}`);
  639. return;
  640. } else if (existingTrack) {
  641. logger.error(
  642. `${this} overwriting remote track for`
  643. + `${ownerEndpointId} ${mediaType}`);
  644. }
  645. const remoteTrack
  646. = new JitsiRemoteTrack(
  647. this.rtc,
  648. this.rtc.conference,
  649. ownerEndpointId,
  650. stream,
  651. track,
  652. mediaType,
  653. videoType,
  654. ssrc,
  655. muted,
  656. this.isP2P);
  657. remoteTracksMap.set(mediaType, remoteTrack);
  658. this.eventEmitter.emit(RTCEvents.REMOTE_TRACK_ADDED, remoteTrack);
  659. };
  660. /* eslint-enable max-params */
  661. /**
  662. * Handles remote stream removal.
  663. * @param stream the WebRTC MediaStream object which is being removed from the
  664. * PeerConnection
  665. */
  666. TraceablePeerConnection.prototype._remoteStreamRemoved = function(stream) {
  667. if (!RTC.isUserStream(stream)) {
  668. const id = RTC.getStreamID(stream);
  669. logger.info(
  670. `Ignored remote 'stream removed' event for non-user stream ${id}`);
  671. return;
  672. }
  673. // Call remoteTrackRemoved for each track in the stream
  674. const streamVideoTracks = stream.getVideoTracks();
  675. for (const videoTrack of streamVideoTracks) {
  676. this._remoteTrackRemoved(stream, videoTrack);
  677. }
  678. const streamAudioTracks = stream.getAudioTracks();
  679. for (const audioTrack of streamAudioTracks) {
  680. this._remoteTrackRemoved(stream, audioTrack);
  681. }
  682. };
  683. /**
  684. * Handles remote media track removal.
  685. * @param {MediaStream} stream WebRTC MediaStream instance which is the parent
  686. * of the track.
  687. * @param {MediaStreamTrack} track the WebRTC MediaStreamTrack which has been
  688. * removed from the PeerConnection.
  689. */
  690. TraceablePeerConnection.prototype._remoteTrackRemoved = function(
  691. stream,
  692. track) {
  693. const streamId = RTC.getStreamID(stream);
  694. const trackId = track && RTC.getTrackID(track);
  695. logger.info(`${this} - remote track removed: ${streamId}, ${trackId}`);
  696. if (!streamId) {
  697. GlobalOnErrorHandler.callErrorHandler(
  698. new Error(`${this} remote track removal failed - no stream ID`));
  699. return;
  700. }
  701. if (!trackId) {
  702. GlobalOnErrorHandler.callErrorHandler(
  703. new Error(`${this} remote track removal failed - no track ID`));
  704. return;
  705. }
  706. if (!this._removeRemoteTrackById(streamId, trackId)) {
  707. // NOTE this warning is always printed when user leaves the room,
  708. // because we remove remote tracks manually on MUC member left event,
  709. // before the SSRCs are removed by Jicofo. In most cases it is fine to
  710. // ignore this warning, but still it's better to keep it printed for
  711. // debugging purposes.
  712. //
  713. // We could change the behaviour to emit track removed only from here,
  714. // but the order of the events will change and consuming apps could
  715. // behave unexpectedly (the "user left" event would come before "track
  716. // removed" events).
  717. logger.warn(
  718. `${this} Removed track not found for msid: ${streamId},
  719. track id: ${trackId}`);
  720. }
  721. };
  722. /**
  723. * Finds remote track by it's stream and track ids.
  724. * @param {string} streamId the media stream id as defined by the WebRTC
  725. * @param {string} trackId the media track id as defined by the WebRTC
  726. * @return {JitsiRemoteTrack|undefined} the track's instance or
  727. * <tt>undefined</tt> if not found.
  728. * @private
  729. */
  730. TraceablePeerConnection.prototype._getRemoteTrackById = function(
  731. streamId,
  732. trackId) {
  733. // .find will break the loop once the first match is found
  734. for (const endpointTrackMap of this.remoteTracks.values()) {
  735. for (const mediaTrack of endpointTrackMap.values()) {
  736. // FIXME verify and try to use ===
  737. /* eslint-disable eqeqeq */
  738. if (mediaTrack.getStreamId() == streamId
  739. && mediaTrack.getTrackId() == trackId) {
  740. return mediaTrack;
  741. }
  742. /* eslint-enable eqeqeq */
  743. }
  744. }
  745. return undefined;
  746. };
  747. /**
  748. * Removes all JitsiRemoteTracks associated with given MUC nickname
  749. * (resource part of the JID). Returns array of removed tracks.
  750. *
  751. * @param {string} owner - The resource part of the MUC JID.
  752. * @returns {JitsiRemoteTrack[]}
  753. */
  754. TraceablePeerConnection.prototype.removeRemoteTracks = function(owner) {
  755. const removedTracks = [];
  756. const remoteTracksMap = this.remoteTracks.get(owner);
  757. if (remoteTracksMap) {
  758. const removedAudioTrack = remoteTracksMap.get(MediaType.AUDIO);
  759. const removedVideoTrack = remoteTracksMap.get(MediaType.VIDEO);
  760. removedAudioTrack && removedTracks.push(removedAudioTrack);
  761. removedVideoTrack && removedTracks.push(removedVideoTrack);
  762. this.remoteTracks.delete(owner);
  763. }
  764. logger.debug(
  765. `${this} removed remote tracks for ${owner} count: ${
  766. removedTracks.length}`);
  767. return removedTracks;
  768. };
  769. /**
  770. * Removes and disposes given <tt>JitsiRemoteTrack</tt> instance. Emits
  771. * {@link RTCEvents.REMOTE_TRACK_REMOVED}.
  772. * @param {JitsiRemoteTrack} toBeRemoved
  773. */
  774. TraceablePeerConnection.prototype._removeRemoteTrack = function(toBeRemoved) {
  775. toBeRemoved.dispose();
  776. const participantId = toBeRemoved.getParticipantId();
  777. const remoteTracksMap = this.remoteTracks.get(participantId);
  778. if (!remoteTracksMap) {
  779. logger.error(
  780. `removeRemoteTrack: no remote tracks map for ${participantId}`);
  781. } else if (!remoteTracksMap.delete(toBeRemoved.getType())) {
  782. logger.error(
  783. `Failed to remove ${toBeRemoved} - type mapping messed up ?`);
  784. }
  785. this.eventEmitter.emit(RTCEvents.REMOTE_TRACK_REMOVED, toBeRemoved);
  786. };
  787. /**
  788. * Removes and disposes <tt>JitsiRemoteTrack</tt> identified by given stream and
  789. * track ids.
  790. *
  791. * @param {string} streamId the media stream id as defined by the WebRTC
  792. * @param {string} trackId the media track id as defined by the WebRTC
  793. * @returns {JitsiRemoteTrack|undefined} the track which has been removed or
  794. * <tt>undefined</tt> if no track matching given stream and track ids was
  795. * found.
  796. */
  797. TraceablePeerConnection.prototype._removeRemoteTrackById = function(
  798. streamId,
  799. trackId) {
  800. const toBeRemoved = this._getRemoteTrackById(streamId, trackId);
  801. if (toBeRemoved) {
  802. this._removeRemoteTrack(toBeRemoved);
  803. }
  804. return toBeRemoved;
  805. };
  806. /**
  807. * @typedef {Object} SSRCGroupInfo
  808. * @property {Array<number>} ssrcs group's SSRCs
  809. * @property {string} semantics
  810. */
  811. /**
  812. * @typedef {Object} TrackSSRCInfo
  813. * @property {Array<number>} ssrcs track's SSRCs
  814. * @property {Array<SSRCGroupInfo>} groups track's SSRC groups
  815. */
  816. /**
  817. * Returns map with keys msid and <tt>TrackSSRCInfo</tt> values.
  818. * @param {Object} desc the WebRTC SDP instance.
  819. * @return {Map<string,TrackSSRCInfo>}
  820. */
  821. function extractSSRCMap(desc) {
  822. /**
  823. * Track SSRC infos mapped by stream ID (msid)
  824. * @type {Map<string,TrackSSRCInfo>}
  825. */
  826. const ssrcMap = new Map();
  827. /**
  828. * Groups mapped by primary SSRC number
  829. * @type {Map<number,Array<SSRCGroupInfo>>}
  830. */
  831. const groupsMap = new Map();
  832. if (typeof desc !== 'object' || desc === null
  833. || typeof desc.sdp !== 'string') {
  834. logger.warn('An empty description was passed as an argument.');
  835. return ssrcMap;
  836. }
  837. const session = transform.parse(desc.sdp);
  838. if (!Array.isArray(session.media)) {
  839. return ssrcMap;
  840. }
  841. for (const mLine of session.media) {
  842. if (!Array.isArray(mLine.ssrcs)) {
  843. continue; // eslint-disable-line no-continue
  844. }
  845. if (Array.isArray(mLine.ssrcGroups)) {
  846. for (const group of mLine.ssrcGroups) {
  847. if (typeof group.semantics !== 'undefined'
  848. && typeof group.ssrcs !== 'undefined') {
  849. // Parse SSRCs and store as numbers
  850. const groupSSRCs
  851. = group.ssrcs.split(' ').map(
  852. ssrcStr => parseInt(ssrcStr, 10));
  853. const primarySSRC = groupSSRCs[0];
  854. // Note that group.semantics is already present
  855. group.ssrcs = groupSSRCs;
  856. // eslint-disable-next-line max-depth
  857. if (!groupsMap.has(primarySSRC)) {
  858. groupsMap.set(primarySSRC, []);
  859. }
  860. groupsMap.get(primarySSRC).push(group);
  861. }
  862. }
  863. }
  864. for (const ssrc of mLine.ssrcs) {
  865. if (ssrc.attribute !== 'msid') {
  866. continue; // eslint-disable-line no-continue
  867. }
  868. const msid = ssrc.value;
  869. let ssrcInfo = ssrcMap.get(msid);
  870. if (!ssrcInfo) {
  871. ssrcInfo = {
  872. ssrcs: [],
  873. groups: [],
  874. msid
  875. };
  876. ssrcMap.set(msid, ssrcInfo);
  877. }
  878. const ssrcNumber = ssrc.id;
  879. ssrcInfo.ssrcs.push(ssrcNumber);
  880. if (groupsMap.has(ssrcNumber)) {
  881. const ssrcGroups = groupsMap.get(ssrcNumber);
  882. for (const group of ssrcGroups) {
  883. ssrcInfo.groups.push(group);
  884. }
  885. }
  886. }
  887. }
  888. return ssrcMap;
  889. }
  890. /**
  891. * Takes a SessionDescription object and returns a "normalized" version.
  892. * Currently it takes care of ordering the a=ssrc lines and denoting receive
  893. * only SSRCs.
  894. */
  895. const normalizePlanB = function(desc) {
  896. if (typeof desc !== 'object' || desc === null
  897. || typeof desc.sdp !== 'string') {
  898. logger.warn('An empty description was passed as an argument.');
  899. return desc;
  900. }
  901. // eslint-disable-next-line no-shadow
  902. const transform = require('sdp-transform');
  903. const session = transform.parse(desc.sdp);
  904. if (typeof session !== 'undefined'
  905. && typeof session.media !== 'undefined'
  906. && Array.isArray(session.media)) {
  907. session.media.forEach(mLine => {
  908. // Chrome appears to be picky about the order in which a=ssrc lines
  909. // are listed in an m-line when rtx is enabled (and thus there are
  910. // a=ssrc-group lines with FID semantics). Specifically if we have
  911. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  912. // the "a=ssrc:S1" lines, SRD fails.
  913. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  914. // first.
  915. const firstSsrcs = [];
  916. const newSsrcLines = [];
  917. if (typeof mLine.ssrcGroups !== 'undefined'
  918. && Array.isArray(mLine.ssrcGroups)) {
  919. mLine.ssrcGroups.forEach(group => {
  920. if (typeof group.semantics !== 'undefined'
  921. && group.semantics === 'FID') {
  922. if (typeof group.ssrcs !== 'undefined') {
  923. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  924. }
  925. }
  926. });
  927. }
  928. if (Array.isArray(mLine.ssrcs)) {
  929. let i;
  930. for (i = 0; i < mLine.ssrcs.length; i++) {
  931. if (typeof mLine.ssrcs[i] === 'object'
  932. && typeof mLine.ssrcs[i].id !== 'undefined'
  933. && firstSsrcs.indexOf(mLine.ssrcs[i].id) >= 0) {
  934. newSsrcLines.push(mLine.ssrcs[i]);
  935. delete mLine.ssrcs[i];
  936. }
  937. }
  938. for (i = 0; i < mLine.ssrcs.length; i++) {
  939. if (typeof mLine.ssrcs[i] !== 'undefined') {
  940. newSsrcLines.push(mLine.ssrcs[i]);
  941. }
  942. }
  943. mLine.ssrcs = replaceDefaultUnifiedPlanMsid(newSsrcLines);
  944. }
  945. });
  946. }
  947. const resStr = transform.write(session);
  948. return new RTCSessionDescription({
  949. type: desc.type,
  950. sdp: resStr
  951. });
  952. };
  953. /**
  954. * Unified plan differentiates a remote track not associated with a stream using
  955. * the msid "-", which can incorrectly trigger an onaddstream event in plan-b.
  956. * For jitsi, these tracks are actually receive-only ssrcs. To prevent
  957. * onaddstream from firing, remove the ssrcs with msid "-" except the cname
  958. * line. Normally the ssrcs are not used by the client, as the bridge controls
  959. * media flow, but keep one reference to the ssrc for the p2p case.
  960. *
  961. * @param {Array<Object>} ssrcLines - The ssrc lines from a remote description.
  962. * @private
  963. * @returns {Array<Object>} ssrcLines with removed lines referencing msid "-".
  964. */
  965. function replaceDefaultUnifiedPlanMsid(ssrcLines = []) {
  966. if (!browser.isChrome() || !browser.isVersionGreaterThan(70)) {
  967. return ssrcLines;
  968. }
  969. let filteredLines = [ ...ssrcLines ];
  970. const problematicSsrcIds = ssrcLines.filter(ssrcLine =>
  971. ssrcLine.attribute === 'mslabel' && ssrcLine.value === '-')
  972. .map(ssrcLine => ssrcLine.id);
  973. problematicSsrcIds.forEach(ssrcId => {
  974. // Find the cname which is to be modified and left in.
  975. const cnameLine = filteredLines.find(line =>
  976. line.id === ssrcId && line.attribute === 'cname');
  977. cnameLine.value = `recvonly-${ssrcId}`;
  978. // Remove all of lines for the ssrc.
  979. filteredLines
  980. = filteredLines.filter(line => line.id !== ssrcId);
  981. // But re-add the cname line so there is a reference kept to the ssrc
  982. // in the SDP.
  983. filteredLines.push(cnameLine);
  984. });
  985. return filteredLines;
  986. }
  987. /**
  988. * Makes sure that both audio and video directions are configured as 'sendrecv'.
  989. * @param {Object} localDescription the SDP object as defined by WebRTC.
  990. */
  991. const enforceSendRecv = function(localDescription) {
  992. if (!localDescription) {
  993. throw new Error('No local description passed in.');
  994. }
  995. const transformer = new SdpTransformWrap(localDescription.sdp);
  996. const audioMedia = transformer.selectMedia('audio');
  997. let changed = false;
  998. if (audioMedia && audioMedia.direction !== 'sendrecv') {
  999. audioMedia.direction = 'sendrecv';
  1000. changed = true;
  1001. }
  1002. const videoMedia = transformer.selectMedia('video');
  1003. if (videoMedia && videoMedia.direction !== 'sendrecv') {
  1004. videoMedia.direction = 'sendrecv';
  1005. changed = true;
  1006. }
  1007. if (changed) {
  1008. return new RTCSessionDescription({
  1009. type: localDescription.type,
  1010. sdp: transformer.toRawSDP()
  1011. });
  1012. }
  1013. return localDescription;
  1014. };
  1015. /**
  1016. *
  1017. * @param {JitsiLocalTrack} localTrack
  1018. */
  1019. TraceablePeerConnection.prototype.getLocalSSRC = function(localTrack) {
  1020. const ssrcInfo = this._getSSRC(localTrack.rtcId);
  1021. return ssrcInfo && ssrcInfo.ssrcs[0];
  1022. };
  1023. /**
  1024. * When doing unified plan simulcast, we'll have a set of ssrcs with the
  1025. * same msid but no ssrc-group, since unified plan signals the simulcast
  1026. * group via the a=simulcast line. Unfortunately, Jicofo will complain
  1027. * if it sees ssrcs with matching msids but no ssrc-group, so we'll inject
  1028. * an ssrc-group line to make Jicofo happy.
  1029. * NOTE: unlike plan B simulcast, the ssrcs in this inject ssrc-group will
  1030. * NOT necessarily be in order of quality (low to high) because:
  1031. * a) when translating between unified plan and plan b the order of the ssrcs
  1032. * is not preserved and
  1033. * b) it isn't guaranteed that firefox will give them to us in order to begin
  1034. * with
  1035. * @param desc A session description object (with 'type' and 'sdp' fields)
  1036. * @return A session description object with its sdp field modified to
  1037. * contain an inject ssrc-group for simulcast
  1038. */
  1039. TraceablePeerConnection.prototype._injectSsrcGroupForUnifiedSimulcast
  1040. = function(desc) {
  1041. const sdp = transform.parse(desc.sdp);
  1042. const video = sdp.media.find(mline => mline.type === 'video');
  1043. if (video.simulcast_03) {
  1044. const ssrcs = [];
  1045. video.ssrcs.forEach(ssrc => {
  1046. if (ssrc.attribute === 'msid') {
  1047. ssrcs.push(ssrc.id);
  1048. }
  1049. });
  1050. video.ssrcGroups = video.ssrcGroups || [];
  1051. if (video.ssrcGroups.find(group => group.semantics === 'SIM')) {
  1052. // Group already exists, no need to do anything
  1053. return desc;
  1054. }
  1055. video.ssrcGroups.push({
  1056. semantics: 'SIM',
  1057. ssrcs: ssrcs.join(' ')
  1058. });
  1059. }
  1060. return new RTCSessionDescription({
  1061. type: desc.type,
  1062. sdp: transform.write(sdp)
  1063. });
  1064. };
  1065. /* eslint-disable-next-line vars-on-top */
  1066. const getters = {
  1067. signalingState() {
  1068. return this.peerconnection.signalingState;
  1069. },
  1070. iceConnectionState() {
  1071. return this.peerconnection.iceConnectionState;
  1072. },
  1073. localDescription() {
  1074. let desc = this.peerconnection.localDescription;
  1075. if (!desc) {
  1076. logger.debug('getLocalDescription no localDescription found');
  1077. return {};
  1078. }
  1079. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  1080. // if we're running on FF, transform to Plan B first.
  1081. if (browser.usesUnifiedPlan()) {
  1082. desc = this.interop.toPlanB(desc);
  1083. this.trace('getLocalDescription::postTransform (Plan B)',
  1084. dumpSDP(desc));
  1085. desc = this._injectSsrcGroupForUnifiedSimulcast(desc);
  1086. this.trace('getLocalDescription::postTransform (inject ssrc group)',
  1087. dumpSDP(desc));
  1088. }
  1089. if (browser.doesVideoMuteByStreamRemove()) {
  1090. desc = this.localSdpMunger.maybeAddMutedLocalVideoTracksToSDP(desc);
  1091. logger.debug(
  1092. 'getLocalDescription::postTransform (munge local SDP)', desc);
  1093. }
  1094. // What comes out of this getter will be signalled over Jingle to
  1095. // the other peer, so we need to make sure the media direction is
  1096. // 'sendrecv' because we won't change the direction later and don't want
  1097. // the other peer to think we can't send or receive.
  1098. //
  1099. // Note that the description we set in chrome does have the accurate
  1100. // direction (e.g. 'recvonly'), since that is technically what is
  1101. // happening (check setLocalDescription impl).
  1102. desc = enforceSendRecv(desc);
  1103. // See the method's doc for more info about this transformation.
  1104. desc = this.localSdpMunger.transformStreamIdentifiers(desc);
  1105. return desc;
  1106. },
  1107. remoteDescription() {
  1108. let desc = this.peerconnection.remoteDescription;
  1109. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  1110. // if we're running on FF, transform to Plan B first.
  1111. if (browser.usesUnifiedPlan()) {
  1112. desc = this.interop.toPlanB(desc);
  1113. this.trace(
  1114. 'getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  1115. }
  1116. return desc || {};
  1117. }
  1118. };
  1119. Object.keys(getters).forEach(prop => {
  1120. Object.defineProperty(
  1121. TraceablePeerConnection.prototype,
  1122. prop, {
  1123. get: getters[prop]
  1124. }
  1125. );
  1126. });
  1127. TraceablePeerConnection.prototype._getSSRC = function(rtcId) {
  1128. return this.localSSRCs.get(rtcId);
  1129. };
  1130. /**
  1131. * Add {@link JitsiLocalTrack} to this TPC.
  1132. * @param {JitsiLocalTrack} track
  1133. */
  1134. TraceablePeerConnection.prototype.addTrack = function(track) {
  1135. const rtcId = track.rtcId;
  1136. logger.info(`add ${track} to: ${this}`);
  1137. if (this.localTracks.has(rtcId)) {
  1138. logger.error(`${track} is already in ${this}`);
  1139. return;
  1140. }
  1141. this.localTracks.set(rtcId, track);
  1142. const webrtcStream = track.getOriginalStream();
  1143. if (webrtcStream) {
  1144. this._addStream(webrtcStream);
  1145. // It's not ok for a track to not have a WebRTC stream if:
  1146. } else if (!browser.doesVideoMuteByStreamRemove()
  1147. || track.isAudioTrack()
  1148. || (track.isVideoTrack() && !track.isMuted())) {
  1149. logger.error(`${this} no WebRTC stream for: ${track}`);
  1150. }
  1151. // Muted video tracks do not have WebRTC stream
  1152. if (browser.doesVideoMuteByStreamRemove()
  1153. && track.isVideoTrack() && track.isMuted()) {
  1154. const ssrcInfo = this.generateNewStreamSSRCInfo(track);
  1155. this.sdpConsistency.setPrimarySsrc(ssrcInfo.ssrcs[0]);
  1156. const simGroup
  1157. = ssrcInfo.groups.find(groupInfo => groupInfo.semantics === 'SIM');
  1158. if (simGroup) {
  1159. this.simulcast.setSsrcCache(simGroup.ssrcs);
  1160. }
  1161. const fidGroups
  1162. = ssrcInfo.groups.filter(
  1163. groupInfo => groupInfo.semantics === 'FID');
  1164. if (fidGroups) {
  1165. const rtxSsrcMapping = new Map();
  1166. fidGroups.forEach(fidGroup => {
  1167. const primarySsrc = fidGroup.ssrcs[0];
  1168. const rtxSsrc = fidGroup.ssrcs[1];
  1169. rtxSsrcMapping.set(primarySsrc, rtxSsrc);
  1170. });
  1171. this.rtxModifier.setSsrcCache(rtxSsrcMapping);
  1172. }
  1173. }
  1174. };
  1175. /**
  1176. * Adds local track as part of the unmute operation.
  1177. * @param {JitsiLocalTrack} track the track to be added as part of the unmute
  1178. * operation
  1179. * @return {boolean} <tt>true</tt> if the state of underlying PC has changed and
  1180. * the renegotiation is required or <tt>false</tt> otherwise.
  1181. */
  1182. TraceablePeerConnection.prototype.addTrackUnmute = function(track) {
  1183. if (!this._assertTrackBelongs('addTrackUnmute', track)) {
  1184. // Abort
  1185. return false;
  1186. }
  1187. logger.info(`Adding ${track} as unmute to ${this}`);
  1188. const webRtcStream = track.getOriginalStream();
  1189. if (!webRtcStream) {
  1190. logger.error(
  1191. `Unable to add ${track} as unmute to ${this} - no WebRTC stream`);
  1192. return false;
  1193. }
  1194. this._addStream(webRtcStream);
  1195. return true;
  1196. };
  1197. /**
  1198. * Adds WebRTC media stream to the underlying PeerConnection
  1199. * @param {MediaStream} mediaStream
  1200. * @private
  1201. */
  1202. TraceablePeerConnection.prototype._addStream = function(mediaStream) {
  1203. this.peerconnection.addStream(mediaStream);
  1204. this._addedStreams.push(mediaStream);
  1205. };
  1206. /**
  1207. * Removes WebRTC media stream from the underlying PeerConection
  1208. * @param {MediaStream} mediaStream
  1209. */
  1210. TraceablePeerConnection.prototype._removeStream = function(mediaStream) {
  1211. if (browser.supportsRtpSender()) {
  1212. this._handleSenderRemoveStream(mediaStream);
  1213. } else {
  1214. this.peerconnection.removeStream(mediaStream);
  1215. }
  1216. this._addedStreams
  1217. = this._addedStreams.filter(stream => stream !== mediaStream);
  1218. };
  1219. /**
  1220. * This method when called will check if given <tt>localTrack</tt> belongs to
  1221. * this TPC (that it has been previously added using {@link addTrack}). If the
  1222. * track does not belong an error message will be logged.
  1223. * @param {string} methodName the method name that will be logged in an error
  1224. * message
  1225. * @param {JitsiLocalTrack} localTrack
  1226. * @return {boolean} <tt>true</tt> if given local track belongs to this TPC or
  1227. * <tt>false</tt> otherwise.
  1228. * @private
  1229. */
  1230. TraceablePeerConnection.prototype._assertTrackBelongs = function(
  1231. methodName,
  1232. localTrack) {
  1233. const doesBelong = this.localTracks.has(localTrack.rtcId);
  1234. if (!doesBelong) {
  1235. logger.error(
  1236. `${methodName}: ${localTrack} does not belong to ${this}`);
  1237. }
  1238. return doesBelong;
  1239. };
  1240. /**
  1241. * Tells if the given WebRTC <tt>MediaStream</tt> has been added to
  1242. * the underlying WebRTC PeerConnection.
  1243. * @param {MediaStream} mediaStream
  1244. * @returns {boolean}
  1245. */
  1246. TraceablePeerConnection.prototype.isMediaStreamInPc = function(mediaStream) {
  1247. return this._addedStreams.indexOf(mediaStream) > -1;
  1248. };
  1249. /**
  1250. * Remove local track from this TPC.
  1251. * @param {JitsiLocalTrack} localTrack the track to be removed from this TPC.
  1252. *
  1253. * FIXME It should probably remove a boolean just like {@link removeTrackMute}
  1254. * The same applies to addTrack.
  1255. */
  1256. TraceablePeerConnection.prototype.removeTrack = function(localTrack) {
  1257. const webRtcStream = localTrack.getOriginalStream();
  1258. this.trace(
  1259. 'removeStream',
  1260. localTrack.rtcId, webRtcStream ? webRtcStream.id : undefined);
  1261. if (!this._assertTrackBelongs('removeStream', localTrack)) {
  1262. // Abort - nothing to be done here
  1263. return;
  1264. }
  1265. this.localTracks.delete(localTrack.rtcId);
  1266. this.localSSRCs.delete(localTrack.rtcId);
  1267. if (webRtcStream) {
  1268. if (browser.supportsRtpSender()) {
  1269. this._handleSenderRemoveStream(webRtcStream);
  1270. } else {
  1271. this.peerconnection.removeStream(webRtcStream);
  1272. }
  1273. }
  1274. };
  1275. /**
  1276. * Returns the sender corresponding to the given MediaStream.
  1277. *
  1278. * @param {MediaStream} stream - The media stream used for the search.
  1279. * @returns {RTPSender|undefined} - The found sender or undefined if no sender
  1280. * was found.
  1281. */
  1282. TraceablePeerConnection.prototype.findSenderByStream = function(stream) {
  1283. const track = stream.getTracks()[0];
  1284. if (!track) {
  1285. logger.error('Cannot find sender: no tracks.');
  1286. return;
  1287. }
  1288. // Find the right sender (for audio or video)
  1289. return this.peerconnection.getSenders().find(s => s.track === track);
  1290. };
  1291. /**
  1292. * Replaces <tt>oldTrack</tt> with <tt>newTrack</tt> from the peer connection.
  1293. * Either <tt>oldTrack</tt> or <tt>newTrack</tt> can be null; replacing a valid
  1294. * <tt>oldTrack</tt> with a null <tt>newTrack</tt> effectively just removes
  1295. * <tt>oldTrack</tt>
  1296. *
  1297. * @param {JitsiLocalTrack|null} oldTrack - The current track in use to be
  1298. * replaced
  1299. * @param {JitsiLocalTrack|null} newTrack - The new track to use
  1300. * @returns {Promise<boolean>} - If the promise resolves with true,
  1301. * renegotiation will be needed. Otherwise no renegotiation is needed.
  1302. */
  1303. TraceablePeerConnection.prototype.replaceTrack = function(oldTrack, newTrack) {
  1304. if (browser.supportsRtpSender() && oldTrack && newTrack) {
  1305. // Add and than remove stream in FF leads to wrong local SDP. In order
  1306. // to workaround the issue we need to use sender.replaceTrack().
  1307. const sender = this.findSenderByStream(oldTrack.getOriginalStream());
  1308. const stream = newTrack.getOriginalStream();
  1309. if (sender && stream) {
  1310. const track = stream.getTracks()[0];
  1311. if (track) {
  1312. return sender.replaceTrack(track, stream).then(() => {
  1313. // Since there is no need to do renegotiations we need to
  1314. // fix all ssrc-msid mappings here.
  1315. // NOTE: after sender.replaceTrack the sdp will remain the
  1316. // same but the stream attach to the new JitsiLocalTrack
  1317. // will have different msid. Luckily on FF we are not doing
  1318. // all the transformations related to video mute.
  1319. const ssrc = this.localSSRCs.get(oldTrack.rtcId);
  1320. this.localTracks.delete(oldTrack.rtcId);
  1321. this.localSSRCs.delete(oldTrack.rtcId);
  1322. this._addedStreams
  1323. = this._addedStreams.filter(s => s !== stream);
  1324. this.localTracks.set(newTrack.rtcId, newTrack);
  1325. // Override the msid of JitsiLocalTrack in order to be
  1326. // consistent with the SDP values.
  1327. newTrack.storedMSID = oldTrack.storedMSID;
  1328. this._addedStreams.push(stream);
  1329. this.localSSRCs.set(newTrack.rtcId, ssrc);
  1330. this.eventEmitter.emit(
  1331. RTCEvents.LOCAL_TRACK_SSRC_UPDATED,
  1332. newTrack,
  1333. extractPrimarySSRC(ssrc));
  1334. return false;
  1335. });
  1336. }
  1337. }
  1338. }
  1339. if (oldTrack) {
  1340. this.removeTrack(oldTrack);
  1341. }
  1342. if (newTrack) {
  1343. this.addTrack(newTrack);
  1344. }
  1345. return Promise.resolve(true);
  1346. };
  1347. /**
  1348. * Removes local track as part of the mute operation.
  1349. * @param {JitsiLocalTrack} localTrack the local track to be remove as part of
  1350. * the mute operation.
  1351. * @return {boolean} <tt>true</tt> if the underlying PeerConnection's state has
  1352. * changed and the renegotiation is required or <tt>false</tt> otherwise.
  1353. */
  1354. TraceablePeerConnection.prototype.removeTrackMute = function(localTrack) {
  1355. const webRtcStream = localTrack.getOriginalStream();
  1356. this.trace(
  1357. 'removeStreamMute',
  1358. localTrack.rtcId, webRtcStream ? webRtcStream.id : null);
  1359. if (!this._assertTrackBelongs('removeStreamMute', localTrack)) {
  1360. // Abort - nothing to be done here
  1361. return false;
  1362. }
  1363. if (webRtcStream) {
  1364. logger.info(
  1365. `Removing ${localTrack} as mute from ${this}`);
  1366. this._removeStream(webRtcStream);
  1367. return true;
  1368. }
  1369. logger.error(`removeStreamMute - no WebRTC stream for ${localTrack}`);
  1370. return false;
  1371. };
  1372. /**
  1373. * Remove stream handling for browsers supporting RTPSender
  1374. * @param stream: webrtc media stream
  1375. */
  1376. TraceablePeerConnection.prototype._handleSenderRemoveStream = function(
  1377. stream) {
  1378. if (!stream) {
  1379. // There is nothing to be changed
  1380. return;
  1381. }
  1382. const sender = this.findSenderByStream(stream);
  1383. if (sender) {
  1384. this.peerconnection.removeTrack(sender);
  1385. } else {
  1386. logger.log('Cannot remove tracks: no RTPSender.');
  1387. }
  1388. };
  1389. TraceablePeerConnection.prototype.createDataChannel = function(label, opts) {
  1390. this.trace('createDataChannel', label, opts);
  1391. return this.peerconnection.createDataChannel(label, opts);
  1392. };
  1393. /**
  1394. * Ensures that the simulcast ssrc-group appears after any other ssrc-groups
  1395. * in the SDP so that simulcast is properly activated.
  1396. *
  1397. * @param {Object} localSdp the WebRTC session description instance for
  1398. * the local description.
  1399. * @private
  1400. */
  1401. TraceablePeerConnection.prototype._ensureSimulcastGroupIsLast = function(
  1402. localSdp) {
  1403. let sdpStr = localSdp.sdp;
  1404. const videoStartIndex = sdpStr.indexOf('m=video');
  1405. const simStartIndex = sdpStr.indexOf('a=ssrc-group:SIM', videoStartIndex);
  1406. let otherStartIndex = sdpStr.lastIndexOf('a=ssrc-group');
  1407. if (simStartIndex === -1
  1408. || otherStartIndex === -1
  1409. || otherStartIndex === simStartIndex) {
  1410. return localSdp;
  1411. }
  1412. const simEndIndex = sdpStr.indexOf('\r\n', simStartIndex);
  1413. const simStr = sdpStr.substring(simStartIndex, simEndIndex + 2);
  1414. sdpStr = sdpStr.replace(simStr, '');
  1415. otherStartIndex = sdpStr.lastIndexOf('a=ssrc-group');
  1416. const otherEndIndex = sdpStr.indexOf('\r\n', otherStartIndex);
  1417. const sdpHead = sdpStr.slice(0, otherEndIndex);
  1418. const simStrTrimmed = simStr.trim();
  1419. const sdpTail = sdpStr.slice(otherEndIndex);
  1420. sdpStr = `${sdpHead}\r\n${simStrTrimmed}${sdpTail}`;
  1421. return new RTCSessionDescription({
  1422. type: localSdp.type,
  1423. sdp: sdpStr
  1424. });
  1425. };
  1426. /**
  1427. * Will adjust audio and video media direction in the given SDP object to
  1428. * reflect the current status of the {@link audioTransferActive} and
  1429. * {@link videoTransferActive} flags.
  1430. * @param {Object} localDescription the WebRTC session description instance for
  1431. * the local description.
  1432. * @private
  1433. */
  1434. TraceablePeerConnection.prototype._adjustLocalMediaDirection = function(
  1435. localDescription) {
  1436. const transformer = new SdpTransformWrap(localDescription.sdp);
  1437. let modifiedDirection = false;
  1438. const audioMedia = transformer.selectMedia('audio');
  1439. if (audioMedia) {
  1440. const desiredAudioDirection
  1441. = this._getDesiredMediaDirection(MediaType.AUDIO);
  1442. if (audioMedia.direction !== desiredAudioDirection) {
  1443. audioMedia.direction = desiredAudioDirection;
  1444. logger.info(
  1445. `Adjusted local audio direction to ${desiredAudioDirection}`);
  1446. modifiedDirection = true;
  1447. }
  1448. } else {
  1449. logger.warn('No "audio" media found int the local description');
  1450. }
  1451. const videoMedia = transformer.selectMedia('video');
  1452. if (videoMedia) {
  1453. const desiredVideoDirection
  1454. = this._getDesiredMediaDirection(MediaType.VIDEO);
  1455. if (videoMedia.direction !== desiredVideoDirection) {
  1456. videoMedia.direction = desiredVideoDirection;
  1457. logger.info(
  1458. `Adjusted local video direction to ${desiredVideoDirection}`);
  1459. modifiedDirection = true;
  1460. }
  1461. } else {
  1462. logger.warn('No "video" media found in the local description');
  1463. }
  1464. if (modifiedDirection) {
  1465. return new RTCSessionDescription({
  1466. type: localDescription.type,
  1467. sdp: transformer.toRawSDP()
  1468. });
  1469. }
  1470. return localDescription;
  1471. };
  1472. TraceablePeerConnection.prototype.setLocalDescription = function(description) {
  1473. let localSdp = description;
  1474. this.trace('setLocalDescription::preTransform', dumpSDP(localSdp));
  1475. if (this.options.disableH264 || this.options.preferH264) {
  1476. const parsedSdp = transform.parse(localSdp.sdp);
  1477. const videoMLine = parsedSdp.media.find(m => m.type === 'video');
  1478. if (this.options.disableH264) {
  1479. SDPUtil.stripVideoCodec(videoMLine, 'h264');
  1480. } else {
  1481. SDPUtil.preferVideoCodec(videoMLine, 'h264');
  1482. }
  1483. localSdp = new RTCSessionDescription({
  1484. type: localSdp.type,
  1485. sdp: transform.write(parsedSdp)
  1486. });
  1487. this.trace('setLocalDescription::postTransform (H264)',
  1488. dumpSDP(localSdp));
  1489. }
  1490. localSdp = this._adjustLocalMediaDirection(localSdp);
  1491. localSdp = this._ensureSimulcastGroupIsLast(localSdp);
  1492. // if we're using unified plan, transform to it first.
  1493. if (browser.usesUnifiedPlan()) {
  1494. localSdp = this.interop.toUnifiedPlan(localSdp);
  1495. this.trace(
  1496. 'setLocalDescription::postTransform (Unified Plan)',
  1497. dumpSDP(localSdp));
  1498. }
  1499. return new Promise((resolve, reject) => {
  1500. this.peerconnection.setLocalDescription(localSdp)
  1501. .then(() => {
  1502. this.trace('setLocalDescriptionOnSuccess');
  1503. const localUfrag = SDPUtil.getUfrag(localSdp.sdp);
  1504. if (localUfrag !== this.localUfrag) {
  1505. this.localUfrag = localUfrag;
  1506. this.eventEmitter.emit(
  1507. RTCEvents.LOCAL_UFRAG_CHANGED, this, localUfrag);
  1508. }
  1509. resolve();
  1510. }, err => {
  1511. this.trace('setLocalDescriptionOnFailure', err);
  1512. this.eventEmitter.emit(
  1513. RTCEvents.SET_LOCAL_DESCRIPTION_FAILED,
  1514. err, this);
  1515. reject(err);
  1516. });
  1517. });
  1518. };
  1519. /**
  1520. * Enables/disables audio media transmission on this peer connection. When
  1521. * disabled the SDP audio media direction in the local SDP will be adjusted to
  1522. * 'inactive' which means that no data will be sent nor accepted, but
  1523. * the connection should be kept alive.
  1524. * @param {boolean} active <tt>true</tt> to enable video media transmission or
  1525. * <tt>false</tt> to disable. If the value is not a boolean the call will have
  1526. * no effect.
  1527. * @return {boolean} <tt>true</tt> if the value has changed and sRD/sLD cycle
  1528. * needs to be executed in order for the changes to take effect or
  1529. * <tt>false</tt> if the given value was the same as the previous one.
  1530. * @public
  1531. */
  1532. TraceablePeerConnection.prototype.setAudioTransferActive = function(active) {
  1533. logger.debug(`${this} audio transfer active: ${active}`);
  1534. const changed = this.audioTransferActive !== active;
  1535. this.audioTransferActive = active;
  1536. return changed;
  1537. };
  1538. /**
  1539. * Takes in a *unified plan* offer and inserts the appropriate
  1540. * parameters for adding simulcast receive support.
  1541. * @param {Object} desc - A session description object
  1542. * @param {String} desc.type - the type (offer/answer)
  1543. * @param {String} desc.sdp - the sdp content
  1544. *
  1545. * @return {Object} A session description (same format as above) object
  1546. * with its sdp field modified to advertise simulcast receive support
  1547. */
  1548. TraceablePeerConnection.prototype._insertUnifiedPlanSimulcastReceive
  1549. = function(desc) {
  1550. const sdp = transform.parse(desc.sdp);
  1551. const video = sdp.media.find(mline => mline.type === 'video');
  1552. // In order of lowest to highest spatial quality
  1553. video.rids = [
  1554. {
  1555. id: SIM_LAYER_1_RID,
  1556. direction: 'recv'
  1557. },
  1558. {
  1559. id: SIM_LAYER_2_RID,
  1560. direction: 'recv'
  1561. },
  1562. {
  1563. id: SIM_LAYER_3_RID,
  1564. direction: 'recv'
  1565. }
  1566. ];
  1567. // eslint-disable-next-line camelcase
  1568. video.simulcast_03 = {
  1569. value: `recv rid=${SIM_LAYER_RIDS.join(';')}`
  1570. };
  1571. return new RTCSessionDescription({
  1572. type: desc.type,
  1573. sdp: transform.write(sdp)
  1574. });
  1575. };
  1576. TraceablePeerConnection.prototype.setRemoteDescription = function(description) {
  1577. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  1578. // TODO the focus should squeze or explode the remote simulcast
  1579. // eslint-disable-next-line no-param-reassign
  1580. description = this.simulcast.mungeRemoteDescription(description);
  1581. this.trace(
  1582. 'setRemoteDescription::postTransform (simulcast)',
  1583. dumpSDP(description));
  1584. if (this.options.preferH264) {
  1585. const parsedSdp = transform.parse(description.sdp);
  1586. const videoMLine = parsedSdp.media.find(m => m.type === 'video');
  1587. SDPUtil.preferVideoCodec(videoMLine, 'h264');
  1588. // eslint-disable-next-line no-param-reassign
  1589. description = new RTCSessionDescription({
  1590. type: description.type,
  1591. sdp: transform.write(parsedSdp)
  1592. });
  1593. }
  1594. // If the browser uses unified plan, transform to it first
  1595. if (browser.usesUnifiedPlan()) {
  1596. // eslint-disable-next-line no-param-reassign
  1597. description = new RTCSessionDescription({
  1598. type: description.type,
  1599. sdp: this.rtxModifier.stripRtx(description.sdp)
  1600. });
  1601. this.trace(
  1602. 'setRemoteDescription::postTransform (stripRtx)',
  1603. dumpSDP(description));
  1604. // eslint-disable-next-line no-param-reassign
  1605. description = this.interop.toUnifiedPlan(description);
  1606. this.trace(
  1607. 'setRemoteDescription::postTransform (Plan A)',
  1608. dumpSDP(description));
  1609. if (this.isSimulcastOn()) {
  1610. // eslint-disable-next-line no-param-reassign
  1611. description = this._insertUnifiedPlanSimulcastReceive(description);
  1612. this.trace(
  1613. 'setRemoteDescription::postTransform (sim receive)',
  1614. dumpSDP(description));
  1615. }
  1616. } else {
  1617. // Plan B
  1618. // eslint-disable-next-line no-param-reassign
  1619. description = normalizePlanB(description);
  1620. }
  1621. // Safari WebRTC errors when no supported video codec is found in the offer.
  1622. // To prevent the error, inject H264 into the video mLine.
  1623. if (browser.isSafariWithWebrtc() && !browser.isSafariWithVP8()) {
  1624. logger.debug('Maybe injecting H264 into the remote description');
  1625. // eslint-disable-next-line no-param-reassign
  1626. description = this._injectH264IfNotPresent(description);
  1627. }
  1628. return new Promise((resolve, reject) => {
  1629. this.peerconnection.setRemoteDescription(description)
  1630. .then(() => {
  1631. this.trace('setRemoteDescriptionOnSuccess');
  1632. const remoteUfrag = SDPUtil.getUfrag(description.sdp);
  1633. if (remoteUfrag !== this.remoteUfrag) {
  1634. this.remoteUfrag = remoteUfrag;
  1635. this.eventEmitter.emit(
  1636. RTCEvents.REMOTE_UFRAG_CHANGED, this, remoteUfrag);
  1637. }
  1638. resolve();
  1639. }, err => {
  1640. this.trace('setRemoteDescriptionOnFailure', err);
  1641. this.eventEmitter.emit(
  1642. RTCEvents.SET_REMOTE_DESCRIPTION_FAILED,
  1643. err,
  1644. this);
  1645. reject(err);
  1646. });
  1647. });
  1648. };
  1649. /**
  1650. * Inserts an H264 payload into the description if not already present. This is
  1651. * need for Safari WebRTC, which errors when no supported video codec is found
  1652. * in the offer. Related bug reports:
  1653. * https://bugs.webkit.org/show_bug.cgi?id=173141
  1654. * https://bugs.chromium.org/p/webrtc/issues/detail?id=4957
  1655. *
  1656. * @param {RTCSessionDescription} description - An RTCSessionDescription
  1657. * to inject with an H264 payload.
  1658. * @private
  1659. * @returns {RTCSessionDescription}
  1660. */
  1661. TraceablePeerConnection.prototype._injectH264IfNotPresent = function(
  1662. description) {
  1663. const parsedSdp = transform.parse(description.sdp);
  1664. const videoMLine = parsedSdp.media.find(m => m.type === 'video');
  1665. if (!videoMLine) {
  1666. logger.debug('No videoMLine found, no need to inject H264.');
  1667. return description;
  1668. }
  1669. if (videoMLine.rtp.some(rtp => rtp.codec.toLowerCase() === 'h264')) {
  1670. logger.debug('H264 codec found in video mLine, no need to inject.');
  1671. return description;
  1672. }
  1673. const { fmtp, payloads, rtp } = videoMLine;
  1674. const payloadsArray = payloads.toString().split(' ');
  1675. let dummyPayloadType;
  1676. for (let i = 127; i >= 96; i--) {
  1677. if (!payloadsArray.includes(i)) {
  1678. dummyPayloadType = i;
  1679. payloadsArray.push(i);
  1680. videoMLine.payloads = payloadsArray.join(' ');
  1681. break;
  1682. }
  1683. }
  1684. if (typeof dummyPayloadType === 'undefined') {
  1685. logger.error('Could not find valid payload type to inject.');
  1686. return description;
  1687. }
  1688. rtp.push({
  1689. codec: 'H264',
  1690. payload: dummyPayloadType,
  1691. rate: 90000
  1692. });
  1693. fmtp.push({
  1694. config: 'level-asymmetry-allowed=1;'
  1695. + 'packetization-mode=1;'
  1696. + 'profile-level-id=42e01f',
  1697. payload: dummyPayloadType
  1698. });
  1699. logger.debug(
  1700. `Injecting H264 payload type ${dummyPayloadType} into video mLine.`);
  1701. return new RTCSessionDescription({
  1702. type: description.type,
  1703. sdp: transform.write(parsedSdp)
  1704. });
  1705. };
  1706. /**
  1707. * Enables/disables video media transmission on this peer connection. When
  1708. * disabled the SDP video media direction in the local SDP will be adjusted to
  1709. * 'inactive' which means that no data will be sent nor accepted, but
  1710. * the connection should be kept alive.
  1711. * @param {boolean} active <tt>true</tt> to enable video media transmission or
  1712. * <tt>false</tt> to disable. If the value is not a boolean the call will have
  1713. * no effect.
  1714. * @return {boolean} <tt>true</tt> if the value has changed and sRD/sLD cycle
  1715. * needs to be executed in order for the changes to take effect or
  1716. * <tt>false</tt> if the given value was the same as the previous one.
  1717. * @public
  1718. */
  1719. TraceablePeerConnection.prototype.setVideoTransferActive = function(active) {
  1720. logger.debug(`${this} video transfer active: ${active}`);
  1721. const changed = this.videoTransferActive !== active;
  1722. this.videoTransferActive = active;
  1723. return changed;
  1724. };
  1725. /**
  1726. * Makes the underlying TraceablePeerConnection generate new SSRC for
  1727. * the recvonly video stream.
  1728. */
  1729. TraceablePeerConnection.prototype.generateRecvonlySsrc = function() {
  1730. const newSSRC = SDPUtil.generateSsrc();
  1731. logger.info(`${this} generated new recvonly SSRC: ${newSSRC}`);
  1732. this.sdpConsistency.setPrimarySsrc(newSSRC);
  1733. };
  1734. /**
  1735. * Makes the underlying TraceablePeerConnection forget the current primary video
  1736. * SSRC.
  1737. */
  1738. TraceablePeerConnection.prototype.clearRecvonlySsrc = function() {
  1739. logger.info('Clearing primary video SSRC!');
  1740. this.sdpConsistency.clearVideoSsrcCache();
  1741. };
  1742. /**
  1743. * Closes underlying WebRTC PeerConnection instance and removes all remote
  1744. * tracks by emitting {@link RTCEvents.REMOTE_TRACK_REMOVED} for each one of
  1745. * them.
  1746. */
  1747. TraceablePeerConnection.prototype.close = function() {
  1748. this.trace('stop');
  1749. // Off SignalingEvents
  1750. this.signalingLayer.off(
  1751. SignalingEvents.PEER_MUTED_CHANGED, this._peerMutedChanged);
  1752. this.signalingLayer.off(
  1753. SignalingEvents.PEER_VIDEO_TYPE_CHANGED, this._peerVideoTypeChanged);
  1754. for (const peerTracks of this.remoteTracks.values()) {
  1755. for (const remoteTrack of peerTracks.values()) {
  1756. this._removeRemoteTrack(remoteTrack);
  1757. }
  1758. }
  1759. this.remoteTracks.clear();
  1760. this._addedStreams = [];
  1761. if (!this.rtc._removePeerConnection(this)) {
  1762. logger.error('RTC._removePeerConnection returned false');
  1763. }
  1764. if (this.statsinterval !== null) {
  1765. window.clearInterval(this.statsinterval);
  1766. this.statsinterval = null;
  1767. }
  1768. logger.info(`Closing ${this}...`);
  1769. this.peerconnection.close();
  1770. };
  1771. /**
  1772. * Modifies the values of the setup attributes (defined by
  1773. * {@link http://tools.ietf.org/html/rfc4145#section-4}) of a specific SDP
  1774. * answer in order to overcome a delay of 1 second in the connection
  1775. * establishment between some devices and Videobridge.
  1776. *
  1777. * @param {SDP} offer - the SDP offer to which the specified SDP answer is
  1778. * being prepared to respond
  1779. * @param {SDP} answer - the SDP to modify
  1780. * @private
  1781. */
  1782. const _fixAnswerRFC4145Setup = function(offer, answer) {
  1783. if (!(browser.isChromiumBased() || browser.isReactNative())) {
  1784. // It looks like Firefox doesn't agree with the fix (at least in its
  1785. // current implementation) because it effectively remains active even
  1786. // after we tell it to become passive. Apart from Firefox which I tested
  1787. // after the fix was deployed, I tested Chrome only. In order to prevent
  1788. // issues with other browsers, limit the fix to known devices for the
  1789. // time being.
  1790. return;
  1791. }
  1792. // XXX Videobridge is the (SDP) offerer and WebRTC (e.g. Chrome) is the
  1793. // answerer (as orchestrated by Jicofo). In accord with
  1794. // http://tools.ietf.org/html/rfc5245#section-5.2 and because both peers
  1795. // are ICE FULL agents, Videobridge will take on the controlling role and
  1796. // WebRTC will take on the controlled role. In accord with
  1797. // https://tools.ietf.org/html/rfc5763#section-5, Videobridge will use the
  1798. // setup attribute value of setup:actpass and WebRTC will be allowed to
  1799. // choose either the setup attribute value of setup:active or
  1800. // setup:passive. Chrome will by default choose setup:active because it is
  1801. // RECOMMENDED by the respective RFC since setup:passive adds additional
  1802. // latency. The case of setup:active allows WebRTC to send a DTLS
  1803. // ClientHello as soon as an ICE connectivity check of its succeeds.
  1804. // Unfortunately, Videobridge will be unable to respond immediately because
  1805. // may not have WebRTC's answer or may have not completed the ICE
  1806. // connectivity establishment. Even more unfortunate is that in the
  1807. // described scenario Chrome's DTLS implementation will insist on
  1808. // retransmitting its ClientHello after a second (the time is in accord
  1809. // with the respective RFC) and will thus cause the whole connection
  1810. // establishment to exceed at least 1 second. To work around Chrome's
  1811. // idiosyncracy, don't allow it to send a ClientHello i.e. change its
  1812. // default choice of setup:active to setup:passive.
  1813. if (offer && answer
  1814. && offer.media && answer.media
  1815. && offer.media.length === answer.media.length) {
  1816. answer.media.forEach((a, i) => {
  1817. if (SDPUtil.findLine(
  1818. offer.media[i],
  1819. 'a=setup:actpass',
  1820. offer.session)) {
  1821. answer.media[i]
  1822. = a.replace(/a=setup:active/g, 'a=setup:passive');
  1823. }
  1824. });
  1825. answer.raw = answer.session + answer.media.join('');
  1826. }
  1827. };
  1828. TraceablePeerConnection.prototype.createAnswer = function(constraints) {
  1829. if (browser.isFirefox() && this.isSimulcastOn()) {
  1830. const videoSender
  1831. = this.peerconnection.getSenders().find(sender =>
  1832. sender.track !== null && sender.track.kind === 'video');
  1833. const simParams = {
  1834. encodings: [
  1835. {
  1836. rid: SIM_LAYER_1_RID,
  1837. scaleResolutionDownBy: 4
  1838. },
  1839. {
  1840. rid: SIM_LAYER_2_RID,
  1841. scaleResolutionDownBy: 2
  1842. },
  1843. {
  1844. rid: SIM_LAYER_3_RID
  1845. }
  1846. ]
  1847. };
  1848. videoSender.setParameters(simParams);
  1849. }
  1850. return this._createOfferOrAnswer(false /* answer */, constraints);
  1851. };
  1852. TraceablePeerConnection.prototype.createOffer = function(constraints) {
  1853. return this._createOfferOrAnswer(true /* offer */, constraints);
  1854. };
  1855. TraceablePeerConnection.prototype._createOfferOrAnswer = function(
  1856. isOffer,
  1857. constraints) {
  1858. const logName = isOffer ? 'Offer' : 'Answer';
  1859. this.trace(`create${logName}`, JSON.stringify(constraints, null, ' '));
  1860. const handleSuccess = (resultSdp, resolveFn, rejectFn) => {
  1861. try {
  1862. this.trace(
  1863. `create${logName}OnSuccess::preTransform`, dumpSDP(resultSdp));
  1864. // if we're using unified plan, transform to Plan B.
  1865. if (browser.usesUnifiedPlan()) {
  1866. // eslint-disable-next-line no-param-reassign
  1867. resultSdp = this.interop.toPlanB(resultSdp);
  1868. this.trace(
  1869. `create${logName}OnSuccess::postTransform (Plan B)`,
  1870. dumpSDP(resultSdp));
  1871. if (this.isSimulcastOn()) {
  1872. // eslint-disable-next-line no-param-reassign
  1873. resultSdp
  1874. = this._injectSsrcGroupForUnifiedSimulcast(resultSdp);
  1875. this.trace(
  1876. `create${logName}OnSuccess::postTransform`
  1877. + '(inject ssrc group)', dumpSDP(resultSdp));
  1878. }
  1879. }
  1880. /**
  1881. * We don't keep ssrcs consitent for Firefox because rewriting
  1882. * the ssrcs between createAnswer and setLocalDescription breaks
  1883. * the caching in sdp-interop (sdp-interop must know about all
  1884. * ssrcs, and it updates its cache in toPlanB so if we rewrite them
  1885. * after that, when we try and go back to unified plan it will
  1886. * complain about unmapped ssrcs)
  1887. */
  1888. if (!browser.usesUnifiedPlan()) {
  1889. // If there are no local video tracks, then a "recvonly"
  1890. // SSRC needs to be generated
  1891. if (!this.hasAnyTracksOfType(MediaType.VIDEO)
  1892. && !this.sdpConsistency.hasPrimarySsrcCached()) {
  1893. this.generateRecvonlySsrc();
  1894. }
  1895. // eslint-disable-next-line no-param-reassign
  1896. resultSdp = new RTCSessionDescription({
  1897. type: resultSdp.type,
  1898. sdp: this.sdpConsistency.makeVideoPrimarySsrcsConsistent(
  1899. resultSdp.sdp)
  1900. });
  1901. this.trace(
  1902. `create${logName}OnSuccess::postTransform `
  1903. + '(make primary audio/video ssrcs consistent)',
  1904. dumpSDP(resultSdp));
  1905. }
  1906. // Add simulcast streams if simulcast is enabled
  1907. if (this.isSimulcastOn()) {
  1908. // eslint-disable-next-line no-param-reassign
  1909. resultSdp = this.simulcast.mungeLocalDescription(resultSdp);
  1910. this.trace(
  1911. `create${logName}`
  1912. + 'OnSuccess::postTransform (simulcast)',
  1913. dumpSDP(resultSdp));
  1914. }
  1915. if (!this.options.disableRtx && browser.supportsRtx()) {
  1916. // eslint-disable-next-line no-param-reassign
  1917. resultSdp = new RTCSessionDescription({
  1918. type: resultSdp.type,
  1919. sdp: this.rtxModifier.modifyRtxSsrcs(resultSdp.sdp)
  1920. });
  1921. this.trace(
  1922. `create${logName}`
  1923. + 'OnSuccess::postTransform (rtx modifier)',
  1924. dumpSDP(resultSdp));
  1925. }
  1926. // Fix the setup attribute (see _fixAnswerRFC4145Setup for
  1927. // details)
  1928. if (!isOffer) {
  1929. const remoteDescription
  1930. = new SDP(this.remoteDescription.sdp);
  1931. const localDescription = new SDP(resultSdp.sdp);
  1932. _fixAnswerRFC4145Setup(remoteDescription, localDescription);
  1933. // eslint-disable-next-line no-param-reassign
  1934. resultSdp = new RTCSessionDescription({
  1935. type: resultSdp.type,
  1936. sdp: localDescription.raw
  1937. });
  1938. }
  1939. const ssrcMap = extractSSRCMap(resultSdp);
  1940. logger.debug('Got local SSRCs MAP: ', ssrcMap);
  1941. this._processLocalSSRCsMap(ssrcMap);
  1942. resolveFn(resultSdp);
  1943. } catch (e) {
  1944. this.trace(`create${logName}OnError`, e);
  1945. this.trace(`create${logName}OnError`, dumpSDP(resultSdp));
  1946. logger.error(`create${logName}OnError`, e, dumpSDP(resultSdp));
  1947. rejectFn(e);
  1948. }
  1949. };
  1950. const handleFailure = (err, rejectFn) => {
  1951. this.trace(`create${logName}OnFailure`, err);
  1952. const eventType
  1953. = isOffer
  1954. ? RTCEvents.CREATE_OFFER_FAILED
  1955. : RTCEvents.CREATE_ANSWER_FAILED;
  1956. this.eventEmitter.emit(eventType, err, this);
  1957. rejectFn(err);
  1958. };
  1959. return new Promise((resolve, reject) => {
  1960. let oaPromise;
  1961. if (isOffer) {
  1962. oaPromise = this.peerconnection.createOffer(constraints);
  1963. } else {
  1964. oaPromise = this.peerconnection.createAnswer(constraints);
  1965. }
  1966. oaPromise
  1967. .then(
  1968. sdp => handleSuccess(sdp, resolve, reject),
  1969. error => handleFailure(error, reject));
  1970. });
  1971. };
  1972. /**
  1973. * Extract primary SSRC from given {@link TrackSSRCInfo} object.
  1974. * @param {TrackSSRCInfo} ssrcObj
  1975. * @return {number|null} the primary SSRC or <tt>null</tt>
  1976. */
  1977. function extractPrimarySSRC(ssrcObj) {
  1978. if (ssrcObj && ssrcObj.groups && ssrcObj.groups.length) {
  1979. return ssrcObj.groups[0].ssrcs[0];
  1980. } else if (ssrcObj && ssrcObj.ssrcs && ssrcObj.ssrcs.length) {
  1981. return ssrcObj.ssrcs[0];
  1982. }
  1983. return null;
  1984. }
  1985. /**
  1986. * Goes over the SSRC map extracted from the latest local description and tries
  1987. * to match them with the local tracks (by MSID). Will update the values
  1988. * currently stored in the {@link TraceablePeerConnection.localSSRCs} map.
  1989. * @param {Map<string,TrackSSRCInfo>} ssrcMap
  1990. * @private
  1991. */
  1992. TraceablePeerConnection.prototype._processLocalSSRCsMap = function(ssrcMap) {
  1993. for (const track of this.localTracks.values()) {
  1994. const trackMSID = track.storedMSID;
  1995. if (ssrcMap.has(trackMSID)) {
  1996. const newSSRC = ssrcMap.get(trackMSID);
  1997. if (!newSSRC) {
  1998. logger.error(`No SSRC found for: ${trackMSID} in ${this}`);
  1999. return;
  2000. }
  2001. const oldSSRC = this.localSSRCs.get(track.rtcId);
  2002. const newSSRCNum = extractPrimarySSRC(newSSRC);
  2003. const oldSSRCNum = extractPrimarySSRC(oldSSRC);
  2004. // eslint-disable-next-line no-negated-condition
  2005. if (newSSRCNum !== oldSSRCNum) {
  2006. if (oldSSRCNum === null) {
  2007. logger.info(
  2008. `Storing new local SSRC for ${track} in ${this}`,
  2009. newSSRC);
  2010. } else {
  2011. logger.error(
  2012. `Overwriting SSRC for ${track} ${trackMSID} in ${this
  2013. } with: `, newSSRC);
  2014. }
  2015. this.localSSRCs.set(track.rtcId, newSSRC);
  2016. this.eventEmitter.emit(
  2017. RTCEvents.LOCAL_TRACK_SSRC_UPDATED, track, newSSRCNum);
  2018. } else {
  2019. logger.debug(
  2020. `The local SSRC(${newSSRCNum}) for ${track} ${trackMSID}`
  2021. + `is still up to date in ${this}`);
  2022. }
  2023. } else {
  2024. logger.warn(`No local track matched with: ${trackMSID} in ${this}`);
  2025. }
  2026. }
  2027. };
  2028. TraceablePeerConnection.prototype.addIceCandidate = function(candidate) {
  2029. this.trace('addIceCandidate', JSON.stringify({
  2030. candidate: candidate.candidate,
  2031. sdpMid: candidate.sdpMid,
  2032. sdpMLineIndex: candidate.sdpMLineIndex,
  2033. usernameFragment: candidate.usernameFragment
  2034. }, null, ' '));
  2035. return this.peerconnection.addIceCandidate(candidate);
  2036. };
  2037. /**
  2038. * Obtains call-related stats from the peer connection.
  2039. *
  2040. * @param {Function} callback - The function to invoke after successfully
  2041. * obtaining stats.
  2042. * @param {Function} errback - The function to invoke after failing to obtain
  2043. * stats.
  2044. * @returns {void}
  2045. */
  2046. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  2047. // TODO (brian): After moving all browsers to adapter, check if adapter is
  2048. // accounting for different getStats apis, making the browser-checking-if
  2049. // unnecessary.
  2050. if (browser.isSafariWithWebrtc() || browser.isFirefox()
  2051. || browser.isReactNative()) {
  2052. // uses the new Promise based getStats
  2053. this.peerconnection.getStats()
  2054. .then(callback)
  2055. .catch(errback || (() => {
  2056. // Making sure that getStats won't fail if error callback is
  2057. // not passed.
  2058. }));
  2059. } else {
  2060. this.peerconnection.getStats(callback);
  2061. }
  2062. };
  2063. /**
  2064. * Generates and stores new SSRC info object for given local track.
  2065. * The method should be called only for a video track being added to this TPC
  2066. * in the muted state (given that the current browser uses this strategy).
  2067. * @param {JitsiLocalTrack} track
  2068. * @return {TPCSSRCInfo}
  2069. */
  2070. TraceablePeerConnection.prototype.generateNewStreamSSRCInfo = function(track) {
  2071. const rtcId = track.rtcId;
  2072. let ssrcInfo = this._getSSRC(rtcId);
  2073. if (ssrcInfo) {
  2074. logger.error(`Will overwrite local SSRCs for track ID: ${rtcId}`);
  2075. }
  2076. if (this.isSimulcastOn()) {
  2077. ssrcInfo = {
  2078. ssrcs: [],
  2079. groups: []
  2080. };
  2081. for (let i = 0; i < SIMULCAST_LAYERS; i++) {
  2082. ssrcInfo.ssrcs.push(SDPUtil.generateSsrc());
  2083. }
  2084. ssrcInfo.groups.push({
  2085. ssrcs: ssrcInfo.ssrcs.slice(),
  2086. semantics: 'SIM'
  2087. });
  2088. } else {
  2089. ssrcInfo = {
  2090. ssrcs: [ SDPUtil.generateSsrc() ],
  2091. groups: []
  2092. };
  2093. }
  2094. if (!this.options.disableRtx && browser.supportsRtx()) {
  2095. // Specifically use a for loop here because we'll
  2096. // be adding to the list we're iterating over, so we
  2097. // only want to iterate through the items originally
  2098. // on the list
  2099. const currNumSsrcs = ssrcInfo.ssrcs.length;
  2100. for (let i = 0; i < currNumSsrcs; ++i) {
  2101. const primarySsrc = ssrcInfo.ssrcs[i];
  2102. const rtxSsrc = SDPUtil.generateSsrc();
  2103. ssrcInfo.ssrcs.push(rtxSsrc);
  2104. ssrcInfo.groups.push({
  2105. ssrcs: [ primarySsrc, rtxSsrc ],
  2106. semantics: 'FID'
  2107. });
  2108. }
  2109. }
  2110. ssrcInfo.msid = track.storedMSID;
  2111. this.localSSRCs.set(rtcId, ssrcInfo);
  2112. return ssrcInfo;
  2113. };
  2114. const handleLayerSuspension = function(peerConnection, isSelected) {
  2115. if (!peerConnection.getSenders) {
  2116. logger.debug('Browser doesn\'t support RTPSender');
  2117. return;
  2118. }
  2119. const videoSender = peerConnection.getSenders()
  2120. .find(sender => sender.track.kind === 'video');
  2121. if (!videoSender) {
  2122. logger.warn('handleLayerSuspension unable to find video sender');
  2123. return;
  2124. }
  2125. if (!videoSender.getParameters) {
  2126. logger.debug('Browser doesn\'t support RTPSender parameters');
  2127. return;
  2128. }
  2129. const parameters = videoSender.getParameters();
  2130. if (isSelected) {
  2131. logger.debug('Currently selected, enabling all sim layers');
  2132. // Make sure all encodings are enabled
  2133. parameters.encodings.forEach(e => {
  2134. e.active = true;
  2135. });
  2136. } else {
  2137. logger.debug('Not currently selected, disabling upper layers');
  2138. // Turn off the upper simulcast layers
  2139. [ 1, 2 ].forEach(simIndex => {
  2140. if (parameters.encodings[simIndex]) {
  2141. parameters.encodings[simIndex].active = false;
  2142. }
  2143. });
  2144. }
  2145. videoSender.setParameters(parameters);
  2146. };
  2147. /**
  2148. * Set whether or not the endpoint is 'selected' by other endpoints, meaning
  2149. * it appears on their main stage
  2150. */
  2151. TraceablePeerConnection.prototype.setIsSelected = function(isSelected) {
  2152. if (this.options.enableLayerSuspension) {
  2153. logger.debug('Layer suspension enabled,'
  2154. + `currently selected? ${isSelected}`);
  2155. handleLayerSuspension(this.peerconnection, isSelected);
  2156. }
  2157. };
  2158. /**
  2159. * Creates a text representation of this <tt>TraceablePeerConnection</tt>
  2160. * instance.
  2161. * @return {string}
  2162. */
  2163. TraceablePeerConnection.prototype.toString = function() {
  2164. return `TPC[${this.id},p2p:${this.isP2P}]`;
  2165. };