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

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