您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

TraceablePeerConnection.js 96KB

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