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