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

TraceablePeerConnection.js 83KB

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