]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/assets/player/peertube-videojs-plugin.ts
[#766] Fix the change of speed when quality changes
[github/Chocobozzz/PeerTube.git] / client / src / assets / player / peertube-videojs-plugin.ts
CommitLineData
63c4db6d 1import * as videojs from 'video.js'
aa8b6df4 2import * as WebTorrent from 'webtorrent'
b6827820 3import { VideoFile } from '../../../../shared/models/videos/video.model'
aa8b6df4 4import { renderVideo } from './video-renderer'
c6352f2c
C
5import './settings-menu-button'
6import { PeertubePluginOptions, VideoJSComponentInterface, videojsUntyped } from './peertube-videojs-typings'
7b3a99d5
C
7import { isMobile, videoFileMaxByResolution, videoFileMinByResolution } from './utils'
8import * as CacheChunkStore from 'cache-chunk-store'
9import { PeertubeChunkStore } from './peertube-chunk-store'
6cca7360 10import {
7b3a99d5 11 getAverageBandwidthInStore,
6cca7360 12 getStoredMute,
7b3a99d5 13 getStoredVolume,
6cca7360
C
14 saveAverageBandwidth,
15 saveMuteInStore,
7b3a99d5
C
16 saveVolumeInStore
17} from './peertube-player-local-storage'
be6a4802 18
b7f1747d 19const Plugin: VideoJSComponentInterface = videojs.getPlugin('plugin')
a22bfc3e 20class PeerTubePlugin extends Plugin {
c6352f2c 21 private readonly playerElement: HTMLVideoElement
a8462c8e 22
c6352f2c 23 private readonly autoplay: boolean = false
f37bad63 24 private readonly startTime: number = 0
c6352f2c 25 private readonly savePlayerSrcFunction: Function
a8462c8e
C
26 private readonly videoFiles: VideoFile[]
27 private readonly videoViewUrl: string
28 private readonly videoDuration: number
29 private readonly CONSTANTS = {
30 INFO_SCHEDULER: 1000, // Don't change this
31 AUTO_QUALITY_SCHEDULER: 3000, // Check quality every 3 seconds
32 AUTO_QUALITY_THRESHOLD_PERCENT: 30, // Bandwidth should be 30% more important than a resolution bitrate to change to it
7ee4a4af
C
33 AUTO_QUALITY_OBSERVATION_TIME: 10000, // Wait 10 seconds after having change the resolution before another check
34 AUTO_QUALITY_HIGHER_RESOLUTION_DELAY: 5000, // Buffering higher resolution during 5 seconds
a8462c8e
C
35 BANDWIDTH_AVERAGE_NUMBER_OF_VALUES: 5 // Last 5 seconds to build average bandwidth
36 }
37
b7f1747d
C
38 private readonly webtorrent = new WebTorrent({
39 tracker: {
40 rtcConfig: {
41 iceServers: [
42 {
43 urls: 'stun:stun.stunprotocol.org'
44 },
45 {
46 urls: 'stun:stun.framasoft.org'
47 }
48 ]
49 }
50 },
51 dht: false
52 })
53
a22bfc3e
C
54 private player: any
55 private currentVideoFile: VideoFile
a22bfc3e 56 private torrent: WebTorrent.Torrent
b7f1747d 57 private renderer
054a103b 58 private fakeRenderer
7ee4a4af 59 private autoResolution = true
c4082b8b 60 private forbidAutoResolution = false
7ee4a4af
C
61 private isAutoResolutionObservation = false
62
8cac1b64 63 private videoViewInterval
3bcfff7f 64 private torrentInfoInterval
a8462c8e 65 private autoQualityInterval
7ee4a4af
C
66 private addTorrentDelay
67 private qualityObservationTimer
68 private runAutoQualitySchedulerTimer
a8462c8e
C
69
70 private downloadSpeeds: number[] = []
a22bfc3e 71
339632b4 72 constructor (player: videojs.Player, options: PeertubePluginOptions) {
a22bfc3e
C
73 super(player, options)
74
e7eb5b39
C
75 // Disable auto play on iOS
76 this.autoplay = options.autoplay && this.isIOS() === false
481d3596 77
f37bad63 78 this.startTime = options.startTime
a22bfc3e 79 this.videoFiles = options.videoFiles
8cac1b64 80 this.videoViewUrl = options.videoViewUrl
3bcfff7f 81 this.videoDuration = options.videoDuration
a22bfc3e 82
bf5685f0 83 this.savePlayerSrcFunction = this.player.src
a22bfc3e
C
84 // Hack to "simulate" src link in video.js >= 6
85 // Without this, we can't play the video after pausing it
86 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
bf5685f0 87 this.player.src = () => true
a22bfc3e
C
88
89 this.playerElement = options.playerElement
90
e6f62797
C
91 if (this.autoplay === true) this.player.addClass('vjs-has-autoplay')
92
a22bfc3e 93 this.player.ready(() => {
c6352f2c
C
94 const volume = getStoredVolume()
95 if (volume !== undefined) this.player.volume(volume)
96 const muted = getStoredMute()
97 if (muted !== undefined) this.player.muted(muted)
98
0dcf9a14 99 this.initializePlayer()
a22bfc3e 100 this.runTorrentInfoScheduler()
3bcfff7f 101 this.runViewAdd()
a8462c8e
C
102
103 this.player.one('play', () => {
f37bad63 104 // Don't run immediately scheduler, wait some seconds the TCP connections are made
7ee4a4af
C
105 this.runAutoQualitySchedulerTimer = setTimeout(() => {
106 this.runAutoQualityScheduler()
107 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
a8462c8e 108 })
a22bfc3e 109 })
c6352f2c
C
110
111 this.player.on('volumechange', () => {
112 saveVolumeInStore(this.player.volume())
113 saveMuteInStore(this.player.muted())
114 })
a22bfc3e
C
115 }
116
117 dispose () {
7ee4a4af
C
118 clearTimeout(this.addTorrentDelay)
119 clearTimeout(this.qualityObservationTimer)
120 clearTimeout(this.runAutoQualitySchedulerTimer)
121
3bcfff7f
C
122 clearInterval(this.videoViewInterval)
123 clearInterval(this.torrentInfoInterval)
a8462c8e 124 clearInterval(this.autoQualityInterval)
3bcfff7f 125
a22bfc3e
C
126 // Don't need to destroy renderer, video player will be destroyed
127 this.flushVideoFile(this.currentVideoFile, false)
054a103b
C
128
129 this.destroyFakeRenderer()
aa8b6df4
C
130 }
131
09700934
C
132 getCurrentResolutionId () {
133 return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
aa8b6df4
C
134 }
135
a22bfc3e 136 getCurrentResolutionLabel () {
395ecf70
C
137 if (!this.currentVideoFile) return ''
138
139 const fps = this.currentVideoFile.fps >= 50 ? this.currentVideoFile.fps : ''
140 return this.currentVideoFile.resolution.label + fps
aa8b6df4
C
141 }
142
3baf9be2
C
143 updateVideoFile (
144 videoFile?: VideoFile,
145 options: {
146 forcePlay?: boolean,
147 seek?: number,
148 delay?: number
149 } = {},
150 done: () => void = () => { /* empty */ }
151 ) {
a8462c8e 152 // Automatically choose the adapted video file
aa8b6df4 153 if (videoFile === undefined) {
7b3a99d5 154 const savedAverageBandwidth = getAverageBandwidthInStore()
a8462c8e
C
155 videoFile = savedAverageBandwidth
156 ? this.getAppropriateFile(savedAverageBandwidth)
8eb8bc20 157 : this.pickAverageVideoFile()
aa8b6df4
C
158 }
159
160 // Don't add the same video file once again
a22bfc3e 161 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
aa8b6df4
C
162 return
163 }
164
c6352f2c 165 // Do not display error to user because we will have multiple fallback
bf5685f0 166 this.disableErrorDisplay()
1198a08c 167
bf5685f0 168 this.player.src = () => true
c6352f2c 169 const oldPlaybackRate = this.player.playbackRate()
bf5685f0 170
a22bfc3e
C
171 const previousVideoFile = this.currentVideoFile
172 this.currentVideoFile = videoFile
aa8b6df4 173
3baf9be2 174 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, options, () => {
c6352f2c
C
175 this.player.playbackRate(oldPlaybackRate)
176 return done()
177 })
a216c623
C
178
179 this.trigger('videoFileUpdate')
180 }
181
3baf9be2
C
182 addTorrent (
183 magnetOrTorrentUrl: string,
184 previousVideoFile: VideoFile,
185 options: {
186 forcePlay?: boolean,
187 seek?: number,
188 delay?: number
189 },
190 done: Function
191 ) {
a216c623
C
192 console.log('Adding ' + magnetOrTorrentUrl + '.')
193
a8462c8e 194 const oldTorrent = this.torrent
3baf9be2 195 const torrentOptions = {
efda99c3
C
196 store: (chunkLength, storeOpts) => new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
197 max: 100
198 })
199 }
200
b7f1747d 201 this.torrent = this.webtorrent.add(magnetOrTorrentUrl, torrentOptions, torrent => {
a216c623 202 console.log('Added ' + magnetOrTorrentUrl + '.')
aa8b6df4 203
a8462c8e 204 if (oldTorrent) {
4a7591e1 205 // Pause the old torrent
a8462c8e
C
206 oldTorrent.pause()
207 // Pause does not remove actual peers (in particular the webseed peer)
208 oldTorrent.removePeer(oldTorrent['ws'])
6d272f39
C
209
210 // We use a fake renderer so we download correct pieces of the next file
6d272f39
C
211 if (options.delay) {
212 const fakeVideoElem = document.createElement('video')
213 renderVideo(torrent.files[0], fakeVideoElem, { autoplay: false, controls: false }, (err, renderer) => {
054a103b 214 this.fakeRenderer = renderer
6d272f39 215
4a7591e1 216 if (err) console.error('Cannot render new torrent in fake video element.', err)
6d272f39
C
217
218 // Load the future file at the correct time
219 fakeVideoElem.currentTime = this.player.currentTime() + (options.delay / 2000)
220 })
221 }
a8462c8e 222 }
aa8b6df4 223
e7eb5b39 224 // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
7ee4a4af 225 this.addTorrentDelay = setTimeout(() => {
054a103b 226 this.destroyFakeRenderer()
6d272f39 227
3baf9be2
C
228 const paused = this.player.paused()
229
a8462c8e 230 this.flushVideoFile(previousVideoFile)
0dcf9a14 231
3baf9be2
C
232 const renderVideoOptions = { autoplay: false, controls: true }
233 renderVideo(torrent.files[0], this.playerElement, renderVideoOptions,(err, renderer) => {
a8462c8e 234 this.renderer = renderer
aa8b6df4 235
a8462c8e 236 if (err) return this.fallbackToHttp(done)
3bcfff7f 237
3baf9be2
C
238 return this.tryToPlay(err => {
239 if (err) return done(err)
a8462c8e 240
3baf9be2
C
241 if (options.seek) this.seek(options.seek)
242 if (options.forcePlay === false && paused === true) this.player.pause()
8244e187
GR
243
244 return done(err)
3baf9be2 245 })
a8462c8e 246 })
3baf9be2 247 }, options.delay || 0)
aa8b6df4
C
248 })
249
332e7032 250 this.torrent.on('error', err => console.error(err))
a216c623 251
a22bfc3e 252 this.torrent.on('warning', (err: any) => {
a96aed15 253 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
531ab5b6 254 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
a216c623 255
7dbdc3ba
C
256 // Users don't care about issues with WebRTC, but developers do so log it in the console
257 if (err.message.indexOf('Ice connection failed') !== -1) {
332e7032 258 console.log(err)
7dbdc3ba
C
259 return
260 }
a96aed15 261
a216c623
C
262 // Magnet hash is not up to date with the torrent file, add directly the torrent file
263 if (err.message.indexOf('incorrect info hash') !== -1) {
264 console.error('Incorrect info hash detected, falling back to torrent file.')
3baf9be2
C
265 const options = { forcePlay: true }
266 return this.addTorrent(this.torrent['xs'], previousVideoFile, options, done)
a216c623
C
267 }
268
332e7032 269 return console.warn(err)
a96aed15 270 })
aa8b6df4
C
271 }
272
a8462c8e 273 updateResolution (resolutionId: number, delay = 0) {
aa8b6df4 274 // Remember player state
a22bfc3e
C
275 const currentTime = this.player.currentTime()
276 const isPaused = this.player.paused()
aa8b6df4 277
531ab5b6
C
278 // Remove poster to have black background
279 this.playerElement.poster = ''
280
aa8b6df4 281 // Hide bigPlayButton
8fa5653a 282 if (!isPaused) {
a22bfc3e 283 this.player.bigPlayButton.hide()
aa8b6df4
C
284 }
285
09700934 286 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
3baf9be2
C
287 const options = {
288 forcePlay: false,
289 delay,
91d95589 290 seek: currentTime + (delay / 1000)
3baf9be2
C
291 }
292 this.updateVideoFile(newVideoFile, options)
aa8b6df4
C
293 }
294
a22bfc3e 295 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
b7f1747d 296 if (videoFile !== undefined && this.webtorrent.get(videoFile.magnetUri)) {
bf5685f0
C
297 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
298
b7f1747d 299 this.webtorrent.remove(videoFile.magnetUri)
a22bfc3e 300 console.log('Removed ' + videoFile.magnetUri)
aa8b6df4
C
301 }
302 }
303
a8462c8e
C
304 isAutoResolutionOn () {
305 return this.autoResolution
306 }
307
308 enableAutoResolution () {
309 this.autoResolution = true
310 this.trigger('autoResolutionUpdate')
311 }
312
c4082b8b
C
313 disableAutoResolution (forbid = false) {
314 if (forbid === true) this.forbidAutoResolution = true
315
a8462c8e
C
316 this.autoResolution = false
317 this.trigger('autoResolutionUpdate')
318 }
319
c4082b8b
C
320 isAutoResolutionForbidden () {
321 return this.forbidAutoResolution === true
322 }
323
960a11e8
C
324 getCurrentVideoFile () {
325 return this.currentVideoFile
326 }
327
77728efa
C
328 getTorrent () {
329 return this.torrent
330 }
331
80109b2d
C
332 private tryToPlay (done?: Function) {
333 if (!done) done = function () { /* empty */ }
1fad099d 334
80109b2d
C
335 const playPromise = this.player.play()
336 if (playPromise !== undefined) {
337 return playPromise.then(done)
338 .catch(err => {
70b40c2e
C
339 if (err.message.indexOf('The play() request was interrupted by a call to pause()') !== -1) {
340 return
341 }
342
80109b2d
C
343 console.error(err)
344 this.player.pause()
345 this.player.posterImage.show()
346 this.player.removeClass('vjs-has-autoplay')
91d95589 347 this.player.removeClass('vjs-has-big-play-button-clicked')
80109b2d
C
348
349 return done()
350 })
351 }
352
353 return done()
354 }
355
f37bad63
C
356 private seek (time: number) {
357 this.player.currentTime(time)
358 this.player.handleTechSeeked_()
359 }
360
a8462c8e
C
361 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
362 if (this.videoFiles === undefined || this.videoFiles.length === 0) return undefined
363 if (this.videoFiles.length === 1) return this.videoFiles[0]
a8462c8e 364
3c40590d
C
365 // Don't change the torrent is the play was ended
366 if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
367
368 if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
a8462c8e 369
06aa2726
NS
370 // Filter videos we can play according to our screen resolution and bandwidth
371 const filteredFiles = this.videoFiles.filter(f => f.resolution.id <= this.playerElement.width)
372 .filter(f => {
a8462c8e
C
373 const fileBitrate = (f.size / this.videoDuration)
374 let threshold = fileBitrate
375
7ee4a4af 376 // If this is for a higher resolution or an initial load: add a margin
a8462c8e
C
377 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
378 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
379 }
380
381 return averageDownloadSpeed > threshold
382 })
383
384 // If the download speed is too bad, return the lowest resolution we have
6cca7360 385 if (filteredFiles.length === 0) return videoFileMinByResolution(this.videoFiles)
a8462c8e 386
6cca7360 387 return videoFileMaxByResolution(filteredFiles)
a8462c8e
C
388 }
389
3c40590d 390 private getAndSaveActualDownloadSpeed () {
a8462c8e
C
391 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
392 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
393 if (lastDownloadSpeeds.length === 0) return -1
394
395 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
396 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
397
398 // Save the average bandwidth for future use
399 saveAverageBandwidth(averageBandwidth)
ed9f9f5f 400
a8462c8e 401 return averageBandwidth
ed9f9f5f
C
402 }
403
0dcf9a14 404 private initializePlayer () {
2ce2fd7f
C
405 if (isMobile()) this.player.addClass('vjs-is-mobile')
406
e993ecb3
C
407 this.initSmoothProgressBar()
408
c6352f2c
C
409 this.alterInactivity()
410
481d3596 411 if (this.autoplay === true) {
33d78552 412 this.player.posterImage.hide()
e6f62797 413
3baf9be2 414 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
aa8b6df4 415 } else {
e7eb5b39
C
416 // Don't try on iOS that does not support MediaSource
417 if (this.isIOS()) {
8eb8bc20 418 this.currentVideoFile = this.pickAverageVideoFile()
e7eb5b39
C
419 return this.fallbackToHttp(undefined, false)
420 }
421
b891f9bc 422 // Proxy first play
c6352f2c
C
423 const oldPlay = this.player.play.bind(this.player)
424 this.player.play = () => {
864e782b 425 this.player.addClass('vjs-has-big-play-button-clicked')
c6352f2c 426 this.player.play = oldPlay
864e782b 427
3baf9be2 428 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
c6352f2c 429 }
aa8b6df4 430 }
a22bfc3e 431 }
aa8b6df4 432
a8462c8e
C
433 private runAutoQualityScheduler () {
434 this.autoQualityInterval = setInterval(() => {
7ee4a4af 435
877b0528
C
436 // Not initialized or in HTTP fallback
437 if (this.torrent === undefined || this.torrent === null) return
a8462c8e
C
438 if (this.isAutoResolutionOn() === false) return
439 if (this.isAutoResolutionObservation === true) return
440
441 const file = this.getAppropriateFile()
442 let changeResolution = false
443 let changeResolutionDelay = 0
444
445 // Lower resolution
446 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
447 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
448 changeResolution = true
7ee4a4af 449 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
a8462c8e
C
450 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
451 changeResolution = true
7ee4a4af 452 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
a8462c8e
C
453 }
454
455 if (changeResolution === true) {
456 this.updateResolution(file.resolution.id, changeResolutionDelay)
457
458 // Wait some seconds in observation of our new resolution
459 this.isAutoResolutionObservation = true
7ee4a4af
C
460
461 this.qualityObservationTimer = setTimeout(() => {
462 this.isAutoResolutionObservation = false
463 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
a8462c8e
C
464 }
465 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
466 }
467
468 private isPlayerWaiting () {
7ee4a4af 469 return this.player && this.player.hasClass('vjs-waiting')
a8462c8e
C
470 }
471
a22bfc3e 472 private runTorrentInfoScheduler () {
3bcfff7f 473 this.torrentInfoInterval = setInterval(() => {
bf5685f0
C
474 // Not initialized yet
475 if (this.torrent === undefined) return
476
477 // Http fallback
478 if (this.torrent === null) return this.trigger('torrentInfo', false)
479
b7f1747d
C
480 // this.webtorrent.downloadSpeed because we need to take into account the potential old torrent too
481 if (this.webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(this.webtorrent.downloadSpeed)
a8462c8e 482
bf5685f0
C
483 return this.trigger('torrentInfo', {
484 downloadSpeed: this.torrent.downloadSpeed,
485 numPeers: this.torrent.numPeers,
1a49822c
C
486 uploadSpeed: this.torrent.uploadSpeed,
487 downloaded: this.torrent.downloaded,
488 uploaded: this.torrent.uploaded
bf5685f0 489 })
a8462c8e 490 }, this.CONSTANTS.INFO_SCHEDULER)
a22bfc3e 491 }
aa8b6df4 492
8cac1b64
C
493 private runViewAdd () {
494 this.clearVideoViewInterval()
495
496 // After 30 seconds (or 3/4 of the video), add a view to the video
497 let minSecondsToView = 30
498
3bcfff7f 499 if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
8cac1b64
C
500
501 let secondsViewed = 0
502 this.videoViewInterval = setInterval(() => {
503 if (this.player && !this.player.paused()) {
504 secondsViewed += 1
505
506 if (secondsViewed > minSecondsToView) {
507 this.clearVideoViewInterval()
508
509 this.addViewToVideo().catch(err => console.error(err))
510 }
511 }
512 }, 1000)
513 }
514
515 private clearVideoViewInterval () {
516 if (this.videoViewInterval !== undefined) {
517 clearInterval(this.videoViewInterval)
518 this.videoViewInterval = undefined
519 }
520 }
521
522 private addViewToVideo () {
f5a2dc48
C
523 if (!this.videoViewUrl) return Promise.resolve(undefined)
524
8cac1b64
C
525 return fetch(this.videoViewUrl, { method: 'POST' })
526 }
527
e7eb5b39 528 private fallbackToHttp (done?: Function, play = true) {
c4082b8b
C
529 this.disableAutoResolution(true)
530
bf5685f0
C
531 this.flushVideoFile(this.currentVideoFile, true)
532 this.torrent = null
533
534 // Enable error display now this is our last fallback
535 this.player.one('error', () => this.enableErrorDisplay())
536
537 const httpUrl = this.currentVideoFile.fileUrl
538 this.player.src = this.savePlayerSrcFunction
539 this.player.src(httpUrl)
e7eb5b39 540 if (play) this.tryToPlay()
c6352f2c 541
e7eb5b39 542 if (done) return done()
bf5685f0
C
543 }
544
a22bfc3e
C
545 private handleError (err: Error | string) {
546 return this.player.trigger('customError', { err })
aa8b6df4 547 }
bf5685f0
C
548
549 private enableErrorDisplay () {
550 this.player.addClass('vjs-error-display-enabled')
551 }
552
553 private disableErrorDisplay () {
554 this.player.removeClass('vjs-error-display-enabled')
555 }
e993ecb3 556
e7eb5b39
C
557 private isIOS () {
558 return !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)
559 }
560
c6352f2c
C
561 private alterInactivity () {
562 let saveInactivityTimeout: number
563
564 const disableInactivity = () => {
565 saveInactivityTimeout = this.player.options_.inactivityTimeout
566 this.player.options_.inactivityTimeout = 0
567 }
568 const enableInactivity = () => {
b891f9bc 569 this.player.options_.inactivityTimeout = saveInactivityTimeout
c6352f2c
C
570 }
571
572 const settingsDialog = this.player.children_.find(c => c.name_ === 'SettingsDialog')
573
574 this.player.controlBar.on('mouseenter', () => disableInactivity())
575 settingsDialog.on('mouseenter', () => disableInactivity())
576 this.player.controlBar.on('mouseleave', () => enableInactivity())
332e7032 577 settingsDialog.on('mouseleave', () => enableInactivity())
c6352f2c
C
578 }
579
8eb8bc20
C
580 private pickAverageVideoFile () {
581 if (this.videoFiles.length === 1) return this.videoFiles[0]
582
583 return this.videoFiles[Math.floor(this.videoFiles.length / 2)]
584 }
585
054a103b
C
586 private destroyFakeRenderer () {
587 if (this.fakeRenderer) {
588 if (this.fakeRenderer.destroy) {
589 try {
590 this.fakeRenderer.destroy()
591 } catch (err) {
592 console.log('Cannot destroy correctly fake renderer.', err)
593 }
594 }
595 this.fakeRenderer = undefined
596 }
597 }
598
e993ecb3
C
599 // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
600 private initSmoothProgressBar () {
601 const SeekBar = videojsUntyped.getComponent('SeekBar')
602 SeekBar.prototype.getPercent = function getPercent () {
603 // Allows for smooth scrubbing, when player can't keep up.
604 // const time = (this.player_.scrubbing()) ?
605 // this.player_.getCache().currentTime :
606 // this.player_.currentTime()
607 const time = this.player_.currentTime()
608 const percent = time / this.player_.duration()
609 return percent >= 1 ? 1 : percent
610 }
611 SeekBar.prototype.handleMouseMove = function handleMouseMove (event) {
612 let newTime = this.calculateDistance(event) * this.player_.duration()
613 if (newTime === this.player_.duration()) {
614 newTime = newTime - 0.1
615 }
616 this.player_.currentTime(newTime)
617 this.update()
618 }
619 }
aa8b6df4 620}
c6352f2c 621
b7f1747d 622videojs.registerPlugin('peertube', PeerTubePlugin)
c6352f2c 623export { PeerTubePlugin }