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