1 import Hlsjs from 'hls.js'
2 import videojs from 'video.js'
3 import { Events, Segment } from '@peertube/p2p-media-loader-core'
4 import { Engine, initHlsJsPlayer, initVideoJsContribHlsJsPlayer } from '@peertube/p2p-media-loader-hlsjs'
5 import { logger } from '@root-helpers/logger'
6 import { timeToInt } from '@shared/core-utils'
7 import { P2PMediaLoaderPluginOptions, PlayerNetworkInfo } from '../../types'
8 import { registerConfigPlugin, registerSourceHandler } from './hls-plugin'
10 registerConfigPlugin(videojs)
11 registerSourceHandler(videojs)
13 const Plugin = videojs.getPlugin('plugin')
14 class P2pMediaLoaderPlugin extends Plugin {
16 private readonly CONSTANTS = {
17 INFO_SCHEDULER: 1000 // Don't change this
19 private readonly options: P2PMediaLoaderPluginOptions
22 private p2pEngine: Engine
23 private statsP2PBytes = {
24 pendingDownload: [] as number[],
25 pendingUpload: [] as number[],
30 private statsHTTPBytes = {
31 pendingDownload: [] as number[],
34 private startTime: number
36 private networkInfoInterval: any
38 constructor (player: videojs.Player, options?: P2PMediaLoaderPluginOptions) {
41 this.options = options
43 // FIXME: typings https://github.com/Microsoft/TypeScript/issues/14080
44 if (!(videojs as any).Html5Hlsjs) {
45 logger.warn('HLS.js does not seem to be supported. Try to fallback to built in HLS.')
47 if (!player.canPlayType('application/vnd.apple.mpegurl')) {
48 const message = 'Cannot fallback to built-in HLS'
51 player.ready(() => player.trigger('error', new Error(message)))
55 // FIXME: typings https://github.com/Microsoft/TypeScript/issues/14080
56 (videojs as any).Html5Hlsjs.addHook('beforeinitialize', (videojsPlayer: any, hlsjs: any) => {
60 initVideoJsContribHlsJsPlayer(player)
63 this.startTime = timeToInt(options.startTime)
73 if ((videojs as any).Html5Hlsjs) {
74 this.initializePlugin()
80 if (this.hlsjs) this.hlsjs.destroy()
81 if (this.p2pEngine) this.p2pEngine.destroy()
83 clearInterval(this.networkInfoInterval)
87 if (!this.hlsjs) return undefined
89 return this.hlsjs.levels[this.hlsjs.currentLevel]
93 return Math.round(this.hlsjs.latency)
100 private initializeCore () {
101 this.player.one('play', () => {
102 this.player.addClass('vjs-has-big-play-button-clicked')
105 this.player.one('canplay', () => {
106 if (this.startTime) {
107 this.player.currentTime(this.startTime)
112 private initializePlugin () {
113 initHlsJsPlayer(this.hlsjs)
115 this.p2pEngine = this.options.loader.getEngine()
117 this.p2pEngine.on(Events.SegmentError, (segment: Segment, err) => {
118 if (navigator.onLine === false) return
120 logger.error(`Segment ${segment.id} error.`, err)
122 this.options.redundancyUrlManager.removeBySegmentUrl(segment.requestUrl)
125 this.statsP2PBytes.numPeers = 1 + this.options.redundancyUrlManager.countBaseUrls()
129 this.hlsjs.on(Hlsjs.Events.LEVEL_SWITCHED, () => this.player.trigger('engineResolutionChange'))
132 private runStats () {
133 this.p2pEngine.on(Events.PieceBytesDownloaded, (method: string, _segment, bytes: number) => {
134 const elem = method === 'p2p' ? this.statsP2PBytes : this.statsHTTPBytes
136 elem.pendingDownload.push(bytes)
137 elem.totalDownload += bytes
140 this.p2pEngine.on(Events.PieceBytesUploaded, (method: string, _segment, bytes: number) => {
141 if (method !== 'p2p') {
142 logger.error(`Received upload from unknown method ${method}`)
146 this.statsP2PBytes.pendingUpload.push(bytes)
147 this.statsP2PBytes.totalUpload += bytes
150 this.p2pEngine.on(Events.PeerConnect, () => this.statsP2PBytes.numPeers++)
151 this.p2pEngine.on(Events.PeerClose, () => this.statsP2PBytes.numPeers--)
153 this.networkInfoInterval = setInterval(() => {
154 const p2pDownloadSpeed = this.arraySum(this.statsP2PBytes.pendingDownload)
155 const p2pUploadSpeed = this.arraySum(this.statsP2PBytes.pendingUpload)
157 const httpDownloadSpeed = this.arraySum(this.statsHTTPBytes.pendingDownload)
159 this.statsP2PBytes.pendingDownload = []
160 this.statsP2PBytes.pendingUpload = []
161 this.statsHTTPBytes.pendingDownload = []
163 return this.player.trigger('p2pInfo', {
164 source: 'p2p-media-loader',
166 downloadSpeed: httpDownloadSpeed,
167 downloaded: this.statsHTTPBytes.totalDownload
170 downloadSpeed: p2pDownloadSpeed,
171 uploadSpeed: p2pUploadSpeed,
172 numPeers: this.statsP2PBytes.numPeers,
173 downloaded: this.statsP2PBytes.totalDownload,
174 uploaded: this.statsP2PBytes.totalUpload
176 bandwidthEstimate: (this.hlsjs as any).bandwidthEstimate / 8
177 } as PlayerNetworkInfo)
178 }, this.CONSTANTS.INFO_SCHEDULER)
181 private arraySum (data: number[]) {
182 return data.reduce((a: number, b: number) => a + b, 0)
186 videojs.registerPlugin('p2pMediaLoader', P2pMediaLoaderPlugin)
187 export { P2pMediaLoaderPlugin }