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

TraceablePeerConnection.js 89KB

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