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

TraceablePeerConnection.js 92KB

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