選択できるのは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.capScreenshareBitrate if set to 'true' simulcast will
  40. * be disabled for screenshare and a max bitrate of 500Kbps will applied on the
  41. * stream.
  42. * @param {boolean} options.disableH264 If set to 'true' H264 will be
  43. * disabled by removing it from the SDP.
  44. * @param {boolean} options.preferH264 if set to 'true' H264 will be preferred
  45. * over other video codecs.
  46. * @param {boolean} options.enableLayerSuspension if set to 'true', we will
  47. * cap the video send bitrate when we are told we have not been selected by
  48. * any endpoints (and therefore the non-thumbnail streams are not in use).
  49. * @param {boolean} options.startSilent If set to 'true' no audio will be sent or received.
  50. *
  51. * FIXME: initially the purpose of TraceablePeerConnection was to be able to
  52. * debug the peer connection. Since many other responsibilities have been added
  53. * it would make sense to extract a separate class from it and come up with
  54. * a more suitable name.
  55. *
  56. * @constructor
  57. */
  58. export default function TraceablePeerConnection(
  59. rtc,
  60. id,
  61. signalingLayer,
  62. iceConfig,
  63. constraints,
  64. isP2P,
  65. options) {
  66. /**
  67. * Indicates whether or not this peer connection instance is actively
  68. * sending/receiving audio media. When set to <tt>false</tt> the SDP audio
  69. * media direction will be adjusted to 'inactive' in order to suspend
  70. * the transmission.
  71. * @type {boolean}
  72. * @private
  73. */
  74. this.audioTransferActive = !(options.startSilent === true);
  75. /**
  76. * The DTMF sender instance used to send DTMF tones.
  77. *
  78. * @type {RTCDTMFSender|undefined}
  79. * @private
  80. */
  81. this._dtmfSender = undefined;
  82. /**
  83. * @typedef {Object} TouchToneRequest
  84. * @property {string} tones - The DTMF tones string as defined by
  85. * {@code RTCDTMFSender.insertDTMF}, 'tones' argument.
  86. * @property {number} duration - The amount of time in milliseconds that
  87. * each DTMF should last.
  88. * @property {string} interToneGap - The length of time in miliseconds to
  89. * wait between tones.
  90. */
  91. /**
  92. * TouchToneRequests which are waiting to be played. This queue is filled
  93. * if there are touch tones currently being played.
  94. *
  95. * @type {Array<TouchToneRequest>}
  96. * @private
  97. */
  98. this._dtmfTonesQueue = [];
  99. /**
  100. * Indicates whether or not this peer connection instance is actively
  101. * sending/receiving video media. When set to <tt>false</tt> the SDP video
  102. * media direction will be adjusted to 'inactive' in order to suspend
  103. * the transmission.
  104. * @type {boolean}
  105. * @private
  106. */
  107. this.videoTransferActive = true;
  108. /**
  109. * The parent instance of RTC service which created this
  110. * <tt>TracablePeerConnection</tt>.
  111. * @type {RTC}
  112. */
  113. this.rtc = rtc;
  114. /**
  115. * The peer connection identifier assigned by the RTC module.
  116. * @type {number}
  117. */
  118. this.id = id;
  119. /**
  120. * Indicates whether or not this instance is used in a peer to peer
  121. * connection.
  122. * @type {boolean}
  123. */
  124. this.isP2P = isP2P;
  125. // FIXME: We should support multiple streams per jid.
  126. /**
  127. * The map holds remote tracks associated with this peer connection.
  128. * It maps user's JID to media type and remote track
  129. * (one track per media type per user's JID).
  130. * @type {Map<string, Map<MediaType, JitsiRemoteTrack>>}
  131. */
  132. this.remoteTracks = new Map();
  133. /**
  134. * A map which stores local tracks mapped by {@link JitsiLocalTrack.rtcId}
  135. * @type {Map<number, JitsiLocalTrack>}
  136. */
  137. this.localTracks = new Map();
  138. /**
  139. * Keeps tracks of the WebRTC <tt>MediaStream</tt>s that have been added to
  140. * the underlying WebRTC PeerConnection.
  141. * @type {Array}
  142. * @private
  143. */
  144. this._addedStreams = [];
  145. /**
  146. * @typedef {Object} TPCGroupInfo
  147. * @property {string} semantics the SSRC groups semantics
  148. * @property {Array<number>} ssrcs group's SSRCs in order where the first
  149. * one is group's primary SSRC, the second one is secondary (RTX) and so
  150. * on...
  151. */
  152. /**
  153. * @typedef {Object} TPCSSRCInfo
  154. * @property {Array<number>} ssrcs an array which holds all track's SSRCs
  155. * @property {Array<TPCGroupInfo>} groups an array stores all track's SSRC
  156. * groups
  157. */
  158. /**
  159. * Holds the info about local track's SSRCs mapped per their
  160. * {@link JitsiLocalTrack.rtcId}
  161. * @type {Map<number, TPCSSRCInfo>}
  162. */
  163. this.localSSRCs = new Map();
  164. /**
  165. * The local ICE username fragment for this session.
  166. */
  167. this.localUfrag = null;
  168. /**
  169. * The remote ICE username fragment for this session.
  170. */
  171. this.remoteUfrag = null;
  172. /**
  173. * The signaling layer which operates this peer connection.
  174. * @type {SignalingLayer}
  175. */
  176. this.signalingLayer = signalingLayer;
  177. // SignalingLayer listeners
  178. this._peerVideoTypeChanged = this._peerVideoTypeChanged.bind(this);
  179. this.signalingLayer.on(
  180. SignalingEvents.PEER_VIDEO_TYPE_CHANGED,
  181. this._peerVideoTypeChanged);
  182. this._peerMutedChanged = this._peerMutedChanged.bind(this);
  183. this.signalingLayer.on(
  184. SignalingEvents.PEER_MUTED_CHANGED,
  185. this._peerMutedChanged);
  186. this.options = options;
  187. this.peerconnection
  188. = new RTCUtils.RTCPeerConnectionType(iceConfig, constraints);
  189. this.tpcUtils = new TPCUtils(this);
  190. this.updateLog = [];
  191. this.stats = {};
  192. this.statsinterval = null;
  193. /**
  194. * @type {number} The max number of stats to keep in this.stats. Limit to
  195. * 300 values, i.e. 5 minutes; set to 0 to disable
  196. */
  197. this.maxstats = options.maxstats;
  198. this.interop = new Interop();
  199. const Simulcast = require('@jitsi/sdp-simulcast');
  200. this.simulcast = new Simulcast(
  201. {
  202. numOfLayers: SIM_LAYER_RIDS.length,
  203. explodeRemoteSimulcast: false,
  204. usesUnifiedPlan: browser.usesUnifiedPlan()
  205. });
  206. this.sdpConsistency = new SdpConsistency(this.toString());
  207. /**
  208. * Munges local SDP provided to the Jingle Session in order to prevent from
  209. * sending SSRC updates on attach/detach and mute/unmute (for video).
  210. * @type {LocalSdpMunger}
  211. */
  212. this.localSdpMunger = new LocalSdpMunger(this);
  213. /**
  214. * TracablePeerConnection uses RTC's eventEmitter
  215. * @type {EventEmitter}
  216. */
  217. this.eventEmitter = rtc.eventEmitter;
  218. this.rtxModifier = new RtxModifier();
  219. // override as desired
  220. this.trace = (what, info) => {
  221. logger.debug(what, info);
  222. this.updateLog.push({
  223. time: new Date(),
  224. type: what,
  225. value: info || ''
  226. });
  227. };
  228. this.onicecandidate = null;
  229. this.peerconnection.onicecandidate = event => {
  230. this.trace(
  231. 'onicecandidate',
  232. JSON.stringify(event.candidate, null, ' '));
  233. if (this.onicecandidate !== null) {
  234. this.onicecandidate(event);
  235. }
  236. };
  237. // Use stream events in plan-b and track events in unified plan.
  238. if (browser.usesPlanB()) {
  239. this.peerconnection.onaddstream
  240. = event => this._remoteStreamAdded(event.stream);
  241. this.peerconnection.onremovestream
  242. = event => this._remoteStreamRemoved(event.stream);
  243. } else {
  244. this.peerconnection.ontrack = event => {
  245. const stream = event.streams[0];
  246. this._remoteTrackAdded(stream, event.track, event.transceiver);
  247. stream.onremovetrack = evt => {
  248. this._remoteTrackRemoved(stream, evt.track);
  249. };
  250. };
  251. }
  252. this.onsignalingstatechange = null;
  253. this.peerconnection.onsignalingstatechange = event => {
  254. this.trace('onsignalingstatechange', this.signalingState);
  255. if (this.onsignalingstatechange !== null) {
  256. this.onsignalingstatechange(event);
  257. }
  258. };
  259. this.oniceconnectionstatechange = null;
  260. this.peerconnection.oniceconnectionstatechange = event => {
  261. this.trace('oniceconnectionstatechange', this.iceConnectionState);
  262. if (this.oniceconnectionstatechange !== null) {
  263. this.oniceconnectionstatechange(event);
  264. }
  265. };
  266. this.onnegotiationneeded = null;
  267. this.peerconnection.onnegotiationneeded = event => {
  268. this.trace('onnegotiationneeded');
  269. if (this.onnegotiationneeded !== null) {
  270. this.onnegotiationneeded(event);
  271. }
  272. };
  273. this.ondatachannel = null;
  274. this.peerconnection.ondatachannel = event => {
  275. this.trace('ondatachannel');
  276. if (this.ondatachannel !== null) {
  277. this.ondatachannel(event);
  278. }
  279. };
  280. if (this.maxstats) {
  281. this.statsinterval = window.setInterval(() => {
  282. this.getStats(stats => {
  283. if (stats.result
  284. && typeof stats.result === 'function') {
  285. const results = stats.result();
  286. for (let i = 0; i < results.length; ++i) {
  287. const res = results[i];
  288. res.names().forEach(name => {
  289. this._processStat(res, name, res.stat(name));
  290. });
  291. }
  292. } else {
  293. stats.forEach(r => this._processStat(r, '', r));
  294. }
  295. }, () => {
  296. // empty error callback
  297. });
  298. }, 1000);
  299. }
  300. logger.info(`Create new ${this}`);
  301. }
  302. /* eslint-enable max-params */
  303. /**
  304. * Process stat and adds it to the array of stats we store.
  305. * @param report the current stats report.
  306. * @param name the name of the report, if available
  307. * @param statValue the value to add.
  308. * @private
  309. */
  310. TraceablePeerConnection.prototype._processStat
  311. = function(report, name, statValue) {
  312. const id = `${report.id}-${name}`;
  313. let s = this.stats[id];
  314. const now = new Date();
  315. if (!s) {
  316. this.stats[id] = s = {
  317. startTime: now,
  318. endTime: now,
  319. values: [],
  320. times: []
  321. };
  322. }
  323. s.values.push(statValue);
  324. s.times.push(now.getTime());
  325. if (s.values.length > this.maxstats) {
  326. s.values.shift();
  327. s.times.shift();
  328. }
  329. s.endTime = now;
  330. };
  331. /**
  332. * Returns a string representation of a SessionDescription object.
  333. */
  334. const dumpSDP = function(description) {
  335. if (typeof description === 'undefined' || description === null) {
  336. return '';
  337. }
  338. return `type: ${description.type}\r\n${description.sdp}`;
  339. };
  340. /**
  341. * Forwards the {@link peerconnection.iceConnectionState} state except that it
  342. * will convert "completed" into "connected" where both mean that the ICE has
  343. * succeeded and is up and running. We never see "completed" state for
  344. * the JVB connection, but it started appearing for the P2P one. This method
  345. * allows to adapt old logic to this new situation.
  346. * @return {string}
  347. */
  348. TraceablePeerConnection.prototype.getConnectionState = function() {
  349. const state = this.peerconnection.iceConnectionState;
  350. if (state === 'completed') {
  351. return 'connected';
  352. }
  353. return state;
  354. };
  355. /**
  356. * Obtains the media direction for given {@link MediaType}. The method takes
  357. * into account whether or not there are any local tracks for media and
  358. * the {@link audioTransferActive} and {@link videoTransferActive} flags.
  359. * @param {MediaType} mediaType
  360. * @return {string} one of the SDP direction constants ('sendrecv, 'recvonly'
  361. * etc.) which should be used when setting local description on the peer
  362. * connection.
  363. * @private
  364. */
  365. TraceablePeerConnection.prototype._getDesiredMediaDirection = function(
  366. mediaType) {
  367. let mediaTransferActive = true;
  368. if (mediaType === MediaType.AUDIO) {
  369. mediaTransferActive = this.audioTransferActive;
  370. } else if (mediaType === MediaType.VIDEO) {
  371. mediaTransferActive = this.videoTransferActive;
  372. }
  373. if (mediaTransferActive) {
  374. return this.hasAnyTracksOfType(mediaType) ? 'sendrecv' : 'recvonly';
  375. }
  376. return 'inactive';
  377. };
  378. /**
  379. * Tells whether or not this TPC instance is using Simulcast.
  380. * @return {boolean} <tt>true</tt> if simulcast is enabled and active or
  381. * <tt>false</tt> if it's turned off.
  382. */
  383. TraceablePeerConnection.prototype.isSimulcastOn = function() {
  384. return !this.options.disableSimulcast;
  385. };
  386. /**
  387. * Handles {@link SignalingEvents.PEER_VIDEO_TYPE_CHANGED}
  388. * @param {string} endpointId the video owner's ID (MUC nickname)
  389. * @param {VideoType} videoType the new value
  390. * @private
  391. */
  392. TraceablePeerConnection.prototype._peerVideoTypeChanged = function(
  393. endpointId,
  394. videoType) {
  395. // Check if endpointId has a value to avoid action on random track
  396. if (!endpointId) {
  397. logger.error(`No endpointID on peerVideoTypeChanged ${this}`);
  398. return;
  399. }
  400. const videoTrack = this.getRemoteTracks(endpointId, MediaType.VIDEO);
  401. if (videoTrack.length) {
  402. // NOTE 1 track per media type is assumed
  403. videoTrack[0]._setVideoType(videoType);
  404. }
  405. };
  406. /**
  407. * Handles remote track mute / unmute events.
  408. * @param {string} endpointId the track owner's identifier (MUC nickname)
  409. * @param {MediaType} mediaType "audio" or "video"
  410. * @param {boolean} isMuted the new mute state
  411. * @private
  412. */
  413. TraceablePeerConnection.prototype._peerMutedChanged = function(
  414. endpointId,
  415. mediaType,
  416. isMuted) {
  417. // Check if endpointId is a value to avoid doing action on all remote tracks
  418. if (!endpointId) {
  419. logger.error('On peerMuteChanged - no endpoint ID');
  420. return;
  421. }
  422. const track = this.getRemoteTracks(endpointId, mediaType);
  423. if (track.length) {
  424. // NOTE 1 track per media type is assumed
  425. track[0].setMute(isMuted);
  426. }
  427. };
  428. /**
  429. * Obtains local tracks for given {@link MediaType}. If the <tt>mediaType</tt>
  430. * argument is omitted the list of all local tracks will be returned.
  431. * @param {MediaType} [mediaType]
  432. * @return {Array<JitsiLocalTrack>}
  433. */
  434. TraceablePeerConnection.prototype.getLocalTracks = function(mediaType) {
  435. let tracks = Array.from(this.localTracks.values());
  436. if (mediaType !== undefined) {
  437. tracks = tracks.filter(track => track.getType() === mediaType);
  438. }
  439. return tracks;
  440. };
  441. /**
  442. * Checks whether or not this {@link TraceablePeerConnection} instance contains
  443. * any local tracks for given <tt>mediaType</tt>.
  444. * @param {MediaType} mediaType
  445. * @return {boolean}
  446. */
  447. TraceablePeerConnection.prototype.hasAnyTracksOfType = function(mediaType) {
  448. if (!mediaType) {
  449. throw new Error('"mediaType" is required');
  450. }
  451. return this.getLocalTracks(mediaType).length > 0;
  452. };
  453. /**
  454. * Obtains all remote tracks currently known to this PeerConnection instance.
  455. * @param {string} [endpointId] the track owner's identifier (MUC nickname)
  456. * @param {MediaType} [mediaType] the remote tracks will be filtered
  457. * by their media type if this argument is specified.
  458. * @return {Array<JitsiRemoteTrack>}
  459. */
  460. TraceablePeerConnection.prototype.getRemoteTracks = function(
  461. endpointId,
  462. mediaType) {
  463. const remoteTracks = [];
  464. const endpoints
  465. = endpointId ? [ endpointId ] : this.remoteTracks.keys();
  466. for (const endpoint of endpoints) {
  467. const endpointTrackMap = this.remoteTracks.get(endpoint);
  468. if (!endpointTrackMap) {
  469. // Otherwise an empty Map() would have to be allocated above
  470. // eslint-disable-next-line no-continue
  471. continue;
  472. }
  473. for (const trackMediaType of endpointTrackMap.keys()) {
  474. // per media type filtering
  475. if (!mediaType || mediaType === trackMediaType) {
  476. const mediaTrack = endpointTrackMap.get(trackMediaType);
  477. if (mediaTrack) {
  478. remoteTracks.push(mediaTrack);
  479. }
  480. }
  481. }
  482. }
  483. return remoteTracks;
  484. };
  485. /**
  486. * Tries to find {@link JitsiTrack} for given SSRC number. It will search both
  487. * local and remote tracks bound to this instance.
  488. * @param {number} ssrc
  489. * @return {JitsiTrack|null}
  490. */
  491. TraceablePeerConnection.prototype.getTrackBySSRC = function(ssrc) {
  492. if (typeof ssrc !== 'number') {
  493. throw new Error(`SSRC ${ssrc} is not a number`);
  494. }
  495. for (const localTrack of this.localTracks.values()) {
  496. if (this.getLocalSSRC(localTrack) === ssrc) {
  497. return localTrack;
  498. }
  499. }
  500. for (const remoteTrack of this.getRemoteTracks()) {
  501. if (remoteTrack.getSSRC() === ssrc) {
  502. return remoteTrack;
  503. }
  504. }
  505. return null;
  506. };
  507. /**
  508. * Tries to find SSRC number for given {@link JitsiTrack} id. It will search
  509. * both local and remote tracks bound to this instance.
  510. * @param {string} id
  511. * @return {number|null}
  512. */
  513. TraceablePeerConnection.prototype.getSsrcByTrackId = function(id) {
  514. const findTrackById = track => track.getTrack().id === id;
  515. const localTrack = this.getLocalTracks().find(findTrackById);
  516. if (localTrack) {
  517. return this.getLocalSSRC(localTrack);
  518. }
  519. const remoteTrack = this.getRemoteTracks().find(findTrackById);
  520. if (remoteTrack) {
  521. return remoteTrack.getSSRC();
  522. }
  523. return null;
  524. };
  525. /**
  526. * Called when new remote MediaStream is added to the PeerConnection.
  527. * @param {MediaStream} stream the WebRTC MediaStream for remote participant
  528. */
  529. TraceablePeerConnection.prototype._remoteStreamAdded = function(stream) {
  530. const streamId = RTC.getStreamID(stream);
  531. if (!RTC.isUserStreamById(streamId)) {
  532. logger.info(
  533. `${this} ignored remote 'stream added' event for non-user stream`
  534. + `id: ${streamId}`);
  535. return;
  536. }
  537. // Bind 'addtrack'/'removetrack' event handlers
  538. if (browser.isChromiumBased()) {
  539. stream.onaddtrack = event => {
  540. this._remoteTrackAdded(stream, event.track);
  541. };
  542. stream.onremovetrack = event => {
  543. this._remoteTrackRemoved(stream, event.track);
  544. };
  545. }
  546. // Call remoteTrackAdded for each track in the stream
  547. const streamAudioTracks = stream.getAudioTracks();
  548. for (const audioTrack of streamAudioTracks) {
  549. this._remoteTrackAdded(stream, audioTrack);
  550. }
  551. const streamVideoTracks = stream.getVideoTracks();
  552. for (const videoTrack of streamVideoTracks) {
  553. this._remoteTrackAdded(stream, videoTrack);
  554. }
  555. };
  556. /**
  557. * Called on "track added" and "stream added" PeerConnection events (because we
  558. * handle streams on per track basis). Finds the owner and the SSRC for
  559. * the track and passes that to ChatRoom for further processing.
  560. * @param {MediaStream} stream the WebRTC MediaStream instance which is
  561. * the parent of the track
  562. * @param {MediaStreamTrack} track the WebRTC MediaStreamTrack added for remote
  563. * participant.
  564. * @param {RTCRtpTransceiver} transceiver the WebRTC transceiver that is created
  565. * for the remote participant in unified plan.
  566. */
  567. TraceablePeerConnection.prototype._remoteTrackAdded = function(stream, track, transceiver = null) {
  568. const streamId = RTC.getStreamID(stream);
  569. const mediaType = track.kind;
  570. if (!this.isP2P && !RTC.isUserStreamById(streamId)) {
  571. logger.info(
  572. `${this} ignored remote 'stream added' event for non-user stream`
  573. + `id: ${streamId}`);
  574. return;
  575. }
  576. logger.info(`${this} remote track added:`, streamId, mediaType);
  577. // look up an associated JID for a stream id
  578. if (!mediaType) {
  579. GlobalOnErrorHandler.callErrorHandler(
  580. new Error(
  581. `MediaType undefined for remote track, stream id: ${streamId}`
  582. ));
  583. // Abort
  584. return;
  585. }
  586. const remoteSDP = browser.usesPlanB()
  587. ? new SDP(this.remoteDescription.sdp)
  588. : new SDP(this.peerconnection.remoteDescription.sdp);
  589. let mediaLines;
  590. if (browser.usesUnifiedPlan()) {
  591. if (transceiver && transceiver.mid) {
  592. const mid = transceiver.mid;
  593. mediaLines = remoteSDP.media.filter(mls => SDPUtil.findLine(mls, `a=mid:${mid}`));
  594. } else {
  595. mediaLines = remoteSDP.media.filter(mls => {
  596. const msid = SDPUtil.findLine(mls, 'a=msid');
  597. return typeof msid !== 'undefined' && streamId === msid.substring(7).split(' ')[0];
  598. });
  599. }
  600. } else {
  601. mediaLines = remoteSDP.media.filter(mls => mls.startsWith(`m=${mediaType}`));
  602. }
  603. if (!mediaLines.length) {
  604. GlobalOnErrorHandler.callErrorHandler(
  605. new Error(
  606. `No media lines for type ${
  607. mediaType} found in remote SDP for remote track: ${
  608. streamId}`));
  609. // Abort
  610. return;
  611. }
  612. let ssrcLines = SDPUtil.findLines(mediaLines[0], 'a=ssrc:');
  613. ssrcLines
  614. = ssrcLines.filter(line => line.indexOf(`msid:${streamId}`) !== -1);
  615. if (!ssrcLines.length) {
  616. GlobalOnErrorHandler.callErrorHandler(
  617. new Error(
  618. `No SSRC lines for streamId ${
  619. streamId} for remote track, media type: ${mediaType}`));
  620. // Abort
  621. return;
  622. }
  623. // FIXME the length of ssrcLines[0] not verified, but it will fail
  624. // with global error handler anyway
  625. const ssrcStr = ssrcLines[0].substring(7).split(' ')[0];
  626. const trackSsrc = Number(ssrcStr);
  627. const ownerEndpointId = this.signalingLayer.getSSRCOwner(trackSsrc);
  628. if (isNaN(trackSsrc) || trackSsrc < 0) {
  629. GlobalOnErrorHandler.callErrorHandler(
  630. new Error(
  631. `Invalid SSRC: ${ssrcStr} for remote track, msid: ${
  632. streamId} media type: ${mediaType}`));
  633. // Abort
  634. return;
  635. } else if (!ownerEndpointId) {
  636. GlobalOnErrorHandler.callErrorHandler(
  637. new Error(
  638. `No SSRC owner known for: ${
  639. trackSsrc} for remote track, msid: ${
  640. streamId} media type: ${mediaType}`));
  641. // Abort
  642. return;
  643. }
  644. logger.log(`${this} associated ssrc`, ownerEndpointId, trackSsrc);
  645. const peerMediaInfo
  646. = this.signalingLayer.getPeerMediaInfo(ownerEndpointId, mediaType);
  647. if (!peerMediaInfo) {
  648. GlobalOnErrorHandler.callErrorHandler(
  649. new Error(
  650. `${this}: no peer media info available for ${
  651. ownerEndpointId}`));
  652. return;
  653. }
  654. const muted = peerMediaInfo.muted;
  655. const videoType = peerMediaInfo.videoType; // can be undefined
  656. this._createRemoteTrack(
  657. ownerEndpointId, stream, track, mediaType, videoType, trackSsrc, muted);
  658. };
  659. // FIXME cleanup params
  660. /* eslint-disable max-params */
  661. /**
  662. * Initializes a new JitsiRemoteTrack instance with the data provided by
  663. * the signaling layer and SDP.
  664. *
  665. * @param {string} ownerEndpointId the owner's endpoint ID (MUC nickname)
  666. * @param {MediaStream} stream the WebRTC stream instance
  667. * @param {MediaStreamTrack} track the WebRTC track instance
  668. * @param {MediaType} mediaType the track's type of the media
  669. * @param {VideoType} [videoType] the track's type of the video (if applicable)
  670. * @param {number} ssrc the track's main SSRC number
  671. * @param {boolean} muted the initial muted status
  672. */
  673. TraceablePeerConnection.prototype._createRemoteTrack = function(
  674. ownerEndpointId,
  675. stream,
  676. track,
  677. mediaType,
  678. videoType,
  679. ssrc,
  680. muted) {
  681. let remoteTracksMap = this.remoteTracks.get(ownerEndpointId);
  682. if (!remoteTracksMap) {
  683. remoteTracksMap = new Map();
  684. this.remoteTracks.set(ownerEndpointId, remoteTracksMap);
  685. }
  686. const existingTrack = remoteTracksMap.get(mediaType);
  687. if (existingTrack && existingTrack.getTrack() === track) {
  688. // Ignore duplicated event which can originate either from
  689. // 'onStreamAdded' or 'onTrackAdded'.
  690. logger.info(
  691. `${this} ignored duplicated remote track added event for: `
  692. + `${ownerEndpointId}, ${mediaType}`);
  693. return;
  694. } else if (existingTrack) {
  695. logger.error(
  696. `${this} overwriting remote track for`
  697. + `${ownerEndpointId} ${mediaType}`);
  698. }
  699. const remoteTrack
  700. = new JitsiRemoteTrack(
  701. this.rtc,
  702. this.rtc.conference,
  703. ownerEndpointId,
  704. stream,
  705. track,
  706. mediaType,
  707. videoType,
  708. ssrc,
  709. muted,
  710. this.isP2P);
  711. remoteTracksMap.set(mediaType, remoteTrack);
  712. this.eventEmitter.emit(RTCEvents.REMOTE_TRACK_ADDED, remoteTrack);
  713. };
  714. /* eslint-enable max-params */
  715. /**
  716. * Handles remote stream removal.
  717. * @param stream the WebRTC MediaStream object which is being removed from the
  718. * PeerConnection
  719. */
  720. TraceablePeerConnection.prototype._remoteStreamRemoved = function(stream) {
  721. if (!RTC.isUserStream(stream)) {
  722. const id = RTC.getStreamID(stream);
  723. logger.info(
  724. `Ignored remote 'stream removed' event for non-user stream ${id}`);
  725. return;
  726. }
  727. // Call remoteTrackRemoved for each track in the stream
  728. const streamVideoTracks = stream.getVideoTracks();
  729. for (const videoTrack of streamVideoTracks) {
  730. this._remoteTrackRemoved(stream, videoTrack);
  731. }
  732. const streamAudioTracks = stream.getAudioTracks();
  733. for (const audioTrack of streamAudioTracks) {
  734. this._remoteTrackRemoved(stream, audioTrack);
  735. }
  736. };
  737. /**
  738. * Handles remote media track removal.
  739. * @param {MediaStream} stream WebRTC MediaStream instance which is the parent
  740. * of the track.
  741. * @param {MediaStreamTrack} track the WebRTC MediaStreamTrack which has been
  742. * removed from the PeerConnection.
  743. */
  744. TraceablePeerConnection.prototype._remoteTrackRemoved = function(
  745. stream,
  746. track) {
  747. const streamId = RTC.getStreamID(stream);
  748. const trackId = track && RTC.getTrackID(track);
  749. logger.info(`${this} - remote track removed: ${streamId}, ${trackId}`);
  750. if (!streamId) {
  751. GlobalOnErrorHandler.callErrorHandler(
  752. new Error(`${this} remote track removal failed - no stream ID`));
  753. return;
  754. }
  755. if (!trackId) {
  756. GlobalOnErrorHandler.callErrorHandler(
  757. new Error(`${this} remote track removal failed - no track ID`));
  758. return;
  759. }
  760. if (!this._removeRemoteTrackById(streamId, trackId)) {
  761. // NOTE this warning is always printed when user leaves the room,
  762. // because we remove remote tracks manually on MUC member left event,
  763. // before the SSRCs are removed by Jicofo. In most cases it is fine to
  764. // ignore this warning, but still it's better to keep it printed for
  765. // debugging purposes.
  766. //
  767. // We could change the behaviour to emit track removed only from here,
  768. // but the order of the events will change and consuming apps could
  769. // behave unexpectedly (the "user left" event would come before "track
  770. // removed" events).
  771. logger.warn(
  772. `${this} Removed track not found for msid: ${streamId},
  773. track id: ${trackId}`);
  774. }
  775. };
  776. /**
  777. * Finds remote track by it's stream and track ids.
  778. * @param {string} streamId the media stream id as defined by the WebRTC
  779. * @param {string} trackId the media track id as defined by the WebRTC
  780. * @return {JitsiRemoteTrack|undefined} the track's instance or
  781. * <tt>undefined</tt> if not found.
  782. * @private
  783. */
  784. TraceablePeerConnection.prototype._getRemoteTrackById = function(
  785. streamId,
  786. trackId) {
  787. // .find will break the loop once the first match is found
  788. for (const endpointTrackMap of this.remoteTracks.values()) {
  789. for (const mediaTrack of endpointTrackMap.values()) {
  790. // FIXME verify and try to use ===
  791. /* eslint-disable eqeqeq */
  792. if (mediaTrack.getStreamId() == streamId
  793. && mediaTrack.getTrackId() == trackId) {
  794. return mediaTrack;
  795. }
  796. /* eslint-enable eqeqeq */
  797. }
  798. }
  799. return undefined;
  800. };
  801. /**
  802. * Removes all JitsiRemoteTracks associated with given MUC nickname
  803. * (resource part of the JID). Returns array of removed tracks.
  804. *
  805. * @param {string} owner - The resource part of the MUC JID.
  806. * @returns {JitsiRemoteTrack[]}
  807. */
  808. TraceablePeerConnection.prototype.removeRemoteTracks = function(owner) {
  809. const removedTracks = [];
  810. const remoteTracksMap = this.remoteTracks.get(owner);
  811. if (remoteTracksMap) {
  812. const removedAudioTrack = remoteTracksMap.get(MediaType.AUDIO);
  813. const removedVideoTrack = remoteTracksMap.get(MediaType.VIDEO);
  814. removedAudioTrack && removedTracks.push(removedAudioTrack);
  815. removedVideoTrack && removedTracks.push(removedVideoTrack);
  816. this.remoteTracks.delete(owner);
  817. }
  818. logger.debug(
  819. `${this} removed remote tracks for ${owner} count: ${
  820. removedTracks.length}`);
  821. return removedTracks;
  822. };
  823. /**
  824. * Removes and disposes given <tt>JitsiRemoteTrack</tt> instance. Emits
  825. * {@link RTCEvents.REMOTE_TRACK_REMOVED}.
  826. * @param {JitsiRemoteTrack} toBeRemoved
  827. */
  828. TraceablePeerConnection.prototype._removeRemoteTrack = function(toBeRemoved) {
  829. toBeRemoved.dispose();
  830. const participantId = toBeRemoved.getParticipantId();
  831. const remoteTracksMap = this.remoteTracks.get(participantId);
  832. if (!remoteTracksMap) {
  833. logger.error(
  834. `removeRemoteTrack: no remote tracks map for ${participantId}`);
  835. } else if (!remoteTracksMap.delete(toBeRemoved.getType())) {
  836. logger.error(
  837. `Failed to remove ${toBeRemoved} - type mapping messed up ?`);
  838. }
  839. this.eventEmitter.emit(RTCEvents.REMOTE_TRACK_REMOVED, toBeRemoved);
  840. };
  841. /**
  842. * Removes and disposes <tt>JitsiRemoteTrack</tt> identified by given stream and
  843. * track ids.
  844. *
  845. * @param {string} streamId the media stream id as defined by the WebRTC
  846. * @param {string} trackId the media track id as defined by the WebRTC
  847. * @returns {JitsiRemoteTrack|undefined} the track which has been removed or
  848. * <tt>undefined</tt> if no track matching given stream and track ids was
  849. * found.
  850. */
  851. TraceablePeerConnection.prototype._removeRemoteTrackById = function(
  852. streamId,
  853. trackId) {
  854. const toBeRemoved = this._getRemoteTrackById(streamId, trackId);
  855. if (toBeRemoved) {
  856. this._removeRemoteTrack(toBeRemoved);
  857. }
  858. return toBeRemoved;
  859. };
  860. /**
  861. * @typedef {Object} SSRCGroupInfo
  862. * @property {Array<number>} ssrcs group's SSRCs
  863. * @property {string} semantics
  864. */
  865. /**
  866. * @typedef {Object} TrackSSRCInfo
  867. * @property {Array<number>} ssrcs track's SSRCs
  868. * @property {Array<SSRCGroupInfo>} groups track's SSRC groups
  869. */
  870. /**
  871. * Returns map with keys msid and <tt>TrackSSRCInfo</tt> values.
  872. * @param {Object} desc the WebRTC SDP instance.
  873. * @return {Map<string,TrackSSRCInfo>}
  874. */
  875. function extractSSRCMap(desc) {
  876. /**
  877. * Track SSRC infos mapped by stream ID (msid)
  878. * @type {Map<string,TrackSSRCInfo>}
  879. */
  880. const ssrcMap = new Map();
  881. /**
  882. * Groups mapped by primary SSRC number
  883. * @type {Map<number,Array<SSRCGroupInfo>>}
  884. */
  885. const groupsMap = new Map();
  886. if (typeof desc !== 'object' || desc === null
  887. || typeof desc.sdp !== 'string') {
  888. logger.warn('An empty description was passed as an argument.');
  889. return ssrcMap;
  890. }
  891. const session = transform.parse(desc.sdp);
  892. if (!Array.isArray(session.media)) {
  893. return ssrcMap;
  894. }
  895. for (const mLine of session.media) {
  896. if (!Array.isArray(mLine.ssrcs)) {
  897. continue; // eslint-disable-line no-continue
  898. }
  899. if (Array.isArray(mLine.ssrcGroups)) {
  900. for (const group of mLine.ssrcGroups) {
  901. if (typeof group.semantics !== 'undefined'
  902. && typeof group.ssrcs !== 'undefined') {
  903. // Parse SSRCs and store as numbers
  904. const groupSSRCs
  905. = group.ssrcs.split(' ').map(
  906. ssrcStr => parseInt(ssrcStr, 10));
  907. const primarySSRC = groupSSRCs[0];
  908. // Note that group.semantics is already present
  909. group.ssrcs = groupSSRCs;
  910. // eslint-disable-next-line max-depth
  911. if (!groupsMap.has(primarySSRC)) {
  912. groupsMap.set(primarySSRC, []);
  913. }
  914. groupsMap.get(primarySSRC).push(group);
  915. }
  916. }
  917. }
  918. for (const ssrc of mLine.ssrcs) {
  919. if (ssrc.attribute !== 'msid') {
  920. continue; // eslint-disable-line no-continue
  921. }
  922. const msid = ssrc.value;
  923. let ssrcInfo = ssrcMap.get(msid);
  924. if (!ssrcInfo) {
  925. ssrcInfo = {
  926. ssrcs: [],
  927. groups: [],
  928. msid
  929. };
  930. ssrcMap.set(msid, ssrcInfo);
  931. }
  932. const ssrcNumber = ssrc.id;
  933. ssrcInfo.ssrcs.push(ssrcNumber);
  934. if (groupsMap.has(ssrcNumber)) {
  935. const ssrcGroups = groupsMap.get(ssrcNumber);
  936. for (const group of ssrcGroups) {
  937. ssrcInfo.groups.push(group);
  938. }
  939. }
  940. }
  941. }
  942. return ssrcMap;
  943. }
  944. /**
  945. * Takes a SessionDescription object and returns a "normalized" version.
  946. * Currently it takes care of ordering the a=ssrc lines and denoting receive
  947. * only SSRCs.
  948. */
  949. const normalizePlanB = function(desc) {
  950. if (typeof desc !== 'object' || desc === null
  951. || typeof desc.sdp !== 'string') {
  952. logger.warn('An empty description was passed as an argument.');
  953. return desc;
  954. }
  955. // eslint-disable-next-line no-shadow
  956. const transform = require('sdp-transform');
  957. const session = transform.parse(desc.sdp);
  958. if (typeof session !== 'undefined'
  959. && typeof session.media !== 'undefined'
  960. && Array.isArray(session.media)) {
  961. session.media.forEach(mLine => {
  962. // Chrome appears to be picky about the order in which a=ssrc lines
  963. // are listed in an m-line when rtx is enabled (and thus there are
  964. // a=ssrc-group lines with FID semantics). Specifically if we have
  965. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  966. // the "a=ssrc:S1" lines, SRD fails.
  967. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  968. // first.
  969. const firstSsrcs = [];
  970. const newSsrcLines = [];
  971. if (typeof mLine.ssrcGroups !== 'undefined'
  972. && Array.isArray(mLine.ssrcGroups)) {
  973. mLine.ssrcGroups.forEach(group => {
  974. if (typeof group.semantics !== 'undefined'
  975. && group.semantics === 'FID') {
  976. if (typeof group.ssrcs !== 'undefined') {
  977. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  978. }
  979. }
  980. });
  981. }
  982. if (Array.isArray(mLine.ssrcs)) {
  983. let i;
  984. for (i = 0; i < mLine.ssrcs.length; i++) {
  985. if (typeof mLine.ssrcs[i] === 'object'
  986. && typeof mLine.ssrcs[i].id !== 'undefined'
  987. && firstSsrcs.indexOf(mLine.ssrcs[i].id) >= 0) {
  988. newSsrcLines.push(mLine.ssrcs[i]);
  989. delete mLine.ssrcs[i];
  990. }
  991. }
  992. for (i = 0; i < mLine.ssrcs.length; i++) {
  993. if (typeof mLine.ssrcs[i] !== 'undefined') {
  994. newSsrcLines.push(mLine.ssrcs[i]);
  995. }
  996. }
  997. mLine.ssrcs = replaceDefaultUnifiedPlanMsid(newSsrcLines);
  998. }
  999. });
  1000. }
  1001. const resStr = transform.write(session);
  1002. return new RTCSessionDescription({
  1003. type: desc.type,
  1004. sdp: resStr
  1005. });
  1006. };
  1007. /**
  1008. * Unified plan differentiates a remote track not associated with a stream using
  1009. * the msid "-", which can incorrectly trigger an onaddstream event in plan-b.
  1010. * For jitsi, these tracks are actually receive-only ssrcs. To prevent
  1011. * onaddstream from firing, remove the ssrcs with msid "-" except the cname
  1012. * line. Normally the ssrcs are not used by the client, as the bridge controls
  1013. * media flow, but keep one reference to the ssrc for the p2p case.
  1014. *
  1015. * @param {Array<Object>} ssrcLines - The ssrc lines from a remote description.
  1016. * @private
  1017. * @returns {Array<Object>} ssrcLines with removed lines referencing msid "-".
  1018. */
  1019. function replaceDefaultUnifiedPlanMsid(ssrcLines = []) {
  1020. if (!browser.isChrome() || !browser.isVersionGreaterThan(70)) {
  1021. return ssrcLines;
  1022. }
  1023. let filteredLines = [ ...ssrcLines ];
  1024. const problematicSsrcIds = ssrcLines.filter(ssrcLine =>
  1025. ssrcLine.attribute === 'mslabel' && ssrcLine.value === '-')
  1026. .map(ssrcLine => ssrcLine.id);
  1027. problematicSsrcIds.forEach(ssrcId => {
  1028. // Find the cname which is to be modified and left in.
  1029. const cnameLine = filteredLines.find(line =>
  1030. line.id === ssrcId && line.attribute === 'cname');
  1031. cnameLine.value = `recvonly-${ssrcId}`;
  1032. // Remove all of lines for the ssrc.
  1033. filteredLines
  1034. = filteredLines.filter(line => line.id !== ssrcId);
  1035. // But re-add the cname line so there is a reference kept to the ssrc
  1036. // in the SDP.
  1037. filteredLines.push(cnameLine);
  1038. });
  1039. return filteredLines;
  1040. }
  1041. /**
  1042. * Makes sure that both audio and video directions are configured as 'sendrecv'.
  1043. * @param {Object} localDescription the SDP object as defined by WebRTC.
  1044. * @param {object} options <tt>TracablePeerConnection</tt> config options.
  1045. */
  1046. const enforceSendRecv = function(localDescription, options) {
  1047. if (!localDescription) {
  1048. throw new Error('No local description passed in.');
  1049. }
  1050. const transformer = new SdpTransformWrap(localDescription.sdp);
  1051. const audioMedia = transformer.selectMedia('audio');
  1052. let changed = false;
  1053. if (audioMedia && audioMedia.direction !== 'sendrecv') {
  1054. if (options.startSilent) {
  1055. audioMedia.direction = 'inactive';
  1056. } else {
  1057. audioMedia.direction = 'sendrecv';
  1058. }
  1059. changed = true;
  1060. }
  1061. const videoMedia = transformer.selectMedia('video');
  1062. if (videoMedia && videoMedia.direction !== 'sendrecv') {
  1063. videoMedia.direction = 'sendrecv';
  1064. changed = true;
  1065. }
  1066. if (changed) {
  1067. return new RTCSessionDescription({
  1068. type: localDescription.type,
  1069. sdp: transformer.toRawSDP()
  1070. });
  1071. }
  1072. return localDescription;
  1073. };
  1074. /**
  1075. *
  1076. * @param {JitsiLocalTrack} localTrack
  1077. */
  1078. TraceablePeerConnection.prototype.getLocalSSRC = function(localTrack) {
  1079. const ssrcInfo = this._getSSRC(localTrack.rtcId);
  1080. return ssrcInfo && ssrcInfo.ssrcs[0];
  1081. };
  1082. /**
  1083. * When doing unified plan simulcast, we'll have a set of ssrcs with the
  1084. * same msid but no ssrc-group, since unified plan signals the simulcast
  1085. * group via the a=simulcast line. Unfortunately, Jicofo will complain
  1086. * if it sees ssrcs with matching msids but no ssrc-group, so we'll inject
  1087. * an ssrc-group line to make Jicofo happy.
  1088. * NOTE: unlike plan B simulcast, the ssrcs in this inject ssrc-group will
  1089. * NOT necessarily be in order of quality (low to high) because:
  1090. * a) when translating between unified plan and plan b the order of the ssrcs
  1091. * is not preserved and
  1092. * b) it isn't guaranteed that firefox will give them to us in order to begin
  1093. * with
  1094. * @param desc A session description object (with 'type' and 'sdp' fields)
  1095. * @return A session description object with its sdp field modified to
  1096. * contain an inject ssrc-group for simulcast
  1097. */
  1098. TraceablePeerConnection.prototype._injectSsrcGroupForUnifiedSimulcast
  1099. = function(desc) {
  1100. const sdp = transform.parse(desc.sdp);
  1101. const video = sdp.media.find(mline => mline.type === 'video');
  1102. if (video.simulcast) {
  1103. const ssrcs = [];
  1104. video.ssrcs.forEach(ssrc => {
  1105. if (ssrc.attribute === 'msid') {
  1106. ssrcs.push(ssrc.id);
  1107. }
  1108. });
  1109. video.ssrcGroups = video.ssrcGroups || [];
  1110. if (video.ssrcGroups.find(group => group.semantics === 'SIM')) {
  1111. // Group already exists, no need to do anything
  1112. return desc;
  1113. }
  1114. video.ssrcGroups.push({
  1115. semantics: 'SIM',
  1116. ssrcs: ssrcs.join(' ')
  1117. });
  1118. }
  1119. return new RTCSessionDescription({
  1120. type: desc.type,
  1121. sdp: transform.write(sdp)
  1122. });
  1123. };
  1124. /* eslint-disable-next-line vars-on-top */
  1125. const getters = {
  1126. signalingState() {
  1127. return this.peerconnection.signalingState;
  1128. },
  1129. iceConnectionState() {
  1130. return this.peerconnection.iceConnectionState;
  1131. },
  1132. localDescription() {
  1133. let desc = this.peerconnection.localDescription;
  1134. if (!desc) {
  1135. logger.debug('getLocalDescription no localDescription found');
  1136. return {};
  1137. }
  1138. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  1139. // if we're running on FF, transform to Plan B first.
  1140. if (browser.usesUnifiedPlan()) {
  1141. desc = this.interop.toPlanB(desc);
  1142. this.trace('getLocalDescription::postTransform (Plan B)',
  1143. dumpSDP(desc));
  1144. desc = this._injectSsrcGroupForUnifiedSimulcast(desc);
  1145. this.trace('getLocalDescription::postTransform (inject ssrc group)',
  1146. dumpSDP(desc));
  1147. } else {
  1148. if (browser.doesVideoMuteByStreamRemove()) {
  1149. desc = this.localSdpMunger.maybeAddMutedLocalVideoTracksToSDP(desc);
  1150. logger.debug(
  1151. 'getLocalDescription::postTransform (munge local SDP)', desc);
  1152. }
  1153. // What comes out of this getter will be signalled over Jingle to
  1154. // the other peer, so we need to make sure the media direction is
  1155. // 'sendrecv' because we won't change the direction later and don't want
  1156. // the other peer to think we can't send or receive.
  1157. //
  1158. // Note that the description we set in chrome does have the accurate
  1159. // direction (e.g. 'recvonly'), since that is technically what is
  1160. // happening (check setLocalDescription impl).
  1161. desc = enforceSendRecv(desc, this.options);
  1162. }
  1163. // See the method's doc for more info about this transformation.
  1164. desc = this.localSdpMunger.transformStreamIdentifiers(desc);
  1165. return desc;
  1166. },
  1167. remoteDescription() {
  1168. let desc = this.peerconnection.remoteDescription;
  1169. if (!desc) {
  1170. logger.debug('getRemoteDescription no remoteDescription found');
  1171. return {};
  1172. }
  1173. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  1174. // if we're running on FF, transform to Plan B first.
  1175. if (browser.usesUnifiedPlan()) {
  1176. desc = this.interop.toPlanB(desc);
  1177. this.trace(
  1178. 'getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  1179. }
  1180. return desc;
  1181. }
  1182. };
  1183. Object.keys(getters).forEach(prop => {
  1184. Object.defineProperty(
  1185. TraceablePeerConnection.prototype,
  1186. prop, {
  1187. get: getters[prop]
  1188. }
  1189. );
  1190. });
  1191. TraceablePeerConnection.prototype._getSSRC = function(rtcId) {
  1192. return this.localSSRCs.get(rtcId);
  1193. };
  1194. /**
  1195. * Add {@link JitsiLocalTrack} to this TPC.
  1196. * @param {JitsiLocalTrack} track
  1197. */
  1198. TraceablePeerConnection.prototype.addTrack = function(track, isInitiator = false) {
  1199. const rtcId = track.rtcId;
  1200. logger.info(`add ${track} to: ${this}`);
  1201. if (this.localTracks.has(rtcId)) {
  1202. logger.error(`${track} is already in ${this}`);
  1203. return;
  1204. }
  1205. this.localTracks.set(rtcId, track);
  1206. if (browser.usesUnifiedPlan() && isInitiator) {
  1207. return this.tpcUtils.addTrack(track, isInitiator);
  1208. }
  1209. const webrtcStream = track.getOriginalStream();
  1210. if (webrtcStream) {
  1211. this._addStream(webrtcStream);
  1212. // It's not ok for a track to not have a WebRTC stream if:
  1213. } else if (!browser.doesVideoMuteByStreamRemove()
  1214. || track.isAudioTrack()
  1215. || (track.isVideoTrack() && !track.isMuted())) {
  1216. logger.error(`${this} no WebRTC stream for: ${track}`);
  1217. }
  1218. // Muted video tracks do not have WebRTC stream
  1219. if (browser.usesPlanB() && browser.doesVideoMuteByStreamRemove()
  1220. && track.isVideoTrack() && track.isMuted()) {
  1221. const ssrcInfo = this.generateNewStreamSSRCInfo(track);
  1222. this.sdpConsistency.setPrimarySsrc(ssrcInfo.ssrcs[0]);
  1223. const simGroup
  1224. = ssrcInfo.groups.find(groupInfo => groupInfo.semantics === 'SIM');
  1225. if (simGroup) {
  1226. this.simulcast.setSsrcCache(simGroup.ssrcs);
  1227. }
  1228. const fidGroups
  1229. = ssrcInfo.groups.filter(
  1230. groupInfo => groupInfo.semantics === 'FID');
  1231. if (fidGroups) {
  1232. const rtxSsrcMapping = new Map();
  1233. fidGroups.forEach(fidGroup => {
  1234. const primarySsrc = fidGroup.ssrcs[0];
  1235. const rtxSsrc = fidGroup.ssrcs[1];
  1236. rtxSsrcMapping.set(primarySsrc, rtxSsrc);
  1237. });
  1238. this.rtxModifier.setSsrcCache(rtxSsrcMapping);
  1239. }
  1240. }
  1241. if (browser.usesUnifiedPlan() && !browser.usesSdpMungingForSimulcast()) {
  1242. this.tpcUtils.setEncodings(track);
  1243. }
  1244. };
  1245. /**
  1246. * Adds local track as part of the unmute operation.
  1247. * @param {JitsiLocalTrack} track the track to be added as part of the unmute
  1248. * operation
  1249. * @return {Promise<boolean>} Promise that resolves to true if the underlying PeerConnection's
  1250. * state has changed and renegotiation is required, false if no renegotiation is needed or
  1251. * Promise is rejected when something goes wrong.
  1252. */
  1253. TraceablePeerConnection.prototype.addTrackUnmute = function(track) {
  1254. if (browser.usesUnifiedPlan()) {
  1255. return this.tpcUtils.addTrackUnmute(track);
  1256. }
  1257. if (!this._assertTrackBelongs('addTrackUnmute', track)) {
  1258. // Abort
  1259. return Promise.reject('Track not found on the peerconnection');
  1260. }
  1261. logger.info(`Adding ${track} as unmute to ${this}`);
  1262. const webRtcStream = track.getOriginalStream();
  1263. if (!webRtcStream) {
  1264. logger.error(
  1265. `Unable to add ${track} as unmute to ${this} - no WebRTC stream`);
  1266. return Promise.reject('Stream not found');
  1267. }
  1268. this._addStream(webRtcStream);
  1269. return Promise.resolve(true);
  1270. };
  1271. /**
  1272. * Adds WebRTC media stream to the underlying PeerConnection
  1273. * @param {MediaStream} mediaStream
  1274. * @private
  1275. */
  1276. TraceablePeerConnection.prototype._addStream = function(mediaStream) {
  1277. this.peerconnection.addStream(mediaStream);
  1278. this._addedStreams.push(mediaStream);
  1279. };
  1280. /**
  1281. * Removes WebRTC media stream from the underlying PeerConection
  1282. * @param {MediaStream} mediaStream
  1283. */
  1284. TraceablePeerConnection.prototype._removeStream = function(mediaStream) {
  1285. if (browser.supportsRtpSender()) {
  1286. this._handleSenderRemoveStream(mediaStream);
  1287. } else {
  1288. this.peerconnection.removeStream(mediaStream);
  1289. }
  1290. this._addedStreams
  1291. = this._addedStreams.filter(stream => stream !== mediaStream);
  1292. };
  1293. /**
  1294. * This method when called will check if given <tt>localTrack</tt> belongs to
  1295. * this TPC (that it has been previously added using {@link addTrack}). If the
  1296. * track does not belong an error message will be logged.
  1297. * @param {string} methodName the method name that will be logged in an error
  1298. * message
  1299. * @param {JitsiLocalTrack} localTrack
  1300. * @return {boolean} <tt>true</tt> if given local track belongs to this TPC or
  1301. * <tt>false</tt> otherwise.
  1302. * @private
  1303. */
  1304. TraceablePeerConnection.prototype._assertTrackBelongs = function(
  1305. methodName,
  1306. localTrack) {
  1307. const doesBelong = this.localTracks.has(localTrack.rtcId);
  1308. if (!doesBelong) {
  1309. logger.error(
  1310. `${methodName}: ${localTrack} does not belong to ${this}`);
  1311. }
  1312. return doesBelong;
  1313. };
  1314. /**
  1315. * Tells if the given WebRTC <tt>MediaStream</tt> has been added to
  1316. * the underlying WebRTC PeerConnection.
  1317. * @param {MediaStream} mediaStream
  1318. * @returns {boolean}
  1319. */
  1320. TraceablePeerConnection.prototype.isMediaStreamInPc = function(mediaStream) {
  1321. return this._addedStreams.indexOf(mediaStream) > -1;
  1322. };
  1323. /**
  1324. * Remove local track from this TPC.
  1325. * @param {JitsiLocalTrack} localTrack the track to be removed from this TPC.
  1326. *
  1327. * FIXME It should probably remove a boolean just like {@link removeTrackMute}
  1328. * The same applies to addTrack.
  1329. */
  1330. TraceablePeerConnection.prototype.removeTrack = function(localTrack) {
  1331. if (browser.usesUnifiedPlan()) {
  1332. return this.tpcUtils.removeTrack(localTrack);
  1333. }
  1334. const webRtcStream = localTrack.getOriginalStream();
  1335. this.trace(
  1336. 'removeStream',
  1337. localTrack.rtcId, webRtcStream ? webRtcStream.id : undefined);
  1338. if (!this._assertTrackBelongs('removeStream', localTrack)) {
  1339. // Abort - nothing to be done here
  1340. return;
  1341. }
  1342. this.localTracks.delete(localTrack.rtcId);
  1343. this.localSSRCs.delete(localTrack.rtcId);
  1344. if (webRtcStream) {
  1345. if (browser.supportsRtpSender()) {
  1346. this._handleSenderRemoveStream(webRtcStream);
  1347. } else {
  1348. this.peerconnection.removeStream(webRtcStream);
  1349. }
  1350. }
  1351. };
  1352. /**
  1353. * Returns the sender corresponding to the given media type.
  1354. * @param {MEDIA_TYPE} mediaType - The media type 'audio' or 'video' to be used for the search.
  1355. * @returns {RTPSender|undefined} - The found sender or undefined if no sender
  1356. * was found.
  1357. */
  1358. TraceablePeerConnection.prototype.findSenderByKind = function(mediaType) {
  1359. return this.peerconnection.getSenders().find(s => s.track && s.track.kind === mediaType);
  1360. };
  1361. /**
  1362. * Returns the sender corresponding to the given MediaStream.
  1363. *
  1364. * @param {MediaStream} stream - The media stream used for the search.
  1365. * @returns {RTPSender|undefined} - The found sender or undefined if no sender
  1366. * was found.
  1367. */
  1368. TraceablePeerConnection.prototype.findSenderByStream = function(stream) {
  1369. const track = stream.getTracks()[0];
  1370. if (!track) {
  1371. logger.error('Cannot find sender: no tracks.');
  1372. return;
  1373. }
  1374. // Find the right sender (for audio or video)
  1375. return this.peerconnection.getSenders().find(s => s.track === track);
  1376. };
  1377. /**
  1378. * Returns the receiver corresponding to the given MediaStreamTrack.
  1379. *
  1380. * @param {MediaSreamTrack} track - The media stream track used for the search.
  1381. * @returns {RTCRtpReceiver|undefined} - The found receiver or undefined if no receiver
  1382. * was found.
  1383. */
  1384. TraceablePeerConnection.prototype.findReceiverForTrack = function(track) {
  1385. return this.peerconnection.getReceivers().find(r => r.track === track);
  1386. };
  1387. /**
  1388. * Returns the sender corresponding to the given MediaStreamTrack.
  1389. *
  1390. * @param {MediaSreamTrack} track - The media stream track used for the search.
  1391. * @returns {RTCRtpSender|undefined} - The found sender or undefined if no sender
  1392. * was found.
  1393. */
  1394. TraceablePeerConnection.prototype.findSenderForTrack = function(track) {
  1395. return this.peerconnection.getSenders().find(s => s.track === track);
  1396. };
  1397. /**
  1398. * Replaces <tt>oldTrack</tt> with <tt>newTrack</tt> from the peer connection.
  1399. * Either <tt>oldTrack</tt> or <tt>newTrack</tt> can be null; replacing a valid
  1400. * <tt>oldTrack</tt> with a null <tt>newTrack</tt> effectively just removes
  1401. * <tt>oldTrack</tt>
  1402. *
  1403. * @param {JitsiLocalTrack|null} oldTrack - The current track in use to be
  1404. * replaced
  1405. * @param {JitsiLocalTrack|null} newTrack - The new track to use
  1406. * @returns {Promise<boolean>} - If the promise resolves with true,
  1407. * renegotiation will be needed. Otherwise no renegotiation is needed.
  1408. */
  1409. TraceablePeerConnection.prototype.replaceTrack = function(oldTrack, newTrack) {
  1410. if (browser.usesUnifiedPlan()) {
  1411. return this.tpcUtils.replaceTrack(oldTrack, newTrack);
  1412. }
  1413. if (oldTrack) {
  1414. this.removeTrack(oldTrack);
  1415. }
  1416. if (newTrack) {
  1417. this.addTrack(newTrack);
  1418. }
  1419. return Promise.resolve(true);
  1420. };
  1421. /**
  1422. * Removes local track as part of the mute operation.
  1423. * @param {JitsiLocalTrack} localTrack the local track to be remove as part of
  1424. * the mute operation.
  1425. * @return {Promise<boolean>} Promise that resolves to true if the underlying PeerConnection's
  1426. * state has changed and renegotiation is required, false if no renegotiation is needed or
  1427. * Promise is rejected when something goes wrong.
  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 Promise.reject('Track not found in the peerconnection');
  1440. }
  1441. if (webRtcStream) {
  1442. logger.info(
  1443. `Removing ${localTrack} as mute from ${this}`);
  1444. this._removeStream(webRtcStream);
  1445. return Promise.resolve(true);
  1446. }
  1447. logger.error(`removeStreamMute - no WebRTC stream for ${localTrack}`);
  1448. return Promise.reject('Stream not found');
  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. };