Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

TraceablePeerConnection.js 97KB

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