]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/assets/player/peertube-videojs-plugin.ts
Automatic resolution according to user bandwidth V1
[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 if (this.torrent === undefined) return
317 if (this.isAutoResolutionOn() === false) return
318 if (this.isAutoResolutionObservation === true) return
319
320 const file = this.getAppropriateFile()
321 let changeResolution = false
322 let changeResolutionDelay = 0
323
324 // Lower resolution
325 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
326 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
327 changeResolution = true
328 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Greater resolution
329 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
330 changeResolution = true
331 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_UPPER_RESOLUTION_DELAY
332 }
333
334 if (changeResolution === true) {
335 this.updateResolution(file.resolution.id, changeResolutionDelay)
336
337 // Wait some seconds in observation of our new resolution
338 this.isAutoResolutionObservation = true
339 setTimeout(() => this.isAutoResolutionObservation = false, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
340 }
341 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
342 }
343
344 private isPlayerWaiting () {
345 return this.player.hasClass('vjs-waiting')
346 }
347
348 private runTorrentInfoScheduler () {
349 this.torrentInfoInterval = setInterval(() => {
350 // Not initialized yet
351 if (this.torrent === undefined) return
352
353 // Http fallback
354 if (this.torrent === null) return this.trigger('torrentInfo', false)
355
356 // webtorrent.downloadSpeed because we need to take into account the potential old torrent too
357 if (webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(webtorrent.downloadSpeed)
358
359 return this.trigger('torrentInfo', {
360 downloadSpeed: this.torrent.downloadSpeed,
361 numPeers: this.torrent.numPeers,
362 uploadSpeed: this.torrent.uploadSpeed
363 })
364 }, this.CONSTANTS.INFO_SCHEDULER)
365 }
366
367 private runViewAdd () {
368 this.clearVideoViewInterval()
369
370 // After 30 seconds (or 3/4 of the video), add a view to the video
371 let minSecondsToView = 30
372
373 if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
374
375 let secondsViewed = 0
376 this.videoViewInterval = setInterval(() => {
377 if (this.player && !this.player.paused()) {
378 secondsViewed += 1
379
380 if (secondsViewed > minSecondsToView) {
381 this.clearVideoViewInterval()
382
383 this.addViewToVideo().catch(err => console.error(err))
384 }
385 }
386 }, 1000)
387 }
388
389 private clearVideoViewInterval () {
390 if (this.videoViewInterval !== undefined) {
391 clearInterval(this.videoViewInterval)
392 this.videoViewInterval = undefined
393 }
394 }
395
396 private addViewToVideo () {
397 return fetch(this.videoViewUrl, { method: 'POST' })
398 }
399
400 private fallbackToHttp (done: Function) {
401 this.flushVideoFile(this.currentVideoFile, true)
402 this.torrent = null
403
404 // Enable error display now this is our last fallback
405 this.player.one('error', () => this.enableErrorDisplay())
406
407 const httpUrl = this.currentVideoFile.fileUrl
408 this.player.src = this.savePlayerSrcFunction
409 this.player.src(httpUrl)
410 this.player.play()
411
412 return done()
413 }
414
415 private handleError (err: Error | string) {
416 return this.player.trigger('customError', { err })
417 }
418
419 private enableErrorDisplay () {
420 this.player.addClass('vjs-error-display-enabled')
421 }
422
423 private disableErrorDisplay () {
424 this.player.removeClass('vjs-error-display-enabled')
425 }
426
427 private alterInactivity () {
428 let saveInactivityTimeout: number
429
430 const disableInactivity = () => {
431 saveInactivityTimeout = this.player.options_.inactivityTimeout
432 this.player.options_.inactivityTimeout = 0
433 }
434 const enableInactivity = () => {
435 this.player.options_.inactivityTimeout = saveInactivityTimeout
436 }
437
438 const settingsDialog = this.player.children_.find(c => c.name_ === 'SettingsDialog')
439
440 this.player.controlBar.on('mouseenter', () => disableInactivity())
441 settingsDialog.on('mouseenter', () => disableInactivity())
442 this.player.controlBar.on('mouseleave', () => enableInactivity())
443 settingsDialog.on('mouseleave', () => enableInactivity())
444 }
445
446 // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
447 private initSmoothProgressBar () {
448 const SeekBar = videojsUntyped.getComponent('SeekBar')
449 SeekBar.prototype.getPercent = function getPercent () {
450 // Allows for smooth scrubbing, when player can't keep up.
451 // const time = (this.player_.scrubbing()) ?
452 // this.player_.getCache().currentTime :
453 // this.player_.currentTime()
454 const time = this.player_.currentTime()
455 const percent = time / this.player_.duration()
456 return percent >= 1 ? 1 : percent
457 }
458 SeekBar.prototype.handleMouseMove = function handleMouseMove (event) {
459 let newTime = this.calculateDistance(event) * this.player_.duration()
460 if (newTime === this.player_.duration()) {
461 newTime = newTime - 0.1
462 }
463 this.player_.currentTime(newTime)
464 this.update()
465 }
466 }
467 }
468
469 videojsUntyped.registerPlugin('peertube', PeerTubePlugin)
470 export { PeerTubePlugin }