Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

TraceablePeerConnection.js 95KB

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