]>
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' |
15a7eafb C |
12 | import { LoadedQualityData, PlayerNetworkInfo, WebtorrentPluginOptions } from '../peertube-videojs-typings' |
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 | |
2adfc7ea | 178 | this.changeQuality() |
3b6f205c | 179 | this.trigger('resolutionChange', { auto: this.autoResolution, resolutionId: this.currentVideoFile.resolution.id }) |
a216c623 C |
180 | } |
181 | ||
b335ccec C |
182 | updateResolution (resolutionId: number, delay = 0) { |
183 | // Remember player state | |
184 | const currentTime = this.player.currentTime() | |
185 | const isPaused = this.player.paused() | |
186 | ||
b335ccec C |
187 | // Hide bigPlayButton |
188 | if (!isPaused) { | |
189 | this.player.bigPlayButton.hide() | |
190 | } | |
191 | ||
3a149e9f C |
192 | // Audio-only (resolutionId === 0) gets special treatment |
193 | if (resolutionId === 0) { | |
5c7d6508 | 194 | // Audio-only: show poster, do not auto-hide controls |
195 | this.player.addClass('vjs-playing-audio-only-content') | |
196 | this.player.posterImage.show() | |
3a149e9f C |
197 | } else { |
198 | // Hide poster to have black background | |
199 | this.player.removeClass('vjs-playing-audio-only-content') | |
200 | this.player.posterImage.hide() | |
5c7d6508 | 201 | } |
202 | ||
b335ccec C |
203 | const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId) |
204 | const options = { | |
205 | forcePlay: false, | |
206 | delay, | |
207 | seek: currentTime + (delay / 1000) | |
208 | } | |
5c7d6508 | 209 | |
b335ccec C |
210 | this.updateVideoFile(newVideoFile, options) |
211 | } | |
212 | ||
213 | flushVideoFile (videoFile: VideoFile, destroyRenderer = true) { | |
214 | if (videoFile !== undefined && this.webtorrent.get(videoFile.magnetUri)) { | |
215 | if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy() | |
216 | ||
217 | this.webtorrent.remove(videoFile.magnetUri) | |
218 | console.log('Removed ' + videoFile.magnetUri) | |
219 | } | |
220 | } | |
221 | ||
b335ccec C |
222 | enableAutoResolution () { |
223 | this.autoResolution = true | |
3b6f205c | 224 | this.trigger('resolutionChange', { auto: this.autoResolution, resolutionId: this.getCurrentResolutionId() }) |
b335ccec C |
225 | } |
226 | ||
227 | disableAutoResolution (forbid = false) { | |
2adfc7ea | 228 | if (forbid === true) this.autoResolutionPossible = false |
b335ccec C |
229 | |
230 | this.autoResolution = false | |
3b6f205c C |
231 | this.trigger('autoResolutionChange', { possible: this.autoResolutionPossible }) |
232 | this.trigger('resolutionChange', { auto: this.autoResolution, resolutionId: this.getCurrentResolutionId() }) | |
b335ccec C |
233 | } |
234 | ||
6377a9f2 C |
235 | isAutoResolutionPossible () { |
236 | return this.autoResolutionPossible | |
237 | } | |
238 | ||
b335ccec C |
239 | getTorrent () { |
240 | return this.torrent | |
241 | } | |
242 | ||
aedf50d1 C |
243 | getCurrentVideoFile () { |
244 | return this.currentVideoFile | |
245 | } | |
246 | ||
b335ccec | 247 | private addTorrent ( |
3baf9be2 C |
248 | magnetOrTorrentUrl: string, |
249 | previousVideoFile: VideoFile, | |
a73115f3 | 250 | options: PlayOptions, |
9df52d66 | 251 | done: (err?: Error) => void |
3baf9be2 | 252 | ) { |
d61893f7 C |
253 | if (!magnetOrTorrentUrl) return this.fallbackToHttp(options, done) |
254 | ||
a216c623 C |
255 | console.log('Adding ' + magnetOrTorrentUrl + '.') |
256 | ||
a8462c8e | 257 | const oldTorrent = this.torrent |
3baf9be2 | 258 | const torrentOptions = { |
85394ba2 C |
259 | // Don't use arrow function: it breaks webtorrent (that uses `new` keyword) |
260 | store: function (chunkLength: number, storeOpts: any) { | |
261 | return new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), { | |
262 | max: 100 | |
263 | }) | |
264 | } | |
efda99c3 C |
265 | } |
266 | ||
b7f1747d | 267 | this.torrent = this.webtorrent.add(magnetOrTorrentUrl, torrentOptions, torrent => { |
a216c623 | 268 | console.log('Added ' + magnetOrTorrentUrl + '.') |
aa8b6df4 | 269 | |
a8462c8e | 270 | if (oldTorrent) { |
4a7591e1 | 271 | // Pause the old torrent |
b335ccec | 272 | this.stopTorrent(oldTorrent) |
6d272f39 C |
273 | |
274 | // We use a fake renderer so we download correct pieces of the next file | |
9df52d66 | 275 | if (options.delay) this.renderFileInFakeElement(torrent.files[0], options.delay) |
a8462c8e | 276 | } |
aa8b6df4 | 277 | |
e7eb5b39 | 278 | // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution) |
7ee4a4af | 279 | this.addTorrentDelay = setTimeout(() => { |
b335ccec | 280 | // We don't need the fake renderer anymore |
054a103b | 281 | this.destroyFakeRenderer() |
6d272f39 | 282 | |
3baf9be2 C |
283 | const paused = this.player.paused() |
284 | ||
a8462c8e | 285 | this.flushVideoFile(previousVideoFile) |
0dcf9a14 | 286 | |
fe05c3ac C |
287 | // Update progress bar (just for the UI), do not wait rendering |
288 | if (options.seek) this.player.currentTime(options.seek) | |
289 | ||
3baf9be2 | 290 | const renderVideoOptions = { autoplay: false, controls: true } |
9df52d66 | 291 | renderVideo(torrent.files[0], this.playerElement, renderVideoOptions, (err, renderer) => { |
a8462c8e | 292 | this.renderer = renderer |
aa8b6df4 | 293 | |
a73115f3 | 294 | if (err) return this.fallbackToHttp(options, done) |
3bcfff7f | 295 | |
c199c427 | 296 | return this.tryToPlay(err => { |
3baf9be2 | 297 | if (err) return done(err) |
a8462c8e | 298 | |
3baf9be2 C |
299 | if (options.seek) this.seek(options.seek) |
300 | if (options.forcePlay === false && paused === true) this.player.pause() | |
8244e187 | 301 | |
a73115f3 | 302 | return done() |
3baf9be2 | 303 | }) |
a8462c8e | 304 | }) |
3baf9be2 | 305 | }, options.delay || 0) |
aa8b6df4 C |
306 | }) |
307 | ||
244b4ae3 | 308 | this.torrent.on('error', (err: any) => console.error(err)) |
a216c623 | 309 | |
a22bfc3e | 310 | this.torrent.on('warning', (err: any) => { |
a96aed15 | 311 | // We don't support HTTP tracker but we don't care -> we use the web socket tracker |
531ab5b6 | 312 | if (err.message.indexOf('Unsupported tracker protocol') !== -1) return |
a216c623 | 313 | |
7dbdc3ba C |
314 | // Users don't care about issues with WebRTC, but developers do so log it in the console |
315 | if (err.message.indexOf('Ice connection failed') !== -1) { | |
332e7032 | 316 | console.log(err) |
7dbdc3ba C |
317 | return |
318 | } | |
a96aed15 | 319 | |
a216c623 C |
320 | // Magnet hash is not up to date with the torrent file, add directly the torrent file |
321 | if (err.message.indexOf('incorrect info hash') !== -1) { | |
322 | console.error('Incorrect info hash detected, falling back to torrent file.') | |
1f6824c9 | 323 | const newOptions = { forcePlay: true, seek: options.seek } |
9df52d66 | 324 | return this.addTorrent(this.torrent['xs'], previousVideoFile, newOptions, done) |
a216c623 C |
325 | } |
326 | ||
6d88de72 | 327 | // Remote instance is down |
0f7fedc3 | 328 | if (err.message.indexOf('from xs param') !== -1) { |
6d88de72 C |
329 | this.handleError(err) |
330 | } | |
331 | ||
332 | console.warn(err) | |
a96aed15 | 333 | }) |
aa8b6df4 C |
334 | } |
335 | ||
c199c427 | 336 | private tryToPlay (done?: (err?: Error) => void) { |
80109b2d | 337 | if (!done) done = function () { /* empty */ } |
1fad099d | 338 | |
80109b2d C |
339 | const playPromise = this.player.play() |
340 | if (playPromise !== undefined) { | |
f5fcd9f7 | 341 | return playPromise.then(() => done()) |
244b4ae3 | 342 | .catch((err: Error) => { |
9df52d66 | 343 | if (err.message.includes('The play() request was interrupted by a call to pause()')) { |
70b40c2e C |
344 | return |
345 | } | |
346 | ||
80109b2d C |
347 | console.error(err) |
348 | this.player.pause() | |
349 | this.player.posterImage.show() | |
350 | this.player.removeClass('vjs-has-autoplay') | |
91d95589 | 351 | this.player.removeClass('vjs-has-big-play-button-clicked') |
5c7d6508 | 352 | this.player.removeClass('vjs-playing-audio-only-content') |
80109b2d C |
353 | |
354 | return done() | |
355 | }) | |
356 | } | |
357 | ||
358 | return done() | |
359 | } | |
360 | ||
f37bad63 C |
361 | private seek (time: number) { |
362 | this.player.currentTime(time) | |
363 | this.player.handleTechSeeked_() | |
364 | } | |
365 | ||
a8462c8e | 366 | private getAppropriateFile (averageDownloadSpeed?: number): VideoFile { |
3cd56a29 C |
367 | if (this.videoFiles === undefined) return undefined |
368 | ||
369 | const files = this.videoFiles.filter(f => f.resolution.id !== 0) | |
370 | ||
371 | if (files.length === 0) return undefined | |
372 | if (files.length === 1) return files[0] | |
a8462c8e | 373 | |
aea53cc6 | 374 | // Don't change the torrent if the player ended |
3c40590d C |
375 | if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile |
376 | ||
377 | if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed() | |
a8462c8e | 378 | |
0b755f3b | 379 | // Limit resolution according to player height |
c4710631 | 380 | const playerHeight = this.playerElement.offsetHeight |
0b755f3b C |
381 | |
382 | // We take the first resolution just above the player height | |
383 | // Example: player height is 530px, we want the 720p file instead of 480p | |
3cd56a29 C |
384 | let maxResolution = files[0].resolution.id |
385 | for (let i = files.length - 1; i >= 0; i--) { | |
386 | const resolutionId = files[i].resolution.id | |
387 | if (resolutionId !== 0 && resolutionId >= playerHeight) { | |
0b755f3b C |
388 | maxResolution = resolutionId |
389 | break | |
a8462c8e | 390 | } |
0b755f3b | 391 | } |
a8462c8e | 392 | |
0b755f3b | 393 | // Filter videos we can play according to our screen resolution and bandwidth |
3cd56a29 C |
394 | const filteredFiles = files.filter(f => f.resolution.id <= maxResolution) |
395 | .filter(f => { | |
396 | const fileBitrate = (f.size / this.videoDuration) | |
397 | let threshold = fileBitrate | |
0b755f3b | 398 | |
3cd56a29 C |
399 | // If this is for a higher resolution or an initial load: add a margin |
400 | if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) { | |
401 | threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100) | |
402 | } | |
0b755f3b | 403 | |
3cd56a29 C |
404 | return averageDownloadSpeed > threshold |
405 | }) | |
a8462c8e C |
406 | |
407 | // If the download speed is too bad, return the lowest resolution we have | |
3cd56a29 | 408 | if (filteredFiles.length === 0) return videoFileMinByResolution(files) |
a8462c8e | 409 | |
6cca7360 | 410 | return videoFileMaxByResolution(filteredFiles) |
a8462c8e C |
411 | } |
412 | ||
3c40590d | 413 | private getAndSaveActualDownloadSpeed () { |
a8462c8e C |
414 | const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0) |
415 | const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length) | |
416 | if (lastDownloadSpeeds.length === 0) return -1 | |
417 | ||
418 | const sum = lastDownloadSpeeds.reduce((a, b) => a + b) | |
419 | const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length) | |
420 | ||
421 | // Save the average bandwidth for future use | |
422 | saveAverageBandwidth(averageBandwidth) | |
ed9f9f5f | 423 | |
a8462c8e | 424 | return averageBandwidth |
ed9f9f5f C |
425 | } |
426 | ||
0dcf9a14 | 427 | private initializePlayer () { |
2adfc7ea | 428 | this.buildQualities() |
c6352f2c | 429 | |
72efdda5 | 430 | if (this.autoplay) { |
33d78552 | 431 | this.player.posterImage.hide() |
e6f62797 | 432 | |
a325db17 | 433 | return this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime }) |
b335ccec | 434 | } |
e7eb5b39 | 435 | |
b335ccec | 436 | // Proxy first play |
f5fcd9f7 C |
437 | const oldPlay = this.player.play.bind(this.player); |
438 | (this.player as any).play = () => { | |
b335ccec C |
439 | this.player.addClass('vjs-has-big-play-button-clicked') |
440 | this.player.play = oldPlay | |
441 | ||
a325db17 | 442 | this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime }) |
aa8b6df4 | 443 | } |
a22bfc3e | 444 | } |
aa8b6df4 | 445 | |
a8462c8e C |
446 | private runAutoQualityScheduler () { |
447 | this.autoQualityInterval = setInterval(() => { | |
7ee4a4af | 448 | |
877b0528 C |
449 | // Not initialized or in HTTP fallback |
450 | if (this.torrent === undefined || this.torrent === null) return | |
2adfc7ea | 451 | if (this.autoResolution === false) return |
a8462c8e C |
452 | if (this.isAutoResolutionObservation === true) return |
453 | ||
454 | const file = this.getAppropriateFile() | |
455 | let changeResolution = false | |
456 | let changeResolutionDelay = 0 | |
457 | ||
458 | // Lower resolution | |
459 | if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) { | |
460 | console.log('Downgrading automatically the resolution to: %s', file.resolution.label) | |
461 | changeResolution = true | |
7ee4a4af | 462 | } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution |
a8462c8e C |
463 | console.log('Upgrading automatically the resolution to: %s', file.resolution.label) |
464 | changeResolution = true | |
7ee4a4af | 465 | changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY |
a8462c8e C |
466 | } |
467 | ||
468 | if (changeResolution === true) { | |
469 | this.updateResolution(file.resolution.id, changeResolutionDelay) | |
470 | ||
471 | // Wait some seconds in observation of our new resolution | |
472 | this.isAutoResolutionObservation = true | |
7ee4a4af C |
473 | |
474 | this.qualityObservationTimer = setTimeout(() => { | |
475 | this.isAutoResolutionObservation = false | |
476 | }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME) | |
a8462c8e C |
477 | } |
478 | }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER) | |
479 | } | |
480 | ||
481 | private isPlayerWaiting () { | |
9df52d66 | 482 | return this.player?.hasClass('vjs-waiting') |
a8462c8e C |
483 | } |
484 | ||
a22bfc3e | 485 | private runTorrentInfoScheduler () { |
3bcfff7f | 486 | this.torrentInfoInterval = setInterval(() => { |
bf5685f0 C |
487 | // Not initialized yet |
488 | if (this.torrent === undefined) return | |
489 | ||
490 | // Http fallback | |
2adfc7ea | 491 | if (this.torrent === null) return this.player.trigger('p2pInfo', false) |
bf5685f0 | 492 | |
b7f1747d C |
493 | // this.webtorrent.downloadSpeed because we need to take into account the potential old torrent too |
494 | if (this.webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(this.webtorrent.downloadSpeed) | |
a8462c8e | 495 | |
2adfc7ea | 496 | return this.player.trigger('p2pInfo', { |
17152837 | 497 | source: 'webtorrent', |
09209296 C |
498 | http: { |
499 | downloadSpeed: 0, | |
500 | uploadSpeed: 0, | |
501 | downloaded: 0, | |
502 | uploaded: 0 | |
503 | }, | |
3b6f205c C |
504 | p2p: { |
505 | downloadSpeed: this.torrent.downloadSpeed, | |
506 | numPeers: this.torrent.numPeers, | |
507 | uploadSpeed: this.torrent.uploadSpeed, | |
508 | downloaded: this.torrent.downloaded, | |
509 | uploaded: this.torrent.uploaded | |
4e11d8f3 C |
510 | }, |
511 | bandwidthEstimate: this.webtorrent.downloadSpeed | |
3b6f205c | 512 | } as PlayerNetworkInfo) |
a8462c8e | 513 | }, this.CONSTANTS.INFO_SCHEDULER) |
a22bfc3e | 514 | } |
aa8b6df4 | 515 | |
9df52d66 | 516 | private fallbackToHttp (options: PlayOptions, done?: (err?: Error) => void) { |
a73115f3 C |
517 | const paused = this.player.paused() |
518 | ||
c4082b8b C |
519 | this.disableAutoResolution(true) |
520 | ||
bf5685f0 C |
521 | this.flushVideoFile(this.currentVideoFile, true) |
522 | this.torrent = null | |
523 | ||
524 | // Enable error display now this is our last fallback | |
525 | this.player.one('error', () => this.enableErrorDisplay()) | |
526 | ||
527 | const httpUrl = this.currentVideoFile.fileUrl | |
528 | this.player.src = this.savePlayerSrcFunction | |
529 | this.player.src(httpUrl) | |
c6352f2c | 530 | |
2adfc7ea C |
531 | this.changeQuality() |
532 | ||
c32bf839 | 533 | // We changed the source, so reinit captions |
2adfc7ea | 534 | this.player.trigger('sourcechange') |
c32bf839 | 535 | |
a73115f3 C |
536 | return this.tryToPlay(err => { |
537 | if (err && done) return done(err) | |
538 | ||
539 | if (options.seek) this.seek(options.seek) | |
540 | if (options.forcePlay === false && paused === true) this.player.pause() | |
541 | ||
542 | if (done) return done() | |
543 | }) | |
bf5685f0 C |
544 | } |
545 | ||
a22bfc3e C |
546 | private handleError (err: Error | string) { |
547 | return this.player.trigger('customError', { err }) | |
aa8b6df4 | 548 | } |
bf5685f0 C |
549 | |
550 | private enableErrorDisplay () { | |
551 | this.player.addClass('vjs-error-display-enabled') | |
552 | } | |
553 | ||
554 | private disableErrorDisplay () { | |
555 | this.player.removeClass('vjs-error-display-enabled') | |
556 | } | |
e993ecb3 | 557 | |
8eb8bc20 C |
558 | private pickAverageVideoFile () { |
559 | if (this.videoFiles.length === 1) return this.videoFiles[0] | |
560 | ||
1a5b67b6 C |
561 | const files = this.videoFiles.filter(f => f.resolution.id !== 0) |
562 | return files[Math.floor(files.length / 2)] | |
8eb8bc20 C |
563 | } |
564 | ||
c199c427 | 565 | private stopTorrent (torrent: WebTorrent.Torrent) { |
b335ccec C |
566 | torrent.pause() |
567 | // Pause does not remove actual peers (in particular the webseed peer) | |
9df52d66 | 568 | torrent.removePeer(torrent['ws']) |
b335ccec C |
569 | } |
570 | ||
571 | private renderFileInFakeElement (file: WebTorrent.TorrentFile, delay: number) { | |
3b019808 | 572 | this.destroyingFakeRenderer = false |
287918da | 573 | |
b335ccec C |
574 | const fakeVideoElem = document.createElement('video') |
575 | renderVideo(file, fakeVideoElem, { autoplay: false, controls: false }, (err, renderer) => { | |
576 | this.fakeRenderer = renderer | |
577 | ||
287918da | 578 | // The renderer returns an error when we destroy it, so skip them |
3b019808 | 579 | if (this.destroyingFakeRenderer === false && err) { |
287918da C |
580 | console.error('Cannot render new torrent in fake video element.', err) |
581 | } | |
b335ccec C |
582 | |
583 | // Load the future file at the correct time (in delay MS - 2 seconds) | |
584 | fakeVideoElem.currentTime = this.player.currentTime() + (delay - 2000) | |
585 | }) | |
586 | } | |
587 | ||
054a103b C |
588 | private destroyFakeRenderer () { |
589 | if (this.fakeRenderer) { | |
3b019808 | 590 | this.destroyingFakeRenderer = true |
287918da | 591 | |
054a103b C |
592 | if (this.fakeRenderer.destroy) { |
593 | try { | |
594 | this.fakeRenderer.destroy() | |
595 | } catch (err) { | |
596 | console.log('Cannot destroy correctly fake renderer.', err) | |
597 | } | |
598 | } | |
599 | this.fakeRenderer = undefined | |
600 | } | |
601 | } | |
602 | ||
2adfc7ea C |
603 | private buildQualities () { |
604 | const qualityLevelsPayload = [] | |
605 | ||
606 | for (const file of this.videoFiles) { | |
607 | const representation = { | |
608 | id: file.resolution.id, | |
609 | label: this.buildQualityLabel(file), | |
610 | height: file.resolution.id, | |
611 | _enabled: true | |
612 | } | |
613 | ||
614 | this.player.qualityLevels().addQualityLevel(representation) | |
615 | ||
616 | qualityLevelsPayload.push({ | |
617 | id: representation.id, | |
618 | label: representation.label, | |
619 | selected: false | |
620 | }) | |
16f7022b | 621 | } |
c32bf839 | 622 | |
2adfc7ea C |
623 | const payload: LoadedQualityData = { |
624 | qualitySwitchCallback: (d: any) => this.qualitySwitchCallback(d), | |
625 | qualityData: { | |
626 | video: qualityLevelsPayload | |
627 | } | |
628 | } | |
f5fcd9f7 | 629 | this.player.tech(true).trigger('loadedqualitydata', payload) |
16f7022b C |
630 | } |
631 | ||
2adfc7ea C |
632 | private buildQualityLabel (file: VideoFile) { |
633 | let label = file.resolution.label | |
634 | ||
635 | if (file.fps && file.fps >= 50) { | |
636 | label += file.fps | |
e993ecb3 | 637 | } |
2adfc7ea C |
638 | |
639 | return label | |
640 | } | |
641 | ||
642 | private qualitySwitchCallback (id: number) { | |
643 | if (id === -1) { | |
644 | if (this.autoResolutionPossible === true) this.enableAutoResolution() | |
645 | return | |
646 | } | |
647 | ||
648 | this.disableAutoResolution() | |
649 | this.updateResolution(id) | |
650 | } | |
651 | ||
652 | private changeQuality () { | |
2b58ca79 | 653 | const resolutionId = this.currentVideoFile.resolution.id as number |
2adfc7ea C |
654 | const qualityLevels = this.player.qualityLevels() |
655 | ||
656 | if (resolutionId === -1) { | |
657 | qualityLevels.selectedIndex = -1 | |
658 | return | |
659 | } | |
660 | ||
f5fcd9f7 | 661 | for (let i = 0; i < qualityLevels.length; i++) { |
cf57794e C |
662 | const q = qualityLevels[i] |
663 | if (q.height === resolutionId) qualityLevels.selectedIndex_ = i | |
e993ecb3 C |
664 | } |
665 | } | |
aa8b6df4 | 666 | } |
c6352f2c | 667 | |
2adfc7ea C |
668 | videojs.registerPlugin('webtorrent', WebTorrentPlugin) |
669 | export { WebTorrentPlugin } |