Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

ParticipantConnectionStatus.js 34KB

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