1 import videojs from 'video.js'
2 import { secondsToTime } from '@shared/core-utils'
3 import { PlayerNetworkInfo as EventPlayerNetworkInfo } from '../peertube-videojs-typings'
4 import { bytes } from '../utils'
6 interface StatsCardOptions extends videojs.ComponentOptions {
9 mode: 'webtorrent' | 'p2p-media-loader'
13 interface PlayerNetworkInfo {
14 downloadSpeed?: string
16 totalDownloaded?: string
17 totalUploaded?: string
19 averageBandwidth?: string
21 downloadedFromServer?: string
22 downloadedFromPeers?: string
25 const Component = videojs.getComponent('Component')
26 class StatsCard extends Component {
27 options_: StatsCardOptions
29 container: HTMLDivElement
32 closeButton: HTMLElement
36 mode: 'webtorrent' | 'p2p-media-loader'
39 metadataStore: any = {}
42 playerNetworkInfo: PlayerNetworkInfo = {}
45 const container = super.createEl('div', {
46 className: 'vjs-stats-content',
47 innerHTML: this.getMainTemplate()
49 this.container = container
50 this.container.style.display = 'none'
52 this.closeButton = this.container.getElementsByClassName('vjs-stats-close')[0] as HTMLElement
53 this.closeButton.onclick = () => this.hide()
55 this.list = this.container.getElementsByClassName('vjs-stats-list')[0] as HTMLDivElement
57 this.player_.on('p2pInfo', (event: any, data: EventPlayerNetworkInfo) => {
58 if (!data) return // HTTP fallback
60 this.mode = data.source
62 const p2pStats = data.p2p
63 const httpStats = data.http
65 this.playerNetworkInfo.downloadSpeed = bytes(p2pStats.downloadSpeed + httpStats.downloadSpeed).join(' ')
66 this.playerNetworkInfo.uploadSpeed = bytes(p2pStats.uploadSpeed + httpStats.uploadSpeed).join(' ')
67 this.playerNetworkInfo.totalDownloaded = bytes(p2pStats.downloaded + httpStats.downloaded).join(' ')
68 this.playerNetworkInfo.totalUploaded = bytes(p2pStats.uploaded + httpStats.uploaded).join(' ')
69 this.playerNetworkInfo.numPeers = p2pStats.numPeers
70 this.playerNetworkInfo.averageBandwidth = bytes(data.bandwidthEstimate).join(' ') + '/s'
72 if (data.source === 'p2p-media-loader') {
73 this.playerNetworkInfo.downloadedFromServer = bytes(httpStats.downloaded).join(' ')
74 this.playerNetworkInfo.downloadedFromPeers = bytes(p2pStats.downloaded).join(' ')
82 if (this.updateInterval) this.hide()
87 this.container.style.display = 'block'
88 this.updateInterval = setInterval(async () => {
90 const options = this.mode === 'p2p-media-loader'
91 ? this.buildHLSOptions()
92 : await this.buildWebTorrentOptions() // Default
94 this.list.innerHTML = this.getListTemplate(options)
96 console.error('Cannot update stats.', err)
97 clearInterval(this.updateInterval)
103 clearInterval(this.updateInterval)
104 this.container.style.display = 'none'
107 private buildHLSOptions () {
108 const p2pMediaLoader = this.player_.p2pMediaLoader()
109 const level = p2pMediaLoader.getCurrentLevel()
111 const codecs = level?.videoCodec || level?.audioCodec
112 ? `${level?.videoCodec || ''} / ${level?.audioCodec || ''}`
115 const resolution = `${level?.height}p${level?.attrs['FRAME-RATE'] || ''}`
116 const buffer = this.timeRangesToString(this.player().buffered())
121 if (this.options_.videoIsLive) {
122 latency = secondsToTime(p2pMediaLoader.getLiveLatency())
124 progress = this.player().bufferedPercent()
128 playerNetworkInfo: this.playerNetworkInfo,
137 private async buildWebTorrentOptions () {
138 const videoFile = this.player_.webtorrent().getCurrentVideoFile()
140 if (!this.metadataStore[videoFile.fileUrl]) {
141 this.metadataStore[videoFile.fileUrl] = await fetch(videoFile.metadataUrl).then(res => res.json())
144 const metadata = this.metadataStore[videoFile.fileUrl]
146 let colorSpace = 'unknown'
147 let codecs = 'unknown'
149 if (metadata?.streams[0]) {
150 const stream = metadata.streams[0]
152 colorSpace = stream['color_space'] !== 'unknown'
153 ? stream['color_space']
156 codecs = stream['codec_name'] || 'avc1'
159 const resolution = videoFile?.resolution.label + videoFile?.fps
160 const buffer = this.timeRangesToString(this.player().buffered())
161 const progress = this.player_.webtorrent().getTorrent()?.progress
164 playerNetworkInfo: this.playerNetworkInfo,
173 private getListTemplate (options: {
174 playerNetworkInfo: PlayerNetworkInfo
183 const { playerNetworkInfo, progress, colorSpace, codecs, resolution, buffer, latency } = options
184 const player = this.player()
186 const videoQuality: VideoPlaybackQuality = player.getVideoPlaybackQuality()
187 const vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0)
188 const vh = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0)
189 const pr = (window.devicePixelRatio || 1).toFixed(2)
190 const frames = `${vw}x${vh}*${pr} / ${videoQuality.droppedVideoFrames} dropped of ${videoQuality.totalVideoFrames}`
192 const duration = player.duration()
194 let volume = `${Math.round(player.volume() * 100)}`
195 if (player.muted()) volume += ' (muted)'
197 const networkActivity = playerNetworkInfo.downloadSpeed
198 ? `${playerNetworkInfo.downloadSpeed} ⇓ / ${playerNetworkInfo.uploadSpeed} ⇑`
201 const totalTransferred = playerNetworkInfo.totalDownloaded
202 ? `${playerNetworkInfo.totalDownloaded} ⇓ / ${playerNetworkInfo.totalUploaded} ⇑`
204 const downloadBreakdown = playerNetworkInfo.downloadedFromServer
205 ? `${playerNetworkInfo.downloadedFromServer} from servers ยท ${playerNetworkInfo.downloadedFromPeers} from peers`
208 const bufferProgress = progress !== undefined
209 ? `${(progress * 100).toFixed(1)}% (${(progress * duration).toFixed(1)}s)`
213 ${this.buildElement(player.localize('Player mode'), this.mode || 'HTTP')}
214 ${this.buildElement(player.localize('P2P'), player.localize(this.p2pEnabled ? 'enabled' : 'disabled'))}
216 ${this.buildElement(player.localize('Video UUID'), this.options_.videoUUID)}
218 ${this.buildElement(player.localize('Viewport / Frames'), frames)}
220 ${this.buildElement(player.localize('Resolution'), resolution)}
222 ${this.buildElement(player.localize('Volume'), volume)}
224 ${this.buildElement(player.localize('Codecs'), codecs)}
225 ${this.buildElement(player.localize('Color'), colorSpace)}
227 ${this.buildElement(player.localize('Connection Speed'), playerNetworkInfo.averageBandwidth)}
229 ${this.buildElement(player.localize('Network Activity'), networkActivity)}
230 ${this.buildElement(player.localize('Total Transfered'), totalTransferred)}
231 ${this.buildElement(player.localize('Download Breakdown'), downloadBreakdown)}
233 ${this.buildElement(player.localize('Buffer Progress'), bufferProgress)}
234 ${this.buildElement(player.localize('Buffer State'), buffer)}
236 ${this.buildElement(player.localize('Live Latency'), latency)}
240 private getMainTemplate () {
242 <button class="vjs-stats-close" tabindex=0 aria-label="Close stats" title="Close stats">[x]</button>
243 <div class="vjs-stats-list"></div>
247 private buildElement (label: string, value?: string) {
248 if (!value) return ''
250 return `<div><div>${label}</div><span>${value}</span></div>`
253 private timeRangesToString (r: videojs.TimeRange) {
256 for (let i = 0; i < r.length; i++) {
257 const start = Math.floor(r.start(i))
258 const end = Math.floor(r.end(i))
260 result += `[${secondsToTime(start)}, ${secondsToTime(end)}] `
267 videojs.registerComponent('StatsCard', StatsCard)