modified lib-jitsi-meet dev repo
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 62KB

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