選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

TraceablePeerConnection.js 102KB

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