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