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