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.

JitsiRemoteTrack.js 9.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. import * as JitsiTrackEvents from '../../JitsiTrackEvents';
  2. import { createTtfmEvent } from '../../service/statistics/AnalyticsEvents';
  3. import Statistics from '../statistics/statistics';
  4. import JitsiTrack from './JitsiTrack';
  5. const logger = require('jitsi-meet-logger').getLogger(__filename);
  6. const RTCEvents = require('../../service/RTC/RTCEvents');
  7. let ttfmTrackerAudioAttached = false;
  8. let ttfmTrackerVideoAttached = false;
  9. /**
  10. * List of container events that we are going to process. _onContainerEventHandler will be added as listener to the
  11. * container for every event in the list.
  12. */
  13. const containerEvents = [
  14. 'abort', 'canplay', 'canplaythrough', 'emptied', 'ended', 'error', 'loadeddata', 'loadedmetadata', 'loadstart',
  15. 'pause', 'play', 'playing', 'ratechange', 'stalled', 'suspend', 'waiting'
  16. ];
  17. /* eslint-disable max-params */
  18. /**
  19. * Represents a single media track (either audio or video).
  20. */
  21. export default class JitsiRemoteTrack extends JitsiTrack {
  22. /**
  23. * Creates new JitsiRemoteTrack instance.
  24. * @param {RTC} rtc the RTC service instance.
  25. * @param {JitsiConference} conference the conference to which this track
  26. * belongs to
  27. * @param {string} ownerEndpointId the endpoint ID of the track owner
  28. * @param {MediaStream} stream WebRTC MediaStream, parent of the track
  29. * @param {MediaStreamTrack} track underlying WebRTC MediaStreamTrack for
  30. * the new JitsiRemoteTrack
  31. * @param {MediaType} mediaType the type of the media
  32. * @param {VideoType} videoType the type of the video if applicable
  33. * @param {number} ssrc the SSRC number of the Media Stream
  34. * @param {boolean} muted the initial muted state
  35. * @param {boolean} isP2P indicates whether or not this track belongs to a
  36. * P2P session
  37. * @throws {TypeError} if <tt>ssrc</tt> is not a number.
  38. * @constructor
  39. */
  40. constructor(
  41. rtc,
  42. conference,
  43. ownerEndpointId,
  44. stream,
  45. track,
  46. mediaType,
  47. videoType,
  48. ssrc,
  49. muted,
  50. isP2P) {
  51. super(
  52. conference,
  53. stream,
  54. track,
  55. () => {
  56. // Nothing to do if the track is inactive.
  57. },
  58. mediaType,
  59. videoType);
  60. this.rtc = rtc;
  61. // Prevent from mixing up type of SSRC which should be a number
  62. if (typeof ssrc !== 'number') {
  63. throw new TypeError(`SSRC ${ssrc} is not a number`);
  64. }
  65. this.ssrc = ssrc;
  66. this.ownerEndpointId = ownerEndpointId;
  67. this.muted = muted;
  68. this.isP2P = isP2P;
  69. logger.debug(`New remote track added: ${this}`);
  70. // we want to mark whether the track has been ever muted
  71. // to detect ttfm events for startmuted conferences, as it can
  72. // significantly increase ttfm values
  73. this.hasBeenMuted = muted;
  74. // Bind 'onmute' and 'onunmute' event handlers
  75. if (this.rtc && this.track) {
  76. this._bindTrackHandlers();
  77. }
  78. this._containerHandlers = {};
  79. containerEvents.forEach(event => {
  80. this._containerHandlers[event] = this._containerEventHandler.bind(this, event);
  81. });
  82. }
  83. /* eslint-enable max-params */
  84. /**
  85. * Attaches the track handlers.
  86. *
  87. * @returns {void}
  88. */
  89. _bindTrackHandlers() {
  90. this.track.addEventListener('mute', () => this._onTrackMute());
  91. this.track.addEventListener('unmute', () => this._onTrackUnmute());
  92. this.track.addEventListener('ended', () => {
  93. logger.debug(`"onended" event(${Date.now()}): ${this}`);
  94. });
  95. }
  96. /**
  97. * Callback invoked when the track is muted. Emits an event notifying
  98. * listeners of the mute event.
  99. *
  100. * @private
  101. * @returns {void}
  102. */
  103. _onTrackMute() {
  104. logger.debug(`"onmute" event(${Date.now()}): ${this}`);
  105. this.rtc.eventEmitter.emit(RTCEvents.REMOTE_TRACK_MUTE, this);
  106. }
  107. /**
  108. * Callback invoked when the track is unmuted. Emits an event notifying
  109. * listeners of the mute event.
  110. *
  111. * @private
  112. * @returns {void}
  113. */
  114. _onTrackUnmute() {
  115. logger.debug(`"onunmute" event(${Date.now()}): ${this}`);
  116. this.rtc.eventEmitter.emit(RTCEvents.REMOTE_TRACK_UNMUTE, this);
  117. }
  118. /**
  119. * Sets current muted status and fires an events for the change.
  120. * @param value the muted status.
  121. */
  122. setMute(value) {
  123. if (this.muted === value) {
  124. return;
  125. }
  126. if (value) {
  127. this.hasBeenMuted = true;
  128. }
  129. // we can have a fake video stream
  130. if (this.stream) {
  131. this.stream.muted = value;
  132. }
  133. this.muted = value;
  134. this.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED, this);
  135. }
  136. /**
  137. * Returns the current muted status of the track.
  138. * @returns {boolean|*|JitsiRemoteTrack.muted} <tt>true</tt> if the track is
  139. * muted and <tt>false</tt> otherwise.
  140. */
  141. isMuted() {
  142. return this.muted;
  143. }
  144. /**
  145. * Returns the participant id which owns the track.
  146. *
  147. * @returns {string} the id of the participants. It corresponds to the
  148. * Colibri endpoint id/MUC nickname in case of Jitsi-meet.
  149. */
  150. getParticipantId() {
  151. return this.ownerEndpointId;
  152. }
  153. /**
  154. * Return false;
  155. */
  156. isLocal() {
  157. return false;
  158. }
  159. /**
  160. * Returns the synchronization source identifier (SSRC) of this remote
  161. * track.
  162. *
  163. * @returns {number} the SSRC of this remote track.
  164. */
  165. getSSRC() {
  166. return this.ssrc;
  167. }
  168. /**
  169. * Changes the video type of the track.
  170. *
  171. * @param {string} type - The new video type("camera", "desktop").
  172. */
  173. _setVideoType(type) {
  174. if (this.videoType === type) {
  175. return;
  176. }
  177. this.videoType = type;
  178. this.emit(JitsiTrackEvents.TRACK_VIDEOTYPE_CHANGED, type);
  179. }
  180. /**
  181. * Handles track play events.
  182. */
  183. _playCallback() {
  184. const type = this.isVideoTrack() ? 'video' : 'audio';
  185. const now = window.performance.now();
  186. console.log(`(TIME) Render ${type}:\t`, now);
  187. this.conference.getConnectionTimes()[`${type}.render`] = now;
  188. // The conference can be started without calling GUM
  189. // FIXME if there would be a module for connection times this kind
  190. // of logic (gumDuration or ttfm) should end up there
  191. const gumStart = window.connectionTimes['obtainPermissions.start'];
  192. const gumEnd = window.connectionTimes['obtainPermissions.end'];
  193. const gumDuration
  194. = !isNaN(gumEnd) && !isNaN(gumStart) ? gumEnd - gumStart : 0;
  195. // Subtract the muc.joined-to-session-initiate duration because jicofo
  196. // waits until there are 2 participants to start Jingle sessions.
  197. const ttfm = now
  198. - (this.conference.getConnectionTimes()['session.initiate']
  199. - this.conference.getConnectionTimes()['muc.joined'])
  200. - gumDuration;
  201. this.conference.getConnectionTimes()[`${type}.ttfm`] = ttfm;
  202. console.log(`(TIME) TTFM ${type}:\t`, ttfm);
  203. Statistics.sendAnalytics(createTtfmEvent(
  204. {
  205. 'media_type': type,
  206. muted: this.hasBeenMuted,
  207. value: ttfm
  208. }));
  209. }
  210. /**
  211. * Attach time to first media tracker only if there is conference and only
  212. * for the first element.
  213. * @param container the HTML container which can be 'video' or 'audio'
  214. * element.
  215. * @private
  216. */
  217. _attachTTFMTracker(container) {
  218. if ((ttfmTrackerAudioAttached && this.isAudioTrack())
  219. || (ttfmTrackerVideoAttached && this.isVideoTrack())) {
  220. return;
  221. }
  222. if (this.isAudioTrack()) {
  223. ttfmTrackerAudioAttached = true;
  224. }
  225. if (this.isVideoTrack()) {
  226. ttfmTrackerVideoAttached = true;
  227. }
  228. container.addEventListener('canplay', this._playCallback.bind(this));
  229. }
  230. /**
  231. * Called when the track has been attached to a new container.
  232. *
  233. * @param {HTMLElement} container the HTML container which can be 'video' or
  234. * 'audio' element.
  235. * @private
  236. */
  237. _onTrackAttach(container) {
  238. logger.debug(`Track has been attached to a container: ${this}`);
  239. containerEvents.forEach(event => {
  240. container.addEventListener(event, this._containerHandlers[event]);
  241. });
  242. }
  243. /**
  244. * Called when the track has been detached from a container.
  245. *
  246. * @param {HTMLElement} container the HTML container which can be 'video' or
  247. * 'audio' element.
  248. * @private
  249. */
  250. _onTrackDetach(container) {
  251. logger.debug(`Track has been detached from a container: ${this}`);
  252. containerEvents.forEach(event => {
  253. container.removeEventListener(event, this._containerHandlers[event]);
  254. });
  255. }
  256. /**
  257. * An event handler for events triggered by the attached container.
  258. *
  259. * @param {string} type - The type of the event.
  260. */
  261. _containerEventHandler(type) {
  262. logger.debug(`${type} handler was called for a container with attached ${this}`);
  263. }
  264. /**
  265. * Returns a string with a description of the current status of the track.
  266. *
  267. * @returns {string}
  268. */
  269. _getStatus() {
  270. const { enabled, muted, readyState } = this.track;
  271. return `readyState: ${readyState}, muted: ${muted}, enabled: ${enabled}`;
  272. }
  273. /**
  274. * Creates a text representation of this remote track instance.
  275. * @return {string}
  276. */
  277. toString() {
  278. return `RemoteTrack[userID: ${this.getParticipantId()}, type: ${this.getType()}, ssrc: ${
  279. this.getSSRC()}, p2p: ${this.isP2P}, status: ${this._getStatus()}]`;
  280. }
  281. }