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

TraceablePeerConnection.js 87KB

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