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

TraceablePeerConnection.js 96KB

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