]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/assets/player/peertube-player-manager.ts
Add signup approval API tests
[github/Chocobozzz/PeerTube.git] / client / src / assets / player / peertube-player-manager.ts
CommitLineData
950b3ce7 1import '@peertube/videojs-contextmenu'
57d65032
C
2import './shared/upnext/end-card'
3import './shared/upnext/upnext-plugin'
4import './shared/stats/stats-card'
5import './shared/stats/stats-plugin'
6import './shared/bezels/bezels-plugin'
7import './shared/peertube/peertube-plugin'
8import './shared/resolutions/peertube-resolutions-plugin'
9import './shared/control-bar/next-previous-video-button'
10import './shared/control-bar/p2p-info-button'
11import './shared/control-bar/peertube-link-button'
12import './shared/control-bar/peertube-load-progress-bar'
13import './shared/control-bar/theater-button'
0e7c4b03 14import './shared/control-bar/peertube-live-display'
57d65032
C
15import './shared/settings/resolution-menu-button'
16import './shared/settings/resolution-menu-item'
17import './shared/settings/settings-dialog'
18import './shared/settings/settings-menu-button'
19import './shared/settings/settings-menu-item'
20import './shared/settings/settings-panel'
21import './shared/settings/settings-panel-child'
22import './shared/playlist/playlist-plugin'
23import './shared/mobile/peertube-mobile-plugin'
24import './shared/mobile/peertube-mobile-buttons'
25import './shared/hotkeys/peertube-hotkeys-plugin'
fd3c2e87 26import './shared/metrics/metrics-plugin'
3e2bc4ea 27import videojs from 'video.js'
42b40636 28import { logger } from '@root-helpers/logger'
72f611ca 29import { PluginsManager } from '@root-helpers/plugins-manager'
57d65032 30import { isMobile } from '@root-helpers/web-browser'
c4207f97 31import { saveAverageBandwidth } from './peertube-player-local-storage'
57d65032 32import { ManagerOptionsBuilder } from './shared/manager-options'
3f9c4955 33import { TranslationsManager } from './translations-manager'
57d65032 34import { CommonOptions, PeertubePlayerManagerOptions, PlayerMode, PlayerNetworkInfo } from './types'
2adfc7ea
C
35
36// Change 'Playback Rate' to 'Speed' (smaller for our settings menu)
f5fcd9f7
C
37(videojs.getComponent('PlaybackRateMenuButton') as any).prototype.controlText_ = 'Speed'
38
39const CaptionsButton = videojs.getComponent('CaptionsButton') as any
2adfc7ea 40// Change Captions to Subtitles/CC
f5fcd9f7 41CaptionsButton.prototype.controlText_ = 'Subtitles/CC'
2adfc7ea 42// We just want to display 'Off' instead of 'captions off', keep a space so the variable == true (hacky I know)
f5fcd9f7 43CaptionsButton.prototype.label_ = ' '
2adfc7ea 44
2adfc7ea 45export class PeertubePlayerManager {
6ec0b75b 46 private static playerElementClassName: string
eaa5dc31
C
47 private static playerElementAttributes: { name: string, value: string }[] = []
48
7e37e111 49 private static onPlayerChange: (player: videojs.Player) => void
9eccae74 50 private static alreadyPlayed = false
72f611ca 51 private static pluginsManager: PluginsManager
9eccae74 52
c4207f97
C
53 private static videojsDecodeErrors = 0
54
55 private static p2pMediaLoaderModule: any
56
1a568b6f 57 static initState () {
c4207f97 58 this.alreadyPlayed = false
1a568b6f
C
59 }
60
7e37e111 61 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions, onPlayerChange: (player: videojs.Player) => void) {
72f611ca 62 this.pluginsManager = options.pluginsManager
63
bfbd9128 64 this.onPlayerChange = onPlayerChange
eaa5dc31 65
6ec0b75b
C
66 this.playerElementClassName = options.common.playerElement.className
67
eaa5dc31
C
68 for (const name of options.common.playerElement.getAttributeNames()) {
69 this.playerElementAttributes.push({ name, value: options.common.playerElement.getAttribute(name) })
70 }
71
57d65032 72 if (mode === 'webtorrent') await import('./shared/webtorrent/webtorrent-plugin')
4348a27d 73 if (mode === 'p2p-media-loader') {
c4207f97 74 const [ p2pMediaLoaderModule ] = await Promise.all([
3e254de8 75 import('@peertube/p2p-media-loader-hlsjs'),
57d65032 76 import('./shared/p2p-media-loader/p2p-media-loader-plugin')
4348a27d 77 ])
2adfc7ea 78
c4207f97
C
79 this.p2pMediaLoaderModule = p2pMediaLoaderModule
80 }
2adfc7ea 81
3f9c4955 82 await TranslationsManager.loadLocaleInVideoJS(options.common.serverUrl, options.common.language, videojs)
2adfc7ea 83
c4207f97
C
84 return this.buildPlayer(mode, options)
85 }
86
87 private static async buildPlayer (mode: PlayerMode, options: PeertubePlayerManagerOptions): Promise<videojs.Player> {
9597920e 88 const videojsOptionsBuilder = new ManagerOptionsBuilder(mode, options, this.p2pMediaLoaderModule)
c4207f97
C
89
90 const videojsOptions = await this.pluginsManager.runHook(
91 'filter:internal.player.videojs.options.result',
92 videojsOptionsBuilder.getVideojsOptions(this.alreadyPlayed)
93 )
94
2adfc7ea
C
95 const self = this
96 return new Promise(res => {
7e37e111 97 videojs(options.common.playerElement, videojsOptions, function (this: videojs.Player) {
2adfc7ea
C
98 const player = this
99
0e08a5e7 100 if (!isNaN(+options.common.playbackRate)) {
101 player.playbackRate(+options.common.playbackRate)
102 }
103
536598cf
C
104 let alreadyFallback = false
105
c4207f97
C
106 const handleError = () => {
107 if (alreadyFallback) return
536598cf 108 alreadyFallback = true
536598cf 109
c4207f97
C
110 if (mode === 'p2p-media-loader') {
111 self.tryToRecoverHLSError(player.error(), player, options)
112 } else {
113 self.maybeFallbackToWebTorrent(mode, player, options)
114 }
115 }
116
117 player.one('error', () => handleError())
6ec0b75b 118
9eccae74 119 player.one('play', () => {
c4207f97 120 self.alreadyPlayed = true
9eccae74
C
121 })
122
c4207f97 123 self.addContextMenu(videojsOptionsBuilder, player, options.common)
2adfc7ea 124
f1a0555a 125 if (isMobile()) player.peertubeMobile()
66b73484 126 if (options.common.enableHotkeys === true) player.peerTubeHotkeysPlugin({ isLive: options.common.isLive })
60f013e1 127 if (options.common.controlBar === false) player.controlBar.addClass('control-bar-hidden')
f1a0555a 128
10475dea 129 player.bezels()
f1a0555a 130
ff563914
RK
131 player.stats({
132 videoUUID: options.common.videoUUID,
133 videoIsLive: options.common.isLive,
95765067
C
134 mode,
135 p2pEnabled: options.common.p2pEnabled
ff563914 136 })
10475dea 137
3e254de8
C
138 player.on('p2pInfo', (_, data: PlayerNetworkInfo) => {
139 if (data.source !== 'p2p-media-loader' || isNaN(data.bandwidthEstimate)) return
140
141 saveAverageBandwidth(data.bandwidthEstimate)
142 })
143
f2a16d93 144 const offlineNotificationElem = document.createElement('div')
145 offlineNotificationElem.classList.add('vjs-peertube-offline-notification')
146 offlineNotificationElem.innerText = player.localize('You seem to be offline and the video may not work')
147
3f9decbd
C
148 let offlineNotificationElemAdded = false
149
f2a16d93 150 const handleOnline = () => {
3f9decbd
C
151 if (!offlineNotificationElemAdded) return
152
f2a16d93 153 player.el().removeChild(offlineNotificationElem)
3f9decbd
C
154 offlineNotificationElemAdded = false
155
f2a16d93 156 logger.info('The browser is online')
157 }
158
159 const handleOffline = () => {
3f9decbd
C
160 if (offlineNotificationElemAdded) return
161
f2a16d93 162 player.el().appendChild(offlineNotificationElem)
3f9decbd
C
163 offlineNotificationElemAdded = true
164
f2a16d93 165 logger.info('The browser is offline')
166 }
167
168 window.addEventListener('online', handleOnline)
169 window.addEventListener('offline', handleOffline)
170
171 player.on('dispose', () => {
172 window.removeEventListener('online', handleOnline)
173 window.removeEventListener('offline', handleOffline)
174 })
175
2adfc7ea
C
176 return res(player)
177 })
178 })
179 }
180
c4207f97 181 private static async tryToRecoverHLSError (err: any, currentPlayer: videojs.Player, options: PeertubePlayerManagerOptions) {
f746622b 182 if (err.code === MediaError.MEDIA_ERR_DECODE) {
6ec0b75b 183
c4207f97
C
184 // Display a notification to user
185 if (this.videojsDecodeErrors === 0) {
186 options.common.errorNotifier(currentPlayer.localize('The video failed to play, will try to fast forward.'))
2adfc7ea 187 }
a950e4c8 188
c4207f97
C
189 if (this.videojsDecodeErrors === 20) {
190 this.maybeFallbackToWebTorrent('p2p-media-loader', currentPlayer, options)
191 return
2adfc7ea 192 }
39aad8cc 193
42b40636 194 logger.info('Fast forwarding HLS to recover from an error.')
dca0fe12 195
c4207f97 196 this.videojsDecodeErrors++
39aad8cc 197
c4207f97
C
198 options.common.startTime = currentPlayer.currentTime() + 2
199 options.common.autoplay = true
200 this.rebuildAndUpdateVideoElement(currentPlayer, options.common)
39aad8cc 201
c4207f97
C
202 const newPlayer = await this.buildPlayer('p2p-media-loader', options)
203 this.onPlayerChange(newPlayer)
204 } else {
205 this.maybeFallbackToWebTorrent('p2p-media-loader', currentPlayer, options)
2adfc7ea 206 }
39aad8cc
C
207 }
208
c4207f97
C
209 private static async maybeFallbackToWebTorrent (
210 currentMode: PlayerMode,
211 currentPlayer: videojs.Player,
212 options: PeertubePlayerManagerOptions
213 ) {
214 if (options.webtorrent.videoFiles.length === 0 || currentMode === 'webtorrent') {
215 currentPlayer.peertube().displayFatalError()
216 return
1dc240a9
RK
217 }
218
42b40636 219 logger.info('Fallback to webtorrent.')
2adfc7ea 220
c4207f97 221 this.rebuildAndUpdateVideoElement(currentPlayer, options.common)
2adfc7ea 222
57d65032 223 await import('./shared/webtorrent/webtorrent-plugin')
2adfc7ea 224
c4207f97
C
225 const newPlayer = await this.buildPlayer('webtorrent', options)
226 this.onPlayerChange(newPlayer)
2adfc7ea
C
227 }
228
c4207f97
C
229 private static rebuildAndUpdateVideoElement (player: videojs.Player, commonOptions: CommonOptions) {
230 const newVideoElement = document.createElement('video')
eaa5dc31
C
231
232 // Reset class
c4207f97 233 newVideoElement.className = this.playerElementClassName
9162fdd3 234
eaa5dc31
C
235 // Reapply attributes
236 for (const { name, value } of this.playerElementAttributes) {
237 newVideoElement.setAttribute(name, value)
238 }
239
c4207f97
C
240 // VideoJS wraps our video element inside a div
241 let currentParentPlayerElement = commonOptions.playerElement.parentNode
242 // Fix on IOS, don't ask me why
243 if (!currentParentPlayerElement) currentParentPlayerElement = document.getElementById(commonOptions.playerElement.id).parentNode
a472cf03 244
c4207f97 245 currentParentPlayerElement.parentNode.insertBefore(newVideoElement, currentParentPlayerElement)
2adfc7ea 246
c4207f97
C
247 commonOptions.playerElement = newVideoElement
248 commonOptions.onPlayerElementChange(newVideoElement)
ff563914 249
c4207f97 250 player.dispose()
2adfc7ea 251
c4207f97 252 return newVideoElement
2adfc7ea
C
253 }
254
9597920e 255 private static addContextMenu (optionsBuilder: ManagerOptionsBuilder, player: videojs.Player, commonOptions: CommonOptions) {
c4207f97 256 const options = optionsBuilder.getContextMenuOptions(player, commonOptions)
64228474 257
c4207f97 258 player.contextmenuUI(options)
64228474 259 }
2adfc7ea
C
260}
261
262// ############################################################################
263
264export {
265 videojs
266}