]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/assets/player/shared/p2p-media-loader/p2p-media-loader-plugin.ts
Support reinjecting token in private m3u8 playlist
[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'
71e3e879 6import { addQueryParams, 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 41 this.options = options
71e3e879 42 this.startTime = timeToInt(options.startTime)
09209296 43
f5fcd9f7
C
44 // FIXME: typings https://github.com/Microsoft/TypeScript/issues/14080
45 if (!(videojs as any).Html5Hlsjs) {
71e3e879
C
46 if (player.canPlayType('application/vnd.apple.mpegurl')) {
47 this.fallbackToBuiltInIOS()
48 return
326f3692
C
49 }
50
71e3e879
C
51 const message = 'HLS.js does not seem to be supported. Cannot fallback to built-in HLS'
52 logger.warn(message)
96cb4527 53
71e3e879
C
54 const error: MediaError = {
55 code: MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED,
56 message,
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
69a01996 61 }
32f44a01 62
71e3e879
C
63 player.ready(() => player.error(error))
64 return
69a01996 65 }
2adfc7ea 66
71e3e879
C
67 // FIXME: typings https://github.com/Microsoft/TypeScript/issues/14080
68 (videojs as any).Html5Hlsjs.addHook('beforeinitialize', (_videojsPlayer: any, hlsjs: any) => {
69 this.hlsjs = hlsjs
70 })
71
72 initVideoJsContribHlsJsPlayer(player)
e2f01c47 73
2adfc7ea
C
74 player.src({
75 type: options.type,
76 src: options.src
77 })
09209296 78
69a01996
C
79 player.ready(() => {
80 this.initializeCore()
6ec0b75b 81
71e3e879 82 this.initializePlugin()
69a01996 83 })
2adfc7ea
C
84 }
85
3b6f205c 86 dispose () {
6ec0b75b
C
87 if (this.hlsjs) this.hlsjs.destroy()
88 if (this.p2pEngine) this.p2pEngine.destroy()
89
3b6f205c
C
90 clearInterval(this.networkInfoInterval)
91 }
92
4e11d8f3 93 getCurrentLevel () {
f2c29ced
C
94 if (!this.hlsjs) return undefined
95
3e254de8 96 return this.hlsjs.levels[this.hlsjs.currentLevel]
4e11d8f3
C
97 }
98
99 getLiveLatency () {
02b2e482 100 return Math.round(this.hlsjs.latency)
4e11d8f3
C
101 }
102
6377a9f2
C
103 getHLSJS () {
104 return this.hlsjs
105 }
106
69a01996
C
107 private initializeCore () {
108 this.player.one('play', () => {
109 this.player.addClass('vjs-has-big-play-button-clicked')
110 })
111
112 this.player.one('canplay', () => {
113 if (this.startTime) {
114 this.player.currentTime(this.startTime)
115 }
116 })
117 }
118
119 private initializePlugin () {
09209296
C
120 initHlsJsPlayer(this.hlsjs)
121
9597920e 122 this.p2pEngine = this.options.loader.getEngine()
3b6f205c 123
da332417 124 this.p2pEngine.on(Events.SegmentError, (segment: Segment, err) => {
f2a16d93 125 if (navigator.onLine === false) return
126
42b40636 127 logger.error(`Segment ${segment.id} error.`, err)
da332417 128
b82df0a3 129 this.options.redundancyUrlManager.removeBySegmentUrl(segment.requestUrl)
09209296
C
130 })
131
da332417 132 this.statsP2PBytes.numPeers = 1 + this.options.redundancyUrlManager.countBaseUrls()
09209296 133
3b6f205c 134 this.runStats()
fd3c2e87
C
135
136 this.hlsjs.on(Hlsjs.Events.LEVEL_SWITCHED, () => this.player.trigger('engineResolutionChange'))
3b6f205c
C
137 }
138
139 private runStats () {
3e254de8 140 this.p2pEngine.on(Events.PieceBytesDownloaded, (method: string, _segment, bytes: number) => {
09209296
C
141 const elem = method === 'p2p' ? this.statsP2PBytes : this.statsHTTPBytes
142
3e254de8
C
143 elem.pendingDownload.push(bytes)
144 elem.totalDownload += bytes
3b6f205c
C
145 })
146
3e254de8 147 this.p2pEngine.on(Events.PieceBytesUploaded, (method: string, _segment, bytes: number) => {
fd3c2e87
C
148 if (method !== 'p2p') {
149 logger.error(`Received upload from unknown method ${method}`)
150 return
151 }
09209296 152
fd3c2e87
C
153 this.statsP2PBytes.pendingUpload.push(bytes)
154 this.statsP2PBytes.totalUpload += bytes
3b6f205c
C
155 })
156
157 this.p2pEngine.on(Events.PeerConnect, () => this.statsP2PBytes.numPeers++)
158 this.p2pEngine.on(Events.PeerClose, () => this.statsP2PBytes.numPeers--)
159
160 this.networkInfoInterval = setInterval(() => {
09209296
C
161 const p2pDownloadSpeed = this.arraySum(this.statsP2PBytes.pendingDownload)
162 const p2pUploadSpeed = this.arraySum(this.statsP2PBytes.pendingUpload)
163
164 const httpDownloadSpeed = this.arraySum(this.statsHTTPBytes.pendingDownload)
3b6f205c
C
165
166 this.statsP2PBytes.pendingDownload = []
167 this.statsP2PBytes.pendingUpload = []
09209296 168 this.statsHTTPBytes.pendingDownload = []
3b6f205c
C
169
170 return this.player.trigger('p2pInfo', {
17152837 171 source: 'p2p-media-loader',
09209296
C
172 http: {
173 downloadSpeed: httpDownloadSpeed,
fd3c2e87 174 downloaded: this.statsHTTPBytes.totalDownload
09209296 175 },
3b6f205c 176 p2p: {
09209296
C
177 downloadSpeed: p2pDownloadSpeed,
178 uploadSpeed: p2pUploadSpeed,
3b6f205c
C
179 numPeers: this.statsP2PBytes.numPeers,
180 downloaded: this.statsP2PBytes.totalDownload,
181 uploaded: this.statsP2PBytes.totalUpload
4e11d8f3
C
182 },
183 bandwidthEstimate: (this.hlsjs as any).bandwidthEstimate / 8
3b6f205c
C
184 } as PlayerNetworkInfo)
185 }, this.CONSTANTS.INFO_SCHEDULER)
186 }
09209296
C
187
188 private arraySum (data: number[]) {
189 return data.reduce((a: number, b: number) => a + b, 0)
190 }
71e3e879
C
191
192 private fallbackToBuiltInIOS () {
193 logger.info('HLS.js does not seem to be supported. Fallback to built-in HLS.');
194
195 // Workaround to force video.js to not re create a video element
196 (this.player as any).playerElIngest_ = this.player.el().parentNode
197
198 this.player.src({
199 type: this.options.type,
200 src: addQueryParams(this.options.src, {
201 videoFileToken: this.options.videoFileToken(),
202 reinjectVideoFileToken: 'true'
203 })
204 })
205
206 this.player.ready(() => {
207 this.initializeCore()
208 })
209 }
2adfc7ea
C
210}
211
212videojs.registerPlugin('p2pMediaLoader', P2pMediaLoaderPlugin)
213export { P2pMediaLoaderPlugin }