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

TraceablePeerConnection.js 92KB

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