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

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