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