]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/assets/player/peertube-player-manager.ts
Merge branch 'release/5.0.0' into develop
[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
536598cf
C
100 let alreadyFallback = false
101
c4207f97
C
102 const handleError = () => {
103 if (alreadyFallback) return
536598cf 104 alreadyFallback = true
536598cf 105
c4207f97
C
106 if (mode === 'p2p-media-loader') {
107 self.tryToRecoverHLSError(player.error(), player, options)
108 } else {
109 self.maybeFallbackToWebTorrent(mode, player, options)
110 }
111 }
112
113 player.one('error', () => handleError())
6ec0b75b 114
9eccae74 115 player.one('play', () => {
c4207f97 116 self.alreadyPlayed = true
9eccae74
C
117 })
118
c4207f97 119 self.addContextMenu(videojsOptionsBuilder, player, options.common)
2adfc7ea 120
f1a0555a 121 if (isMobile()) player.peertubeMobile()
d7b052ff 122 if (options.common.enableHotkeys === true) player.peerTubeHotkeysPlugin()
60f013e1 123 if (options.common.controlBar === false) player.controlBar.addClass('control-bar-hidden')
f1a0555a 124
10475dea 125 player.bezels()
f1a0555a 126
ff563914
RK
127 player.stats({
128 videoUUID: options.common.videoUUID,
129 videoIsLive: options.common.isLive,
95765067
C
130 mode,
131 p2pEnabled: options.common.p2pEnabled
ff563914 132 })
10475dea 133
3e254de8
C
134 player.on('p2pInfo', (_, data: PlayerNetworkInfo) => {
135 if (data.source !== 'p2p-media-loader' || isNaN(data.bandwidthEstimate)) return
136
137 saveAverageBandwidth(data.bandwidthEstimate)
138 })
139
f2a16d93 140 const offlineNotificationElem = document.createElement('div')
141 offlineNotificationElem.classList.add('vjs-peertube-offline-notification')
142 offlineNotificationElem.innerText = player.localize('You seem to be offline and the video may not work')
143
3f9decbd
C
144 let offlineNotificationElemAdded = false
145
f2a16d93 146 const handleOnline = () => {
3f9decbd
C
147 if (!offlineNotificationElemAdded) return
148
f2a16d93 149 player.el().removeChild(offlineNotificationElem)
3f9decbd
C
150 offlineNotificationElemAdded = false
151
f2a16d93 152 logger.info('The browser is online')
153 }
154
155 const handleOffline = () => {
3f9decbd
C
156 if (offlineNotificationElemAdded) return
157
f2a16d93 158 player.el().appendChild(offlineNotificationElem)
3f9decbd
C
159 offlineNotificationElemAdded = true
160
f2a16d93 161 logger.info('The browser is offline')
162 }
163
164 window.addEventListener('online', handleOnline)
165 window.addEventListener('offline', handleOffline)
166
167 player.on('dispose', () => {
168 window.removeEventListener('online', handleOnline)
169 window.removeEventListener('offline', handleOffline)
170 })
171
2adfc7ea
C
172 return res(player)
173 })
174 })
175 }
176
c4207f97 177 private static async tryToRecoverHLSError (err: any, currentPlayer: videojs.Player, options: PeertubePlayerManagerOptions) {
f746622b 178 if (err.code === MediaError.MEDIA_ERR_DECODE) {
6ec0b75b 179
c4207f97
C
180 // Display a notification to user
181 if (this.videojsDecodeErrors === 0) {
182 options.common.errorNotifier(currentPlayer.localize('The video failed to play, will try to fast forward.'))
2adfc7ea 183 }
a950e4c8 184
c4207f97
C
185 if (this.videojsDecodeErrors === 20) {
186 this.maybeFallbackToWebTorrent('p2p-media-loader', currentPlayer, options)
187 return
2adfc7ea 188 }
39aad8cc 189
42b40636 190 logger.info('Fast forwarding HLS to recover from an error.')
dca0fe12 191
c4207f97 192 this.videojsDecodeErrors++
39aad8cc 193
c4207f97
C
194 options.common.startTime = currentPlayer.currentTime() + 2
195 options.common.autoplay = true
196 this.rebuildAndUpdateVideoElement(currentPlayer, options.common)
39aad8cc 197
c4207f97
C
198 const newPlayer = await this.buildPlayer('p2p-media-loader', options)
199 this.onPlayerChange(newPlayer)
200 } else {
201 this.maybeFallbackToWebTorrent('p2p-media-loader', currentPlayer, options)
2adfc7ea 202 }
39aad8cc
C
203 }
204
c4207f97
C
205 private static async maybeFallbackToWebTorrent (
206 currentMode: PlayerMode,
207 currentPlayer: videojs.Player,
208 options: PeertubePlayerManagerOptions
209 ) {
210 if (options.webtorrent.videoFiles.length === 0 || currentMode === 'webtorrent') {
211 currentPlayer.peertube().displayFatalError()
212 return
1dc240a9
RK
213 }
214
42b40636 215 logger.info('Fallback to webtorrent.')
2adfc7ea 216
c4207f97 217 this.rebuildAndUpdateVideoElement(currentPlayer, options.common)
2adfc7ea 218
57d65032 219 await import('./shared/webtorrent/webtorrent-plugin')
2adfc7ea 220
c4207f97
C
221 const newPlayer = await this.buildPlayer('webtorrent', options)
222 this.onPlayerChange(newPlayer)
2adfc7ea
C
223 }
224
c4207f97
C
225 private static rebuildAndUpdateVideoElement (player: videojs.Player, commonOptions: CommonOptions) {
226 const newVideoElement = document.createElement('video')
eaa5dc31
C
227
228 // Reset class
c4207f97 229 newVideoElement.className = this.playerElementClassName
9162fdd3 230
eaa5dc31
C
231 // Reapply attributes
232 for (const { name, value } of this.playerElementAttributes) {
233 newVideoElement.setAttribute(name, value)
234 }
235
c4207f97
C
236 // VideoJS wraps our video element inside a div
237 let currentParentPlayerElement = commonOptions.playerElement.parentNode
238 // Fix on IOS, don't ask me why
239 if (!currentParentPlayerElement) currentParentPlayerElement = document.getElementById(commonOptions.playerElement.id).parentNode
a472cf03 240
c4207f97 241 currentParentPlayerElement.parentNode.insertBefore(newVideoElement, currentParentPlayerElement)
2adfc7ea 242
c4207f97
C
243 commonOptions.playerElement = newVideoElement
244 commonOptions.onPlayerElementChange(newVideoElement)
ff563914 245
c4207f97 246 player.dispose()
2adfc7ea 247
c4207f97 248 return newVideoElement
2adfc7ea
C
249 }
250
9597920e 251 private static addContextMenu (optionsBuilder: ManagerOptionsBuilder, player: videojs.Player, commonOptions: CommonOptions) {
c4207f97 252 const options = optionsBuilder.getContextMenuOptions(player, commonOptions)
64228474 253
c4207f97 254 player.contextmenuUI(options)
64228474 255 }
2adfc7ea
C
256}
257
258// ############################################################################
259
260export {
261 videojs
262}