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 { addQueryParams, 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
42 this.startTime = timeToInt(options.startTime)
44 // FIXME: typings https://github.com/Microsoft/TypeScript/issues/14080
45 if (!(videojs as any).Html5Hlsjs) {
46 if (player.canPlayType('application/vnd.apple.mpegurl')) {
47 this.fallbackToBuiltInIOS()
51 const message = 'HLS.js does not seem to be supported. Cannot fallback to built-in HLS'
54 const error: MediaError = {
55 code: MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED,
57 MEDIA_ERR_ABORTED: MediaError.MEDIA_ERR_ABORTED,
58 MEDIA_ERR_DECODE: MediaError.MEDIA_ERR_DECODE,
59 MEDIA_ERR_NETWORK: MediaError.MEDIA_ERR_NETWORK,
60 MEDIA_ERR_SRC_NOT_SUPPORTED: MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED
63 player.ready(() => player.error(error))
67 // FIXME: typings https://github.com/Microsoft/TypeScript/issues/14080
68 (videojs as any).Html5Hlsjs.addHook('beforeinitialize', (_videojsPlayer: any, hlsjs: any) => {
72 initVideoJsContribHlsJsPlayer(player)
82 this.initializePlugin()
87 if (this.hlsjs) this.hlsjs.destroy()
88 if (this.p2pEngine) this.p2pEngine.destroy()
90 clearInterval(this.networkInfoInterval)
94 if (!this.hlsjs) return undefined
96 return this.hlsjs.levels[this.hlsjs.currentLevel]
100 return Math.round(this.hlsjs.latency)
107 private initializeCore () {
108 this.player.one('play', () => {
109 this.player.addClass('vjs-has-big-play-button-clicked')
112 this.player.one('canplay', () => {
113 if (this.startTime) {
114 this.player.currentTime(this.startTime)
119 private initializePlugin () {
120 initHlsJsPlayer(this.hlsjs)
122 this.p2pEngine = this.options.loader.getEngine()
124 this.p2pEngine.on(Events.SegmentError, (segment: Segment, err) => {
125 if (navigator.onLine === false) return
127 logger.error(`Segment ${segment.id} error.`, err)
129 this.options.redundancyUrlManager.removeBySegmentUrl(segment.requestUrl)
132 this.statsP2PBytes.numPeers = 1 + this.options.redundancyUrlManager.countBaseUrls()
136 this.hlsjs.on(Hlsjs.Events.LEVEL_SWITCHED, () => this.player.trigger('engineResolutionChange'))
139 private runStats () {
140 this.p2pEngine.on(Events.PieceBytesDownloaded, (method: string, _segment, bytes: number) => {
141 const elem = method === 'p2p' ? this.statsP2PBytes : this.statsHTTPBytes
143 elem.pendingDownload.push(bytes)
144 elem.totalDownload += bytes
147 this.p2pEngine.on(Events.PieceBytesUploaded, (method: string, _segment, bytes: number) => {
148 if (method !== 'p2p') {
149 logger.error(`Received upload from unknown method ${method}`)
153 this.statsP2PBytes.pendingUpload.push(bytes)
154 this.statsP2PBytes.totalUpload += bytes
157 this.p2pEngine.on(Events.PeerConnect, () => this.statsP2PBytes.numPeers++)
158 this.p2pEngine.on(Events.PeerClose, () => this.statsP2PBytes.numPeers--)
160 this.networkInfoInterval = setInterval(() => {
161 const p2pDownloadSpeed = this.arraySum(this.statsP2PBytes.pendingDownload)
162 const p2pUploadSpeed = this.arraySum(this.statsP2PBytes.pendingUpload)
164 const httpDownloadSpeed = this.arraySum(this.statsHTTPBytes.pendingDownload)
166 this.statsP2PBytes.pendingDownload = []
167 this.statsP2PBytes.pendingUpload = []
168 this.statsHTTPBytes.pendingDownload = []
170 return this.player.trigger('p2pInfo', {
171 source: 'p2p-media-loader',
173 downloadSpeed: httpDownloadSpeed,
174 downloaded: this.statsHTTPBytes.totalDownload
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)
192 private fallbackToBuiltInIOS () {
193 logger.info('HLS.js does not seem to be supported. Fallback to built-in HLS.');
195 // Workaround to force video.js to not re create a video element
196 (this.player as any).playerElIngest_ = this.player.el().parentNode
199 type: this.options.type,
200 src: addQueryParams(this.options.src, {
201 videoFileToken: this.options.videoFileToken(),
202 reinjectVideoFileToken: 'true'
206 this.player.ready(() => {
207 this.initializeCore()
212 videojs.registerPlugin('p2pMediaLoader', P2pMediaLoaderPlugin)
213 export { P2pMediaLoaderPlugin }