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

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