]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/assets/player/shared/p2p-media-loader/p2p-media-loader-plugin.ts
Fix broken player on non MSE devices
[github/Chocobozzz/PeerTube.git] / client / src / assets / player / shared / p2p-media-loader / p2p-media-loader-plugin.ts
CommitLineData
134006b0 1import Hlsjs from 'hls.js'
512decf3 2import videojs from 'video.js'
3e254de8
C
3import { Events, Segment } from '@peertube/p2p-media-loader-core'
4import { Engine, initHlsJsPlayer, initVideoJsContribHlsJsPlayer } from '@peertube/p2p-media-loader-hlsjs'
fd3c2e87 5import { logger } from '@root-helpers/logger'
15a7eafb 6import { timeToInt } from '@shared/core-utils'
57d65032 7import { P2PMediaLoaderPluginOptions, PlayerNetworkInfo } from '../../types'
83fcadac 8import { registerConfigPlugin, registerSourceHandler } from './hls-plugin'
2adfc7ea 9
83fcadac
C
10registerConfigPlugin(videojs)
11registerSourceHandler(videojs)
2adfc7ea 12
f5fcd9f7 13const Plugin = videojs.getPlugin('plugin')
2adfc7ea
C
14class P2pMediaLoaderPlugin extends Plugin {
15
3b6f205c
C
16 private readonly CONSTANTS = {
17 INFO_SCHEDULER: 1000 // Don't change this
18 }
09209296 19 private readonly options: P2PMediaLoaderPluginOptions
3b6f205c 20
83fcadac 21 private hlsjs: Hlsjs
3b6f205c
C
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 }
09209296
C
30 private statsHTTPBytes = {
31 pendingDownload: [] as number[],
fd3c2e87 32 totalDownload: 0
09209296 33 }
e2f01c47 34 private startTime: number
3b6f205c
C
35
36 private networkInfoInterval: any
37
7e37e111 38 constructor (player: videojs.Player, options?: P2PMediaLoaderPluginOptions) {
f5fcd9f7 39 super(player)
2adfc7ea 40
09209296
C
41 this.options = options
42
f5fcd9f7
C
43 // FIXME: typings https://github.com/Microsoft/TypeScript/issues/14080
44 if (!(videojs as any).Html5Hlsjs) {
42b40636 45 logger.warn('HLS.js does not seem to be supported. Try to fallback to built in HLS.')
96cb4527 46
69a01996
C
47 if (!player.canPlayType('application/vnd.apple.mpegurl')) {
48 const message = 'Cannot fallback to built-in HLS'
42b40636 49 logger.warn(message)
96cb4527 50
69a01996
C
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 })
3b6f205c 59
69a01996
C
60 initVideoJsContribHlsJsPlayer(player)
61 }
2adfc7ea 62
e2f01c47
C
63 this.startTime = timeToInt(options.startTime)
64
2adfc7ea
C
65 player.src({
66 type: options.type,
67 src: options.src
68 })
09209296 69
69a01996
C
70 player.ready(() => {
71 this.initializeCore()
6ec0b75b 72
69a01996
C
73 if ((videojs as any).Html5Hlsjs) {
74 this.initializePlugin()
75 }
76 })
2adfc7ea
C
77 }
78
3b6f205c 79 dispose () {
6ec0b75b
C
80 if (this.hlsjs) this.hlsjs.destroy()
81 if (this.p2pEngine) this.p2pEngine.destroy()
82
3b6f205c
C
83 clearInterval(this.networkInfoInterval)
84 }
85
4e11d8f3 86 getCurrentLevel () {
f2c29ced
C
87 if (!this.hlsjs) return undefined
88
3e254de8 89 return this.hlsjs.levels[this.hlsjs.currentLevel]
4e11d8f3
C
90 }
91
92 getLiveLatency () {
02b2e482 93 return Math.round(this.hlsjs.latency)
4e11d8f3
C
94 }
95
6377a9f2
C
96 getHLSJS () {
97 return this.hlsjs
98 }
99
69a01996
C
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 () {
09209296
C
113 initHlsJsPlayer(this.hlsjs)
114
9597920e 115 this.p2pEngine = this.options.loader.getEngine()
3b6f205c 116
da332417 117 this.p2pEngine.on(Events.SegmentError, (segment: Segment, err) => {
42b40636 118 logger.error(`Segment ${segment.id} error.`, err)
da332417 119
b82df0a3 120 this.options.redundancyUrlManager.removeBySegmentUrl(segment.requestUrl)
09209296
C
121 })
122
da332417 123 this.statsP2PBytes.numPeers = 1 + this.options.redundancyUrlManager.countBaseUrls()
09209296 124
3b6f205c 125 this.runStats()
fd3c2e87
C
126
127 this.hlsjs.on(Hlsjs.Events.LEVEL_SWITCHED, () => this.player.trigger('engineResolutionChange'))
3b6f205c
C
128 }
129
130 private runStats () {
3e254de8 131 this.p2pEngine.on(Events.PieceBytesDownloaded, (method: string, _segment, bytes: number) => {
09209296
C
132 const elem = method === 'p2p' ? this.statsP2PBytes : this.statsHTTPBytes
133
3e254de8
C
134 elem.pendingDownload.push(bytes)
135 elem.totalDownload += bytes
3b6f205c
C
136 })
137
3e254de8 138 this.p2pEngine.on(Events.PieceBytesUploaded, (method: string, _segment, bytes: number) => {
fd3c2e87
C
139 if (method !== 'p2p') {
140 logger.error(`Received upload from unknown method ${method}`)
141 return
142 }
09209296 143
fd3c2e87
C
144 this.statsP2PBytes.pendingUpload.push(bytes)
145 this.statsP2PBytes.totalUpload += bytes
3b6f205c
C
146 })
147
148 this.p2pEngine.on(Events.PeerConnect, () => this.statsP2PBytes.numPeers++)
149 this.p2pEngine.on(Events.PeerClose, () => this.statsP2PBytes.numPeers--)
150
151 this.networkInfoInterval = setInterval(() => {
09209296
C
152 const p2pDownloadSpeed = this.arraySum(this.statsP2PBytes.pendingDownload)
153 const p2pUploadSpeed = this.arraySum(this.statsP2PBytes.pendingUpload)
154
155 const httpDownloadSpeed = this.arraySum(this.statsHTTPBytes.pendingDownload)
3b6f205c
C
156
157 this.statsP2PBytes.pendingDownload = []
158 this.statsP2PBytes.pendingUpload = []
09209296 159 this.statsHTTPBytes.pendingDownload = []
3b6f205c
C
160
161 return this.player.trigger('p2pInfo', {
17152837 162 source: 'p2p-media-loader',
09209296
C
163 http: {
164 downloadSpeed: httpDownloadSpeed,
fd3c2e87 165 downloaded: this.statsHTTPBytes.totalDownload
09209296 166 },
3b6f205c 167 p2p: {
09209296
C
168 downloadSpeed: p2pDownloadSpeed,
169 uploadSpeed: p2pUploadSpeed,
3b6f205c
C
170 numPeers: this.statsP2PBytes.numPeers,
171 downloaded: this.statsP2PBytes.totalDownload,
172 uploaded: this.statsP2PBytes.totalUpload
4e11d8f3
C
173 },
174 bandwidthEstimate: (this.hlsjs as any).bandwidthEstimate / 8
3b6f205c
C
175 } as PlayerNetworkInfo)
176 }, this.CONSTANTS.INFO_SCHEDULER)
177 }
09209296
C
178
179 private arraySum (data: number[]) {
180 return data.reduce((a: number, b: number) => a + b, 0)
181 }
2adfc7ea
C
182}
183
184videojs.registerPlugin('p2pMediaLoader', P2pMediaLoaderPlugin)
185export { P2pMediaLoaderPlugin }