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