]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/assets/player/shared/p2p-media-loader/p2p-media-loader-plugin.ts
feat(plugins): add p2p-media-loader options filter (#5318)
[github/Chocobozzz/PeerTube.git] / client / src / assets / player / shared / p2p-media-loader / p2p-media-loader-plugin.ts
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'
9
10 registerConfigPlugin(videojs)
11 registerSourceHandler(videojs)
12
13 const Plugin = videojs.getPlugin('plugin')
14 class P2pMediaLoaderPlugin extends Plugin {
15
16 private readonly CONSTANTS = {
17 INFO_SCHEDULER: 1000 // Don't change this
18 }
19 private readonly options: P2PMediaLoaderPluginOptions
20
21 private hlsjs: Hlsjs
22 private p2pEngine: Engine
23 private statsP2PBytes = {
24 pendingDownload: [] as number[],
25 pendingUpload: [] as number[],
26 numPeers: 0,
27 totalDownload: 0,
28 totalUpload: 0
29 }
30 private statsHTTPBytes = {
31 pendingDownload: [] as number[],
32 totalDownload: 0
33 }
34 private startTime: number
35
36 private networkInfoInterval: any
37
38 constructor (player: videojs.Player, options?: P2PMediaLoaderPluginOptions) {
39 super(player)
40
41 this.options = options
42
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.')
46
47 if (!player.canPlayType('application/vnd.apple.mpegurl')) {
48 const message = 'Cannot fallback to built-in HLS'
49 logger.warn(message)
50
51 player.ready(() => player.trigger('error', new Error(message)))
52 return
53 }
54 } else {
55 // FIXME: typings https://github.com/Microsoft/TypeScript/issues/14080
56 (videojs as any).Html5Hlsjs.addHook('beforeinitialize', (videojsPlayer: any, hlsjs: any) => {
57 this.hlsjs = hlsjs
58 })
59
60 initVideoJsContribHlsJsPlayer(player)
61 }
62
63 this.startTime = timeToInt(options.startTime)
64
65 player.src({
66 type: options.type,
67 src: options.src
68 })
69
70 player.ready(() => {
71 this.initializeCore()
72
73 if ((videojs as any).Html5Hlsjs) {
74 this.initializePlugin()
75 }
76 })
77 }
78
79 dispose () {
80 if (this.hlsjs) this.hlsjs.destroy()
81 if (this.p2pEngine) this.p2pEngine.destroy()
82
83 clearInterval(this.networkInfoInterval)
84 }
85
86 getCurrentLevel () {
87 if (!this.hlsjs) return undefined
88
89 return this.hlsjs.levels[this.hlsjs.currentLevel]
90 }
91
92 getLiveLatency () {
93 return Math.round(this.hlsjs.latency)
94 }
95
96 getHLSJS () {
97 return this.hlsjs
98 }
99
100 private initializeCore () {
101 this.player.one('play', () => {
102 this.player.addClass('vjs-has-big-play-button-clicked')
103 })
104
105 this.player.one('canplay', () => {
106 if (this.startTime) {
107 this.player.currentTime(this.startTime)
108 }
109 })
110 }
111
112 private initializePlugin () {
113 initHlsJsPlayer(this.hlsjs)
114
115 this.p2pEngine = this.options.loader.getEngine()
116
117 this.p2pEngine.on(Events.SegmentError, (segment: Segment, err) => {
118 if (navigator.onLine === false) return
119
120 logger.error(`Segment ${segment.id} error.`, err)
121
122 this.options.redundancyUrlManager.removeBySegmentUrl(segment.requestUrl)
123 })
124
125 this.statsP2PBytes.numPeers = 1 + this.options.redundancyUrlManager.countBaseUrls()
126
127 this.runStats()
128
129 this.hlsjs.on(Hlsjs.Events.LEVEL_SWITCHED, () => this.player.trigger('engineResolutionChange'))
130 }
131
132 private runStats () {
133 this.p2pEngine.on(Events.PieceBytesDownloaded, (method: string, _segment, bytes: number) => {
134 const elem = method === 'p2p' ? this.statsP2PBytes : this.statsHTTPBytes
135
136 elem.pendingDownload.push(bytes)
137 elem.totalDownload += bytes
138 })
139
140 this.p2pEngine.on(Events.PieceBytesUploaded, (method: string, _segment, bytes: number) => {
141 if (method !== 'p2p') {
142 logger.error(`Received upload from unknown method ${method}`)
143 return
144 }
145
146 this.statsP2PBytes.pendingUpload.push(bytes)
147 this.statsP2PBytes.totalUpload += bytes
148 })
149
150 this.p2pEngine.on(Events.PeerConnect, () => this.statsP2PBytes.numPeers++)
151 this.p2pEngine.on(Events.PeerClose, () => this.statsP2PBytes.numPeers--)
152
153 this.networkInfoInterval = setInterval(() => {
154 const p2pDownloadSpeed = this.arraySum(this.statsP2PBytes.pendingDownload)
155 const p2pUploadSpeed = this.arraySum(this.statsP2PBytes.pendingUpload)
156
157 const httpDownloadSpeed = this.arraySum(this.statsHTTPBytes.pendingDownload)
158
159 this.statsP2PBytes.pendingDownload = []
160 this.statsP2PBytes.pendingUpload = []
161 this.statsHTTPBytes.pendingDownload = []
162
163 return this.player.trigger('p2pInfo', {
164 source: 'p2p-media-loader',
165 http: {
166 downloadSpeed: httpDownloadSpeed,
167 downloaded: this.statsHTTPBytes.totalDownload
168 },
169 p2p: {
170 downloadSpeed: p2pDownloadSpeed,
171 uploadSpeed: p2pUploadSpeed,
172 numPeers: this.statsP2PBytes.numPeers,
173 downloaded: this.statsP2PBytes.totalDownload,
174 uploaded: this.statsP2PBytes.totalUpload
175 },
176 bandwidthEstimate: (this.hlsjs as any).bandwidthEstimate / 8
177 } as PlayerNetworkInfo)
178 }, this.CONSTANTS.INFO_SCHEDULER)
179 }
180
181 private arraySum (data: number[]) {
182 return data.reduce((a: number, b: number) => a + b, 0)
183 }
184 }
185
186 videojs.registerPlugin('p2pMediaLoader', P2pMediaLoaderPlugin)
187 export { P2pMediaLoaderPlugin }