您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

TraceablePeerConnection.js 63KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926
  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 RTCBrowserType from './RTCBrowserType';
  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. /* eslint-disable max-params */
  22. /**
  23. * Creates new instance of 'TraceablePeerConnection'.
  24. *
  25. * @param {RTC} rtc the instance of <tt>RTC</tt> service
  26. * @param {number} id the peer connection id assigned by the parent RTC module.
  27. * @param {SignalingLayer} signalingLayer the signaling layer instance
  28. * @param {object} iceConfig WebRTC 'PeerConnection' ICE config
  29. * @param {object} constraints WebRTC 'PeerConnection' constraints
  30. * @param {boolean} isP2P indicates whether or not the new instance will be used
  31. * in a peer to peer connection
  32. * @param {object} options <tt>TracablePeerConnection</tt> config options.
  33. * @param {boolean} options.disableSimulcast if set to 'true' will disable
  34. * the simulcast
  35. * @param {boolean} options.disableRtx if set to 'true' will disable the RTX
  36. * @param {boolean} options.preferH264 if set to 'true' H264 will be preferred
  37. * over other video codecs.
  38. *
  39. * FIXME: initially the purpose of TraceablePeerConnection was to be able to
  40. * debug the peer connection. Since many other responsibilities have been added
  41. * it would make sense to extract a separate class from it and come up with
  42. * a more suitable name.
  43. *
  44. * @constructor
  45. */
  46. export default function TraceablePeerConnection(
  47. rtc,
  48. id,
  49. signalingLayer,
  50. iceConfig,
  51. constraints,
  52. isP2P,
  53. options) {
  54. /**
  55. * Indicates whether or not this peer connection instance is actively
  56. * sending/receiving media. When set to <tt>false</tt> the SDP media
  57. * direction will be adjusted to 'inactive' in order to suspend media
  58. * transmission.
  59. * @type {boolean}
  60. * @private
  61. */
  62. this.mediaTransferActive = true;
  63. /**
  64. * The parent instance of RTC service which created this
  65. * <tt>TracablePeerConnection</tt>.
  66. * @type {RTC}
  67. */
  68. this.rtc = rtc;
  69. /**
  70. * The peer connection identifier assigned by the RTC module.
  71. * @type {number}
  72. */
  73. this.id = id;
  74. /**
  75. * Indicates whether or not this instance is used in a peer to peer
  76. * connection.
  77. * @type {boolean}
  78. */
  79. this.isP2P = isP2P;
  80. // FIXME: We should support multiple streams per jid.
  81. /**
  82. * The map holds remote tracks associated with this peer connection.
  83. * It maps user's JID to media type and remote track
  84. * (one track per media type per user's JID).
  85. * @type {Map<string, Map<MediaType, JitsiRemoteTrack>>}
  86. */
  87. this.remoteTracks = new Map();
  88. /**
  89. * A map which stores local tracks mapped by {@link JitsiLocalTrack.rtcId}
  90. * @type {Map<number, JitsiLocalTrack>}
  91. */
  92. this.localTracks = new Map();
  93. /**
  94. * @typedef {Object} TPCGroupInfo
  95. * @property {string} semantics the SSRC groups semantics
  96. * @property {Array<number>} ssrcs group's SSRCs in order where the first
  97. * one is group's primary SSRC, the second one is secondary (RTX) and so
  98. * on...
  99. */
  100. /**
  101. * @typedef {Object} TPCSSRCInfo
  102. * @property {Array<number>} ssrcs an array which holds all track's SSRCs
  103. * @property {Array<TPCGroupInfo>} groups an array stores all track's SSRC
  104. * groups
  105. */
  106. /**
  107. * Holds the info about local track's SSRCs mapped per their
  108. * {@link JitsiLocalTrack.rtcId}
  109. * @type {Map<number, TPCSSRCInfo>}
  110. */
  111. this.localSSRCs = new Map();
  112. /**
  113. * The local ICE username fragment for this session.
  114. */
  115. this.localUfrag = null;
  116. /**
  117. * The remote ICE username fragment for this session.
  118. */
  119. this.remoteUfrag = null;
  120. /**
  121. * The signaling layer which operates this peer connection.
  122. * @type {SignalingLayer}
  123. */
  124. this.signalingLayer = signalingLayer;
  125. // SignalingLayer listeners
  126. this._peerVideoTypeChanged = this._peerVideoTypeChanged.bind(this);
  127. this.signalingLayer.on(
  128. SignalingEvents.PEER_VIDEO_TYPE_CHANGED,
  129. this._peerVideoTypeChanged);
  130. this._peerMutedChanged = this._peerMutedChanged.bind(this);
  131. this.signalingLayer.on(
  132. SignalingEvents.PEER_MUTED_CHANGED,
  133. this._peerMutedChanged);
  134. this.options = options;
  135. this.peerconnection
  136. = new RTCUtils.RTCPeerConnectionType(iceConfig, constraints);
  137. this.updateLog = [];
  138. this.stats = {};
  139. this.statsinterval = null;
  140. /**
  141. * @type {number}
  142. */
  143. this.maxstats = 0;
  144. const Interop = require('sdp-interop').Interop;
  145. this.interop = new Interop();
  146. const Simulcast = require('sdp-simulcast');
  147. this.simulcast = new Simulcast({ numOfLayers: SIMULCAST_LAYERS,
  148. explodeRemoteSimulcast: false });
  149. this.sdpConsistency = new SdpConsistency(this.toString());
  150. /**
  151. * Munges local SDP provided to the Jingle Session in order to prevent from
  152. * sending SSRC updates on attach/detach and mute/unmute (for video).
  153. * @type {LocalSdpMunger}
  154. */
  155. this.localSdpMunger = new LocalSdpMunger(this);
  156. /**
  157. * TracablePeerConnection uses RTC's eventEmitter
  158. * @type {EventEmitter}
  159. */
  160. this.eventEmitter = rtc.eventEmitter;
  161. this.rtxModifier = new RtxModifier();
  162. // override as desired
  163. this.trace = (what, info) => {
  164. /* logger.warn('WTRACE', what, info);
  165. if (info && RTCBrowserType.isIExplorer()) {
  166. if (info.length > 1024) {
  167. logger.warn('WTRACE', what, info.substr(1024));
  168. }
  169. if (info.length > 2048) {
  170. logger.warn('WTRACE', what, info.substr(2048));
  171. }
  172. }*/
  173. this.updateLog.push({
  174. time: new Date(),
  175. type: what,
  176. value: info || ''
  177. });
  178. };
  179. this.onicecandidate = null;
  180. this.peerconnection.onicecandidate = event => {
  181. // FIXME: this causes stack overflow with Temasys Plugin
  182. if (!RTCBrowserType.isTemasysPluginUsed()) {
  183. this.trace(
  184. 'onicecandidate',
  185. JSON.stringify(event.candidate, null, ' '));
  186. }
  187. if (this.onicecandidate !== null) {
  188. this.onicecandidate(event);
  189. }
  190. };
  191. this.onaddstream = null;
  192. this.peerconnection.onaddstream = event => {
  193. this.trace('onaddstream', event.stream.id);
  194. if (this.onaddstream !== null) {
  195. this.onaddstream(event);
  196. }
  197. };
  198. this.onremovestream = null;
  199. this.peerconnection.onremovestream = event => {
  200. this.trace('onremovestream', event.stream.id);
  201. if (this.onremovestream !== null) {
  202. this.onremovestream(event);
  203. }
  204. };
  205. this.peerconnection.onaddstream
  206. = event => this._remoteStreamAdded(event.stream);
  207. this.peerconnection.onremovestream
  208. = event => this._remoteStreamRemoved(event.stream);
  209. this.onsignalingstatechange = null;
  210. this.peerconnection.onsignalingstatechange = event => {
  211. this.trace('onsignalingstatechange', this.signalingState);
  212. if (this.onsignalingstatechange !== null) {
  213. this.onsignalingstatechange(event);
  214. }
  215. };
  216. this.oniceconnectionstatechange = null;
  217. this.peerconnection.oniceconnectionstatechange = event => {
  218. this.trace('oniceconnectionstatechange', this.iceConnectionState);
  219. if (this.oniceconnectionstatechange !== null) {
  220. this.oniceconnectionstatechange(event);
  221. }
  222. };
  223. this.onnegotiationneeded = null;
  224. this.peerconnection.onnegotiationneeded = event => {
  225. this.trace('onnegotiationneeded');
  226. if (this.onnegotiationneeded !== null) {
  227. this.onnegotiationneeded(event);
  228. }
  229. };
  230. this.ondatachannel = null;
  231. this.peerconnection.ondatachannel = event => {
  232. this.trace('ondatachannel', event);
  233. if (this.ondatachannel !== null) {
  234. this.ondatachannel(event);
  235. }
  236. };
  237. // XXX: do all non-firefox browsers which we support also support this?
  238. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  239. this.statsinterval = window.setInterval(() => {
  240. this.peerconnection.getStats(stats => {
  241. const results = stats.result();
  242. const now = new Date();
  243. for (let i = 0; i < results.length; ++i) {
  244. results[i].names().forEach(name => {
  245. // eslint-disable-next-line no-shadow
  246. const id = `${results[i].id}-${name}`;
  247. let s = this.stats[id];
  248. if (!s) {
  249. this.stats[id] = s = {
  250. startTime: now,
  251. endTime: now,
  252. values: [],
  253. times: []
  254. };
  255. }
  256. s.values.push(results[i].stat(name));
  257. s.times.push(now.getTime());
  258. if (s.values.length > this.maxstats) {
  259. s.values.shift();
  260. s.times.shift();
  261. }
  262. s.endTime = now;
  263. });
  264. }
  265. });
  266. }, 1000);
  267. }
  268. logger.info(`Create new ${this}`);
  269. }
  270. /* eslint-enable max-params */
  271. /**
  272. * Returns a string representation of a SessionDescription object.
  273. */
  274. const dumpSDP = function(description) {
  275. if (typeof description === 'undefined' || description === null) {
  276. return '';
  277. }
  278. return `type: ${description.type}\r\n${description.sdp}`;
  279. };
  280. /**
  281. * Forwards the {@link peerconnection.iceConnectionState} state except that it
  282. * will convert "completed" into "connected" where both mean that the ICE has
  283. * succeeded and is up and running. We never see "completed" state for
  284. * the JVB connection, but it started appearing for the P2P one. This method
  285. * allows to adapt old logic to this new situation.
  286. * @return {string}
  287. */
  288. TraceablePeerConnection.prototype.getConnectionState = function() {
  289. const state = this.peerconnection.iceConnectionState;
  290. if (state === 'completed') {
  291. return 'connected';
  292. }
  293. return state;
  294. };
  295. /**
  296. * Obtains the media direction for given {@link MediaType}. The method takes
  297. * into account whether or not there are any local tracks for media and
  298. * the {@link mediaTransferActive} flag.
  299. * @param {MediaType} mediaType
  300. * @return {string} one of the SDP direction constants ('sendrecv, 'recvonly'
  301. * etc.) which should be used when setting local description on the peer
  302. * connection.
  303. * @private
  304. */
  305. TraceablePeerConnection.prototype._getDesiredMediaDirection
  306. = function(mediaType) {
  307. if (this.mediaTransferActive) {
  308. return this.hasAnyTracksOfType(mediaType) ? 'sendrecv' : 'recvonly';
  309. }
  310. return 'inactive';
  311. };
  312. /**
  313. * Tells whether or not this TPC instance is using Simulcast.
  314. * @return {boolean} <tt>true</tt> if simulcast is enabled and active or
  315. * <tt>false</tt> if it's turned off.
  316. */
  317. TraceablePeerConnection.prototype.isSimulcastOn = function() {
  318. return !this.options.disableSimulcast
  319. && RTCBrowserType.supportsSimulcast()
  320. && !this.isP2P;
  321. };
  322. /**
  323. * Handles {@link SignalingEvents.PEER_VIDEO_TYPE_CHANGED}
  324. * @param {string} endpointId the video owner's ID (MUC nickname)
  325. * @param {VideoType} videoType the new value
  326. * @private
  327. */
  328. TraceablePeerConnection.prototype._peerVideoTypeChanged
  329. = function(endpointId, videoType) {
  330. // Check if endpointId has a value to avoid action on random track
  331. if (!endpointId) {
  332. logger.error(`No endpointID on peerVideoTypeChanged ${this}`);
  333. return;
  334. }
  335. const videoTrack = this.getRemoteTracks(endpointId, MediaType.VIDEO);
  336. if (videoTrack.length) {
  337. // NOTE 1 track per media type is assumed
  338. videoTrack[0]._setVideoType(videoType);
  339. }
  340. };
  341. /**
  342. * Handles remote track mute / unmute events.
  343. * @param {string} endpointId the track owner's identifier (MUC nickname)
  344. * @param {MediaType} mediaType "audio" or "video"
  345. * @param {boolean} isMuted the new mute state
  346. * @private
  347. */
  348. TraceablePeerConnection.prototype._peerMutedChanged
  349. = function(endpointId, mediaType, isMuted) {
  350. // Check if endpointId is a value to avoid doing action on all remote tracks
  351. if (!endpointId) {
  352. logger.error('On peerMuteChanged - no endpoint ID');
  353. return;
  354. }
  355. const track = this.getRemoteTracks(endpointId, mediaType);
  356. if (track.length) {
  357. // NOTE 1 track per media type is assumed
  358. track[0].setMute(isMuted);
  359. }
  360. };
  361. /**
  362. * Obtains local tracks for given {@link MediaType}. If the <tt>mediaType</tt>
  363. * argument is omitted the list of all local tracks will be returned.
  364. * @param {MediaType} [mediaType]
  365. * @return {Array<JitsiLocalTrack>}
  366. */
  367. TraceablePeerConnection.prototype.getLocalTracks = function(mediaType) {
  368. let tracks = Array.from(this.localTracks.values());
  369. if (mediaType !== undefined) {
  370. tracks = tracks.filter(track => track.getType() === mediaType);
  371. }
  372. return tracks;
  373. };
  374. /**
  375. * Checks whether or not this {@link TraceablePeerConnection} instance contains
  376. * any local tracks for given <tt>mediaType</tt>.
  377. * @param {MediaType} mediaType
  378. * @return {boolean}
  379. */
  380. TraceablePeerConnection.prototype.hasAnyTracksOfType = function(mediaType) {
  381. if (!mediaType) {
  382. throw new Error('"mediaType" is required');
  383. }
  384. return this.getLocalTracks(mediaType).length > 0;
  385. };
  386. /**
  387. * Obtains all remote tracks currently known to this PeerConnection instance.
  388. * @param {string} [endpointId] the track owner's identifier (MUC nickname)
  389. * @param {MediaType} [mediaType] the remote tracks will be filtered
  390. * by their media type if this argument is specified.
  391. * @return {Array<JitsiRemoteTrack>}
  392. */
  393. TraceablePeerConnection.prototype.getRemoteTracks
  394. = function(endpointId, mediaType) {
  395. const remoteTracks = [];
  396. const endpoints
  397. = endpointId ? [ endpointId ] : this.remoteTracks.keys();
  398. for (const endpoint of endpoints) {
  399. const endpointTrackMap = this.remoteTracks.get(endpoint);
  400. if (!endpointTrackMap) {
  401. // Otherwise an empty Map() would have to be allocated above
  402. // eslint-disable-next-line no-continue
  403. continue;
  404. }
  405. for (const trackMediaType of endpointTrackMap.keys()) {
  406. // per media type filtering
  407. if (!mediaType || mediaType === trackMediaType) {
  408. const mediaTrack = endpointTrackMap.get(trackMediaType);
  409. if (mediaTrack) {
  410. remoteTracks.push(mediaTrack);
  411. }
  412. }
  413. }
  414. }
  415. return remoteTracks;
  416. };
  417. /**
  418. * Tries to find {@link JitsiTrack} for given SSRC number. It will search both
  419. * local and remote tracks bound to this instance.
  420. * @param {number} ssrc
  421. * @return {JitsiTrack|null}
  422. */
  423. TraceablePeerConnection.prototype.getTrackBySSRC = function(ssrc) {
  424. if (typeof ssrc !== 'number') {
  425. throw new Error(`SSRC ${ssrc} is not a number`);
  426. }
  427. for (const localTrack of this.localTracks.values()) {
  428. if (this.getLocalSSRC(localTrack) === ssrc) {
  429. return localTrack;
  430. }
  431. }
  432. for (const remoteTrack of this.getRemoteTracks()) {
  433. if (remoteTrack.getSSRC() === ssrc) {
  434. return remoteTrack;
  435. }
  436. }
  437. return null;
  438. };
  439. /**
  440. * Called when new remote MediaStream is added to the PeerConnection.
  441. * @param {MediaStream} stream the WebRTC MediaStream for remote participant
  442. */
  443. TraceablePeerConnection.prototype._remoteStreamAdded = function(stream) {
  444. const streamId = RTC.getStreamID(stream);
  445. if (!RTC.isUserStreamById(streamId)) {
  446. logger.info(
  447. `${this} ignored remote 'stream added' event for non-user stream`
  448. + `id: ${streamId}`);
  449. return;
  450. }
  451. // Bind 'addtrack'/'removetrack' event handlers
  452. if (RTCBrowserType.isChrome() || RTCBrowserType.isNWJS()
  453. || RTCBrowserType.isElectron()) {
  454. stream.onaddtrack = event => {
  455. this._remoteTrackAdded(event.target, event.track);
  456. };
  457. stream.onremovetrack = event => {
  458. this._remoteTrackRemoved(event.target, event.track);
  459. };
  460. }
  461. // Call remoteTrackAdded for each track in the stream
  462. const streamAudioTracks = stream.getAudioTracks();
  463. for (const audioTrack of streamAudioTracks) {
  464. this._remoteTrackAdded(stream, audioTrack);
  465. }
  466. const streamVideoTracks = stream.getVideoTracks();
  467. for (const videoTrack of streamVideoTracks) {
  468. this._remoteTrackAdded(stream, videoTrack);
  469. }
  470. };
  471. /**
  472. * Called on "track added" and "stream added" PeerConnection events (because we
  473. * handle streams on per track basis). Finds the owner and the SSRC for
  474. * the track and passes that to ChatRoom for further processing.
  475. * @param {MediaStream} stream the WebRTC MediaStream instance which is
  476. * the parent of the track
  477. * @param {MediaStreamTrack} track the WebRTC MediaStreamTrack added for remote
  478. * participant
  479. */
  480. TraceablePeerConnection.prototype._remoteTrackAdded = function(stream, track) {
  481. const streamId = RTC.getStreamID(stream);
  482. const mediaType = track.kind;
  483. logger.info(`${this} remote track added:`, streamId, mediaType);
  484. // look up an associated JID for a stream id
  485. if (!mediaType) {
  486. GlobalOnErrorHandler.callErrorHandler(
  487. new Error(
  488. `MediaType undefined for remote track, stream id: ${streamId}`
  489. ));
  490. // Abort
  491. return;
  492. }
  493. const remoteSDP = new SDP(this.remoteDescription.sdp);
  494. const mediaLines
  495. = remoteSDP.media.filter(mls => mls.startsWith(`m=${mediaType}`));
  496. if (!mediaLines.length) {
  497. GlobalOnErrorHandler.callErrorHandler(
  498. new Error(
  499. `No media lines for type ${mediaType
  500. } found in remote SDP for remote track: ${streamId}`));
  501. // Abort
  502. return;
  503. }
  504. let ssrcLines = SDPUtil.findLines(mediaLines[0], 'a=ssrc:');
  505. ssrcLines = ssrcLines.filter(
  506. line => {
  507. const msid
  508. = RTCBrowserType.isTemasysPluginUsed() ? 'mslabel' : 'msid';
  509. return line.indexOf(`${msid}:${streamId}`) !== -1;
  510. });
  511. if (!ssrcLines.length) {
  512. GlobalOnErrorHandler.callErrorHandler(
  513. new Error(
  514. `No SSRC lines for streamId ${streamId
  515. } for remote track, media type: ${mediaType}`));
  516. // Abort
  517. return;
  518. }
  519. // FIXME the length of ssrcLines[0] not verified, but it will fail
  520. // with global error handler anyway
  521. const ssrcStr = ssrcLines[0].substring(7).split(' ')[0];
  522. const trackSsrc = Number(ssrcStr);
  523. const ownerEndpointId = this.signalingLayer.getSSRCOwner(trackSsrc);
  524. if (isNaN(trackSsrc) || trackSsrc < 0) {
  525. GlobalOnErrorHandler.callErrorHandler(
  526. new Error(
  527. `Invalid SSRC: ${ssrcStr
  528. } for remote track, msid: ${streamId
  529. } media type: ${mediaType}`));
  530. // Abort
  531. return;
  532. } else if (!ownerEndpointId) {
  533. GlobalOnErrorHandler.callErrorHandler(
  534. new Error(
  535. `No SSRC owner known for: ${trackSsrc
  536. } for remote track, msid: ${streamId
  537. } media type: ${mediaType}`));
  538. // Abort
  539. return;
  540. }
  541. logger.log(`${this} associated ssrc`, ownerEndpointId, trackSsrc);
  542. const peerMediaInfo
  543. = this.signalingLayer.getPeerMediaInfo(ownerEndpointId, mediaType);
  544. if (!peerMediaInfo) {
  545. GlobalOnErrorHandler.callErrorHandler(
  546. new Error(
  547. `${this}: no peer media info available for ${
  548. ownerEndpointId}`));
  549. return;
  550. }
  551. const muted = peerMediaInfo.muted;
  552. const videoType = peerMediaInfo.videoType; // can be undefined
  553. this._createRemoteTrack(
  554. ownerEndpointId, stream, track, mediaType, videoType, trackSsrc, muted);
  555. };
  556. // FIXME cleanup params
  557. /* eslint-disable max-params */
  558. /**
  559. * Initializes a new JitsiRemoteTrack instance with the data provided by
  560. * the signaling layer and SDP.
  561. *
  562. * @param {string} ownerEndpointId the owner's endpoint ID (MUC nickname)
  563. * @param {MediaStream} stream the WebRTC stream instance
  564. * @param {MediaStreamTrack} track the WebRTC track instance
  565. * @param {MediaType} mediaType the track's type of the media
  566. * @param {VideoType} [videoType] the track's type of the video (if applicable)
  567. * @param {number} ssrc the track's main SSRC number
  568. * @param {boolean} muted the initial muted status
  569. */
  570. TraceablePeerConnection.prototype._createRemoteTrack
  571. = function(ownerEndpointId, stream, track, mediaType, videoType, ssrc, muted) {
  572. const remoteTrack
  573. = new JitsiRemoteTrack(
  574. this.rtc, this.rtc.conference,
  575. ownerEndpointId,
  576. stream, track, mediaType, videoType, ssrc, muted, this.isP2P);
  577. let remoteTracksMap = this.remoteTracks.get(ownerEndpointId);
  578. if (!remoteTracksMap) {
  579. remoteTracksMap = new Map();
  580. this.remoteTracks.set(ownerEndpointId, remoteTracksMap);
  581. }
  582. if (remoteTracksMap.has(mediaType)) {
  583. logger.error(
  584. `${this} overwriting remote track! ${remoteTrack}`,
  585. ownerEndpointId, mediaType);
  586. }
  587. remoteTracksMap.set(mediaType, remoteTrack);
  588. // FIXME not cool to use RTC's eventEmitter
  589. this.rtc.eventEmitter.emit(RTCEvents.REMOTE_TRACK_ADDED, remoteTrack);
  590. };
  591. /* eslint-enable max-params */
  592. /**
  593. * Handles remote stream removal.
  594. * @param stream the WebRTC MediaStream object which is being removed from the
  595. * PeerConnection
  596. */
  597. TraceablePeerConnection.prototype._remoteStreamRemoved = function(stream) {
  598. if (!RTC.isUserStream(stream)) {
  599. const id = RTC.getStreamID(stream);
  600. logger.info(
  601. `Ignored remote 'stream removed' event for non-user stream ${id}`);
  602. return;
  603. }
  604. // Call remoteTrackRemoved for each track in the stream
  605. const streamVideoTracks = stream.getVideoTracks();
  606. for (const videoTrack of streamVideoTracks) {
  607. this._remoteTrackRemoved(stream, videoTrack);
  608. }
  609. const streamAudioTracks = stream.getAudioTracks();
  610. for (const audioTrack of streamAudioTracks) {
  611. this._remoteTrackRemoved(stream, audioTrack);
  612. }
  613. };
  614. /**
  615. * Handles remote media track removal.
  616. * @param {MediaStream} stream WebRTC MediaStream instance which is the parent
  617. * of the track.
  618. * @param {MediaStreamTrack} track the WebRTC MediaStreamTrack which has been
  619. * removed from the PeerConnection.
  620. */
  621. TraceablePeerConnection.prototype._remoteTrackRemoved
  622. = function(stream, track) {
  623. const streamId = RTC.getStreamID(stream);
  624. const trackId = track && track.id;
  625. logger.info(`${this} - remote track removed: ${streamId}, ${trackId}`);
  626. if (!streamId) {
  627. GlobalOnErrorHandler.callErrorHandler(
  628. new Error(`${this} remote track removal failed - no stream ID`));
  629. return;
  630. }
  631. if (!trackId) {
  632. GlobalOnErrorHandler.callErrorHandler(
  633. new Error(`${this} remote track removal failed - no track ID`));
  634. return;
  635. }
  636. if (!this._removeRemoteTrack(streamId, trackId)) {
  637. // NOTE this warning is always printed when user leaves the room,
  638. // because we remove remote tracks manually on MUC member left event,
  639. // before the SSRCs are removed by Jicofo. In most cases it is fine to
  640. // ignore this warning, but still it's better to keep it printed for
  641. // debugging purposes.
  642. //
  643. // We could change the behaviour to emit track removed only from here,
  644. // but the order of the events will change and consuming apps could
  645. // behave unexpectedly (the "user left" event would come before "track
  646. // removed" events).
  647. logger.warn(
  648. `${this} Removed track not found for msid: ${streamId},
  649. track id: ${trackId}`);
  650. }
  651. };
  652. /**
  653. * Finds remote track by it's stream and track ids.
  654. * @param {string} streamId the media stream id as defined by the WebRTC
  655. * @param {string} trackId the media track id as defined by the WebRTC
  656. * @return {JitsiRemoteTrack|undefined} the track's instance or
  657. * <tt>undefined</tt> if not found.
  658. * @private
  659. */
  660. TraceablePeerConnection.prototype._getRemoteTrackById
  661. = function(streamId, trackId) {
  662. // .find will break the loop once the first match is found
  663. for (const endpointTrackMap of this.remoteTracks.values()) {
  664. for (const mediaTrack of endpointTrackMap.values()) {
  665. // FIXME verify and try to use ===
  666. /* eslint-disable eqeqeq */
  667. if (mediaTrack.getStreamId() == streamId
  668. && mediaTrack.getTrackId() == trackId) {
  669. return mediaTrack;
  670. }
  671. /* eslint-enable eqeqeq */
  672. }
  673. }
  674. return undefined;
  675. };
  676. /**
  677. * Removes all JitsiRemoteTracks associated with given MUC nickname
  678. * (resource part of the JID). Returns array of removed tracks.
  679. *
  680. * @param {string} owner - The resource part of the MUC JID.
  681. * @returns {JitsiRemoteTrack[]}
  682. */
  683. TraceablePeerConnection.prototype.removeRemoteTracks = function(owner) {
  684. const removedTracks = [];
  685. const remoteTracksMap = this.remoteTracks.get(owner);
  686. if (remoteTracksMap) {
  687. const removedAudioTrack = remoteTracksMap.get(MediaType.AUDIO);
  688. const removedVideoTrack = remoteTracksMap.get(MediaType.VIDEO);
  689. removedAudioTrack && removedTracks.push(removedAudioTrack);
  690. removedVideoTrack && removedTracks.push(removedVideoTrack);
  691. this.remoteTracks.delete(owner);
  692. }
  693. logger.debug(
  694. `${this} removed remote tracks for ${owner
  695. } count: ${removedTracks.length}`);
  696. return removedTracks;
  697. };
  698. /**
  699. * Removes and disposes <tt>JitsiRemoteTrack</tt> identified by given stream and
  700. * track ids.
  701. *
  702. * @param {string} streamId the media stream id as defined by the WebRTC
  703. * @param {string} trackId the media track id as defined by the WebRTC
  704. * @returns {JitsiRemoteTrack|undefined} the track which has been removed or
  705. * <tt>undefined</tt> if no track matching given stream and track ids was
  706. * found.
  707. */
  708. TraceablePeerConnection.prototype._removeRemoteTrack
  709. = function(streamId, trackId) {
  710. const toBeRemoved = this._getRemoteTrackById(streamId, trackId);
  711. if (toBeRemoved) {
  712. toBeRemoved.dispose();
  713. const remoteTracksMap
  714. = this.remoteTracks.get(toBeRemoved.getParticipantId());
  715. // If _getRemoteTrackById succeeded it must be a valid value or
  716. // we're good to crash
  717. if (!remoteTracksMap.delete(toBeRemoved.getType())) {
  718. logger.error(
  719. `Failed to remove ${toBeRemoved} - type mapping messed up ?`);
  720. }
  721. // FIXME not cool to use RTC's eventEmitter
  722. this.rtc.eventEmitter.emit(
  723. RTCEvents.REMOTE_TRACK_REMOVED, toBeRemoved);
  724. }
  725. return toBeRemoved;
  726. };
  727. /**
  728. * @typedef {Object} SSRCGroupInfo
  729. * @property {Array<number>} ssrcs group's SSRCs
  730. * @property {string} semantics
  731. */
  732. /**
  733. * @typedef {Object} TrackSSRCInfo
  734. * @property {Array<number>} ssrcs track's SSRCs
  735. * @property {Array<SSRCGroupInfo>} groups track's SSRC groups
  736. */
  737. /**
  738. * Returns map with keys msid and <tt>TrackSSRCInfo</tt> values.
  739. * @param {Object} desc the WebRTC SDP instance.
  740. * @return {Map<string,TrackSSRCInfo>}
  741. */
  742. function extractSSRCMap(desc) {
  743. /**
  744. * Track SSRC infos mapped by stream ID (msid)
  745. * @type {Map<string,TrackSSRCInfo>}
  746. */
  747. const ssrcMap = new Map();
  748. /**
  749. * Groups mapped by primary SSRC number
  750. * @type {Map<number,Array<SSRCGroupInfo>>}
  751. */
  752. const groupsMap = new Map();
  753. if (typeof desc !== 'object' || desc === null
  754. || typeof desc.sdp !== 'string') {
  755. logger.warn('An empty description was passed as an argument.');
  756. return ssrcMap;
  757. }
  758. const session = transform.parse(desc.sdp);
  759. if (!Array.isArray(session.media)) {
  760. return ssrcMap;
  761. }
  762. for (const mLine of session.media) {
  763. if (!Array.isArray(mLine.ssrcs)) {
  764. continue; // eslint-disable-line no-continue
  765. }
  766. if (Array.isArray(mLine.ssrcGroups)) {
  767. for (const group of mLine.ssrcGroups) {
  768. if (typeof group.semantics !== 'undefined'
  769. && typeof group.ssrcs !== 'undefined') {
  770. // Parse SSRCs and store as numbers
  771. const groupSSRCs
  772. = group.ssrcs.split(' ')
  773. .map(ssrcStr => parseInt(ssrcStr, 10));
  774. const primarySSRC = groupSSRCs[0];
  775. // Note that group.semantics is already present
  776. group.ssrcs = groupSSRCs;
  777. // eslint-disable-next-line max-depth
  778. if (!groupsMap.has(primarySSRC)) {
  779. groupsMap.set(primarySSRC, []);
  780. }
  781. groupsMap.get(primarySSRC).push(group);
  782. }
  783. }
  784. }
  785. for (const ssrc of mLine.ssrcs) {
  786. if (ssrc.attribute !== 'msid') {
  787. continue; // eslint-disable-line no-continue
  788. }
  789. const msid = ssrc.value;
  790. let ssrcInfo = ssrcMap.get(msid);
  791. if (!ssrcInfo) {
  792. ssrcInfo = {
  793. ssrcs: [],
  794. groups: [],
  795. msid
  796. };
  797. ssrcMap.set(msid, ssrcInfo);
  798. }
  799. const ssrcNumber = ssrc.id;
  800. ssrcInfo.ssrcs.push(ssrcNumber);
  801. if (groupsMap.has(ssrcNumber)) {
  802. const ssrcGroups = groupsMap.get(ssrcNumber);
  803. for (const group of ssrcGroups) {
  804. ssrcInfo.groups.push(group);
  805. }
  806. }
  807. }
  808. }
  809. return ssrcMap;
  810. }
  811. /**
  812. * Takes a SessionDescription object and returns a "normalized" version.
  813. * Currently it only takes care of ordering the a=ssrc lines.
  814. */
  815. const normalizePlanB = function(desc) {
  816. if (typeof desc !== 'object' || desc === null
  817. || typeof desc.sdp !== 'string') {
  818. logger.warn('An empty description was passed as an argument.');
  819. return desc;
  820. }
  821. // eslint-disable-next-line no-shadow
  822. const transform = require('sdp-transform');
  823. const session = transform.parse(desc.sdp);
  824. if (typeof session !== 'undefined'
  825. && typeof session.media !== 'undefined'
  826. && Array.isArray(session.media)) {
  827. session.media.forEach(mLine => {
  828. // Chrome appears to be picky about the order in which a=ssrc lines
  829. // are listed in an m-line when rtx is enabled (and thus there are
  830. // a=ssrc-group lines with FID semantics). Specifically if we have
  831. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  832. // the "a=ssrc:S1" lines, SRD fails.
  833. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  834. // first.
  835. const firstSsrcs = [];
  836. const newSsrcLines = [];
  837. if (typeof mLine.ssrcGroups !== 'undefined'
  838. && Array.isArray(mLine.ssrcGroups)) {
  839. mLine.ssrcGroups.forEach(group => {
  840. if (typeof group.semantics !== 'undefined'
  841. && group.semantics === 'FID') {
  842. if (typeof group.ssrcs !== 'undefined') {
  843. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  844. }
  845. }
  846. });
  847. }
  848. if (Array.isArray(mLine.ssrcs)) {
  849. let i;
  850. for (i = 0; i < mLine.ssrcs.length; i++) {
  851. if (typeof mLine.ssrcs[i] === 'object'
  852. && typeof mLine.ssrcs[i].id !== 'undefined'
  853. && firstSsrcs.indexOf(mLine.ssrcs[i].id) >= 0) {
  854. newSsrcLines.push(mLine.ssrcs[i]);
  855. delete mLine.ssrcs[i];
  856. }
  857. }
  858. for (i = 0; i < mLine.ssrcs.length; i++) {
  859. if (typeof mLine.ssrcs[i] !== 'undefined') {
  860. newSsrcLines.push(mLine.ssrcs[i]);
  861. }
  862. }
  863. mLine.ssrcs = newSsrcLines;
  864. }
  865. });
  866. }
  867. const resStr = transform.write(session);
  868. return new RTCSessionDescription({
  869. type: desc.type,
  870. sdp: resStr
  871. });
  872. };
  873. /**
  874. *
  875. * @param {JitsiLocalTrack} localTrack
  876. */
  877. TraceablePeerConnection.prototype.getLocalSSRC = function(localTrack) {
  878. const ssrcInfo = this._getSSRC(localTrack.rtcId);
  879. return ssrcInfo && ssrcInfo.ssrcs[0];
  880. };
  881. /* eslint-disable-next-line vars-on-top */
  882. const getters = {
  883. signalingState() {
  884. return this.peerconnection.signalingState;
  885. },
  886. iceConnectionState() {
  887. return this.peerconnection.iceConnectionState;
  888. },
  889. localDescription() {
  890. let desc = this.peerconnection.localDescription;
  891. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  892. // if we're running on FF, transform to Plan B first.
  893. if (RTCBrowserType.usesUnifiedPlan()) {
  894. desc = this.interop.toPlanB(desc);
  895. this.trace('getLocalDescription::postTransform (Plan B)',
  896. dumpSDP(desc));
  897. }
  898. if (RTCBrowserType.doesVideoMuteByStreamRemove()) {
  899. this.localSdpMunger.maybeMungeLocalSdp(desc);
  900. logger.debug(
  901. 'getLocalDescription::postTransform (munge local SDP)', desc);
  902. }
  903. return desc || {};
  904. },
  905. remoteDescription() {
  906. let desc = this.peerconnection.remoteDescription;
  907. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  908. // if we're running on FF, transform to Plan B first.
  909. if (RTCBrowserType.usesUnifiedPlan()) {
  910. desc = this.interop.toPlanB(desc);
  911. this.trace(
  912. 'getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  913. }
  914. return desc || {};
  915. }
  916. };
  917. Object.keys(getters).forEach(prop => {
  918. Object.defineProperty(
  919. TraceablePeerConnection.prototype,
  920. prop, {
  921. get: getters[prop]
  922. }
  923. );
  924. });
  925. TraceablePeerConnection.prototype._getSSRC = function(rtcId) {
  926. return this.localSSRCs.get(rtcId);
  927. };
  928. /**
  929. * Add {@link JitsiLocalTrack} to this TPC.
  930. * @param {JitsiLocalTrack} track
  931. */
  932. TraceablePeerConnection.prototype.addTrack = function(track) {
  933. const rtcId = track.rtcId;
  934. logger.info(`add ${track} to: ${this}`);
  935. if (this.localTracks.has(rtcId)) {
  936. logger.error(`${track} is already in ${this}`);
  937. return;
  938. }
  939. this.localTracks.set(rtcId, track);
  940. const webrtcStream = track.getOriginalStream();
  941. if (webrtcStream) {
  942. this._addStream(webrtcStream);
  943. // It's not ok for a track to not have a WebRTC stream if:
  944. } else if (!RTCBrowserType.doesVideoMuteByStreamRemove()
  945. || track.isAudioTrack()
  946. || (track.isVideoTrack() && !track.isMuted())) {
  947. logger.error(`${this} no WebRTC stream for: ${track}`);
  948. }
  949. // Muted video tracks do not have WebRTC stream
  950. if (RTCBrowserType.doesVideoMuteByStreamRemove()
  951. && track.isVideoTrack() && track.isMuted()) {
  952. const ssrcInfo = this.generateNewStreamSSRCInfo(track);
  953. this.sdpConsistency.setPrimarySsrc(ssrcInfo.ssrcs[0]);
  954. const simGroup
  955. = ssrcInfo.groups.find(groupInfo => groupInfo.semantics === 'SIM');
  956. if (simGroup) {
  957. this.simulcast.setSsrcCache(simGroup.ssrcs);
  958. }
  959. const fidGroups
  960. = ssrcInfo.groups.filter(
  961. groupInfo => groupInfo.semantics === 'FID');
  962. if (fidGroups) {
  963. const rtxSsrcMapping = new Map();
  964. fidGroups.forEach(fidGroup => {
  965. const primarySsrc = fidGroup.ssrcs[0];
  966. const rtxSsrc = fidGroup.ssrcs[1];
  967. rtxSsrcMapping.set(primarySsrc, rtxSsrc);
  968. });
  969. this.rtxModifier.setSsrcCache(rtxSsrcMapping);
  970. }
  971. }
  972. };
  973. /**
  974. * Adds local track as part of the unmute operation.
  975. * @param {JitsiLocalTrack} track the track to be added as part of the unmute
  976. * operation
  977. * @return {boolean} <tt>true</tt> if the state of underlying PC has changed and
  978. * the renegotiation is required or <tt>false</tt> otherwise.
  979. */
  980. TraceablePeerConnection.prototype.addTrackUnmute = function(track) {
  981. if (!this._assertTrackBelongs('addTrackUnmute', track)) {
  982. // Abort
  983. return false;
  984. }
  985. logger.info(`Adding ${track} as unmute to ${this}`);
  986. const webRtcStream = track.getOriginalStream();
  987. if (!webRtcStream) {
  988. logger.error(
  989. `Unable to add ${track} as unmute to ${this} - no WebRTC stream`);
  990. return false;
  991. }
  992. this._addStream(webRtcStream);
  993. return true;
  994. };
  995. /**
  996. * Adds WebRTC media stream to the underlying PeerConnection
  997. * @param {MediaStream} mediaStream
  998. * @private
  999. */
  1000. TraceablePeerConnection.prototype._addStream = function(mediaStream) {
  1001. this.peerconnection.addStream(mediaStream);
  1002. };
  1003. /**
  1004. * Removes WebRTC media stream from the underlying PeerConection
  1005. * @param {MediaStream} mediaStream
  1006. */
  1007. TraceablePeerConnection.prototype._removeStream = function(mediaStream) {
  1008. if (RTCBrowserType.isFirefox()) {
  1009. this._handleFirefoxRemoveStream(mediaStream);
  1010. } else {
  1011. this.peerconnection.removeStream(mediaStream);
  1012. }
  1013. };
  1014. /**
  1015. * This method when called will check if given <tt>localTrack</tt> belongs to
  1016. * this TPC (that it has been previously added using {@link addTrack}). If the
  1017. * track does not belong an error message will be logged.
  1018. * @param {string} methodName the method name that will be logged in an error
  1019. * message
  1020. * @param {JitsiLocalTrack} localTrack
  1021. * @return {boolean} <tt>true</tt> if given local track belongs to this TPC or
  1022. * <tt>false</tt> otherwise.
  1023. * @private
  1024. */
  1025. TraceablePeerConnection.prototype._assertTrackBelongs
  1026. = function(methodName, localTrack) {
  1027. const doesBelong = this.localTracks.has(localTrack.rtcId);
  1028. if (!doesBelong) {
  1029. logger.error(
  1030. `${methodName}: ${localTrack} does not belong to ${this}`);
  1031. }
  1032. return doesBelong;
  1033. };
  1034. /**
  1035. * Remove local track from this TPC.
  1036. * @param {JitsiLocalTrack} localTrack the track to be removed from this TPC.
  1037. *
  1038. * FIXME It should probably remove a boolean just like {@link removeTrackMute}
  1039. * The same applies to addTrack.
  1040. */
  1041. TraceablePeerConnection.prototype.removeTrack = function(localTrack) {
  1042. const webRtcStream = localTrack.getOriginalStream();
  1043. this.trace(
  1044. 'removeStream',
  1045. localTrack.rtcId, webRtcStream ? webRtcStream.id : undefined);
  1046. if (!this._assertTrackBelongs('removeStream', localTrack)) {
  1047. // Abort - nothing to be done here
  1048. return;
  1049. }
  1050. this.localTracks.delete(localTrack.rtcId);
  1051. this.localSSRCs.delete(localTrack.rtcId);
  1052. if (webRtcStream) {
  1053. if (RTCBrowserType.isFirefox()) {
  1054. this._handleFirefoxRemoveStream(webRtcStream);
  1055. } else {
  1056. this.peerconnection.removeStream(webRtcStream);
  1057. }
  1058. }
  1059. };
  1060. /**
  1061. * Removes local track as part of the mute operation.
  1062. * @param {JitsiLocalTrack} localTrack the local track to be remove as part of
  1063. * the mute operation.
  1064. * @return {boolean} <tt>true</tt> if the underlying PeerConnection's state has
  1065. * changed and the renegotiation is required or <tt>false</tt> otherwise.
  1066. */
  1067. TraceablePeerConnection.prototype.removeTrackMute = function(localTrack) {
  1068. const webRtcStream = localTrack.getOriginalStream();
  1069. this.trace(
  1070. 'removeStreamMute',
  1071. localTrack.rtcId, webRtcStream ? webRtcStream.id : null);
  1072. if (!this._assertTrackBelongs('removeStreamMute', localTrack)) {
  1073. // Abort - nothing to be done here
  1074. return false;
  1075. }
  1076. if (webRtcStream) {
  1077. logger.info(
  1078. `Removing ${localTrack} as mute from ${this}`);
  1079. this._removeStream(webRtcStream);
  1080. return true;
  1081. }
  1082. logger.error(`removeStreamMute - no WebRTC stream for ${localTrack}`);
  1083. return false;
  1084. };
  1085. /**
  1086. * Remove stream handling for firefox
  1087. * @param stream: webrtc media stream
  1088. */
  1089. TraceablePeerConnection.prototype._handleFirefoxRemoveStream
  1090. = function(stream) {
  1091. if (!stream) {
  1092. // There is nothing to be changed
  1093. return;
  1094. }
  1095. let sender = null;
  1096. // On Firefox we don't replace MediaStreams as this messes up the
  1097. // m-lines (which can't be removed in Plan Unified) and brings a lot
  1098. // of complications. Instead, we use the RTPSender and remove just
  1099. // the track.
  1100. let track = null;
  1101. if (stream.getAudioTracks() && stream.getAudioTracks().length) {
  1102. track = stream.getAudioTracks()[0];
  1103. } else if (stream.getVideoTracks() && stream.getVideoTracks().length) {
  1104. track = stream.getVideoTracks()[0];
  1105. }
  1106. if (!track) {
  1107. logger.error('Cannot remove tracks: no tracks.');
  1108. return;
  1109. }
  1110. // Find the right sender (for audio or video)
  1111. this.peerconnection.getSenders().some(s => {
  1112. if (s.track === track) {
  1113. sender = s;
  1114. return true;
  1115. }
  1116. return false;
  1117. });
  1118. if (sender) {
  1119. this.peerconnection.removeTrack(sender);
  1120. } else {
  1121. logger.log('Cannot remove tracks: no RTPSender.');
  1122. }
  1123. };
  1124. TraceablePeerConnection.prototype.createDataChannel = function(label, opts) {
  1125. this.trace('createDataChannel', label, opts);
  1126. return this.peerconnection.createDataChannel(label, opts);
  1127. };
  1128. /**
  1129. * Ensures that the simulcast ssrc-group appears after any other ssrc-groups
  1130. * in the SDP so that simulcast is properly activated.
  1131. *
  1132. * @param {Object} localSdp the WebRTC session description instance for
  1133. * the local description.
  1134. * @private
  1135. */
  1136. TraceablePeerConnection.prototype._ensureSimulcastGroupIsLast
  1137. = function(localSdp) {
  1138. let sdpStr = localSdp.sdp;
  1139. const videoStartIndex = sdpStr.indexOf('m=video');
  1140. const simStartIndex = sdpStr.indexOf('a=ssrc-group:SIM', videoStartIndex);
  1141. let otherStartIndex = sdpStr.lastIndexOf('a=ssrc-group');
  1142. if (simStartIndex === -1
  1143. || otherStartIndex === -1
  1144. || otherStartIndex === simStartIndex) {
  1145. return;
  1146. }
  1147. const simEndIndex = sdpStr.indexOf('\r\n', simStartIndex);
  1148. const simStr = sdpStr.substring(simStartIndex, simEndIndex + 2);
  1149. sdpStr = sdpStr.replace(simStr, '');
  1150. otherStartIndex = sdpStr.lastIndexOf('a=ssrc-group');
  1151. const otherEndIndex = sdpStr.indexOf('\r\n', otherStartIndex);
  1152. const sdpHead = sdpStr.slice(0, otherEndIndex);
  1153. const simStrTrimmed = simStr.trim();
  1154. const sdpTail = sdpStr.slice(otherEndIndex);
  1155. sdpStr = `${sdpHead}\r\n${simStrTrimmed}${sdpTail}`;
  1156. localSdp.sdp = sdpStr;
  1157. };
  1158. /**
  1159. * Will adjust audio and video media direction in the given SDP object to
  1160. * reflect the current status of the {@link mediaTransferActive} flag.
  1161. * @param {Object} localDescription the WebRTC session description instance for
  1162. * the local description.
  1163. * @private
  1164. */
  1165. TraceablePeerConnection.prototype._adjustLocalMediaDirection
  1166. = function(localDescription) {
  1167. const transformer = new SdpTransformWrap(localDescription.sdp);
  1168. let modifiedDirection = false;
  1169. const audioMedia = transformer.selectMedia('audio');
  1170. if (audioMedia) {
  1171. const desiredAudioDirection
  1172. = this._getDesiredMediaDirection(MediaType.AUDIO);
  1173. if (audioMedia.direction !== desiredAudioDirection) {
  1174. audioMedia.direction = desiredAudioDirection;
  1175. logger.info(
  1176. `Adjusted local audio direction to ${desiredAudioDirection}`);
  1177. modifiedDirection = true;
  1178. }
  1179. } else {
  1180. logger.warn('No "audio" media found int the local description');
  1181. }
  1182. const videoMedia = transformer.selectMedia('video');
  1183. if (videoMedia) {
  1184. const desiredVideoDirection
  1185. = this._getDesiredMediaDirection(MediaType.VIDEO);
  1186. if (videoMedia.direction !== desiredVideoDirection) {
  1187. videoMedia.direction = desiredVideoDirection;
  1188. logger.info(
  1189. `Adjusted local video direction to ${desiredVideoDirection}`);
  1190. modifiedDirection = true;
  1191. }
  1192. } else {
  1193. logger.warn('No "video" media found in the local description');
  1194. }
  1195. if (modifiedDirection) {
  1196. localDescription.sdp = transformer.toRawSDP();
  1197. }
  1198. };
  1199. TraceablePeerConnection.prototype.setLocalDescription
  1200. = function(description, successCallback, failureCallback) {
  1201. let localSdp = description;
  1202. this.trace('setLocalDescription::preTransform', dumpSDP(localSdp));
  1203. this._adjustLocalMediaDirection(localSdp);
  1204. this._ensureSimulcastGroupIsLast(localSdp);
  1205. // if we're using unified plan, transform to it first.
  1206. if (RTCBrowserType.usesUnifiedPlan()) {
  1207. localSdp = this.interop.toUnifiedPlan(localSdp);
  1208. this.trace(
  1209. 'setLocalDescription::postTransform (Unified Plan)',
  1210. dumpSDP(localSdp));
  1211. }
  1212. this.peerconnection.setLocalDescription(localSdp,
  1213. () => {
  1214. this.trace('setLocalDescriptionOnSuccess');
  1215. const localUfrag = SDPUtil.getUfrag(localSdp.sdp);
  1216. if (localUfrag !== this.localUfrag) {
  1217. this.localUfrag = localUfrag;
  1218. this.rtc.eventEmitter.emit(
  1219. RTCEvents.LOCAL_UFRAG_CHANGED, this, localUfrag);
  1220. }
  1221. successCallback();
  1222. },
  1223. err => {
  1224. this.trace('setLocalDescriptionOnFailure', err);
  1225. this.eventEmitter.emit(
  1226. RTCEvents.SET_LOCAL_DESCRIPTION_FAILED,
  1227. err, this);
  1228. failureCallback(err);
  1229. }
  1230. );
  1231. };
  1232. /**
  1233. * Enables/disables media transmission on this peer connection. When disabled
  1234. * the SDP media direction in the local SDP will be adjusted to 'inactive' which
  1235. * means that no data will be received or sent, but the connection should be
  1236. * kept alive.
  1237. * @param {boolean} active <tt>true</tt> to enable the media transmission or
  1238. * <tt>false</tt> to disable.
  1239. * @public
  1240. */
  1241. TraceablePeerConnection.prototype.setMediaTransferActive = function(active) {
  1242. this.mediaTransferActive = active;
  1243. };
  1244. TraceablePeerConnection.prototype.setRemoteDescription
  1245. = function(description, successCallback, failureCallback) {
  1246. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  1247. // TODO the focus should squeze or explode the remote simulcast
  1248. // eslint-disable-next-line no-param-reassign
  1249. description = this.simulcast.mungeRemoteDescription(description);
  1250. this.trace(
  1251. 'setRemoteDescription::postTransform (simulcast)',
  1252. dumpSDP(description));
  1253. if (this.options.preferH264) {
  1254. const parsedSdp = transform.parse(description.sdp);
  1255. const videoMLine = parsedSdp.media.find(m => m.type === 'video');
  1256. SDPUtil.preferVideoCodec(videoMLine, 'h264');
  1257. description.sdp = transform.write(parsedSdp);
  1258. }
  1259. // If the browser uses unified plan, transform to it first
  1260. if (RTCBrowserType.usesUnifiedPlan()) {
  1261. description.sdp = this.rtxModifier.stripRtx(description.sdp);
  1262. this.trace(
  1263. 'setRemoteDescription::postTransform (stripRtx)',
  1264. dumpSDP(description));
  1265. // eslint-disable-next-line no-param-reassign
  1266. description = this.interop.toUnifiedPlan(description);
  1267. this.trace(
  1268. 'setRemoteDescription::postTransform (Plan A)',
  1269. dumpSDP(description));
  1270. } else {
  1271. // Plan B
  1272. // eslint-disable-next-line no-param-reassign
  1273. description = normalizePlanB(description);
  1274. }
  1275. this.peerconnection.setRemoteDescription(
  1276. description,
  1277. () => {
  1278. this.trace('setRemoteDescriptionOnSuccess');
  1279. const remoteUfrag = SDPUtil.getUfrag(description.sdp);
  1280. if (remoteUfrag !== this.remoteUfrag) {
  1281. this.remoteUfrag = remoteUfrag;
  1282. this.rtc.eventEmitter.emit(
  1283. RTCEvents.REMOTE_UFRAG_CHANGED, this, remoteUfrag);
  1284. }
  1285. successCallback();
  1286. },
  1287. err => {
  1288. this.trace('setRemoteDescriptionOnFailure', err);
  1289. this.eventEmitter.emit(
  1290. RTCEvents.SET_REMOTE_DESCRIPTION_FAILED,
  1291. err,
  1292. this);
  1293. failureCallback(err);
  1294. });
  1295. };
  1296. /**
  1297. * Makes the underlying TraceablePeerConnection generate new SSRC for
  1298. * the recvonly video stream.
  1299. */
  1300. TraceablePeerConnection.prototype.generateRecvonlySsrc = function() {
  1301. const newSSRC = SDPUtil.generateSsrc();
  1302. logger.info(`${this} generated new recvonly SSRC: ${newSSRC}`);
  1303. this.sdpConsistency.setPrimarySsrc(newSSRC);
  1304. };
  1305. /**
  1306. * Makes the underlying TraceablePeerConnection forget the current primary video
  1307. * SSRC.
  1308. */
  1309. TraceablePeerConnection.prototype.clearRecvonlySsrc = function() {
  1310. logger.info('Clearing primary video SSRC!');
  1311. this.sdpConsistency.clearVideoSsrcCache();
  1312. };
  1313. TraceablePeerConnection.prototype.close = function() {
  1314. this.trace('stop');
  1315. // Off SignalingEvents
  1316. this.signalingLayer.off(
  1317. SignalingEvents.PEER_MUTED_CHANGED, this._peerMutedChanged);
  1318. this.signalingLayer.off(
  1319. SignalingEvents.PEER_VIDEO_TYPE_CHANGED, this._peerVideoTypeChanged);
  1320. if (!this.rtc._removePeerConnection(this)) {
  1321. logger.error('RTC._removePeerConnection returned false');
  1322. }
  1323. if (this.statsinterval !== null) {
  1324. window.clearInterval(this.statsinterval);
  1325. this.statsinterval = null;
  1326. }
  1327. this.peerconnection.close();
  1328. };
  1329. /**
  1330. * Modifies the values of the setup attributes (defined by
  1331. * {@link http://tools.ietf.org/html/rfc4145#section-4}) of a specific SDP
  1332. * answer in order to overcome a delay of 1 second in the connection
  1333. * establishment between Chrome and Videobridge.
  1334. *
  1335. * @param {SDP} offer - the SDP offer to which the specified SDP answer is
  1336. * being prepared to respond
  1337. * @param {SDP} answer - the SDP to modify
  1338. * @private
  1339. */
  1340. const _fixAnswerRFC4145Setup = function(offer, answer) {
  1341. if (!RTCBrowserType.isChrome()) {
  1342. // It looks like Firefox doesn't agree with the fix (at least in its
  1343. // current implementation) because it effectively remains active even
  1344. // after we tell it to become passive. Apart from Firefox which I tested
  1345. // after the fix was deployed, I tested Chrome only. In order to prevent
  1346. // issues with other browsers, limit the fix to Chrome for the time
  1347. // being.
  1348. return;
  1349. }
  1350. // XXX Videobridge is the (SDP) offerer and WebRTC (e.g. Chrome) is the
  1351. // answerer (as orchestrated by Jicofo). In accord with
  1352. // http://tools.ietf.org/html/rfc5245#section-5.2 and because both peers
  1353. // are ICE FULL agents, Videobridge will take on the controlling role and
  1354. // WebRTC will take on the controlled role. In accord with
  1355. // https://tools.ietf.org/html/rfc5763#section-5, Videobridge will use the
  1356. // setup attribute value of setup:actpass and WebRTC will be allowed to
  1357. // choose either the setup attribute value of setup:active or
  1358. // setup:passive. Chrome will by default choose setup:active because it is
  1359. // RECOMMENDED by the respective RFC since setup:passive adds additional
  1360. // latency. The case of setup:active allows WebRTC to send a DTLS
  1361. // ClientHello as soon as an ICE connectivity check of its succeeds.
  1362. // Unfortunately, Videobridge will be unable to respond immediately because
  1363. // may not have WebRTC's answer or may have not completed the ICE
  1364. // connectivity establishment. Even more unfortunate is that in the
  1365. // described scenario Chrome's DTLS implementation will insist on
  1366. // retransmitting its ClientHello after a second (the time is in accord
  1367. // with the respective RFC) and will thus cause the whole connection
  1368. // establishment to exceed at least 1 second. To work around Chrome's
  1369. // idiosyncracy, don't allow it to send a ClientHello i.e. change its
  1370. // default choice of setup:active to setup:passive.
  1371. if (offer && answer
  1372. && offer.media && answer.media
  1373. && offer.media.length === answer.media.length) {
  1374. answer.media.forEach((a, i) => {
  1375. if (SDPUtil.findLine(
  1376. offer.media[i],
  1377. 'a=setup:actpass',
  1378. offer.session)) {
  1379. answer.media[i]
  1380. = a.replace(/a=setup:active/g, 'a=setup:passive');
  1381. }
  1382. });
  1383. answer.raw = answer.session + answer.media.join('');
  1384. }
  1385. };
  1386. TraceablePeerConnection.prototype.createAnswer
  1387. = function(successCallback, failureCallback, constraints) {
  1388. this._createOfferOrAnswer(
  1389. false /* answer */, successCallback, failureCallback, constraints);
  1390. };
  1391. TraceablePeerConnection.prototype.createOffer
  1392. = function(successCallback, failureCallback, constraints) {
  1393. this._createOfferOrAnswer(
  1394. true /* offer */, successCallback, failureCallback, constraints);
  1395. };
  1396. /* eslint-disable max-params */
  1397. TraceablePeerConnection.prototype._createOfferOrAnswer
  1398. = function(isOffer, successCallback, failureCallback, constraints) {
  1399. const logName = isOffer ? 'Offer' : 'Answer';
  1400. this.trace(`create${logName}`, JSON.stringify(constraints, null, ' '));
  1401. const _successCallback = resultSdp => {
  1402. try {
  1403. this.trace(
  1404. `create${logName}OnSuccess::preTransform`, dumpSDP(resultSdp));
  1405. // if we're using unified plan, transform to Plan B.
  1406. if (RTCBrowserType.usesUnifiedPlan()) {
  1407. // eslint-disable-next-line no-param-reassign
  1408. resultSdp = this.interop.toPlanB(resultSdp);
  1409. this.trace(
  1410. `create${logName}OnSuccess::postTransform (Plan B)`,
  1411. dumpSDP(resultSdp));
  1412. }
  1413. /**
  1414. * We don't keep ssrcs consitent for Firefox because rewriting
  1415. * the ssrcs between createAnswer and setLocalDescription breaks
  1416. * the caching in sdp-interop (sdp-interop must know about all
  1417. * ssrcs, and it updates its cache in toPlanB so if we rewrite them
  1418. * after that, when we try and go back to unified plan it will
  1419. * complain about unmapped ssrcs)
  1420. */
  1421. if (!RTCBrowserType.isFirefox()) {
  1422. // If there are no local video tracks, then a "recvonly"
  1423. // SSRC needs to be generated
  1424. if (!this.hasAnyTracksOfType(MediaType.VIDEO)
  1425. && !this.sdpConsistency.hasPrimarySsrcCached()) {
  1426. this.generateRecvonlySsrc();
  1427. }
  1428. resultSdp.sdp
  1429. = this.sdpConsistency.makeVideoPrimarySsrcsConsistent(
  1430. resultSdp.sdp);
  1431. this.trace(
  1432. `create${logName}OnSuccess::postTransform `
  1433. + '(make primary audio/video ssrcs consistent)',
  1434. dumpSDP(resultSdp));
  1435. }
  1436. // Add simulcast streams if simulcast is enabled
  1437. if (this.isSimulcastOn()) {
  1438. // eslint-disable-next-line no-param-reassign
  1439. resultSdp = this.simulcast.mungeLocalDescription(resultSdp);
  1440. this.trace(
  1441. `create${logName}`
  1442. + 'OnSuccess::postTransform (simulcast)',
  1443. dumpSDP(resultSdp));
  1444. }
  1445. if (!this.options.disableRtx && RTCBrowserType.supportsRtx()) {
  1446. resultSdp.sdp
  1447. = this.rtxModifier.modifyRtxSsrcs(resultSdp.sdp);
  1448. this.trace(
  1449. `create${logName}`
  1450. + 'OnSuccess::postTransform (rtx modifier)',
  1451. dumpSDP(resultSdp));
  1452. }
  1453. // Fix the setup attribute (see _fixAnswerRFC4145Setup for
  1454. // details)
  1455. if (!isOffer) {
  1456. const remoteDescription
  1457. = new SDP(this.remoteDescription.sdp);
  1458. const localDescription = new SDP(resultSdp.sdp);
  1459. _fixAnswerRFC4145Setup(remoteDescription, localDescription);
  1460. resultSdp.sdp = localDescription.raw;
  1461. }
  1462. const ssrcMap = extractSSRCMap(resultSdp);
  1463. logger.debug('Got local SSRCs MAP: ', ssrcMap);
  1464. this._processLocalSSRCsMap(ssrcMap);
  1465. successCallback(resultSdp);
  1466. } catch (e) {
  1467. this.trace(`create${logName}OnError`, e);
  1468. this.trace(`create${logName}OnError`, dumpSDP(resultSdp));
  1469. logger.error(`create${logName}OnError`, e, dumpSDP(resultSdp));
  1470. failureCallback(e);
  1471. }
  1472. };
  1473. const _errorCallback = err => {
  1474. this.trace(`create${logName}OnFailure`, err);
  1475. const eventType
  1476. = isOffer
  1477. ? RTCEvents.CREATE_OFFER_FAILED
  1478. : RTCEvents.CREATE_ANSWER_FAILED;
  1479. this.eventEmitter.emit(eventType, err, this);
  1480. failureCallback(err);
  1481. };
  1482. // NOTE Temasys plugin does not support "bind" on peerconnection methods
  1483. if (isOffer) {
  1484. this.peerconnection.createOffer(
  1485. _successCallback, _errorCallback, constraints);
  1486. } else {
  1487. this.peerconnection.createAnswer(
  1488. _successCallback, _errorCallback, constraints);
  1489. }
  1490. };
  1491. /* eslint-enable max-params */
  1492. /**
  1493. * Extract primary SSRC from given {@link TrackSSRCInfo} object.
  1494. * @param {TrackSSRCInfo} ssrcObj
  1495. * @return {number|null} the primary SSRC or <tt>null</tt>
  1496. */
  1497. function extractPrimarySSRC(ssrcObj) {
  1498. if (ssrcObj && ssrcObj.groups && ssrcObj.groups.length) {
  1499. return ssrcObj.groups[0].ssrcs[0];
  1500. } else if (ssrcObj && ssrcObj.ssrcs && ssrcObj.ssrcs.length) {
  1501. return ssrcObj.ssrcs[0];
  1502. }
  1503. return null;
  1504. }
  1505. /**
  1506. * Goes over the SSRC map extracted from the latest local description and tries
  1507. * to match them with the local tracks (by MSID). Will update the values
  1508. * currently stored in the {@link TraceablePeerConnection.localSSRCs} map.
  1509. * @param {Map<string,TrackSSRCInfo>} ssrcMap
  1510. * @private
  1511. */
  1512. TraceablePeerConnection.prototype._processLocalSSRCsMap = function(ssrcMap) {
  1513. for (const track of this.localTracks.values()) {
  1514. const trackMSID = track.getMSID();
  1515. if (ssrcMap.has(trackMSID)) {
  1516. const newSSRC = ssrcMap.get(trackMSID);
  1517. if (!newSSRC) {
  1518. logger.error(`No SSRC found for: ${trackMSID} in ${this}`);
  1519. return;
  1520. }
  1521. const oldSSRC = this.localSSRCs.get(track.rtcId);
  1522. const newSSRCNum = extractPrimarySSRC(newSSRC);
  1523. const oldSSRCNum = extractPrimarySSRC(oldSSRC);
  1524. // eslint-disable-next-line no-negated-condition
  1525. if (newSSRCNum !== oldSSRCNum) {
  1526. if (oldSSRCNum === null) {
  1527. logger.info(
  1528. `Storing new local SSRC for ${track} in ${this}`,
  1529. newSSRC);
  1530. } else {
  1531. logger.error(
  1532. `Overwriting SSRC for ${track} ${trackMSID} in ${this
  1533. } with: `, newSSRC);
  1534. }
  1535. this.localSSRCs.set(track.rtcId, newSSRC);
  1536. } else {
  1537. logger.debug(
  1538. `The local SSRC(${newSSRCNum}) for ${track} ${trackMSID}`
  1539. + `is still up to date in ${this}`);
  1540. }
  1541. } else {
  1542. logger.warn(`No local track matched with: ${trackMSID} in ${this}`);
  1543. }
  1544. }
  1545. };
  1546. TraceablePeerConnection.prototype.addIceCandidate
  1547. = function(candidate, successCallback, failureCallback) {
  1548. // var self = this;
  1549. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  1550. this.peerconnection.addIceCandidate(
  1551. candidate, successCallback, failureCallback);
  1552. /* maybe later
  1553. this.peerconnection.addIceCandidate(candidate,
  1554. function () {
  1555. self.trace('addIceCandidateOnSuccess');
  1556. successCallback();
  1557. },
  1558. function (err) {
  1559. self.trace('addIceCandidateOnFailure', err);
  1560. failureCallback(err);
  1561. }
  1562. );
  1563. */
  1564. };
  1565. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  1566. // TODO: Is this the correct way to handle Opera, Temasys?
  1567. if (RTCBrowserType.isFirefox()
  1568. || RTCBrowserType.isTemasysPluginUsed()
  1569. || RTCBrowserType.isReactNative()) {
  1570. this.peerconnection.getStats(
  1571. null,
  1572. callback,
  1573. errback || (() => {
  1574. // Making sure that getStats won't fail if error callback is
  1575. // not passed.
  1576. }));
  1577. } else {
  1578. this.peerconnection.getStats(callback);
  1579. }
  1580. };
  1581. /**
  1582. * Generates and stores new SSRC info object for given local track.
  1583. * The method should be called only for a video track being added to this TPC
  1584. * in the muted state (given that the current browser uses this strategy).
  1585. * @param {JitsiLocalTrack} track
  1586. * @return {TPCSSRCInfo}
  1587. */
  1588. TraceablePeerConnection.prototype.generateNewStreamSSRCInfo = function(track) {
  1589. const rtcId = track.rtcId;
  1590. let ssrcInfo = this._getSSRC(rtcId);
  1591. if (ssrcInfo) {
  1592. logger.error(`Will overwrite local SSRCs for track ID: ${rtcId}`);
  1593. }
  1594. if (this.isSimulcastOn()) {
  1595. ssrcInfo = {
  1596. ssrcs: [],
  1597. groups: []
  1598. };
  1599. for (let i = 0; i < SIMULCAST_LAYERS; i++) {
  1600. ssrcInfo.ssrcs.push(SDPUtil.generateSsrc());
  1601. }
  1602. ssrcInfo.groups.push({
  1603. ssrcs: ssrcInfo.ssrcs.slice(),
  1604. semantics: 'SIM'
  1605. });
  1606. } else {
  1607. ssrcInfo = {
  1608. ssrcs: [ SDPUtil.generateSsrc() ],
  1609. groups: []
  1610. };
  1611. }
  1612. if (!this.options.disableRtx && RTCBrowserType.supportsRtx()) {
  1613. // Specifically use a for loop here because we'll
  1614. // be adding to the list we're iterating over, so we
  1615. // only want to iterate through the items originally
  1616. // on the list
  1617. const currNumSsrcs = ssrcInfo.ssrcs.length;
  1618. for (let i = 0; i < currNumSsrcs; ++i) {
  1619. const primarySsrc = ssrcInfo.ssrcs[i];
  1620. const rtxSsrc = SDPUtil.generateSsrc();
  1621. ssrcInfo.ssrcs.push(rtxSsrc);
  1622. ssrcInfo.groups.push({
  1623. ssrcs: [ primarySsrc, rtxSsrc ],
  1624. semantics: 'FID'
  1625. });
  1626. }
  1627. }
  1628. ssrcInfo.msid = track.storedMSID;
  1629. this.localSSRCs.set(rtcId, ssrcInfo);
  1630. return ssrcInfo;
  1631. };
  1632. /**
  1633. * Creates a text representation of this <tt>TraceablePeerConnection</tt>
  1634. * instance.
  1635. * @return {string}
  1636. */
  1637. TraceablePeerConnection.prototype.toString = function() {
  1638. return `TPC[${this.id},p2p:${this.isP2P}]`;
  1639. };