Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

TraceablePeerConnection.js 95KB

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