1 import videojs from 'video.js'
2 import { PlaybackMetricCreate } from '../../../../../../shared/models'
3 import { MetricsPluginOptions, PlayerMode, PlayerNetworkInfo } from '../../types'
5 const Plugin = videojs.getPlugin('plugin')
7 class MetricsPlugin extends Plugin {
8 private readonly metricsUrl: string
9 private readonly videoUUID: string
10 private readonly mode: PlayerMode
12 private downloadedBytesP2P = 0
13 private downloadedBytesHTTP = 0
14 private uploadedBytesP2P = 0
16 private resolutionChanges = 0
19 private lastPlayerNetworkInfo: PlayerNetworkInfo
21 private metricsInterval: any
23 private readonly CONSTANTS = {
24 METRICS_INTERVAL: 15000
27 constructor (player: videojs.Player, options: MetricsPluginOptions) {
30 this.metricsUrl = options.metricsUrl
31 this.videoUUID = options.videoUUID
32 this.mode = options.mode
34 this.player.one('play', () => {
35 this.runMetricsInterval()
38 this.trackResolutionChange()
44 if (this.metricsInterval) clearInterval(this.metricsInterval)
47 private runMetricsInterval () {
48 this.metricsInterval = setInterval(() => {
49 let resolution: number
52 if (this.mode === 'p2p-media-loader') {
53 const level = this.player.p2pMediaLoader().getCurrentLevel()
56 resolution = Math.min(level.height || 0, level.width || 0)
58 const framerate = level?.attrs['FRAME-RATE']
60 ? parseInt(framerate, 10)
62 } else { // webtorrent
63 const videoFile = this.player.webtorrent().getCurrentVideoFile()
64 if (!videoFile) return
66 resolution = videoFile.resolution.id
70 const body: PlaybackMetricCreate = {
74 playerMode: this.mode,
76 resolutionChanges: this.resolutionChanges,
80 downloadedBytesP2P: this.downloadedBytesP2P,
81 downloadedBytesHTTP: this.downloadedBytesHTTP,
83 uploadedBytesP2P: this.uploadedBytesP2P,
85 videoId: this.videoUUID
88 this.resolutionChanges = 0
90 this.downloadedBytesP2P = 0
91 this.downloadedBytesHTTP = 0
93 this.uploadedBytesP2P = 0
97 const headers = new Headers({ 'Content-type': 'application/json; charset=UTF-8' })
99 return fetch(this.metricsUrl, { method: 'POST', body: JSON.stringify(body), headers })
100 }, this.CONSTANTS.METRICS_INTERVAL)
103 private trackBytes () {
104 this.player.on('p2pInfo', (_event, data: PlayerNetworkInfo) => {
105 this.downloadedBytesHTTP += data.http.downloaded - (this.lastPlayerNetworkInfo?.http.downloaded || 0)
106 this.downloadedBytesP2P += data.p2p.downloaded - (this.lastPlayerNetworkInfo?.p2p.downloaded || 0)
108 this.uploadedBytesP2P += data.p2p.uploaded - (this.lastPlayerNetworkInfo?.p2p.uploaded || 0)
110 this.lastPlayerNetworkInfo = data
114 private trackResolutionChange () {
115 this.player.on('engineResolutionChange', () => {
116 this.resolutionChanges++
120 private trackErrors () {
121 this.player.on('error', () => {
127 videojs.registerPlugin('metrics', MetricsPlugin)
128 export { MetricsPlugin }