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 100KB

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