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