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

TraceablePeerConnection.js 99KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850
  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.isWebKitBased()) {
  756. this._remoteTrackRemoved(existingTrack.getOriginalStream(), existingTrack.getTrack());
  757. }
  758. if (existingTrack && existingTrack.getTrack() === track) {
  759. // Ignore duplicated event which can originate either from 'onStreamAdded' or 'onTrackAdded'.
  760. logger.info(
  761. `${this} ignored duplicated remote track added event for: `
  762. + `${ownerEndpointId}, ${mediaType}`);
  763. return;
  764. } else if (existingTrack) {
  765. logger.error(`${this} received a second remote track for ${ownerEndpointId} ${mediaType}, `
  766. + 'deleting the existing track.');
  767. // The exisiting track needs to be removed here. We can get here when Jicofo reverses the order of source-add
  768. // and source-remove messages. Ideally, when a remote endpoint changes source, like switching devices, it sends
  769. // a source-remove (for old ssrc) followed by a source-add (for new ssrc) and Jicofo then should forward these
  770. // two messages to all the other endpoints in the conference in the same order. However, sometimes, these
  771. // messages arrive at the client in the reverse order resulting in two remote tracks (of same media type) being
  772. // created and in case of video, a black strip (that of the first track which has ended) appears over the live
  773. // track obscuring it. Removing the existing track when that happens will fix this issue.
  774. this._remoteTrackRemoved(existingTrack.getOriginalStream(), existingTrack.getTrack());
  775. }
  776. const remoteTrack
  777. = new JitsiRemoteTrack(
  778. this.rtc,
  779. this.rtc.conference,
  780. ownerEndpointId,
  781. stream,
  782. track,
  783. mediaType,
  784. videoType,
  785. ssrc,
  786. muted,
  787. this.isP2P);
  788. remoteTracksMap.set(mediaType, remoteTrack);
  789. this.eventEmitter.emit(RTCEvents.REMOTE_TRACK_ADDED, remoteTrack, this);
  790. };
  791. /* eslint-enable max-params */
  792. /**
  793. * Handles remote stream removal.
  794. * @param stream the WebRTC MediaStream object which is being removed from the
  795. * PeerConnection
  796. */
  797. TraceablePeerConnection.prototype._remoteStreamRemoved = function(stream) {
  798. if (!RTC.isUserStream(stream)) {
  799. const id = RTC.getStreamID(stream);
  800. logger.info(
  801. `Ignored remote 'stream removed' event for non-user stream ${id}`);
  802. return;
  803. }
  804. // Call remoteTrackRemoved for each track in the stream
  805. const streamVideoTracks = stream.getVideoTracks();
  806. for (const videoTrack of streamVideoTracks) {
  807. this._remoteTrackRemoved(stream, videoTrack);
  808. }
  809. const streamAudioTracks = stream.getAudioTracks();
  810. for (const audioTrack of streamAudioTracks) {
  811. this._remoteTrackRemoved(stream, audioTrack);
  812. }
  813. };
  814. /**
  815. * Handles remote media track removal.
  816. * @param {MediaStream} stream WebRTC MediaStream instance which is the parent
  817. * of the track.
  818. * @param {MediaStreamTrack} track the WebRTC MediaStreamTrack which has been
  819. * removed from the PeerConnection.
  820. */
  821. TraceablePeerConnection.prototype._remoteTrackRemoved = function(
  822. stream,
  823. track) {
  824. const streamId = RTC.getStreamID(stream);
  825. const trackId = track && RTC.getTrackID(track);
  826. logger.info(`${this} - remote track removed: ${streamId}, ${trackId}`);
  827. if (!streamId) {
  828. GlobalOnErrorHandler.callErrorHandler(
  829. new Error(`${this} remote track removal failed - no stream ID`));
  830. return;
  831. }
  832. if (!trackId) {
  833. GlobalOnErrorHandler.callErrorHandler(
  834. new Error(`${this} remote track removal failed - no track ID`));
  835. return;
  836. }
  837. if (!this._removeRemoteTrackById(streamId, trackId)) {
  838. // NOTE this warning is always printed when user leaves the room,
  839. // because we remove remote tracks manually on MUC member left event,
  840. // before the SSRCs are removed by Jicofo. In most cases it is fine to
  841. // ignore this warning, but still it's better to keep it printed for
  842. // debugging purposes.
  843. //
  844. // We could change the behaviour to emit track removed only from here,
  845. // but the order of the events will change and consuming apps could
  846. // behave unexpectedly (the "user left" event would come before "track
  847. // removed" events).
  848. logger.warn(
  849. `${this} Removed track not found for msid: ${streamId},
  850. track id: ${trackId}`);
  851. }
  852. };
  853. /**
  854. * Finds remote track by it's stream and track ids.
  855. * @param {string} streamId the media stream id as defined by the WebRTC
  856. * @param {string} trackId the media track id as defined by the WebRTC
  857. * @return {JitsiRemoteTrack|undefined} the track's instance or
  858. * <tt>undefined</tt> if not found.
  859. * @private
  860. */
  861. TraceablePeerConnection.prototype._getRemoteTrackById = function(
  862. streamId,
  863. trackId) {
  864. // .find will break the loop once the first match is found
  865. for (const endpointTrackMap of this.remoteTracks.values()) {
  866. for (const mediaTrack of endpointTrackMap.values()) {
  867. // FIXME verify and try to use ===
  868. /* eslint-disable eqeqeq */
  869. if (mediaTrack.getStreamId() == streamId
  870. && mediaTrack.getTrackId() == trackId) {
  871. return mediaTrack;
  872. }
  873. /* eslint-enable eqeqeq */
  874. }
  875. }
  876. return undefined;
  877. };
  878. /**
  879. * Removes all JitsiRemoteTracks associated with given MUC nickname
  880. * (resource part of the JID). Returns array of removed tracks.
  881. *
  882. * @param {string} owner - The resource part of the MUC JID.
  883. * @returns {JitsiRemoteTrack[]}
  884. */
  885. TraceablePeerConnection.prototype.removeRemoteTracks = function(owner) {
  886. const removedTracks = [];
  887. const remoteTracksMap = this.remoteTracks.get(owner);
  888. if (remoteTracksMap) {
  889. const removedAudioTrack = remoteTracksMap.get(MediaType.AUDIO);
  890. const removedVideoTrack = remoteTracksMap.get(MediaType.VIDEO);
  891. removedAudioTrack && removedTracks.push(removedAudioTrack);
  892. removedVideoTrack && removedTracks.push(removedVideoTrack);
  893. this.remoteTracks.delete(owner);
  894. }
  895. logger.debug(
  896. `${this} removed remote tracks for ${owner} count: ${
  897. removedTracks.length}`);
  898. return removedTracks;
  899. };
  900. /**
  901. * Removes and disposes given <tt>JitsiRemoteTrack</tt> instance. Emits
  902. * {@link RTCEvents.REMOTE_TRACK_REMOVED}.
  903. * @param {JitsiRemoteTrack} toBeRemoved
  904. */
  905. TraceablePeerConnection.prototype._removeRemoteTrack = function(toBeRemoved) {
  906. toBeRemoved.dispose();
  907. const participantId = toBeRemoved.getParticipantId();
  908. const remoteTracksMap = this.remoteTracks.get(participantId);
  909. if (!remoteTracksMap) {
  910. logger.error(
  911. `removeRemoteTrack: no remote tracks map for ${participantId}`);
  912. } else if (!remoteTracksMap.delete(toBeRemoved.getType())) {
  913. logger.error(
  914. `Failed to remove ${toBeRemoved} - type mapping messed up ?`);
  915. }
  916. this.eventEmitter.emit(RTCEvents.REMOTE_TRACK_REMOVED, toBeRemoved);
  917. };
  918. /**
  919. * Removes and disposes <tt>JitsiRemoteTrack</tt> identified by given stream and
  920. * track ids.
  921. *
  922. * @param {string} streamId the media stream id as defined by the WebRTC
  923. * @param {string} trackId the media track id as defined by the WebRTC
  924. * @returns {JitsiRemoteTrack|undefined} the track which has been removed or
  925. * <tt>undefined</tt> if no track matching given stream and track ids was
  926. * found.
  927. */
  928. TraceablePeerConnection.prototype._removeRemoteTrackById = function(
  929. streamId,
  930. trackId) {
  931. const toBeRemoved = this._getRemoteTrackById(streamId, trackId);
  932. if (toBeRemoved) {
  933. this._removeRemoteTrack(toBeRemoved);
  934. }
  935. return toBeRemoved;
  936. };
  937. /**
  938. * @typedef {Object} SSRCGroupInfo
  939. * @property {Array<number>} ssrcs group's SSRCs
  940. * @property {string} semantics
  941. */
  942. /**
  943. * @typedef {Object} TrackSSRCInfo
  944. * @property {Array<number>} ssrcs track's SSRCs
  945. * @property {Array<SSRCGroupInfo>} groups track's SSRC groups
  946. */
  947. /**
  948. * Returns map with keys msid and <tt>TrackSSRCInfo</tt> values.
  949. * @param {Object} desc the WebRTC SDP instance.
  950. * @return {Map<string,TrackSSRCInfo>}
  951. */
  952. function extractSSRCMap(desc) {
  953. /**
  954. * Track SSRC infos mapped by stream ID (msid)
  955. * @type {Map<string,TrackSSRCInfo>}
  956. */
  957. const ssrcMap = new Map();
  958. /**
  959. * Groups mapped by primary SSRC number
  960. * @type {Map<number,Array<SSRCGroupInfo>>}
  961. */
  962. const groupsMap = new Map();
  963. if (typeof desc !== 'object' || desc === null
  964. || typeof desc.sdp !== 'string') {
  965. logger.warn('An empty description was passed as an argument.');
  966. return ssrcMap;
  967. }
  968. const session = transform.parse(desc.sdp);
  969. if (!Array.isArray(session.media)) {
  970. return ssrcMap;
  971. }
  972. for (const mLine of session.media) {
  973. if (!Array.isArray(mLine.ssrcs)) {
  974. continue; // eslint-disable-line no-continue
  975. }
  976. if (Array.isArray(mLine.ssrcGroups)) {
  977. for (const group of mLine.ssrcGroups) {
  978. if (typeof group.semantics !== 'undefined'
  979. && typeof group.ssrcs !== 'undefined') {
  980. // Parse SSRCs and store as numbers
  981. const groupSSRCs
  982. = group.ssrcs.split(' ').map(
  983. ssrcStr => parseInt(ssrcStr, 10));
  984. const primarySSRC = groupSSRCs[0];
  985. // Note that group.semantics is already present
  986. group.ssrcs = groupSSRCs;
  987. // eslint-disable-next-line max-depth
  988. if (!groupsMap.has(primarySSRC)) {
  989. groupsMap.set(primarySSRC, []);
  990. }
  991. groupsMap.get(primarySSRC).push(group);
  992. }
  993. }
  994. }
  995. for (const ssrc of mLine.ssrcs) {
  996. if (ssrc.attribute !== 'msid') {
  997. continue; // eslint-disable-line no-continue
  998. }
  999. const msid = ssrc.value;
  1000. let ssrcInfo = ssrcMap.get(msid);
  1001. if (!ssrcInfo) {
  1002. ssrcInfo = {
  1003. ssrcs: [],
  1004. groups: [],
  1005. msid
  1006. };
  1007. ssrcMap.set(msid, ssrcInfo);
  1008. }
  1009. const ssrcNumber = ssrc.id;
  1010. ssrcInfo.ssrcs.push(ssrcNumber);
  1011. if (groupsMap.has(ssrcNumber)) {
  1012. const ssrcGroups = groupsMap.get(ssrcNumber);
  1013. for (const group of ssrcGroups) {
  1014. ssrcInfo.groups.push(group);
  1015. }
  1016. }
  1017. }
  1018. }
  1019. return ssrcMap;
  1020. }
  1021. /**
  1022. * Takes a SessionDescription object and returns a "normalized" version.
  1023. * Currently it takes care of ordering the a=ssrc lines and denoting receive
  1024. * only SSRCs.
  1025. */
  1026. const normalizePlanB = function(desc) {
  1027. if (typeof desc !== 'object' || desc === null
  1028. || typeof desc.sdp !== 'string') {
  1029. logger.warn('An empty description was passed as an argument.');
  1030. return desc;
  1031. }
  1032. // eslint-disable-next-line no-shadow
  1033. const transform = require('sdp-transform');
  1034. const session = transform.parse(desc.sdp);
  1035. if (typeof session !== 'undefined'
  1036. && typeof session.media !== 'undefined'
  1037. && Array.isArray(session.media)) {
  1038. session.media.forEach(mLine => {
  1039. // Chrome appears to be picky about the order in which a=ssrc lines
  1040. // are listed in an m-line when rtx is enabled (and thus there are
  1041. // a=ssrc-group lines with FID semantics). Specifically if we have
  1042. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  1043. // the "a=ssrc:S1" lines, SRD fails.
  1044. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  1045. // first.
  1046. const firstSsrcs = [];
  1047. const newSsrcLines = [];
  1048. if (typeof mLine.ssrcGroups !== 'undefined'
  1049. && Array.isArray(mLine.ssrcGroups)) {
  1050. mLine.ssrcGroups.forEach(group => {
  1051. if (typeof group.semantics !== 'undefined'
  1052. && group.semantics === 'FID') {
  1053. if (typeof group.ssrcs !== 'undefined') {
  1054. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  1055. }
  1056. }
  1057. });
  1058. }
  1059. if (Array.isArray(mLine.ssrcs)) {
  1060. let i;
  1061. for (i = 0; i < mLine.ssrcs.length; i++) {
  1062. if (typeof mLine.ssrcs[i] === 'object'
  1063. && typeof mLine.ssrcs[i].id !== 'undefined'
  1064. && firstSsrcs.indexOf(mLine.ssrcs[i].id) >= 0) {
  1065. newSsrcLines.push(mLine.ssrcs[i]);
  1066. delete mLine.ssrcs[i];
  1067. }
  1068. }
  1069. for (i = 0; i < mLine.ssrcs.length; i++) {
  1070. if (typeof mLine.ssrcs[i] !== 'undefined') {
  1071. newSsrcLines.push(mLine.ssrcs[i]);
  1072. }
  1073. }
  1074. mLine.ssrcs = replaceDefaultUnifiedPlanMsid(newSsrcLines);
  1075. }
  1076. });
  1077. }
  1078. const resStr = transform.write(session);
  1079. return new RTCSessionDescription({
  1080. type: desc.type,
  1081. sdp: resStr
  1082. });
  1083. };
  1084. /**
  1085. * Unified plan differentiates a remote track not associated with a stream using
  1086. * the msid "-", which can incorrectly trigger an onaddstream event in plan-b.
  1087. * For jitsi, these tracks are actually receive-only ssrcs. To prevent
  1088. * onaddstream from firing, remove the ssrcs with msid "-" except the cname
  1089. * line. Normally the ssrcs are not used by the client, as the bridge controls
  1090. * media flow, but keep one reference to the ssrc for the p2p case.
  1091. *
  1092. * @param {Array<Object>} ssrcLines - The ssrc lines from a remote description.
  1093. * @private
  1094. * @returns {Array<Object>} ssrcLines with removed lines referencing msid "-".
  1095. */
  1096. function replaceDefaultUnifiedPlanMsid(ssrcLines = []) {
  1097. if (!browser.isChrome() || !browser.isVersionGreaterThan(70)) {
  1098. return ssrcLines;
  1099. }
  1100. let filteredLines = [ ...ssrcLines ];
  1101. const problematicSsrcIds = ssrcLines.filter(ssrcLine =>
  1102. ssrcLine.attribute === 'mslabel' && ssrcLine.value === '-')
  1103. .map(ssrcLine => ssrcLine.id);
  1104. problematicSsrcIds.forEach(ssrcId => {
  1105. // Find the cname which is to be modified and left in.
  1106. const cnameLine = filteredLines.find(line =>
  1107. line.id === ssrcId && line.attribute === 'cname');
  1108. cnameLine.value = `recvonly-${ssrcId}`;
  1109. // Remove all of lines for the ssrc.
  1110. filteredLines
  1111. = filteredLines.filter(line => line.id !== ssrcId);
  1112. // But re-add the cname line so there is a reference kept to the ssrc
  1113. // in the SDP.
  1114. filteredLines.push(cnameLine);
  1115. });
  1116. return filteredLines;
  1117. }
  1118. /**
  1119. * Makes sure that both audio and video directions are configured as 'sendrecv'.
  1120. * @param {Object} localDescription the SDP object as defined by WebRTC.
  1121. * @param {object} options <tt>TracablePeerConnection</tt> config options.
  1122. */
  1123. const enforceSendRecv = function(localDescription, options) {
  1124. if (!localDescription) {
  1125. throw new Error('No local description passed in.');
  1126. }
  1127. const transformer = new SdpTransformWrap(localDescription.sdp);
  1128. const audioMedia = transformer.selectMedia('audio');
  1129. let changed = false;
  1130. if (audioMedia && audioMedia.direction !== 'sendrecv') {
  1131. if (options.startSilent) {
  1132. audioMedia.direction = 'inactive';
  1133. } else {
  1134. audioMedia.direction = 'sendrecv';
  1135. }
  1136. changed = true;
  1137. }
  1138. const videoMedia = transformer.selectMedia('video');
  1139. if (videoMedia && videoMedia.direction !== 'sendrecv') {
  1140. videoMedia.direction = 'sendrecv';
  1141. changed = true;
  1142. }
  1143. if (changed) {
  1144. return new RTCSessionDescription({
  1145. type: localDescription.type,
  1146. sdp: transformer.toRawSDP()
  1147. });
  1148. }
  1149. return localDescription;
  1150. };
  1151. /**
  1152. *
  1153. * @param {JitsiLocalTrack} localTrack
  1154. */
  1155. TraceablePeerConnection.prototype.getLocalSSRC = function(localTrack) {
  1156. const ssrcInfo = this._getSSRC(localTrack.rtcId);
  1157. return ssrcInfo && ssrcInfo.ssrcs[0];
  1158. };
  1159. /**
  1160. * When doing unified plan simulcast, we'll have a set of ssrcs with the
  1161. * same msid but no ssrc-group, since unified plan signals the simulcast
  1162. * group via the a=simulcast line. Unfortunately, Jicofo will complain
  1163. * if it sees ssrcs with matching msids but no ssrc-group, so we'll inject
  1164. * an ssrc-group line to make Jicofo happy.
  1165. * @param desc A session description object (with 'type' and 'sdp' fields)
  1166. * @return A session description object with its sdp field modified to
  1167. * contain an inject ssrc-group for simulcast
  1168. */
  1169. TraceablePeerConnection.prototype._injectSsrcGroupForUnifiedSimulcast
  1170. = function(desc) {
  1171. const sdp = transform.parse(desc.sdp);
  1172. const video = sdp.media.find(mline => mline.type === 'video');
  1173. // Check if the browser supports RTX, add only the primary ssrcs to the
  1174. // SIM group if that is the case.
  1175. video.ssrcGroups = video.ssrcGroups || [];
  1176. const fidGroups = video.ssrcGroups.filter(group => group.semantics === 'FID');
  1177. if (video.simulcast || video.simulcast_03) {
  1178. const ssrcs = [];
  1179. if (fidGroups && fidGroups.length) {
  1180. fidGroups.forEach(group => {
  1181. ssrcs.push(group.ssrcs.split(' ')[0]);
  1182. });
  1183. } else {
  1184. video.ssrcs.forEach(ssrc => {
  1185. if (ssrc.attribute === 'msid') {
  1186. ssrcs.push(ssrc.id);
  1187. }
  1188. });
  1189. }
  1190. if (video.ssrcGroups.find(group => group.semantics === 'SIM')) {
  1191. // Group already exists, no need to do anything
  1192. return desc;
  1193. }
  1194. video.ssrcGroups.push({
  1195. semantics: 'SIM',
  1196. ssrcs: ssrcs.join(' ')
  1197. });
  1198. }
  1199. return new RTCSessionDescription({
  1200. type: desc.type,
  1201. sdp: transform.write(sdp)
  1202. });
  1203. };
  1204. /* eslint-disable-next-line vars-on-top */
  1205. const getters = {
  1206. signalingState() {
  1207. return this.peerconnection.signalingState;
  1208. },
  1209. iceConnectionState() {
  1210. return this.peerconnection.iceConnectionState;
  1211. },
  1212. localDescription() {
  1213. let desc = this.peerconnection.localDescription;
  1214. if (!desc) {
  1215. logger.debug('getLocalDescription no localDescription found');
  1216. return {};
  1217. }
  1218. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  1219. // if we're running on FF, transform to Plan B first.
  1220. if (browser.usesUnifiedPlan()) {
  1221. desc = this.interop.toPlanB(desc);
  1222. this.trace('getLocalDescription::postTransform (Plan B)',
  1223. dumpSDP(desc));
  1224. desc = this._injectSsrcGroupForUnifiedSimulcast(desc);
  1225. this.trace('getLocalDescription::postTransform (inject ssrc group)',
  1226. dumpSDP(desc));
  1227. } else {
  1228. if (browser.doesVideoMuteByStreamRemove()) {
  1229. desc = this.localSdpMunger.maybeAddMutedLocalVideoTracksToSDP(desc);
  1230. logger.debug(
  1231. 'getLocalDescription::postTransform (munge local SDP)', desc);
  1232. }
  1233. // What comes out of this getter will be signalled over Jingle to
  1234. // the other peer, so we need to make sure the media direction is
  1235. // 'sendrecv' because we won't change the direction later and don't want
  1236. // the other peer to think we can't send or receive.
  1237. //
  1238. // Note that the description we set in chrome does have the accurate
  1239. // direction (e.g. 'recvonly'), since that is technically what is
  1240. // happening (check setLocalDescription impl).
  1241. desc = enforceSendRecv(desc, this.options);
  1242. }
  1243. // See the method's doc for more info about this transformation.
  1244. desc = this.localSdpMunger.transformStreamIdentifiers(desc);
  1245. return desc;
  1246. },
  1247. remoteDescription() {
  1248. let desc = this.peerconnection.remoteDescription;
  1249. if (!desc) {
  1250. logger.debug('getRemoteDescription no remoteDescription found');
  1251. return {};
  1252. }
  1253. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  1254. // if we're running on FF, transform to Plan B first.
  1255. if (browser.usesUnifiedPlan()) {
  1256. desc = this.interop.toPlanB(desc);
  1257. this.trace(
  1258. 'getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  1259. }
  1260. return desc;
  1261. }
  1262. };
  1263. Object.keys(getters).forEach(prop => {
  1264. Object.defineProperty(
  1265. TraceablePeerConnection.prototype,
  1266. prop, {
  1267. get: getters[prop]
  1268. }
  1269. );
  1270. });
  1271. TraceablePeerConnection.prototype._getSSRC = function(rtcId) {
  1272. return this.localSSRCs.get(rtcId);
  1273. };
  1274. /**
  1275. * Checks if screensharing is in progress.
  1276. *
  1277. * @returns {boolean} Returns true if a desktop track has been added to the
  1278. * peerconnection, false otherwise.
  1279. */
  1280. TraceablePeerConnection.prototype._isSharingScreen = function() {
  1281. const track = this.getLocalVideoTrack();
  1282. return track && track.videoType === VideoType.DESKTOP;
  1283. };
  1284. /**
  1285. * Munges the order of the codecs in the SDP passed based on the preference
  1286. * set through config.js settings. All instances of the specified codec are
  1287. * moved up to the top of the list when it is preferred. The specified codec
  1288. * is deleted from the list if the configuration specifies that the codec be
  1289. * disabled.
  1290. * @param {RTCSessionDescription} description that needs to be munged.
  1291. * @returns {RTCSessionDescription} the munged description.
  1292. */
  1293. TraceablePeerConnection.prototype._mungeCodecOrder = function(description) {
  1294. if (!this.codecPreference || browser.supportsCodecPreferences()) {
  1295. return description;
  1296. }
  1297. const parsedSdp = transform.parse(description.sdp);
  1298. const mLine = parsedSdp.media.find(m => m.type === this.codecPreference.mediaType);
  1299. if (this.codecPreference.enable) {
  1300. SDPUtil.preferCodec(mLine, this.codecPreference.mimeType);
  1301. // Strip the high profile H264 codecs on mobile clients for p2p connection.
  1302. // High profile codecs give better quality at the expense of higher load which
  1303. // we do not want on mobile clients.
  1304. // Jicofo offers only the baseline code for the jvb connection.
  1305. // TODO - add check for mobile browsers once js-utils provides that check.
  1306. if (this.codecPreference.mimeType === CodecMimeType.H264 && browser.isReactNative() && this.isP2P) {
  1307. SDPUtil.stripCodec(mLine, this.codecPreference.mimeType, true /* high profile */);
  1308. }
  1309. // Set the max bitrate here on the SDP so that the configured max. bitrate is effective
  1310. // as soon as the browser switches to VP9.
  1311. if (this.codecPreference.mimeType === CodecMimeType.VP9) {
  1312. const bitrates = Object.values(this.videoBitrates.VP9 || this.videoBitrates);
  1313. // Use only the HD bitrate for now as there is no API available yet for configuring
  1314. // the bitrates on the individual SVC layers.
  1315. mLine.bandwidth = [ {
  1316. type: 'AS',
  1317. limit: this._isSharingScreen() ? HD_BITRATE : Math.floor(bitrates[2] / 1000)
  1318. } ];
  1319. }
  1320. } else {
  1321. SDPUtil.stripCodec(mLine, this.codecPreference.mimeType);
  1322. }
  1323. return new RTCSessionDescription({
  1324. type: description.type,
  1325. sdp: transform.write(parsedSdp)
  1326. });
  1327. };
  1328. /**
  1329. * Checks if given track belongs to this peerconnection instance.
  1330. *
  1331. * @param {JitsiLocalTrack|JitsiRemoteTrack} track - The track to be checked.
  1332. * @returns {boolean}
  1333. */
  1334. TraceablePeerConnection.prototype.containsTrack = function(track) {
  1335. if (track.isLocal()) {
  1336. return this.localTracks.has(track.rtcId);
  1337. }
  1338. const participantId = track.getParticipantId();
  1339. const remoteTracksMap = this.remoteTracks.get(participantId);
  1340. return Boolean(remoteTracksMap && remoteTracksMap.get(track.getType()) === track);
  1341. };
  1342. /**
  1343. * Add {@link JitsiLocalTrack} to this TPC.
  1344. * @param {JitsiLocalTrack} track
  1345. * @param {boolean} isInitiator indicates if the endpoint is the offerer.
  1346. * @returns {Promise<void>} - resolved when done.
  1347. */
  1348. TraceablePeerConnection.prototype.addTrack = function(track, isInitiator = false) {
  1349. const rtcId = track.rtcId;
  1350. logger.info(`add ${track} to: ${this}`);
  1351. if (this.localTracks.has(rtcId)) {
  1352. return Promise.reject(new Error(`${track} is already in ${this}`));
  1353. }
  1354. this.localTracks.set(rtcId, track);
  1355. // For p2p unified case, use addTransceiver API to add the tracks on the peerconnection.
  1356. if (browser.usesUnifiedPlan() && this.isP2P) {
  1357. this.tpcUtils.addTrack(track, isInitiator);
  1358. } else {
  1359. // In all other cases, i.e., plan-b and unified plan bridge case, use addStream API to
  1360. // add the track to the peerconnection.
  1361. // TODO - addTransceiver doesn't generate a MSID for the stream, which is needed for signaling
  1362. // the ssrc to Jicofo. Switch to using UUID as MSID when addTransceiver is used in Unified plan
  1363. // JVB connection case as well.
  1364. const webrtcStream = track.getOriginalStream();
  1365. if (webrtcStream) {
  1366. this._addStream(webrtcStream);
  1367. // It's not ok for a track to not have a WebRTC stream if:
  1368. } else if (!browser.doesVideoMuteByStreamRemove()
  1369. || track.isAudioTrack()
  1370. || (track.isVideoTrack() && !track.isMuted())) {
  1371. return Promise.reject(new Error(`${this} no WebRTC stream for: ${track}`));
  1372. }
  1373. // Muted video tracks do not have WebRTC stream
  1374. if (browser.usesPlanB() && browser.doesVideoMuteByStreamRemove()
  1375. && track.isVideoTrack() && track.isMuted()) {
  1376. const ssrcInfo = this.generateNewStreamSSRCInfo(track);
  1377. this.sdpConsistency.setPrimarySsrc(ssrcInfo.ssrcs[0]);
  1378. const simGroup
  1379. = ssrcInfo.groups.find(groupInfo => groupInfo.semantics === 'SIM');
  1380. if (simGroup) {
  1381. this.simulcast.setSsrcCache(simGroup.ssrcs);
  1382. }
  1383. const fidGroups
  1384. = ssrcInfo.groups.filter(
  1385. groupInfo => groupInfo.semantics === 'FID');
  1386. if (fidGroups) {
  1387. const rtxSsrcMapping = new Map();
  1388. fidGroups.forEach(fidGroup => {
  1389. const primarySsrc = fidGroup.ssrcs[0];
  1390. const rtxSsrc = fidGroup.ssrcs[1];
  1391. rtxSsrcMapping.set(primarySsrc, rtxSsrc);
  1392. });
  1393. this.rtxModifier.setSsrcCache(rtxSsrcMapping);
  1394. }
  1395. }
  1396. }
  1397. let promiseChain = Promise.resolve();
  1398. // On Firefox, the encodings have to be configured on the sender only after the transceiver is created.
  1399. if (browser.isFirefox()) {
  1400. promiseChain = this.tpcUtils.setEncodings(track);
  1401. }
  1402. return promiseChain;
  1403. };
  1404. /**
  1405. * Adds local track as part of the unmute operation.
  1406. * @param {JitsiLocalTrack} track the track to be added as part of the unmute
  1407. * operation
  1408. * @return {Promise<boolean>} Promise that resolves to true if the underlying PeerConnection's
  1409. * state has changed and renegotiation is required, false if no renegotiation is needed or
  1410. * Promise is rejected when something goes wrong.
  1411. */
  1412. TraceablePeerConnection.prototype.addTrackUnmute = function(track) {
  1413. if (!this._assertTrackBelongs('addTrackUnmute', track)) {
  1414. // Abort
  1415. return Promise.reject('Track not found on the peerconnection');
  1416. }
  1417. logger.info(`Adding ${track} as unmute to ${this}`);
  1418. const webRtcStream = track.getOriginalStream();
  1419. if (!webRtcStream) {
  1420. logger.error(
  1421. `Unable to add ${track} as unmute to ${this} - no WebRTC stream`);
  1422. return Promise.reject('Stream not found');
  1423. }
  1424. if (browser.usesUnifiedPlan()) {
  1425. return this.tpcUtils.addTrackUnmute(track);
  1426. }
  1427. this._addStream(webRtcStream);
  1428. return Promise.resolve(true);
  1429. };
  1430. /**
  1431. * Adds WebRTC media stream to the underlying PeerConnection
  1432. * @param {MediaStream} mediaStream
  1433. * @private
  1434. */
  1435. TraceablePeerConnection.prototype._addStream = function(mediaStream) {
  1436. this.peerconnection.addStream(mediaStream);
  1437. this._addedStreams.push(mediaStream);
  1438. };
  1439. /**
  1440. * Removes WebRTC media stream from the underlying PeerConection
  1441. * @param {MediaStream} mediaStream
  1442. */
  1443. TraceablePeerConnection.prototype._removeStream = function(mediaStream) {
  1444. this.peerconnection.removeStream(mediaStream);
  1445. this._addedStreams
  1446. = this._addedStreams.filter(stream => stream !== mediaStream);
  1447. };
  1448. /**
  1449. * This method when called will check if given <tt>localTrack</tt> belongs to
  1450. * this TPC (that it has been previously added using {@link addTrack}). If the
  1451. * track does not belong an error message will be logged.
  1452. * @param {string} methodName the method name that will be logged in an error
  1453. * message
  1454. * @param {JitsiLocalTrack} localTrack
  1455. * @return {boolean} <tt>true</tt> if given local track belongs to this TPC or
  1456. * <tt>false</tt> otherwise.
  1457. * @private
  1458. */
  1459. TraceablePeerConnection.prototype._assertTrackBelongs = function(
  1460. methodName,
  1461. localTrack) {
  1462. const doesBelong = this.localTracks.has(localTrack.rtcId);
  1463. if (!doesBelong) {
  1464. logger.error(
  1465. `${methodName}: ${localTrack} does not belong to ${this}`);
  1466. }
  1467. return doesBelong;
  1468. };
  1469. /**
  1470. * Returns the codec that is configured on the client as the preferred video codec.
  1471. * This takes into account the current order of codecs in the local description sdp.
  1472. *
  1473. * @returns {CodecMimeType} The codec that is set as the preferred codec to receive
  1474. * video in the local SDP.
  1475. */
  1476. TraceablePeerConnection.prototype.getConfiguredVideoCodec = function() {
  1477. const sdp = this.localDescription.sdp;
  1478. const defaultCodec = CodecMimeType.VP8;
  1479. if (!sdp) {
  1480. return defaultCodec;
  1481. }
  1482. const parsedSdp = transform.parse(sdp);
  1483. const mLine = parsedSdp.media.find(m => m.type === MediaType.VIDEO);
  1484. const codec = mLine.rtp[0].codec;
  1485. if (codec) {
  1486. return Object.values(CodecMimeType).find(value => value === codec.toLowerCase());
  1487. }
  1488. return defaultCodec;
  1489. };
  1490. /**
  1491. * Sets the codec preference on the peerconnection. The codec preference goes into effect when
  1492. * the next renegotiation happens.
  1493. *
  1494. * @param {CodecMimeType} preferredCodec the preferred codec.
  1495. * @param {CodecMimeType} disabledCodec the codec that needs to be disabled.
  1496. * @returns {void}
  1497. */
  1498. TraceablePeerConnection.prototype.setVideoCodecs = function(preferredCodec = null, disabledCodec = null) {
  1499. // If both enable and disable are set, disable settings will prevail.
  1500. const enable = disabledCodec === null;
  1501. const mimeType = disabledCodec ? disabledCodec : preferredCodec;
  1502. if (this.codecPreference && (preferredCodec || disabledCodec)) {
  1503. this.codecPreference.enable = enable;
  1504. this.codecPreference.mimeType = mimeType;
  1505. } else if (preferredCodec || disabledCodec) {
  1506. this.codecPreference = {
  1507. enable,
  1508. mediaType: MediaType.VIDEO,
  1509. mimeType
  1510. };
  1511. } else {
  1512. logger.warn(`Invalid codec settings: preferred ${preferredCodec}, disabled ${disabledCodec},
  1513. atleast one value is needed`);
  1514. }
  1515. if (browser.supportsCodecPreferences()) {
  1516. // TODO implement codec preference using RTCRtpTransceiver.setCodecPreferences()
  1517. // We are using SDP munging for now until all browsers support this.
  1518. }
  1519. };
  1520. /**
  1521. * Tells if the given WebRTC <tt>MediaStream</tt> has been added to
  1522. * the underlying WebRTC PeerConnection.
  1523. * @param {MediaStream} mediaStream
  1524. * @returns {boolean}
  1525. */
  1526. TraceablePeerConnection.prototype.isMediaStreamInPc = function(mediaStream) {
  1527. return this._addedStreams.indexOf(mediaStream) > -1;
  1528. };
  1529. /**
  1530. * Remove local track from this TPC.
  1531. * @param {JitsiLocalTrack} localTrack the track to be removed from this TPC.
  1532. *
  1533. * FIXME It should probably remove a boolean just like {@link removeTrackMute}
  1534. * The same applies to addTrack.
  1535. */
  1536. TraceablePeerConnection.prototype.removeTrack = function(localTrack) {
  1537. const webRtcStream = localTrack.getOriginalStream();
  1538. this.trace(
  1539. 'removeStream',
  1540. localTrack.rtcId, webRtcStream ? webRtcStream.id : undefined);
  1541. if (!this._assertTrackBelongs('removeStream', localTrack)) {
  1542. // Abort - nothing to be done here
  1543. return;
  1544. }
  1545. this.localTracks.delete(localTrack.rtcId);
  1546. this.localSSRCs.delete(localTrack.rtcId);
  1547. if (webRtcStream) {
  1548. this.peerconnection.removeStream(webRtcStream);
  1549. }
  1550. };
  1551. /**
  1552. * Returns the sender corresponding to the given media type.
  1553. * @param {MEDIA_TYPE} mediaType - The media type 'audio' or 'video' to be used for the search.
  1554. * @returns {RTPSender|undefined} - The found sender or undefined if no sender
  1555. * was found.
  1556. */
  1557. TraceablePeerConnection.prototype.findSenderByKind = function(mediaType) {
  1558. return this.peerconnection.getSenders().find(s => s.track && s.track.kind === mediaType);
  1559. };
  1560. /**
  1561. * Returns the receiver corresponding to the given MediaStreamTrack.
  1562. *
  1563. * @param {MediaSreamTrack} track - The media stream track used for the search.
  1564. * @returns {RTCRtpReceiver|undefined} - The found receiver or undefined if no receiver
  1565. * was found.
  1566. */
  1567. TraceablePeerConnection.prototype.findReceiverForTrack = function(track) {
  1568. return this.peerconnection.getReceivers().find(r => r.track === track);
  1569. };
  1570. /**
  1571. * Returns the sender corresponding to the given MediaStreamTrack.
  1572. *
  1573. * @param {MediaSreamTrack} track - The media stream track used for the search.
  1574. * @returns {RTCRtpSender|undefined} - The found sender or undefined if no sender
  1575. * was found.
  1576. */
  1577. TraceablePeerConnection.prototype.findSenderForTrack = function(track) {
  1578. return this.peerconnection.getSenders().find(s => s.track === track);
  1579. };
  1580. /**
  1581. * Replaces <tt>oldTrack</tt> with <tt>newTrack</tt> from the peer connection.
  1582. * Either <tt>oldTrack</tt> or <tt>newTrack</tt> can be null; replacing a valid
  1583. * <tt>oldTrack</tt> with a null <tt>newTrack</tt> effectively just removes
  1584. * <tt>oldTrack</tt>
  1585. *
  1586. * @param {JitsiLocalTrack|null} oldTrack - The current track in use to be
  1587. * replaced
  1588. * @param {JitsiLocalTrack|null} newTrack - The new track to use
  1589. * @returns {Promise<boolean>} - If the promise resolves with true,
  1590. * renegotiation will be needed. Otherwise no renegotiation is needed.
  1591. */
  1592. TraceablePeerConnection.prototype.replaceTrack = function(oldTrack, newTrack) {
  1593. if (browser.usesUnifiedPlan()) {
  1594. logger.debug('TPC.replaceTrack using unified plan.');
  1595. return this.tpcUtils.replaceTrack(oldTrack, newTrack)
  1596. // renegotiate when SDP is used for simulcast munging
  1597. .then(() => this.isSimulcastOn() && browser.usesSdpMungingForSimulcast());
  1598. }
  1599. logger.debug('TPC.replaceTrack using plan B.');
  1600. let promiseChain = Promise.resolve();
  1601. if (oldTrack) {
  1602. this.removeTrack(oldTrack);
  1603. }
  1604. if (newTrack) {
  1605. promiseChain = this.addTrack(newTrack);
  1606. }
  1607. return promiseChain.then(() => true);
  1608. };
  1609. /**
  1610. * Removes local track as part of the mute operation.
  1611. * @param {JitsiLocalTrack} localTrack the local track to be remove as part of
  1612. * the mute operation.
  1613. * @return {Promise<boolean>} Promise that resolves to true if the underlying PeerConnection's
  1614. * state has changed and renegotiation is required, false if no renegotiation is needed or
  1615. * Promise is rejected when something goes wrong.
  1616. */
  1617. TraceablePeerConnection.prototype.removeTrackMute = function(localTrack) {
  1618. const webRtcStream = localTrack.getOriginalStream();
  1619. this.trace(
  1620. 'removeStreamMute',
  1621. localTrack.rtcId, webRtcStream ? webRtcStream.id : null);
  1622. if (!this._assertTrackBelongs('removeStreamMute', localTrack)) {
  1623. // Abort - nothing to be done here
  1624. return Promise.reject('Track not found in the peerconnection');
  1625. }
  1626. if (browser.usesUnifiedPlan()) {
  1627. return this.tpcUtils.removeTrackMute(localTrack);
  1628. }
  1629. if (webRtcStream) {
  1630. logger.info(
  1631. `Removing ${localTrack} as mute from ${this}`);
  1632. this._removeStream(webRtcStream);
  1633. return Promise.resolve(true);
  1634. }
  1635. logger.error(`removeStreamMute - no WebRTC stream for ${localTrack}`);
  1636. return Promise.reject('Stream not found');
  1637. };
  1638. TraceablePeerConnection.prototype.createDataChannel = function(label, opts) {
  1639. this.trace('createDataChannel', label, opts);
  1640. return this.peerconnection.createDataChannel(label, opts);
  1641. };
  1642. /**
  1643. * Ensures that the simulcast ssrc-group appears after any other ssrc-groups
  1644. * in the SDP so that simulcast is properly activated.
  1645. *
  1646. * @param {Object} localSdp the WebRTC session description instance for
  1647. * the local description.
  1648. * @private
  1649. */
  1650. TraceablePeerConnection.prototype._ensureSimulcastGroupIsLast = function(
  1651. localSdp) {
  1652. let sdpStr = localSdp.sdp;
  1653. const videoStartIndex = sdpStr.indexOf('m=video');
  1654. const simStartIndex = sdpStr.indexOf('a=ssrc-group:SIM', videoStartIndex);
  1655. let otherStartIndex = sdpStr.lastIndexOf('a=ssrc-group');
  1656. if (simStartIndex === -1
  1657. || otherStartIndex === -1
  1658. || otherStartIndex === simStartIndex) {
  1659. return localSdp;
  1660. }
  1661. const simEndIndex = sdpStr.indexOf('\r\n', simStartIndex);
  1662. const simStr = sdpStr.substring(simStartIndex, simEndIndex + 2);
  1663. sdpStr = sdpStr.replace(simStr, '');
  1664. otherStartIndex = sdpStr.lastIndexOf('a=ssrc-group');
  1665. const otherEndIndex = sdpStr.indexOf('\r\n', otherStartIndex);
  1666. const sdpHead = sdpStr.slice(0, otherEndIndex);
  1667. const simStrTrimmed = simStr.trim();
  1668. const sdpTail = sdpStr.slice(otherEndIndex);
  1669. sdpStr = `${sdpHead}\r\n${simStrTrimmed}${sdpTail}`;
  1670. return new RTCSessionDescription({
  1671. type: localSdp.type,
  1672. sdp: sdpStr
  1673. });
  1674. };
  1675. /**
  1676. * Will adjust audio and video media direction in the given SDP object to
  1677. * reflect the current status of the {@link audioTransferActive} and
  1678. * {@link videoTransferActive} flags.
  1679. * @param {Object} localDescription the WebRTC session description instance for
  1680. * the local description.
  1681. * @private
  1682. */
  1683. TraceablePeerConnection.prototype._adjustLocalMediaDirection = function(
  1684. localDescription) {
  1685. const transformer = new SdpTransformWrap(localDescription.sdp);
  1686. let modifiedDirection = false;
  1687. const audioMedia = transformer.selectMedia('audio');
  1688. if (audioMedia) {
  1689. const desiredAudioDirection
  1690. = this._getDesiredMediaDirection(MediaType.AUDIO);
  1691. if (audioMedia.direction !== desiredAudioDirection) {
  1692. audioMedia.direction = desiredAudioDirection;
  1693. logger.info(
  1694. `Adjusted local audio direction to ${desiredAudioDirection}`);
  1695. modifiedDirection = true;
  1696. }
  1697. } else {
  1698. logger.warn('No "audio" media found int the local description');
  1699. }
  1700. const videoMedia = transformer.selectMedia('video');
  1701. if (videoMedia) {
  1702. const desiredVideoDirection
  1703. = this._getDesiredMediaDirection(MediaType.VIDEO);
  1704. if (videoMedia.direction !== desiredVideoDirection) {
  1705. videoMedia.direction = desiredVideoDirection;
  1706. logger.info(
  1707. `Adjusted local video direction to ${desiredVideoDirection}`);
  1708. modifiedDirection = true;
  1709. }
  1710. } else {
  1711. logger.warn('No "video" media found in the local description');
  1712. }
  1713. if (modifiedDirection) {
  1714. return new RTCSessionDescription({
  1715. type: localDescription.type,
  1716. sdp: transformer.toRawSDP()
  1717. });
  1718. }
  1719. return localDescription;
  1720. };
  1721. TraceablePeerConnection.prototype.setLocalDescription = function(description) {
  1722. let localSdp = description;
  1723. this.trace('setLocalDescription::preTransform', dumpSDP(localSdp));
  1724. // Munge the order of the codecs based on the preferences set through config.js
  1725. localSdp = this._mungeCodecOrder(localSdp);
  1726. if (browser.usesPlanB()) {
  1727. localSdp = this._adjustLocalMediaDirection(localSdp);
  1728. localSdp = this._ensureSimulcastGroupIsLast(localSdp);
  1729. } else {
  1730. // if we're using unified plan, transform to it first.
  1731. localSdp = this.interop.toUnifiedPlan(localSdp);
  1732. this.trace(
  1733. 'setLocalDescription::postTransform (Unified Plan)',
  1734. dumpSDP(localSdp));
  1735. }
  1736. return new Promise((resolve, reject) => {
  1737. this.peerconnection.setLocalDescription(localSdp)
  1738. .then(() => {
  1739. this.trace('setLocalDescriptionOnSuccess');
  1740. const localUfrag = SDPUtil.getUfrag(localSdp.sdp);
  1741. if (localUfrag !== this.localUfrag) {
  1742. this.localUfrag = localUfrag;
  1743. this.eventEmitter.emit(
  1744. RTCEvents.LOCAL_UFRAG_CHANGED, this, localUfrag);
  1745. }
  1746. resolve();
  1747. }, err => {
  1748. this.trace('setLocalDescriptionOnFailure', err);
  1749. this.eventEmitter.emit(
  1750. RTCEvents.SET_LOCAL_DESCRIPTION_FAILED,
  1751. err, this);
  1752. reject(err);
  1753. });
  1754. });
  1755. };
  1756. /**
  1757. * Enables/disables audio media transmission on this peer connection. When
  1758. * disabled the SDP audio media direction in the local SDP will be adjusted to
  1759. * 'inactive' which means that no data will be sent nor accepted, but
  1760. * the connection should be kept alive.
  1761. * @param {boolean} active <tt>true</tt> to enable audio media transmission or
  1762. * <tt>false</tt> to disable. If the value is not a boolean the call will have
  1763. * no effect.
  1764. * @return {boolean} <tt>true</tt> if the value has changed and sRD/sLD cycle
  1765. * needs to be executed in order for the changes to take effect or
  1766. * <tt>false</tt> if the given value was the same as the previous one.
  1767. * @public
  1768. */
  1769. TraceablePeerConnection.prototype.setAudioTransferActive = function(active) {
  1770. logger.debug(`${this} audio transfer active: ${active}`);
  1771. const changed = this.audioTransferActive !== active;
  1772. this.audioTransferActive = active;
  1773. if (browser.usesUnifiedPlan()) {
  1774. this.tpcUtils.setAudioTransferActive(active);
  1775. // false means no renegotiation up the chain which is not needed in the Unified mode
  1776. return false;
  1777. }
  1778. return changed;
  1779. };
  1780. /**
  1781. * Sets the degradation preference on the video sender. This setting determines if
  1782. * resolution or framerate will be preferred when bandwidth or cpu is constrained.
  1783. * Sets it to 'maintain-framerate' when a camera track is added to the pc, sets it
  1784. * to 'maintain-resolution' when a desktop track is being shared instead.
  1785. * @returns {Promise<void>}
  1786. */
  1787. TraceablePeerConnection.prototype.setSenderVideoDegradationPreference = function() {
  1788. if (!this.peerconnection.getSenders) {
  1789. logger.debug('Browser does not support RTCRtpSender');
  1790. return Promise.resolve();
  1791. }
  1792. const localVideoTrack = this.getLocalVideoTrack();
  1793. const videoSender = this.findSenderByKind(MediaType.VIDEO);
  1794. if (!videoSender) {
  1795. return Promise.resolve();
  1796. }
  1797. const parameters = videoSender.getParameters();
  1798. if (!parameters.encodings || !parameters.encodings.length) {
  1799. return Promise.resolve();
  1800. }
  1801. for (const encoding in parameters.encodings) {
  1802. if (parameters.encodings.hasOwnProperty(encoding)) {
  1803. const preference = localVideoTrack.videoType === VideoType.CAMERA
  1804. ? DEGRADATION_PREFERENCE_CAMERA
  1805. : DEGRADATION_PREFERENCE_DESKTOP;
  1806. logger.info(`Setting video sender degradation preference on ${this} to ${preference}`);
  1807. parameters.encodings[encoding].degradationPreference = preference;
  1808. }
  1809. }
  1810. this.tpcUtils.updateEncodingsResolution(parameters);
  1811. return videoSender.setParameters(parameters);
  1812. };
  1813. /**
  1814. * Sets the max bitrate on the RTCRtpSender so that the
  1815. * bitrate of the enocder doesn't exceed the configured value.
  1816. * This is needed for the desktop share until spec-complaint
  1817. * simulcast is implemented.
  1818. * @param {JitsiLocalTrack} localTrack - the local track whose
  1819. * max bitrate is to be configured.
  1820. * @returns {Promise<void>}
  1821. */
  1822. TraceablePeerConnection.prototype.setMaxBitRate = function() {
  1823. // For VP9, max bitrate is configured by setting b=AS value in SDP. Browsers do
  1824. // not yet support setting max bitrates for individual VP9 SVC layers.
  1825. if (this.getConfiguredVideoCodec() === CodecMimeType.VP9 || !window.RTCRtpSender) {
  1826. return Promise.resolve();
  1827. }
  1828. const localVideoTrack = this.getLocalVideoTrack();
  1829. if (!localVideoTrack) {
  1830. return Promise.resolve();
  1831. }
  1832. const videoType = localVideoTrack.videoType;
  1833. const planBScreenSharing = browser.usesPlanB() && videoType === VideoType.DESKTOP;
  1834. // Apply the maxbitrates on the video track when one of the conditions is met.
  1835. // 1. Max. bitrates for video are specified through videoQuality settings in config.js
  1836. // 2. Track is a desktop track and bitrate is capped using capScreenshareBitrate option in plan-b mode.
  1837. // 3. The client is running in Unified plan mode.
  1838. if (!((this.options.videoQuality && this.options.videoQuality.maxBitratesVideo)
  1839. || (planBScreenSharing && this.options.capScreenshareBitrate)
  1840. || browser.usesUnifiedPlan())) {
  1841. return Promise.resolve();
  1842. }
  1843. const presenterEnabled = localVideoTrack._originalStream
  1844. && localVideoTrack._originalStream.id !== localVideoTrack.getStreamId();
  1845. const videoSender = this.findSenderByKind(MediaType.VIDEO);
  1846. if (!videoSender) {
  1847. return Promise.resolve();
  1848. }
  1849. const parameters = videoSender.getParameters();
  1850. if (!(parameters.encodings && parameters.encodings.length)) {
  1851. return Promise.resolve();
  1852. }
  1853. if (this.isSimulcastOn()) {
  1854. for (const encoding in parameters.encodings) {
  1855. if (parameters.encodings.hasOwnProperty(encoding)) {
  1856. let bitrate;
  1857. if (planBScreenSharing) {
  1858. // On chromium, set a max bitrate of 500 Kbps for screenshare when capScreenshareBitrate
  1859. // is enabled through config.js and presenter is not turned on.
  1860. // FIXME the top 'isSimulcastOn' condition is confusing for screensharing, because
  1861. // if capScreenshareBitrate option is enabled then the simulcast is turned off
  1862. bitrate = this.options.capScreenshareBitrate
  1863. ? presenterEnabled ? HD_BITRATE : DESKTOP_SHARE_RATE
  1864. // Remove the bitrate config if not capScreenshareBitrate:
  1865. // When switching from camera to desktop and videoQuality.maxBitratesVideo were set,
  1866. // then the 'maxBitrate' setting must be cleared, because if simulcast is enabled for screen
  1867. // and maxBitrates are set then Chrome will not send the screen stream (plan B).
  1868. : undefined;
  1869. } else {
  1870. bitrate = this.tpcUtils.localStreamEncodingsConfig[encoding].maxBitrate;
  1871. }
  1872. logger.info(`${this} Setting a max bitrate of ${bitrate} bps on layer `
  1873. + `${this.tpcUtils.localStreamEncodingsConfig[encoding].rid}`);
  1874. parameters.encodings[encoding].maxBitrate = bitrate;
  1875. }
  1876. }
  1877. } else {
  1878. // Do not change the max bitrate for desktop tracks in non-simulcast mode.
  1879. let bitrate = this.videoBitrates.high;
  1880. if (videoType === VideoType.CAMERA) {
  1881. // Determine the bitrates based on the sender constraint applied for unicast tracks.
  1882. const scaleFactor = this.senderVideoMaxHeight
  1883. ? Math.floor(localVideoTrack.resolution / this.senderVideoMaxHeight)
  1884. : 1;
  1885. const encoding = this.tpcUtils.localStreamEncodingsConfig
  1886. .find(layer => layer.scaleResolutionDownBy === scaleFactor);
  1887. if (encoding) {
  1888. logger.info(`${this} Setting a max bitrate of ${encoding.maxBitrate} bps on local video track`);
  1889. bitrate = encoding.maxBitrate;
  1890. }
  1891. }
  1892. parameters.encodings[0].maxBitrate = bitrate;
  1893. }
  1894. this.tpcUtils.updateEncodingsResolution(parameters);
  1895. return videoSender.setParameters(parameters);
  1896. };
  1897. TraceablePeerConnection.prototype.setRemoteDescription = function(description) {
  1898. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  1899. // Munge the order of the codecs based on the preferences set through config.js
  1900. // eslint-disable-next-line no-param-reassign
  1901. description = this._mungeCodecOrder(description);
  1902. if (browser.usesPlanB()) {
  1903. // TODO the focus should squeze or explode the remote simulcast
  1904. if (this.isSimulcastOn()) {
  1905. // eslint-disable-next-line no-param-reassign
  1906. description = this.simulcast.mungeRemoteDescription(description, true /* add x-google-conference flag */);
  1907. this.trace(
  1908. 'setRemoteDescription::postTransform (simulcast)',
  1909. dumpSDP(description));
  1910. }
  1911. // eslint-disable-next-line no-param-reassign
  1912. description = normalizePlanB(description);
  1913. } else {
  1914. const currentDescription = this.peerconnection.remoteDescription;
  1915. // eslint-disable-next-line no-param-reassign
  1916. description = this.interop.toUnifiedPlan(description, currentDescription);
  1917. this.trace(
  1918. 'setRemoteDescription::postTransform (Unified)',
  1919. dumpSDP(description));
  1920. if (this.isSimulcastOn()) {
  1921. // eslint-disable-next-line no-param-reassign
  1922. description = this.simulcast.mungeRemoteDescription(description);
  1923. // eslint-disable-next-line no-param-reassign
  1924. description = this.tpcUtils.insertUnifiedPlanSimulcastReceive(description);
  1925. this.trace(
  1926. 'setRemoteDescription::postTransform (sim receive)',
  1927. dumpSDP(description));
  1928. // eslint-disable-next-line no-param-reassign
  1929. description = this.tpcUtils.ensureCorrectOrderOfSsrcs(description);
  1930. }
  1931. }
  1932. return new Promise((resolve, reject) => {
  1933. this.peerconnection.setRemoteDescription(description)
  1934. .then(() => {
  1935. this.trace('setRemoteDescriptionOnSuccess');
  1936. const remoteUfrag = SDPUtil.getUfrag(description.sdp);
  1937. if (remoteUfrag !== this.remoteUfrag) {
  1938. this.remoteUfrag = remoteUfrag;
  1939. this.eventEmitter.emit(
  1940. RTCEvents.REMOTE_UFRAG_CHANGED, this, remoteUfrag);
  1941. }
  1942. resolve();
  1943. }, err => {
  1944. this.trace('setRemoteDescriptionOnFailure', err);
  1945. this.eventEmitter.emit(
  1946. RTCEvents.SET_REMOTE_DESCRIPTION_FAILED,
  1947. err,
  1948. this);
  1949. reject(err);
  1950. });
  1951. });
  1952. };
  1953. /**
  1954. * Changes the resolution of the video stream that is sent to the peer based on
  1955. * the user preferred value. If simulcast is enabled on the peerconection, all the
  1956. * simulcast encodings that have a resolution height lower or equal to the value
  1957. * provided will remain active. For the non-simulcast case, video constraint is
  1958. * applied on the track.
  1959. * @param {number} frameHeight - The user preferred max frame height.
  1960. * @returns {Promise} promise that will be resolved when the operation is
  1961. * successful and rejected otherwise.
  1962. */
  1963. TraceablePeerConnection.prototype.setSenderVideoConstraint = function(frameHeight = null) {
  1964. if (frameHeight < 0) {
  1965. throw new Error(`Invalid frameHeight: ${frameHeight}`);
  1966. }
  1967. // XXX: This is not yet supported on mobile.
  1968. if (browser.isReactNative()) {
  1969. return Promise.resolve();
  1970. }
  1971. // Need to explicitly check for null as 0 is falsy, but a valid value
  1972. const newHeight = frameHeight === null ? this.senderVideoMaxHeight : frameHeight;
  1973. this.senderVideoMaxHeight = newHeight;
  1974. // If layer suspension is disabled and sender constraint is not configured for the conference,
  1975. // resolve here so that the encodings stay enabled. This can happen in custom apps built using
  1976. // lib-jitsi-meet.
  1977. if (newHeight === null) {
  1978. return Promise.resolve();
  1979. }
  1980. logger.log(`${this} senderVideoMaxHeight: ${newHeight}`);
  1981. const localVideoTrack = this.getLocalVideoTrack();
  1982. if (!localVideoTrack || localVideoTrack.isMuted()) {
  1983. return Promise.resolve();
  1984. }
  1985. const videoSender = this.findSenderByKind(MediaType.VIDEO);
  1986. if (!videoSender) {
  1987. return Promise.resolve();
  1988. }
  1989. const parameters = videoSender.getParameters();
  1990. if (!parameters || !parameters.encodings || !parameters.encodings.length) {
  1991. return Promise.resolve();
  1992. }
  1993. if (this.isSimulcastOn()) {
  1994. // Determine the encodings that need to stay enabled based on the new frameHeight provided.
  1995. const encodingsEnabledState = this.tpcUtils.getLocalStreamHeightConstraints(localVideoTrack.track)
  1996. .map(height => height <= newHeight);
  1997. // Always keep the LD stream enabled, specifically when the LD stream's resolution is higher than of the
  1998. // requested resolution. This can happen when camera is captured at resolutions higher than 720p but the
  1999. // requested resolution is 180. Since getParameters doesn't give us information about the resolutions
  2000. // of the simulcast encodings, we have to rely on our initial config for the simulcast streams.
  2001. const ldStreamIndex = this.tpcUtils.localStreamEncodingsConfig
  2002. .findIndex(layer => layer.scaleResolutionDownBy === 4.0);
  2003. if (newHeight > 0 && ldStreamIndex !== -1) {
  2004. encodingsEnabledState[ldStreamIndex] = true;
  2005. }
  2006. for (const encoding in parameters.encodings) {
  2007. if (parameters.encodings.hasOwnProperty(encoding)) {
  2008. parameters.encodings[encoding].active = encodingsEnabledState[encoding];
  2009. }
  2010. }
  2011. this.tpcUtils.updateEncodingsResolution(parameters);
  2012. } else if (newHeight > 0) {
  2013. // Do not scale down the desktop tracks until SendVideoController is able to propagate the sender constraints
  2014. // only on the active media connection. Right now, the sender constraints received on the bridge channel
  2015. // are propagated on both the jvb and p2p connections in cases where they both are active at the same time.
  2016. parameters.encodings[0].scaleResolutionDownBy
  2017. = localVideoTrack.videoType === VideoType.DESKTOP || localVideoTrack.resolution <= newHeight
  2018. ? 1
  2019. : Math.floor(localVideoTrack.resolution / newHeight);
  2020. parameters.encodings[0].active = true;
  2021. } else {
  2022. parameters.encodings[0].scaleResolutionDownBy = undefined;
  2023. parameters.encodings[0].active = false;
  2024. }
  2025. logger.info(`${this} setting max height of ${newHeight}, encodings: ${JSON.stringify(parameters.encodings)}`);
  2026. return videoSender.setParameters(parameters).then(() => {
  2027. localVideoTrack.maxEnabledResolution = newHeight;
  2028. this.eventEmitter.emit(RTCEvents.LOCAL_TRACK_MAX_ENABLED_RESOLUTION_CHANGED, localVideoTrack);
  2029. // Max bitrate needs to be reconfigured on the sender in p2p/non-simulcast case if needed when
  2030. // the send resolution changes.
  2031. if (this.isP2P || !this.isSimulcastOn()) {
  2032. return this.setMaxBitRate();
  2033. }
  2034. });
  2035. };
  2036. /**
  2037. * Enables/disables video media transmission on this peer connection. When
  2038. * disabled the SDP video media direction in the local SDP will be adjusted to
  2039. * 'inactive' which means that no data will be sent nor accepted, but
  2040. * the connection should be kept alive.
  2041. * @param {boolean} active <tt>true</tt> to enable video media transmission or
  2042. * <tt>false</tt> to disable. If the value is not a boolean the call will have
  2043. * no effect.
  2044. * @return {boolean} <tt>true</tt> if the value has changed and sRD/sLD cycle
  2045. * needs to be executed in order for the changes to take effect or
  2046. * <tt>false</tt> if the given value was the same as the previous one.
  2047. * @public
  2048. */
  2049. TraceablePeerConnection.prototype.setVideoTransferActive = function(active) {
  2050. logger.debug(`${this} video transfer active: ${active}`);
  2051. const changed = this.videoTransferActive !== active;
  2052. this.videoTransferActive = active;
  2053. if (browser.usesUnifiedPlan()) {
  2054. this.tpcUtils.setVideoTransferActive(active);
  2055. // false means no renegotiation up the chain which is not needed in the Unified mode
  2056. return false;
  2057. }
  2058. return changed;
  2059. };
  2060. /**
  2061. * Sends DTMF tones if possible.
  2062. *
  2063. * @param {string} tones - The DTMF tones string as defined by {@code RTCDTMFSender.insertDTMF}, 'tones' argument.
  2064. * @param {number} duration - The amount of time in milliseconds that each DTMF should last. It's 200ms by default.
  2065. * @param {number} interToneGap - The length of time in miliseconds to wait between tones. It's 200ms by default.
  2066. *
  2067. * @returns {void}
  2068. */
  2069. TraceablePeerConnection.prototype.sendTones = function(tones, duration = 200, interToneGap = 200) {
  2070. if (!this._dtmfSender) {
  2071. if (this.peerconnection.getSenders) {
  2072. const rtpSender = this.peerconnection.getSenders().find(s => s.dtmf);
  2073. this._dtmfSender = rtpSender && rtpSender.dtmf;
  2074. this._dtmfSender && logger.info(`${this} initialized DTMFSender using getSenders`);
  2075. }
  2076. if (!this._dtmfSender) {
  2077. const localAudioTrack = Array.from(this.localTracks.values()).find(t => t.isAudioTrack());
  2078. if (this.peerconnection.createDTMFSender && localAudioTrack) {
  2079. this._dtmfSender = this.peerconnection.createDTMFSender(localAudioTrack.getTrack());
  2080. }
  2081. this._dtmfSender && logger.info(`${this} initialized DTMFSender using deprecated createDTMFSender`);
  2082. }
  2083. if (this._dtmfSender) {
  2084. this._dtmfSender.ontonechange = this._onToneChange.bind(this);
  2085. }
  2086. }
  2087. if (this._dtmfSender) {
  2088. if (this._dtmfSender.toneBuffer) {
  2089. this._dtmfTonesQueue.push({
  2090. tones,
  2091. duration,
  2092. interToneGap
  2093. });
  2094. return;
  2095. }
  2096. this._dtmfSender.insertDTMF(tones, duration, interToneGap);
  2097. } else {
  2098. logger.warn(`${this} sendTones - failed to select DTMFSender`);
  2099. }
  2100. };
  2101. /**
  2102. * Callback ivoked by {@code this._dtmfSender} when it has finished playing
  2103. * a single tone.
  2104. *
  2105. * @param {Object} event - The tonechange event which indicates what characters
  2106. * are left to be played for the current tone.
  2107. * @private
  2108. * @returns {void}
  2109. */
  2110. TraceablePeerConnection.prototype._onToneChange = function(event) {
  2111. // An empty event.tone indicates the current tones have finished playing.
  2112. // Automatically start playing any queued tones on finish.
  2113. if (this._dtmfSender && event.tone === '' && this._dtmfTonesQueue.length) {
  2114. const { tones, duration, interToneGap } = this._dtmfTonesQueue.shift();
  2115. this._dtmfSender.insertDTMF(tones, duration, interToneGap);
  2116. }
  2117. };
  2118. /**
  2119. * Makes the underlying TraceablePeerConnection generate new SSRC for
  2120. * the recvonly video stream.
  2121. */
  2122. TraceablePeerConnection.prototype.generateRecvonlySsrc = function() {
  2123. const newSSRC = SDPUtil.generateSsrc();
  2124. logger.info(`${this} generated new recvonly SSRC: ${newSSRC}`);
  2125. this.sdpConsistency.setPrimarySsrc(newSSRC);
  2126. };
  2127. /**
  2128. * Makes the underlying TraceablePeerConnection forget the current primary video
  2129. * SSRC.
  2130. */
  2131. TraceablePeerConnection.prototype.clearRecvonlySsrc = function() {
  2132. logger.info('Clearing primary video SSRC!');
  2133. this.sdpConsistency.clearVideoSsrcCache();
  2134. };
  2135. /**
  2136. * Closes underlying WebRTC PeerConnection instance and removes all remote
  2137. * tracks by emitting {@link RTCEvents.REMOTE_TRACK_REMOVED} for each one of
  2138. * them.
  2139. */
  2140. TraceablePeerConnection.prototype.close = function() {
  2141. this.trace('stop');
  2142. // Off SignalingEvents
  2143. this.signalingLayer.off(
  2144. SignalingEvents.PEER_MUTED_CHANGED, this._peerMutedChanged);
  2145. this.signalingLayer.off(
  2146. SignalingEvents.PEER_VIDEO_TYPE_CHANGED, this._peerVideoTypeChanged);
  2147. for (const peerTracks of this.remoteTracks.values()) {
  2148. for (const remoteTrack of peerTracks.values()) {
  2149. this._removeRemoteTrack(remoteTrack);
  2150. }
  2151. }
  2152. this.remoteTracks.clear();
  2153. this._addedStreams = [];
  2154. this._dtmfSender = null;
  2155. this._dtmfTonesQueue = [];
  2156. if (!this.rtc._removePeerConnection(this)) {
  2157. logger.error('RTC._removePeerConnection returned false');
  2158. }
  2159. if (this.statsinterval !== null) {
  2160. window.clearInterval(this.statsinterval);
  2161. this.statsinterval = null;
  2162. }
  2163. logger.info(`Closing ${this}...`);
  2164. this.peerconnection.close();
  2165. };
  2166. TraceablePeerConnection.prototype.createAnswer = function(constraints) {
  2167. return this._createOfferOrAnswer(false /* answer */, constraints);
  2168. };
  2169. TraceablePeerConnection.prototype.createOffer = function(constraints) {
  2170. return this._createOfferOrAnswer(true /* offer */, constraints);
  2171. };
  2172. TraceablePeerConnection.prototype._createOfferOrAnswer = function(
  2173. isOffer,
  2174. constraints) {
  2175. const logName = isOffer ? 'Offer' : 'Answer';
  2176. this.trace(`create${logName}`, JSON.stringify(constraints, null, ' '));
  2177. const handleSuccess = (resultSdp, resolveFn, rejectFn) => {
  2178. try {
  2179. this.trace(
  2180. `create${logName}OnSuccess::preTransform`, dumpSDP(resultSdp));
  2181. if (browser.usesPlanB()) {
  2182. // If there are no local video tracks, then a "recvonly"
  2183. // SSRC needs to be generated
  2184. if (!this.hasAnyTracksOfType(MediaType.VIDEO)
  2185. && !this.sdpConsistency.hasPrimarySsrcCached()) {
  2186. this.generateRecvonlySsrc();
  2187. }
  2188. // eslint-disable-next-line no-param-reassign
  2189. resultSdp = new RTCSessionDescription({
  2190. type: resultSdp.type,
  2191. sdp: this.sdpConsistency.makeVideoPrimarySsrcsConsistent(
  2192. resultSdp.sdp)
  2193. });
  2194. this.trace(
  2195. `create${logName}OnSuccess::postTransform `
  2196. + '(make primary audio/video ssrcs consistent)',
  2197. dumpSDP(resultSdp));
  2198. }
  2199. // Configure simulcast for camera tracks always and for desktop tracks only when
  2200. // the "capScreenshareBitrate" flag in config.js is disabled.
  2201. if (this.isSimulcastOn() && browser.usesSdpMungingForSimulcast()
  2202. && (!this.options.capScreenshareBitrate
  2203. || (this.options.capScreenshareBitrate && !this._isSharingScreen()))) {
  2204. // eslint-disable-next-line no-param-reassign
  2205. resultSdp = this.simulcast.mungeLocalDescription(resultSdp);
  2206. this.trace(
  2207. `create${logName}`
  2208. + 'OnSuccess::postTransform (simulcast)',
  2209. dumpSDP(resultSdp));
  2210. }
  2211. if (!this.options.disableRtx && browser.usesSdpMungingForSimulcast()) {
  2212. // eslint-disable-next-line no-param-reassign
  2213. resultSdp = new RTCSessionDescription({
  2214. type: resultSdp.type,
  2215. sdp: this.rtxModifier.modifyRtxSsrcs(resultSdp.sdp)
  2216. });
  2217. this.trace(
  2218. `create${logName}`
  2219. + 'OnSuccess::postTransform (rtx modifier)',
  2220. dumpSDP(resultSdp));
  2221. }
  2222. const ssrcMap = extractSSRCMap(resultSdp);
  2223. logger.debug('Got local SSRCs MAP: ', ssrcMap);
  2224. this._processLocalSSRCsMap(ssrcMap);
  2225. resolveFn(resultSdp);
  2226. } catch (e) {
  2227. this.trace(`create${logName}OnError`, e);
  2228. this.trace(`create${logName}OnError`, dumpSDP(resultSdp));
  2229. logger.error(`create${logName}OnError`, e, dumpSDP(resultSdp));
  2230. rejectFn(e);
  2231. }
  2232. };
  2233. const handleFailure = (err, rejectFn) => {
  2234. this.trace(`create${logName}OnFailure`, err);
  2235. const eventType
  2236. = isOffer
  2237. ? RTCEvents.CREATE_OFFER_FAILED
  2238. : RTCEvents.CREATE_ANSWER_FAILED;
  2239. this.eventEmitter.emit(eventType, err, this);
  2240. rejectFn(err);
  2241. };
  2242. return new Promise((resolve, reject) => {
  2243. let oaPromise;
  2244. if (isOffer) {
  2245. oaPromise = this.peerconnection.createOffer(constraints);
  2246. } else {
  2247. oaPromise = this.peerconnection.createAnswer(constraints);
  2248. }
  2249. oaPromise
  2250. .then(
  2251. sdp => handleSuccess(sdp, resolve, reject),
  2252. error => handleFailure(error, reject));
  2253. });
  2254. };
  2255. /**
  2256. * Extract primary SSRC from given {@link TrackSSRCInfo} object.
  2257. * @param {TrackSSRCInfo} ssrcObj
  2258. * @return {number|null} the primary SSRC or <tt>null</tt>
  2259. */
  2260. TraceablePeerConnection.prototype._extractPrimarySSRC = function(ssrcObj) {
  2261. if (ssrcObj && ssrcObj.groups && ssrcObj.groups.length) {
  2262. return ssrcObj.groups[0].ssrcs[0];
  2263. } else if (ssrcObj && ssrcObj.ssrcs && ssrcObj.ssrcs.length) {
  2264. return ssrcObj.ssrcs[0];
  2265. }
  2266. return null;
  2267. };
  2268. /**
  2269. * Goes over the SSRC map extracted from the latest local description and tries
  2270. * to match them with the local tracks (by MSID). Will update the values
  2271. * currently stored in the {@link TraceablePeerConnection.localSSRCs} map.
  2272. * @param {Map<string,TrackSSRCInfo>} ssrcMap
  2273. * @private
  2274. */
  2275. TraceablePeerConnection.prototype._processLocalSSRCsMap = function(ssrcMap) {
  2276. for (const track of this.localTracks.values()) {
  2277. const trackMSID = track.storedMSID;
  2278. if (ssrcMap.has(trackMSID)) {
  2279. const newSSRC = ssrcMap.get(trackMSID);
  2280. if (!newSSRC) {
  2281. logger.error(`No SSRC found for: ${trackMSID} in ${this}`);
  2282. return;
  2283. }
  2284. const oldSSRC = this.localSSRCs.get(track.rtcId);
  2285. const newSSRCNum = this._extractPrimarySSRC(newSSRC);
  2286. const oldSSRCNum = this._extractPrimarySSRC(oldSSRC);
  2287. // eslint-disable-next-line no-negated-condition
  2288. if (newSSRCNum !== oldSSRCNum) {
  2289. if (oldSSRCNum === null) {
  2290. logger.info(
  2291. `Storing new local SSRC for ${track} in ${this}`,
  2292. newSSRC);
  2293. } else {
  2294. logger.error(
  2295. `Overwriting SSRC for ${track} ${trackMSID} in ${this
  2296. } with: `, newSSRC);
  2297. }
  2298. this.localSSRCs.set(track.rtcId, newSSRC);
  2299. this.eventEmitter.emit(
  2300. RTCEvents.LOCAL_TRACK_SSRC_UPDATED, track, newSSRCNum);
  2301. } else {
  2302. logger.debug(
  2303. `The local SSRC(${newSSRCNum}) for ${track} ${trackMSID}`
  2304. + `is still up to date in ${this}`);
  2305. }
  2306. } else if (!track.isVideoTrack() && !track.isMuted()) {
  2307. // It is normal to find no SSRCs for a muted video track in
  2308. // the local SDP as the recv-only SSRC is no longer munged in.
  2309. // So log the warning only if it's not a muted video track.
  2310. logger.warn(`No SSRCs found in the local SDP for ${track} MSID: ${trackMSID} in ${this}`);
  2311. }
  2312. }
  2313. };
  2314. TraceablePeerConnection.prototype.addIceCandidate = function(candidate) {
  2315. this.trace('addIceCandidate', JSON.stringify({
  2316. candidate: candidate.candidate,
  2317. sdpMid: candidate.sdpMid,
  2318. sdpMLineIndex: candidate.sdpMLineIndex,
  2319. usernameFragment: candidate.usernameFragment
  2320. }, null, ' '));
  2321. return this.peerconnection.addIceCandidate(candidate);
  2322. };
  2323. /**
  2324. * Obtains call-related stats from the peer connection.
  2325. *
  2326. * @param {Function} callback - The function to invoke after successfully
  2327. * obtaining stats.
  2328. * @param {Function} errback - The function to invoke after failing to obtain
  2329. * stats.
  2330. * @returns {void}
  2331. */
  2332. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  2333. // TODO (brian): After moving all browsers to adapter, check if adapter is
  2334. // accounting for different getStats apis, making the browser-checking-if
  2335. // unnecessary.
  2336. if (browser.isWebKitBased() || browser.isFirefox() || browser.isReactNative()) {
  2337. // uses the new Promise based getStats
  2338. this.peerconnection.getStats()
  2339. .then(callback)
  2340. .catch(errback || (() => {
  2341. // Making sure that getStats won't fail if error callback is
  2342. // not passed.
  2343. }));
  2344. } else {
  2345. this.peerconnection.getStats(callback);
  2346. }
  2347. };
  2348. /**
  2349. * Generates and stores new SSRC info object for given local track.
  2350. * The method should be called only for a video track being added to this TPC
  2351. * in the muted state (given that the current browser uses this strategy).
  2352. * @param {JitsiLocalTrack} track
  2353. * @return {TPCSSRCInfo}
  2354. */
  2355. TraceablePeerConnection.prototype.generateNewStreamSSRCInfo = function(track) {
  2356. const rtcId = track.rtcId;
  2357. let ssrcInfo = this._getSSRC(rtcId);
  2358. if (ssrcInfo) {
  2359. logger.error(`Will overwrite local SSRCs for track ID: ${rtcId}`);
  2360. }
  2361. // Configure simulcast for camera tracks always and for desktop tracks only when
  2362. // the "capScreenshareBitrate" flag in config.js is disabled.
  2363. if (this.isSimulcastOn()
  2364. && (!this.options.capScreenshareBitrate
  2365. || (this.options.capScreenshareBitrate && !this._isSharingScreen()))) {
  2366. ssrcInfo = {
  2367. ssrcs: [],
  2368. groups: []
  2369. };
  2370. for (let i = 0; i < SIM_LAYER_RIDS.length; i++) {
  2371. ssrcInfo.ssrcs.push(SDPUtil.generateSsrc());
  2372. }
  2373. ssrcInfo.groups.push({
  2374. ssrcs: ssrcInfo.ssrcs.slice(),
  2375. semantics: 'SIM'
  2376. });
  2377. } else {
  2378. ssrcInfo = {
  2379. ssrcs: [ SDPUtil.generateSsrc() ],
  2380. groups: []
  2381. };
  2382. }
  2383. if (!this.options.disableRtx) {
  2384. // Specifically use a for loop here because we'll
  2385. // be adding to the list we're iterating over, so we
  2386. // only want to iterate through the items originally
  2387. // on the list
  2388. const currNumSsrcs = ssrcInfo.ssrcs.length;
  2389. for (let i = 0; i < currNumSsrcs; ++i) {
  2390. const primarySsrc = ssrcInfo.ssrcs[i];
  2391. const rtxSsrc = SDPUtil.generateSsrc();
  2392. ssrcInfo.ssrcs.push(rtxSsrc);
  2393. ssrcInfo.groups.push({
  2394. ssrcs: [ primarySsrc, rtxSsrc ],
  2395. semantics: 'FID'
  2396. });
  2397. }
  2398. }
  2399. ssrcInfo.msid = track.storedMSID;
  2400. this.localSSRCs.set(rtcId, ssrcInfo);
  2401. return ssrcInfo;
  2402. };
  2403. /**
  2404. * Creates a text representation of this <tt>TraceablePeerConnection</tt>
  2405. * instance.
  2406. * @return {string}
  2407. */
  2408. TraceablePeerConnection.prototype.toString = function() {
  2409. return `TPC[${this.id},p2p:${this.isP2P}]`;
  2410. };