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