]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/assets/player/peertube-videojs-plugin.ts
Fix auto quality with http fallback
[github/Chocobozzz/PeerTube.git] / client / src / assets / player / peertube-videojs-plugin.ts
1 import * as videojs from 'video.js'
2 import * as WebTorrent from 'webtorrent'
3 import { VideoFile } from '../../../../shared/models/videos/video.model'
4 import { renderVideo } from './video-renderer'
5 import './settings-menu-button'
6 import { PeertubePluginOptions, VideoJSComponentInterface, videojsUntyped } from './peertube-videojs-typings'
7 import {
8 getAverageBandwidth,
9 getStoredMute,
10 getStoredVolume,
11 saveAverageBandwidth,
12 saveMuteInStore,
13 saveVolumeInStore
14 } from './utils'
15 import minBy from 'lodash-es/minBy'
16 import maxBy from 'lodash-es/maxBy'
17
18 const webtorrent = new WebTorrent({
19 tracker: {
20 rtcConfig: {
21 iceServers: [
22 {
23 urls: 'stun:stun.stunprotocol.org'
24 },
25 {
26 urls: 'stun:stun.framasoft.org'
27 }
28 ]
29 }
30 },
31 dht: false
32 })
33
34 const Plugin: VideoJSComponentInterface = videojsUntyped.getPlugin('plugin')
35 class PeerTubePlugin extends Plugin {
36 private readonly playerElement: HTMLVideoElement
37
38 private readonly autoplay: boolean = false
39 private readonly savePlayerSrcFunction: Function
40 private readonly videoFiles: VideoFile[]
41 private readonly videoViewUrl: string
42 private readonly videoDuration: number
43 private readonly CONSTANTS = {
44 INFO_SCHEDULER: 1000, // Don't change this
45 AUTO_QUALITY_SCHEDULER: 3000, // Check quality every 3 seconds
46 AUTO_QUALITY_THRESHOLD_PERCENT: 30, // Bandwidth should be 30% more important than a resolution bitrate to change to it
47 AUTO_QUALITY_OBSERVATION_TIME: 10000, // Wait 10 seconds before potentially changing the definition
48 AUTO_QUALITY_UPPER_RESOLUTION_DELAY: 5000, // Buffer upper resolution during 5 seconds
49 BANDWIDTH_AVERAGE_NUMBER_OF_VALUES: 5 // Last 5 seconds to build average bandwidth
50 }
51
52 private player: any
53 private currentVideoFile: VideoFile
54 private torrent: WebTorrent.Torrent
55 private videoViewInterval
56 private torrentInfoInterval
57 private autoQualityInterval
58 private autoResolution = true
59 private isAutoResolutionObservation = false
60
61 private downloadSpeeds: number[] = []
62
63 constructor (player: videojs.Player, options: PeertubePluginOptions) {
64 super(player, options)
65
66 // Fix canplay event on google chrome by disabling default videojs autoplay
67 this.autoplay = this.player.options_.autoplay
68 this.player.options_.autoplay = false
69
70 this.videoFiles = options.videoFiles
71 this.videoViewUrl = options.videoViewUrl
72 this.videoDuration = options.videoDuration
73
74 this.savePlayerSrcFunction = this.player.src
75 // Hack to "simulate" src link in video.js >= 6
76 // Without this, we can't play the video after pausing it
77 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
78 this.player.src = () => true
79
80 this.playerElement = options.playerElement
81
82 this.player.ready(() => {
83 const volume = getStoredVolume()
84 if (volume !== undefined) this.player.volume(volume)
85 const muted = getStoredMute()
86 if (muted !== undefined) this.player.muted(muted)
87
88 this.initializePlayer()
89 this.runTorrentInfoScheduler()
90 this.runViewAdd()
91
92 this.player.one('play', () => {
93 // Don't run immediately scheduler, wait some seconds the TCP connections are maid
94 setTimeout(() => this.runAutoQualityScheduler(), this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
95 })
96 })
97
98 this.player.on('volumechange', () => {
99 saveVolumeInStore(this.player.volume())
100 saveMuteInStore(this.player.muted())
101 })
102 }
103
104 dispose () {
105 clearInterval(this.videoViewInterval)
106 clearInterval(this.torrentInfoInterval)
107 clearInterval(this.autoQualityInterval)
108
109 // Don't need to destroy renderer, video player will be destroyed
110 this.flushVideoFile(this.currentVideoFile, false)
111 }
112
113 getCurrentResolutionId () {
114 return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
115 }
116
117 getCurrentResolutionLabel () {
118 return this.currentVideoFile ? this.currentVideoFile.resolution.label : ''
119 }
120
121 updateVideoFile (videoFile?: VideoFile, delay = 0, done?: () => void) {
122 if (done === undefined) {
123 done = () => { /* empty */ }
124 }
125
126 // Automatically choose the adapted video file
127 if (videoFile === undefined) {
128 const savedAverageBandwidth = getAverageBandwidth()
129 videoFile = savedAverageBandwidth
130 ? this.getAppropriateFile(savedAverageBandwidth)
131 : this.videoFiles[0]
132 }
133
134 // Don't add the same video file once again
135 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
136 return
137 }
138
139 // Do not display error to user because we will have multiple fallback
140 this.disableErrorDisplay()
141
142 this.player.src = () => true
143 const oldPlaybackRate = this.player.playbackRate()
144
145 const previousVideoFile = this.currentVideoFile
146 this.currentVideoFile = videoFile
147
148 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, delay, () => {
149 this.player.playbackRate(oldPlaybackRate)
150 return done()
151 })
152
153 this.trigger('videoFileUpdate')
154 }
155
156 addTorrent (magnetOrTorrentUrl: string, previousVideoFile: VideoFile, delay = 0, done: Function) {
157 console.log('Adding ' + magnetOrTorrentUrl + '.')
158
159 const oldTorrent = this.torrent
160 this.torrent = webtorrent.add(magnetOrTorrentUrl, torrent => {
161 console.log('Added ' + magnetOrTorrentUrl + '.')
162
163 // Pause the old torrent
164 if (oldTorrent) {
165 oldTorrent.pause()
166 // Pause does not remove actual peers (in particular the webseed peer)
167 oldTorrent.removePeer(oldTorrent['ws'])
168 }
169
170 setTimeout(() => {
171 this.flushVideoFile(previousVideoFile)
172
173 const options = { autoplay: true, controls: true }
174 renderVideo(torrent.files[0], this.playerElement, options,(err, renderer) => {
175 this.renderer = renderer
176
177 if (err) return this.fallbackToHttp(done)
178
179 if (!this.player.paused()) {
180 const playPromise = this.player.play()
181 if (playPromise !== undefined) return playPromise.then(done)
182
183 return done()
184 }
185
186 return done()
187 })
188 }, delay)
189 })
190
191 this.torrent.on('error', err => this.handleError(err))
192
193 this.torrent.on('warning', (err: any) => {
194 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
195 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
196
197 // Users don't care about issues with WebRTC, but developers do so log it in the console
198 if (err.message.indexOf('Ice connection failed') !== -1) {
199 console.error(err)
200 return
201 }
202
203 // Magnet hash is not up to date with the torrent file, add directly the torrent file
204 if (err.message.indexOf('incorrect info hash') !== -1) {
205 console.error('Incorrect info hash detected, falling back to torrent file.')
206 return this.addTorrent(this.torrent['xs'], previousVideoFile, 0, done)
207 }
208
209 return this.handleError(err)
210 })
211 }
212
213 updateResolution (resolutionId: number, delay = 0) {
214 // Remember player state
215 const currentTime = this.player.currentTime()
216 const isPaused = this.player.paused()
217
218 // Remove poster to have black background
219 this.playerElement.poster = ''
220
221 // Hide bigPlayButton
222 if (!isPaused) {
223 this.player.bigPlayButton.hide()
224 }
225
226 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
227 this.updateVideoFile(newVideoFile, delay, () => {
228 this.player.currentTime(currentTime)
229 this.player.handleTechSeeked_()
230 })
231 }
232
233 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
234 if (videoFile !== undefined && webtorrent.get(videoFile.magnetUri)) {
235 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
236
237 webtorrent.remove(videoFile.magnetUri)
238 console.log('Removed ' + videoFile.magnetUri)
239 }
240 }
241
242 isAutoResolutionOn () {
243 return this.autoResolution
244 }
245
246 enableAutoResolution () {
247 this.autoResolution = true
248 this.trigger('autoResolutionUpdate')
249 }
250
251 disableAutoResolution () {
252 this.autoResolution = false
253 this.trigger('autoResolutionUpdate')
254 }
255
256 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
257 if (this.videoFiles === undefined || this.videoFiles.length === 0) return undefined
258 if (this.videoFiles.length === 1) return this.videoFiles[0]
259 if (this.torrent && this.torrent.progress === 1) return this.currentVideoFile
260
261 if (!averageDownloadSpeed) averageDownloadSpeed = this.getActualDownloadSpeed()
262
263 // Filter videos we can play according to our bandwidth
264 const filteredFiles = this.videoFiles.filter(f => {
265 const fileBitrate = (f.size / this.videoDuration)
266 let threshold = fileBitrate
267
268 // If this is for a higher resolution, or an initial load -> add a upper margin
269 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
270 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
271 }
272
273 return averageDownloadSpeed > threshold
274 })
275
276 // If the download speed is too bad, return the lowest resolution we have
277 if (filteredFiles.length === 0) return minBy(this.videoFiles, 'resolution.id')
278
279 return maxBy(filteredFiles, 'resolution.id')
280 }
281
282 private getActualDownloadSpeed () {
283 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
284 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
285 if (lastDownloadSpeeds.length === 0) return -1
286
287 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
288 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
289
290 // Save the average bandwidth for future use
291 saveAverageBandwidth(averageBandwidth)
292
293 return averageBandwidth
294 }
295
296 private initializePlayer () {
297 this.initSmoothProgressBar()
298
299 this.alterInactivity()
300
301 if (this.autoplay === true) {
302 this.player.posterImage.hide()
303 this.updateVideoFile(undefined, 0, () => this.player.play())
304 } else {
305 // Proxy first play
306 const oldPlay = this.player.play.bind(this.player)
307 this.player.play = () => {
308 this.updateVideoFile(undefined, 0, () => oldPlay)
309 this.player.play = oldPlay
310 }
311 }
312 }
313
314 private runAutoQualityScheduler () {
315 this.autoQualityInterval = setInterval(() => {
316 // Not initialized or in HTTP fallback
317 if (this.torrent === undefined || this.torrent === null) return
318 if (this.isAutoResolutionOn() === false) return
319 if (this.isAutoResolutionObservation === true) return
320
321 const file = this.getAppropriateFile()
322 let changeResolution = false
323 let changeResolutionDelay = 0
324
325 // Lower resolution
326 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
327 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
328 changeResolution = true
329 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Greater resolution
330 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
331 changeResolution = true
332 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_UPPER_RESOLUTION_DELAY
333 }
334
335 if (changeResolution === true) {
336 this.updateResolution(file.resolution.id, changeResolutionDelay)
337
338 // Wait some seconds in observation of our new resolution
339 this.isAutoResolutionObservation = true
340 setTimeout(() => this.isAutoResolutionObservation = false, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
341 }
342 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
343 }
344
345 private isPlayerWaiting () {
346 return this.player.hasClass('vjs-waiting')
347 }
348
349 private runTorrentInfoScheduler () {
350 this.torrentInfoInterval = setInterval(() => {
351 // Not initialized yet
352 if (this.torrent === undefined) return
353
354 // Http fallback
355 if (this.torrent === null) return this.trigger('torrentInfo', false)
356
357 // webtorrent.downloadSpeed because we need to take into account the potential old torrent too
358 if (webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(webtorrent.downloadSpeed)
359
360 return this.trigger('torrentInfo', {
361 downloadSpeed: this.torrent.downloadSpeed,
362 numPeers: this.torrent.numPeers,
363 uploadSpeed: this.torrent.uploadSpeed
364 })
365 }, this.CONSTANTS.INFO_SCHEDULER)
366 }
367
368 private runViewAdd () {
369 this.clearVideoViewInterval()
370
371 // After 30 seconds (or 3/4 of the video), add a view to the video
372 let minSecondsToView = 30
373
374 if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
375
376 let secondsViewed = 0
377 this.videoViewInterval = setInterval(() => {
378 if (this.player && !this.player.paused()) {
379 secondsViewed += 1
380
381 if (secondsViewed > minSecondsToView) {
382 this.clearVideoViewInterval()
383
384 this.addViewToVideo().catch(err => console.error(err))
385 }
386 }
387 }, 1000)
388 }
389
390 private clearVideoViewInterval () {
391 if (this.videoViewInterval !== undefined) {
392 clearInterval(this.videoViewInterval)
393 this.videoViewInterval = undefined
394 }
395 }
396
397 private addViewToVideo () {
398 return fetch(this.videoViewUrl, { method: 'POST' })
399 }
400
401 private fallbackToHttp (done: Function) {
402 this.flushVideoFile(this.currentVideoFile, true)
403 this.torrent = null
404
405 // Enable error display now this is our last fallback
406 this.player.one('error', () => this.enableErrorDisplay())
407
408 const httpUrl = this.currentVideoFile.fileUrl
409 this.player.src = this.savePlayerSrcFunction
410 this.player.src(httpUrl)
411 this.player.play()
412
413 return done()
414 }
415
416 private handleError (err: Error | string) {
417 return this.player.trigger('customError', { err })
418 }
419
420 private enableErrorDisplay () {
421 this.player.addClass('vjs-error-display-enabled')
422 }
423
424 private disableErrorDisplay () {
425 this.player.removeClass('vjs-error-display-enabled')
426 }
427
428 private alterInactivity () {
429 let saveInactivityTimeout: number
430
431 const disableInactivity = () => {
432 saveInactivityTimeout = this.player.options_.inactivityTimeout
433 this.player.options_.inactivityTimeout = 0
434 }
435 const enableInactivity = () => {
436 this.player.options_.inactivityTimeout = saveInactivityTimeout
437 }
438
439 const settingsDialog = this.player.children_.find(c => c.name_ === 'SettingsDialog')
440
441 this.player.controlBar.on('mouseenter', () => disableInactivity())
442 settingsDialog.on('mouseenter', () => disableInactivity())
443 this.player.controlBar.on('mouseleave', () => enableInactivity())
444 settingsDialog.on('mouseleave', () => enableInactivity())
445 }
446
447 // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
448 private initSmoothProgressBar () {
449 const SeekBar = videojsUntyped.getComponent('SeekBar')
450 SeekBar.prototype.getPercent = function getPercent () {
451 // Allows for smooth scrubbing, when player can't keep up.
452 // const time = (this.player_.scrubbing()) ?
453 // this.player_.getCache().currentTime :
454 // this.player_.currentTime()
455 const time = this.player_.currentTime()
456 const percent = time / this.player_.duration()
457 return percent >= 1 ? 1 : percent
458 }
459 SeekBar.prototype.handleMouseMove = function handleMouseMove (event) {
460 let newTime = this.calculateDistance(event) * this.player_.duration()
461 if (newTime === this.player_.duration()) {
462 newTime = newTime - 0.1
463 }
464 this.player_.currentTime(newTime)
465 this.update()
466 }
467 }
468 }
469
470 videojsUntyped.registerPlugin('peertube', PeerTubePlugin)
471 export { PeerTubePlugin }