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