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

ParticipantConnectionStatus.js 33KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880
  1. /* global __filename */
  2. import { getLogger } from 'jitsi-meet-logger';
  3. import * as JitsiConferenceEvents from '../../JitsiConferenceEvents';
  4. import * as JitsiTrackEvents from '../../JitsiTrackEvents';
  5. import * as MediaType from '../../service/RTC/MediaType';
  6. import RTCEvents from '../../service/RTC/RTCEvents';
  7. import { createParticipantConnectionStatusEvent } from '../../service/statistics/AnalyticsEvents';
  8. import browser from '../browser';
  9. import Statistics from '../statistics/statistics';
  10. const logger = getLogger(__filename);
  11. /**
  12. * Default value of 500 milliseconds for
  13. * {@link ParticipantConnectionStatus.outOfLastNTimeout}.
  14. *
  15. * @type {number}
  16. */
  17. const DEFAULT_NOT_IN_LAST_N_TIMEOUT = 500;
  18. /**
  19. * Default value of 2000 milliseconds for
  20. * {@link ParticipantConnectionStatus.rtcMuteTimeout}.
  21. *
  22. * @type {number}
  23. */
  24. const DEFAULT_RTC_MUTE_TIMEOUT = 10000;
  25. /**
  26. * The time to wait a track to be restored. Track which was out of lastN
  27. * should be inactive and when entering lastN it becomes restoring and when
  28. * data is received from bridge it will become active, but if no data is
  29. * received for some time we set status of that participant connection to
  30. * interrupted.
  31. * @type {number}
  32. */
  33. const DEFAULT_RESTORING_TIMEOUT = 10000;
  34. /**
  35. * Participant connection statuses.
  36. *
  37. * @type {{
  38. * ACTIVE: string,
  39. * INACTIVE: string,
  40. * INTERRUPTED: string,
  41. * RESTORING: string
  42. * }}
  43. */
  44. export const ParticipantConnectionStatus = {
  45. /**
  46. * Status indicating that connection is currently active.
  47. */
  48. ACTIVE: 'active',
  49. /**
  50. * Status indicating that connection is currently inactive.
  51. * Inactive means the connection was stopped on purpose from the bridge,
  52. * like exiting lastN or adaptivity decided to drop video because of not
  53. * enough bandwidth.
  54. */
  55. INACTIVE: 'inactive',
  56. /**
  57. * Status indicating that connection is currently interrupted.
  58. */
  59. INTERRUPTED: 'interrupted',
  60. /**
  61. * Status indicating that connection is currently restoring.
  62. */
  63. RESTORING: 'restoring'
  64. };
  65. /**
  66. * Class is responsible for emitting
  67. * JitsiConferenceEvents.PARTICIPANT_CONN_STATUS_CHANGED events.
  68. */
  69. export default class ParticipantConnectionStatusHandler {
  70. /* eslint-disable max-params*/
  71. /**
  72. * Calculates the new {@link ParticipantConnectionStatus} based on
  73. * the values given for some specific remote user. It is assumed that
  74. * the conference is currently in the JVB mode (in contrary to the P2P mode)
  75. * @param {boolean} isConnectionActiveByJvb true if the JVB did not get any
  76. * data from the user for the last 15 seconds.
  77. * @param {boolean} isInLastN indicates whether the user is in the last N
  78. * set. When set to false it means that JVB is not sending any video for
  79. * the user.
  80. * @param {boolean} isRestoringTimedout if true it means that the user has
  81. * been outside of last N too long to be considered
  82. * {@link ParticipantConnectionStatus.RESTORING}.
  83. * @param {boolean} isVideoMuted true if the user is video muted and we
  84. * should not expect to receive any video.
  85. * @param {boolean} isVideoTrackFrozen if the current browser support video
  86. * frozen detection then it will be set to true when the video track is
  87. * frozen. If the current browser does not support frozen detection the it's
  88. * always false.
  89. * @return {ParticipantConnectionStatus} the new connection status for
  90. * the user for whom the values above were provided.
  91. * @private
  92. */
  93. static _getNewStateForJvbMode(
  94. isConnectionActiveByJvb,
  95. isInLastN,
  96. isRestoringTimedout,
  97. isVideoMuted,
  98. isVideoTrackFrozen) {
  99. if (!isConnectionActiveByJvb) {
  100. // when there is a connection problem signaled from jvb
  101. // it means no media was flowing for at least 15secs, so both audio
  102. // and video are most likely interrupted
  103. return ParticipantConnectionStatus.INTERRUPTED;
  104. } else if (isVideoMuted) {
  105. // If the connection is active according to JVB and the user is
  106. // video muted there is no way for the connection to be inactive,
  107. // because the detection logic below only makes sense for video.
  108. return ParticipantConnectionStatus.ACTIVE;
  109. }
  110. // Logic when isVideoTrackFrozen is supported
  111. if (browser.supportsVideoMuteOnConnInterrupted()) {
  112. if (!isVideoTrackFrozen) {
  113. // If the video is playing we're good
  114. return ParticipantConnectionStatus.ACTIVE;
  115. } else if (isInLastN) {
  116. return isRestoringTimedout
  117. ? ParticipantConnectionStatus.INTERRUPTED
  118. : ParticipantConnectionStatus.RESTORING;
  119. }
  120. return ParticipantConnectionStatus.INACTIVE;
  121. }
  122. // Because this browser is incapable of detecting frozen video we must
  123. // rely on the lastN value
  124. return isInLastN
  125. ? ParticipantConnectionStatus.ACTIVE
  126. : ParticipantConnectionStatus.INACTIVE;
  127. }
  128. /* eslint-enable max-params*/
  129. /**
  130. * In P2P mode we don't care about any values coming from the JVB and
  131. * the connection status can be only active or interrupted.
  132. * @param {boolean} isVideoMuted the user if video muted
  133. * @param {boolean} isVideoTrackFrozen true if the video track for
  134. * the remote user is currently frozen. If the current browser does not
  135. * support video frozen detection then it's always false.
  136. * @return {ParticipantConnectionStatus}
  137. * @private
  138. */
  139. static _getNewStateForP2PMode(isVideoMuted, isVideoTrackFrozen) {
  140. if (!browser.supportsVideoMuteOnConnInterrupted()) {
  141. // There's no way to detect problems in P2P when there's no video
  142. // track frozen detection...
  143. return ParticipantConnectionStatus.ACTIVE;
  144. }
  145. return isVideoMuted || !isVideoTrackFrozen
  146. ? ParticipantConnectionStatus.ACTIVE
  147. : ParticipantConnectionStatus.INTERRUPTED;
  148. }
  149. /**
  150. * Creates new instance of <tt>ParticipantConnectionStatus</tt>.
  151. *
  152. * @constructor
  153. * @param {RTC} rtc the RTC service instance
  154. * @param {JitsiConference} conference parent conference instance
  155. * @param {Object} options
  156. * @param {number} [options.rtcMuteTimeout=2000] custom value for
  157. * {@link ParticipantConnectionStatus.rtcMuteTimeout}.
  158. * @param {number} [options.outOfLastNTimeout=500] custom value for
  159. * {@link ParticipantConnectionStatus.outOfLastNTimeout}.
  160. */
  161. constructor(rtc, conference, options) {
  162. this.rtc = rtc;
  163. this.conference = conference;
  164. /**
  165. * A map of the "endpoint ID"(which corresponds to the resource part
  166. * of MUC JID(nickname)) to the timeout callback IDs scheduled using
  167. * window.setTimeout.
  168. * @type {Object.<string, number>}
  169. */
  170. this.trackTimers = {};
  171. /**
  172. * This map holds the endpoint connection status received from the JVB
  173. * (as it might be different than the one stored in JitsiParticipant).
  174. * Required for getting back in sync when remote video track is removed.
  175. * @type {Object.<string, boolean>}
  176. */
  177. this.connStatusFromJvb = { };
  178. /**
  179. * If video track frozen detection through RTC mute event is supported,
  180. * we wait some time until video track is considered frozen. But because
  181. * when the user falls out of last N it is expected for the video to
  182. * freeze this timeout must be significantly reduced in "out of last N"
  183. * case.
  184. *
  185. * Basically this value is used instead of {@link rtcMuteTimeout} when
  186. * user is not in last N.
  187. * @type {number}
  188. */
  189. this.outOfLastNTimeout
  190. = typeof options.outOfLastNTimeout === 'number'
  191. ? options.outOfLastNTimeout : DEFAULT_NOT_IN_LAST_N_TIMEOUT;
  192. /**
  193. * How long we're going to wait after the RTC video track muted event
  194. * for the corresponding signalling mute event, before the connection
  195. * interrupted is fired. The default value is
  196. * {@link DEFAULT_RTC_MUTE_TIMEOUT}.
  197. *
  198. * @type {number} amount of time in milliseconds
  199. */
  200. this.rtcMuteTimeout
  201. = typeof options.rtcMuteTimeout === 'number'
  202. ? options.rtcMuteTimeout : DEFAULT_RTC_MUTE_TIMEOUT;
  203. /**
  204. * This map holds a timestamp indicating when participant's video track
  205. * was RTC muted (it is assumed that each participant can have only 1
  206. * video track at a time). The purpose of storing the timestamp is to
  207. * avoid the transition to disconnected status in case of legitimate
  208. * video mute operation where the signalling video muted event can
  209. * arrive shortly after RTC muted event.
  210. *
  211. * The key is participant's ID which is the same as endpoint id in
  212. * the Colibri conference allocated on the JVB.
  213. *
  214. * The value is a timestamp measured in milliseconds obtained with
  215. * <tt>Date.now()</tt>.
  216. *
  217. * FIXME merge this logic with NO_DATA_FROM_SOURCE event
  218. * implemented in JitsiLocalTrack by extending the event to
  219. * the remote track and allowing to set different timeout for
  220. * local and remote tracks.
  221. *
  222. * @type {Object.<string, number>}
  223. */
  224. this.rtcMutedTimestamp = { };
  225. logger.info(`RtcMuteTimeout set to: ${this.rtcMuteTimeout}`);
  226. /**
  227. * This map holds the timestamps indicating when participant's video
  228. * entered lastN set. Participants entering lastN will have connection
  229. * status restoring and when we start receiving video will become
  230. * active, but if video is not received for certain time
  231. * {@link DEFAULT_RESTORING_TIMEOUT} that participant connection status
  232. * will become interrupted.
  233. *
  234. * @type {Map<string, number>}
  235. */
  236. this.enteredLastNTimestamp = new Map();
  237. /**
  238. * A map of the "endpoint ID"(which corresponds to the resource part
  239. * of MUC JID(nickname)) to the restoring timeout callback IDs
  240. * scheduled using window.setTimeout.
  241. *
  242. * @type {Map<string, number>}
  243. */
  244. this.restoringTimers = new Map();
  245. /**
  246. * A map that holds the current connection status (along with all the internal events that happen
  247. * while in that state).
  248. *
  249. * The goal is to send this information to the analytics backend for post-mortem analysis.
  250. */
  251. this.connectionStatusMap = new Map();
  252. }
  253. /**
  254. * Gets the video frozen timeout for given user.
  255. * @param {string} id endpoint/participant ID
  256. * @return {number} how long are we going to wait since RTC video muted
  257. * even, before a video track is considered frozen.
  258. * @private
  259. */
  260. _getVideoFrozenTimeout(id) {
  261. return this.rtc.isInLastN(id)
  262. ? this.rtcMuteTimeout : this.outOfLastNTimeout;
  263. }
  264. /**
  265. * Initializes <tt>ParticipantConnectionStatus</tt> and bind required event
  266. * listeners.
  267. */
  268. init() {
  269. this._onEndpointConnStatusChanged
  270. = this.onEndpointConnStatusChanged.bind(this);
  271. this.rtc.addListener(
  272. RTCEvents.ENDPOINT_CONN_STATUS_CHANGED,
  273. this._onEndpointConnStatusChanged);
  274. // Handles P2P status changes
  275. this._onP2PStatus = this.refreshConnectionStatusForAll.bind(this);
  276. this.conference.on(JitsiConferenceEvents.P2P_STATUS, this._onP2PStatus);
  277. // Used to send analytics events for the participant that left the call.
  278. this._onUserLeft = this.onUserLeft.bind(this);
  279. this.conference.on(JitsiConferenceEvents.USER_LEFT, this._onUserLeft);
  280. // On some browsers MediaStreamTrack trigger "onmute"/"onunmute"
  281. // events for video type tracks when they stop receiving data which is
  282. // often a sign that remote user is having connectivity issues
  283. if (browser.supportsVideoMuteOnConnInterrupted()) {
  284. this._onTrackRtcMuted = this.onTrackRtcMuted.bind(this);
  285. this.rtc.addListener(
  286. RTCEvents.REMOTE_TRACK_MUTE, this._onTrackRtcMuted);
  287. this._onTrackRtcUnmuted = this.onTrackRtcUnmuted.bind(this);
  288. this.rtc.addListener(
  289. RTCEvents.REMOTE_TRACK_UNMUTE, this._onTrackRtcUnmuted);
  290. // Track added/removed listeners are used to bind "mute"/"unmute"
  291. // event handlers
  292. this._onRemoteTrackAdded = this.onRemoteTrackAdded.bind(this);
  293. this.conference.on(
  294. JitsiConferenceEvents.TRACK_ADDED,
  295. this._onRemoteTrackAdded);
  296. this._onRemoteTrackRemoved = this.onRemoteTrackRemoved.bind(this);
  297. this.conference.on(
  298. JitsiConferenceEvents.TRACK_REMOVED,
  299. this._onRemoteTrackRemoved);
  300. // Listened which will be bound to JitsiRemoteTrack to listen for
  301. // signalling mute/unmute events.
  302. this._onSignallingMuteChanged
  303. = this.onSignallingMuteChanged.bind(this);
  304. // Used to send an analytics event when the video type changes.
  305. this._onTrackVideoTypeChanged
  306. = this.onTrackVideoTypeChanged.bind(this);
  307. }
  308. this._onLastNChanged = this._onLastNChanged.bind(this);
  309. this.conference.on(
  310. JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  311. this._onLastNChanged);
  312. this._onLastNValueChanged
  313. = this.refreshConnectionStatusForAll.bind(this);
  314. this.rtc.on(
  315. RTCEvents.LASTN_VALUE_CHANGED, this._onLastNValueChanged);
  316. }
  317. /**
  318. * Removes all event listeners and disposes of all resources held by this
  319. * instance.
  320. */
  321. dispose() {
  322. this.rtc.removeListener(
  323. RTCEvents.ENDPOINT_CONN_STATUS_CHANGED,
  324. this._onEndpointConnStatusChanged);
  325. if (browser.supportsVideoMuteOnConnInterrupted()) {
  326. this.rtc.removeListener(
  327. RTCEvents.REMOTE_TRACK_MUTE,
  328. this._onTrackRtcMuted);
  329. this.rtc.removeListener(
  330. RTCEvents.REMOTE_TRACK_UNMUTE,
  331. this._onTrackRtcUnmuted);
  332. this.conference.off(
  333. JitsiConferenceEvents.TRACK_ADDED,
  334. this._onRemoteTrackAdded);
  335. this.conference.off(
  336. JitsiConferenceEvents.TRACK_REMOVED,
  337. this._onRemoteTrackRemoved);
  338. }
  339. this.conference.off(
  340. JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  341. this._onLastNChanged);
  342. this.rtc.removeListener(
  343. RTCEvents.LASTN_VALUE_CHANGED, this._onLastNValueChanged);
  344. this.conference.off(
  345. JitsiConferenceEvents.P2P_STATUS, this._onP2PStatus);
  346. this.conference.off(
  347. JitsiConferenceEvents.USER_LEFT, this._onUserLeft);
  348. const participantIds = Object.keys(this.trackTimers);
  349. for (const participantId of participantIds) {
  350. this.clearTimeout(participantId);
  351. this.clearRtcMutedTimestamp(participantId);
  352. }
  353. for (const id in this.connectionStatusMap) {
  354. if (this.connectionStatusMap.hasOwnProperty(id)) {
  355. this.onUserLeft(id);
  356. }
  357. }
  358. // Clear RTC connection status cache
  359. this.connStatusFromJvb = {};
  360. }
  361. /**
  362. * Handles RTCEvents.ENDPOINT_CONN_STATUS_CHANGED triggered when we receive
  363. * notification over the data channel from the bridge about endpoint's
  364. * connection status update.
  365. * @param {string} endpointId - The endpoint ID(MUC nickname/resource JID).
  366. * @param {boolean} isActive - true if the connection is OK or false otherwise.
  367. */
  368. onEndpointConnStatusChanged(endpointId, isActive) {
  369. logger.debug(
  370. `Detector RTCEvents.ENDPOINT_CONN_STATUS_CHANGED(${Date.now()}): ${
  371. endpointId}: ${isActive}`);
  372. // Filter out events for the local JID for now
  373. if (endpointId !== this.conference.myUserId()) {
  374. // Store the status received over the data channels
  375. this.connStatusFromJvb[endpointId] = isActive;
  376. this.figureOutConnectionStatus(endpointId);
  377. }
  378. }
  379. /**
  380. * Changes connection status.
  381. * @param {JitsiParticipant} participant
  382. * @param newStatus
  383. */
  384. _changeConnectionStatus(participant, newStatus) {
  385. if (participant.getConnectionStatus() !== newStatus) {
  386. const endpointId = participant.getId();
  387. participant._setConnectionStatus(newStatus);
  388. logger.debug(
  389. `Emit endpoint conn status(${Date.now()}) ${endpointId}: ${
  390. newStatus}`);
  391. // Log the event on CallStats
  392. Statistics.sendLog(
  393. JSON.stringify({
  394. id: 'peer.conn.status',
  395. participant: endpointId,
  396. status: newStatus
  397. }));
  398. this.conference.eventEmitter.emit(
  399. JitsiConferenceEvents.PARTICIPANT_CONN_STATUS_CHANGED,
  400. endpointId, newStatus);
  401. }
  402. }
  403. /**
  404. * Reset the postponed "connection interrupted" event which was previously
  405. * scheduled as a timeout on RTC 'onmute' event.
  406. *
  407. * @param {string} participantId - The participant for which the "connection
  408. * interrupted" timeout was scheduled.
  409. */
  410. clearTimeout(participantId) {
  411. if (this.trackTimers[participantId]) {
  412. window.clearTimeout(this.trackTimers[participantId]);
  413. this.trackTimers[participantId] = null;
  414. }
  415. }
  416. /**
  417. * Clears the timestamp of the RTC muted event for participant's video track
  418. * @param {string} participantId the id of the conference participant which
  419. * is the same as the Colibri endpoint ID of the video channel allocated for
  420. * the user on the videobridge.
  421. */
  422. clearRtcMutedTimestamp(participantId) {
  423. this.rtcMutedTimestamp[participantId] = null;
  424. }
  425. /**
  426. * Bind signalling mute event listeners for video {JitsiRemoteTrack} when
  427. * a new one is added to the conference.
  428. *
  429. * @param {JitsiTrack} remoteTrack - The {JitsiTrack} which is being added to
  430. * the conference.
  431. */
  432. onRemoteTrackAdded(remoteTrack) {
  433. if (!remoteTrack.isLocal()
  434. && remoteTrack.getType() === MediaType.VIDEO) {
  435. logger.debug(
  436. `Detector on remote track added for: ${
  437. remoteTrack.getParticipantId()}`);
  438. remoteTrack.on(
  439. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  440. this._onSignallingMuteChanged);
  441. remoteTrack.on(
  442. JitsiTrackEvents.TRACK_VIDEOTYPE_CHANGED,
  443. videoType => this._onTrackVideoTypeChanged(remoteTrack, videoType));
  444. }
  445. }
  446. /**
  447. * Removes all event listeners bound to the remote video track and clears
  448. * any related timeouts.
  449. *
  450. * @param {JitsiRemoteTrack} remoteTrack - The remote track which is being
  451. * removed from the conference.
  452. */
  453. onRemoteTrackRemoved(remoteTrack) {
  454. if (!remoteTrack.isLocal()
  455. && remoteTrack.getType() === MediaType.VIDEO) {
  456. const endpointId = remoteTrack.getParticipantId();
  457. logger.debug(`Detector on remote track removed: ${endpointId}`);
  458. remoteTrack.off(
  459. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  460. this._onSignallingMuteChanged);
  461. this.clearTimeout(endpointId);
  462. this.clearRtcMutedTimestamp(endpointId);
  463. this.figureOutConnectionStatus(endpointId);
  464. }
  465. }
  466. /**
  467. * Checks if given participant's video is considered frozen.
  468. * @param {JitsiParticipant} participant - The participant.
  469. * @return {boolean} <tt>true</tt> if the video has frozen for given
  470. * participant or <tt>false</tt> when it's either not considered frozen
  471. * (yet) or if freeze detection is not supported by the current browser.
  472. *
  473. * FIXME merge this logic with NO_DATA_FROM_SOURCE event
  474. * implemented in JitsiLocalTrack by extending the event to
  475. * the remote track and allowing to set different timeout for
  476. * local and remote tracks.
  477. *
  478. */
  479. isVideoTrackFrozen(participant) {
  480. if (!browser.supportsVideoMuteOnConnInterrupted()) {
  481. return false;
  482. }
  483. const id = participant.getId();
  484. const hasAnyVideoRTCMuted = participant.hasAnyVideoTrackWebRTCMuted();
  485. const rtcMutedTimestamp = this.rtcMutedTimestamp[id];
  486. const timeout = this._getVideoFrozenTimeout(id);
  487. return hasAnyVideoRTCMuted
  488. && typeof rtcMutedTimestamp === 'number'
  489. && (Date.now() - rtcMutedTimestamp) >= timeout;
  490. }
  491. /**
  492. * Goes over every participant and updates connectivity status.
  493. * Should be called when a parameter which affects all of the participants
  494. * is changed (P2P for example).
  495. */
  496. refreshConnectionStatusForAll() {
  497. const participants = this.conference.getParticipants();
  498. for (const participant of participants) {
  499. this.figureOutConnectionStatus(participant.getId());
  500. }
  501. }
  502. /**
  503. * Figures out (and updates) the current connectivity status for
  504. * the participant identified by the given id.
  505. *
  506. * @param {string} id - The participant's id (MUC nickname or Colibri endpoint ID).
  507. */
  508. figureOutConnectionStatus(id) {
  509. const participant = this.conference.getParticipantById(id);
  510. if (!participant) {
  511. // Probably the participant is no longer in the conference
  512. // (at the time of writing this code, participant is
  513. // detached from the conference and TRACK_REMOVED events are
  514. // fired),
  515. // so we don't care, but let's print a log message for debugging purposes.
  516. logger.debug(`figure out conn status - no participant for: ${id}`);
  517. return;
  518. }
  519. const inP2PMode = this.conference.isP2PActive();
  520. const isRestoringTimedOut = this._isRestoringTimedout(id);
  521. const audioOnlyMode = this.rtc.getLastN() === 0;
  522. // NOTE Overriding videoMuted to true for audioOnlyMode should disable
  523. // any detection based on video playback or the last N.
  524. const isVideoMuted = participant.isVideoMuted() || audioOnlyMode;
  525. const isVideoTrackFrozen = this.isVideoTrackFrozen(participant);
  526. const isInLastN = this.rtc.isInLastN(id);
  527. let isConnActiveByJvb = this.connStatusFromJvb[id];
  528. if (typeof isConnActiveByJvb !== 'boolean') {
  529. // If no status was received from the JVB it means that it's active
  530. // (the bridge does not send notification unless there is a problem)
  531. logger.debug('Assuming connection active by JVB - no notification');
  532. isConnActiveByJvb = true;
  533. }
  534. const newState
  535. = inP2PMode
  536. ? ParticipantConnectionStatusHandler._getNewStateForP2PMode(
  537. isVideoMuted,
  538. isVideoTrackFrozen)
  539. : ParticipantConnectionStatusHandler._getNewStateForJvbMode(
  540. isConnActiveByJvb,
  541. isInLastN,
  542. isRestoringTimedOut,
  543. isVideoMuted,
  544. isVideoTrackFrozen);
  545. // if the new state is not restoring clear timers and timestamps
  546. // that we use to track the restoring state
  547. if (newState !== ParticipantConnectionStatus.RESTORING) {
  548. this._clearRestoringTimer(id);
  549. }
  550. logger.debug(
  551. `Figure out conn status for ${id}, is video muted: ${
  552. isVideoMuted} is active(jvb): ${
  553. isConnActiveByJvb} video track frozen: ${
  554. isVideoTrackFrozen} p2p mode: ${
  555. inP2PMode} is in last N: ${
  556. isInLastN} currentStatus => newStatus: ${
  557. participant.getConnectionStatus()} => ${newState}`);
  558. const oldConnectionStatus = this.connectionStatusMap[id] || {};
  559. // Send an analytics event (guard on either the p2p flag or the connection status has changed
  560. // since the last time this code block run).
  561. if (!('p2p' in oldConnectionStatus)
  562. || !('connectionStatus' in oldConnectionStatus)
  563. || oldConnectionStatus.p2p !== inP2PMode
  564. || oldConnectionStatus.connectionStatus !== newState) {
  565. const nowMs = Date.now();
  566. this.maybeSendParticipantConnectionStatusEvent(id, nowMs);
  567. this.connectionStatusMap[id] = {
  568. ...oldConnectionStatus,
  569. connectionStatus: newState,
  570. p2p: inP2PMode,
  571. startedMs: nowMs
  572. };
  573. // sometimes (always?) we're late to hook the TRACK_VIDEOTYPE_CHANGED event and the
  574. // video type is not in oldConnectionStatus.
  575. if (!('videoType' in this.connectionStatusMap[id])) {
  576. const videoTracks = participant.getTracksByMediaType(MediaType.VIDEO);
  577. if (Array.isArray(videoTracks) && videoTracks.length !== 0) {
  578. this.connectionStatusMap[id].videoType = videoTracks[0].videoType;
  579. }
  580. }
  581. }
  582. this._changeConnectionStatus(participant, newState);
  583. }
  584. /**
  585. * Computes the duration of the current connection status for the participant with the specified id (i.e. 15 seconds
  586. * in the INTERRUPTED state) and sends a participant connection status event.
  587. * @param {string} id - The jid of the participant.
  588. * @param {Number} nowMs - The current time (in millis).
  589. * @returns {void}
  590. */
  591. maybeSendParticipantConnectionStatusEvent(id, nowMs) {
  592. const participantConnectionStatus = this.connectionStatusMap[id];
  593. if (participantConnectionStatus
  594. && 'startedMs' in participantConnectionStatus
  595. && 'videoType' in participantConnectionStatus
  596. && 'connectionStatus' in participantConnectionStatus
  597. && 'p2p' in participantConnectionStatus) {
  598. participantConnectionStatus.value = nowMs - participantConnectionStatus.startedMs;
  599. Statistics.sendAnalytics(
  600. createParticipantConnectionStatusEvent(participantConnectionStatus));
  601. }
  602. }
  603. /**
  604. * On change in Last N set check all leaving and entering participants to
  605. * change their corresponding statuses.
  606. *
  607. * @param {Array<string>} leavingLastN - The array of ids leaving lastN.
  608. * @param {Array<string>} enteringLastN - The array of ids entering lastN.
  609. * @private
  610. */
  611. _onLastNChanged(leavingLastN = [], enteringLastN = []) {
  612. const now = Date.now();
  613. logger.debug(
  614. 'leaving/entering lastN', leavingLastN, enteringLastN, now);
  615. for (const id of leavingLastN) {
  616. this.enteredLastNTimestamp.delete(id);
  617. this._clearRestoringTimer(id);
  618. this.figureOutConnectionStatus(id);
  619. }
  620. for (const id of enteringLastN) {
  621. // store the timestamp this id is entering lastN
  622. this.enteredLastNTimestamp.set(id, now);
  623. this.figureOutConnectionStatus(id);
  624. }
  625. }
  626. /**
  627. * Clears the restoring timer for participant's video track and the
  628. * timestamp for entering lastN.
  629. *
  630. * @param {string} participantId - The id of the conference participant which
  631. * is the same as the Colibri endpoint ID of the video channel allocated for
  632. * the user on the videobridge.
  633. */
  634. _clearRestoringTimer(participantId) {
  635. const rTimer = this.restoringTimers.get(participantId);
  636. if (rTimer) {
  637. clearTimeout(rTimer);
  638. this.restoringTimers.delete(participantId);
  639. }
  640. }
  641. /**
  642. * Checks whether a track had stayed enough in restoring state, compares
  643. * current time and the time the track entered in lastN. If it hasn't
  644. * timedout and there is no timer added, add new timer in order to give it
  645. * more time to become active or mark it as interrupted on next check.
  646. *
  647. * @param {string} participantId - The id of the conference participant which
  648. * is the same as the Colibri endpoint ID of the video channel allocated for
  649. * the user on the videobridge.
  650. * @returns {boolean} <tt>true</tt> if the track was in restoring state
  651. * more than the timeout ({@link DEFAULT_RESTORING_TIMEOUT}.) in order to
  652. * set its status to interrupted.
  653. * @private
  654. */
  655. _isRestoringTimedout(participantId) {
  656. const enteredLastNTimestamp
  657. = this.enteredLastNTimestamp.get(participantId);
  658. if (enteredLastNTimestamp
  659. && (Date.now() - enteredLastNTimestamp)
  660. >= DEFAULT_RESTORING_TIMEOUT) {
  661. return true;
  662. }
  663. // still haven't reached timeout, if there is no timer scheduled,
  664. // schedule one so we can track the restoring state and change it after
  665. // reaching the timeout
  666. const rTimer = this.restoringTimers.get(participantId);
  667. if (!rTimer) {
  668. this.restoringTimers.set(participantId, setTimeout(
  669. () => this.figureOutConnectionStatus(participantId),
  670. DEFAULT_RESTORING_TIMEOUT));
  671. }
  672. return false;
  673. }
  674. /**
  675. * Sends a last/final participant connection status event for the participant that left the conference.
  676. * @param {string} id - The id of the participant that left the conference.
  677. * @returns {void}
  678. */
  679. onUserLeft(id) {
  680. this.maybeSendParticipantConnectionStatusEvent(id, Date.now());
  681. delete this.connectionStatusMap[id];
  682. }
  683. /**
  684. * Handles RTC 'onmute' event for the video track.
  685. *
  686. * @param {JitsiRemoteTrack} track - The video track for which 'onmute' event
  687. * will be processed.
  688. */
  689. onTrackRtcMuted(track) {
  690. const participantId = track.getParticipantId();
  691. const participant = this.conference.getParticipantById(participantId);
  692. logger.debug(`Detector track RTC muted: ${participantId}`, Date.now());
  693. if (!participant) {
  694. logger.error(`No participant for id: ${participantId}`);
  695. return;
  696. }
  697. this.rtcMutedTimestamp[participantId] = Date.now();
  698. if (!participant.isVideoMuted()) {
  699. // If the user is not muted according to the signalling we'll give
  700. // it some time, before the connection interrupted event is
  701. // triggered.
  702. this.clearTimeout(participantId);
  703. // The timeout is reduced when user is not in the last N
  704. const timeout = this._getVideoFrozenTimeout(participantId);
  705. this.trackTimers[participantId] = window.setTimeout(() => {
  706. logger.debug(
  707. `Set RTC mute timeout for: ${participantId}\
  708. of ${timeout} ms`);
  709. this.clearTimeout(participantId);
  710. this.figureOutConnectionStatus(participantId);
  711. }, timeout);
  712. }
  713. }
  714. /**
  715. * Handles RTC 'onunmute' event for the video track.
  716. *
  717. * @param {JitsiRemoteTrack} track - The video track for which 'onunmute'
  718. * event will be processed.
  719. */
  720. onTrackRtcUnmuted(track) {
  721. const participantId = track.getParticipantId();
  722. logger.debug(
  723. `Detector track RTC unmuted: ${participantId}`, Date.now());
  724. this.clearTimeout(participantId);
  725. this.clearRtcMutedTimestamp(participantId);
  726. this.figureOutConnectionStatus(participantId);
  727. }
  728. /**
  729. * Here the signalling "mute"/"unmute" events are processed.
  730. *
  731. * @param {JitsiRemoteTrack} track - The remote video track for which
  732. * the signalling mute/unmute event will be processed.
  733. */
  734. onSignallingMuteChanged(track) {
  735. const participantId = track.getParticipantId();
  736. logger.debug(
  737. `Detector on track signalling mute changed: ${participantId}`,
  738. track.isMuted());
  739. this.figureOutConnectionStatus(participantId);
  740. }
  741. /**
  742. * Sends a participant connection status event as a result of the video type
  743. * changing.
  744. * @param {JitsiRemoteTrack} track - The track.
  745. * @param {VideoType} type - The video type.
  746. * @returns {void}
  747. */
  748. onTrackVideoTypeChanged(track, type) {
  749. const id = track.getParticipantId();
  750. const nowMs = Date.now();
  751. this.maybeSendParticipantConnectionStatusEvent(id, nowMs);
  752. this.connectionStatusMap[id] = {
  753. ...this.connectionStatusMap[id] || {},
  754. videoType: type,
  755. startedMs: nowMs
  756. };
  757. }
  758. }