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