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