1 import * as Hlsjs from 'hls.js/dist/hls.light.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 { timeToInt } from '@shared/core-utils'
6 import { P2PMediaLoaderPluginOptions, PlayerNetworkInfo } from '../peertube-videojs-typings'
7 import { registerConfigPlugin, registerSourceHandler } from './hls-plugin'
9 registerConfigPlugin(videojs)
10 registerSourceHandler(videojs)
12 const Plugin = videojs.getPlugin('plugin')
13 class P2pMediaLoaderPlugin extends Plugin {
15 private readonly CONSTANTS = {
16 INFO_SCHEDULER: 1000 // Don't change this
18 private readonly options: P2PMediaLoaderPluginOptions
21 private p2pEngine: Engine
22 private statsP2PBytes = {
23 pendingDownload: [] as number[],
24 pendingUpload: [] as number[],
29 private statsHTTPBytes = {
30 pendingDownload: [] as number[],
31 pendingUpload: [] as number[],
35 private startTime: number
37 private networkInfoInterval: any
39 constructor (player: videojs.Player, options?: P2PMediaLoaderPluginOptions) {
42 this.options = options
44 // FIXME: typings https://github.com/Microsoft/TypeScript/issues/14080
45 if (!(videojs as any).Html5Hlsjs) {
46 console.warn('HLS.js does not seem to be supported. Try to fallback to built in HLS.')
48 if (!player.canPlayType('application/vnd.apple.mpegurl')) {
49 const message = 'Cannot fallback to built-in HLS'
52 player.ready(() => player.trigger('error', new Error(message)))
56 // FIXME: typings https://github.com/Microsoft/TypeScript/issues/14080
57 (videojs as any).Html5Hlsjs.addHook('beforeinitialize', (videojsPlayer: any, hlsjs: any) => {
61 initVideoJsContribHlsJsPlayer(player)
64 this.startTime = timeToInt(options.startTime)
74 if ((videojs as any).Html5Hlsjs) {
75 this.initializePlugin()
81 if (this.hlsjs) this.hlsjs.destroy()
82 if (this.p2pEngine) this.p2pEngine.destroy()
84 clearInterval(this.networkInfoInterval)
88 return this.hlsjs.levels[this.hlsjs.currentLevel]
93 return Math.round((this.hlsjs as any).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)
116 const options = this.player.tech(true).options_ as any
117 this.p2pEngine = options.hlsjsConfig.loader.getEngine()
119 this.hlsjs.on(Hlsjs.Events.LEVEL_SWITCHING, (_: any, data: any) => {
120 this.trigger('resolutionChange', { auto: this.hlsjs.autoLevelEnabled, resolutionId: data.height })
123 this.hlsjs.on(Hlsjs.Events.MANIFEST_LOADED, (_: any, data: any) => {
124 this.trigger('resolutionsLoaded')
127 this.p2pEngine.on(Events.SegmentError, (segment: Segment, err) => {
128 console.error('Segment error.', segment, err)
130 this.options.redundancyUrlManager.removeBySegmentUrl(segment.requestUrl)
133 this.statsP2PBytes.numPeers = 1 + this.options.redundancyUrlManager.countBaseUrls()
138 private runStats () {
139 this.p2pEngine.on(Events.PieceBytesDownloaded, (method: string, _segment, bytes: number) => {
140 const elem = method === 'p2p' ? this.statsP2PBytes : this.statsHTTPBytes
142 elem.pendingDownload.push(bytes)
143 elem.totalDownload += bytes
146 this.p2pEngine.on(Events.PieceBytesUploaded, (method: string, _segment, bytes: number) => {
147 const elem = method === 'p2p' ? this.statsP2PBytes : this.statsHTTPBytes
149 elem.pendingUpload.push(bytes)
150 elem.totalUpload += bytes
153 this.p2pEngine.on(Events.PeerConnect, () => this.statsP2PBytes.numPeers++)
154 this.p2pEngine.on(Events.PeerClose, () => this.statsP2PBytes.numPeers--)
156 this.networkInfoInterval = setInterval(() => {
157 const p2pDownloadSpeed = this.arraySum(this.statsP2PBytes.pendingDownload)
158 const p2pUploadSpeed = this.arraySum(this.statsP2PBytes.pendingUpload)
160 const httpDownloadSpeed = this.arraySum(this.statsHTTPBytes.pendingDownload)
161 const httpUploadSpeed = this.arraySum(this.statsHTTPBytes.pendingUpload)
163 this.statsP2PBytes.pendingDownload = []
164 this.statsP2PBytes.pendingUpload = []
165 this.statsHTTPBytes.pendingDownload = []
166 this.statsHTTPBytes.pendingUpload = []
168 return this.player.trigger('p2pInfo', {
169 source: 'p2p-media-loader',
171 downloadSpeed: httpDownloadSpeed,
172 uploadSpeed: httpUploadSpeed,
173 downloaded: this.statsHTTPBytes.totalDownload,
174 uploaded: this.statsHTTPBytes.totalUpload
177 downloadSpeed: p2pDownloadSpeed,
178 uploadSpeed: p2pUploadSpeed,
179 numPeers: this.statsP2PBytes.numPeers,
180 downloaded: this.statsP2PBytes.totalDownload,
181 uploaded: this.statsP2PBytes.totalUpload
183 bandwidthEstimate: (this.hlsjs as any).bandwidthEstimate / 8
184 } as PlayerNetworkInfo)
185 }, this.CONSTANTS.INFO_SCHEDULER)
188 private arraySum (data: number[]) {
189 return data.reduce((a: number, b: number) => a + b, 0)
193 videojs.registerPlugin('p2pMediaLoader', P2pMediaLoaderPlugin)
194 export { P2pMediaLoaderPlugin }