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