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