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

TraceablePeerConnection.js 84KB

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