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