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.

ParticipantConnectionStatus.js 34KB

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