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
67 fps = videoFile.fps && videoFile.fps !== -1
72 const body: PlaybackMetricCreate = {
76 playerMode: this.mode,
78 resolutionChanges: this.resolutionChanges,
82 downloadedBytesP2P: this.downloadedBytesP2P,
83 downloadedBytesHTTP: this.downloadedBytesHTTP,
85 uploadedBytesP2P: this.uploadedBytesP2P,
87 videoId: this.videoUUID
90 this.resolutionChanges = 0
92 this.downloadedBytesP2P = 0
93 this.downloadedBytesHTTP = 0
95 this.uploadedBytesP2P = 0
99 const headers = new Headers({ 'Content-type': 'application/json; charset=UTF-8' })
101 return fetch(this.metricsUrl, { method: 'POST', body: JSON.stringify(body), headers })
102 }, this.CONSTANTS.METRICS_INTERVAL)
105 private trackBytes () {
106 this.player.on('p2pInfo', (_event, data: PlayerNetworkInfo) => {
109 this.downloadedBytesHTTP += data.http.downloaded - (this.lastPlayerNetworkInfo?.http.downloaded || 0)
110 this.downloadedBytesP2P += data.p2p.downloaded - (this.lastPlayerNetworkInfo?.p2p.downloaded || 0)
112 this.uploadedBytesP2P += data.p2p.uploaded - (this.lastPlayerNetworkInfo?.p2p.uploaded || 0)
114 this.lastPlayerNetworkInfo = data
118 private trackResolutionChange () {
119 this.player.on('engineResolutionChange', () => {
120 this.resolutionChanges++
124 private trackErrors () {
125 this.player.on('error', () => {
131 videojs.registerPlugin('metrics', MetricsPlugin)
132 export { MetricsPlugin }