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

TraceablePeerConnection.js 82KB

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