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