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