aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/assets/player/shared/webtorrent
diff options
context:
space:
mode:
authorChocobozzz <me@florianbigard.com>2022-03-14 14:28:20 +0100
committerChocobozzz <me@florianbigard.com>2022-03-14 14:36:35 +0100
commit57d6503286b114fee61b5e4725825e2490dcac29 (patch)
tree2d3d23f697b2986d7e41bb443754394296b66ec3 /client/src/assets/player/shared/webtorrent
parent9597920ee3d4ac99803e7107983ddf98a9dfb3c4 (diff)
downloadPeerTube-57d6503286b114fee61b5e4725825e2490dcac29.tar.gz
PeerTube-57d6503286b114fee61b5e4725825e2490dcac29.tar.zst
PeerTube-57d6503286b114fee61b5e4725825e2490dcac29.zip
Reorganize player files
Diffstat (limited to 'client/src/assets/player/shared/webtorrent')
-rw-r--r--client/src/assets/player/shared/webtorrent/peertube-chunk-store.ts233
-rw-r--r--client/src/assets/player/shared/webtorrent/video-renderer.ts133
-rw-r--r--client/src/assets/player/shared/webtorrent/webtorrent-plugin.ts641
3 files changed, 1007 insertions, 0 deletions
diff --git a/client/src/assets/player/shared/webtorrent/peertube-chunk-store.ts b/client/src/assets/player/shared/webtorrent/peertube-chunk-store.ts
new file mode 100644
index 000000000..81378c277
--- /dev/null
+++ b/client/src/assets/player/shared/webtorrent/peertube-chunk-store.ts
@@ -0,0 +1,233 @@
1// From https://github.com/MinEduTDF/idb-chunk-store
2// We use temporary IndexDB (all data are removed on destroy) to avoid RAM issues
3// Thanks @santiagogil and @Feross
4
5import { EventEmitter } from 'events'
6import Dexie from 'dexie'
7
8class ChunkDatabase extends Dexie {
9 chunks: Dexie.Table<{ id: number, buf: Buffer }, number>
10
11 constructor (dbname: string) {
12 super(dbname)
13
14 this.version(1).stores({
15 chunks: 'id'
16 })
17 }
18}
19
20class ExpirationDatabase extends Dexie {
21 databases: Dexie.Table<{ name: string, expiration: number }, number>
22
23 constructor () {
24 super('webtorrent-expiration')
25
26 this.version(1).stores({
27 databases: 'name,expiration'
28 })
29 }
30}
31
32export class PeertubeChunkStore extends EventEmitter {
33 private static readonly BUFFERING_PUT_MS = 1000
34 private static readonly CLEANER_INTERVAL_MS = 1000 * 60 // 1 minute
35 private static readonly CLEANER_EXPIRATION_MS = 1000 * 60 * 5 // 5 minutes
36
37 chunkLength: number
38
39 private pendingPut: { id: number, buf: Buffer, cb: (err?: Error) => void }[] = []
40 // If the store is full
41 private memoryChunks: { [ id: number ]: Buffer | true } = {}
42 private databaseName: string
43 private putBulkTimeout: any
44 private cleanerInterval: any
45 private db: ChunkDatabase
46 private expirationDB: ExpirationDatabase
47 private readonly length: number
48 private readonly lastChunkLength: number
49 private readonly lastChunkIndex: number
50
51 constructor (chunkLength: number, opts: any) {
52 super()
53
54 this.databaseName = 'webtorrent-chunks-'
55
56 if (!opts) opts = {}
57 if (opts.torrent?.infoHash) this.databaseName += opts.torrent.infoHash
58 else this.databaseName += '-default'
59
60 this.setMaxListeners(100)
61
62 this.chunkLength = Number(chunkLength)
63 if (!this.chunkLength) throw new Error('First argument must be a chunk length')
64
65 this.length = Number(opts.length) || Infinity
66
67 if (this.length !== Infinity) {
68 this.lastChunkLength = (this.length % this.chunkLength) || this.chunkLength
69 this.lastChunkIndex = Math.ceil(this.length / this.chunkLength) - 1
70 }
71
72 this.db = new ChunkDatabase(this.databaseName)
73 // Track databases that expired
74 this.expirationDB = new ExpirationDatabase()
75
76 this.runCleaner()
77 }
78
79 put (index: number, buf: Buffer, cb: (err?: Error) => void) {
80 const isLastChunk = (index === this.lastChunkIndex)
81 if (isLastChunk && buf.length !== this.lastChunkLength) {
82 return this.nextTick(cb, new Error('Last chunk length must be ' + this.lastChunkLength))
83 }
84 if (!isLastChunk && buf.length !== this.chunkLength) {
85 return this.nextTick(cb, new Error('Chunk length must be ' + this.chunkLength))
86 }
87
88 // Specify we have this chunk
89 this.memoryChunks[index] = true
90
91 // Add it to the pending put
92 this.pendingPut.push({ id: index, buf, cb })
93 // If it's already planned, return
94 if (this.putBulkTimeout) return
95
96 // Plan a future bulk insert
97 this.putBulkTimeout = setTimeout(async () => {
98 const processing = this.pendingPut
99 this.pendingPut = []
100 this.putBulkTimeout = undefined
101
102 try {
103 await this.db.transaction('rw', this.db.chunks, () => {
104 return this.db.chunks.bulkPut(processing.map(p => ({ id: p.id, buf: p.buf })))
105 })
106 } catch (err) {
107 console.log('Cannot bulk insert chunks. Store them in memory.', { err })
108
109 processing.forEach(p => {
110 this.memoryChunks[p.id] = p.buf
111 })
112 } finally {
113 processing.forEach(p => p.cb())
114 }
115 }, PeertubeChunkStore.BUFFERING_PUT_MS)
116 }
117
118 get (index: number, opts: any, cb: (err?: Error, buf?: Buffer) => void): void {
119 if (typeof opts === 'function') return this.get(index, null, opts)
120
121 // IndexDB could be slow, use our memory index first
122 const memoryChunk = this.memoryChunks[index]
123 if (memoryChunk === undefined) {
124 const err = new Error('Chunk not found') as any
125 err['notFound'] = true
126
127 return process.nextTick(() => cb(err))
128 }
129
130 // Chunk in memory
131 if (memoryChunk !== true) return cb(null, memoryChunk)
132
133 // Chunk in store
134 this.db.transaction('r', this.db.chunks, async () => {
135 const result = await this.db.chunks.get({ id: index })
136 if (result === undefined) return cb(null, Buffer.alloc(0))
137
138 const buf = result.buf
139 if (!opts) return this.nextTick(cb, null, buf)
140
141 const offset = opts.offset || 0
142 const len = opts.length || (buf.length - offset)
143 return cb(null, buf.slice(offset, len + offset))
144 })
145 .catch(err => {
146 console.error(err)
147 return cb(err)
148 })
149 }
150
151 close (cb: (err?: Error) => void) {
152 return this.destroy(cb)
153 }
154
155 async destroy (cb: (err?: Error) => void) {
156 try {
157 if (this.pendingPut) {
158 clearTimeout(this.putBulkTimeout)
159 this.pendingPut = null
160 }
161 if (this.cleanerInterval) {
162 clearInterval(this.cleanerInterval)
163 this.cleanerInterval = null
164 }
165
166 if (this.db) {
167 this.db.close()
168
169 await this.dropDatabase(this.databaseName)
170 }
171
172 if (this.expirationDB) {
173 this.expirationDB.close()
174 this.expirationDB = null
175 }
176
177 return cb()
178 } catch (err) {
179 console.error('Cannot destroy peertube chunk store.', err)
180 return cb(err)
181 }
182 }
183
184 private runCleaner () {
185 this.checkExpiration()
186
187 this.cleanerInterval = setInterval(() => {
188 this.checkExpiration()
189 }, PeertubeChunkStore.CLEANER_INTERVAL_MS)
190 }
191
192 private async checkExpiration () {
193 let databasesToDeleteInfo: { name: string }[] = []
194
195 try {
196 await this.expirationDB.transaction('rw', this.expirationDB.databases, async () => {
197 // Update our database expiration since we are alive
198 await this.expirationDB.databases.put({
199 name: this.databaseName,
200 expiration: new Date().getTime() + PeertubeChunkStore.CLEANER_EXPIRATION_MS
201 })
202
203 const now = new Date().getTime()
204 databasesToDeleteInfo = await this.expirationDB.databases.where('expiration').below(now).toArray()
205 })
206 } catch (err) {
207 console.error('Cannot update expiration of fetch expired databases.', err)
208 }
209
210 for (const databaseToDeleteInfo of databasesToDeleteInfo) {
211 await this.dropDatabase(databaseToDeleteInfo.name)
212 }
213 }
214
215 private async dropDatabase (databaseName: string) {
216 const dbToDelete = new ChunkDatabase(databaseName)
217 console.log('Destroying IndexDB database %s.', databaseName)
218
219 try {
220 await dbToDelete.delete()
221
222 await this.expirationDB.transaction('rw', this.expirationDB.databases, () => {
223 return this.expirationDB.databases.where({ name: databaseName }).delete()
224 })
225 } catch (err) {
226 console.error('Cannot delete %s.', databaseName, err)
227 }
228 }
229
230 private nextTick <T> (cb: (err?: Error, val?: T) => void, err: Error, val?: T) {
231 process.nextTick(() => cb(err, val), undefined)
232 }
233}
diff --git a/client/src/assets/player/shared/webtorrent/video-renderer.ts b/client/src/assets/player/shared/webtorrent/video-renderer.ts
new file mode 100644
index 000000000..9b80fea2c
--- /dev/null
+++ b/client/src/assets/player/shared/webtorrent/video-renderer.ts
@@ -0,0 +1,133 @@
1// Thanks: https://github.com/feross/render-media
2
3const MediaElementWrapper = require('mediasource')
4import { extname } from 'path'
5const Videostream = require('videostream')
6
7const VIDEOSTREAM_EXTS = [
8 '.m4a',
9 '.m4v',
10 '.mp4'
11]
12
13type RenderMediaOptions = {
14 controls: boolean
15 autoplay: boolean
16}
17
18function renderVideo (
19 file: any,
20 elem: HTMLVideoElement,
21 opts: RenderMediaOptions,
22 callback: (err: Error, renderer: any) => void
23) {
24 validateFile(file)
25
26 return renderMedia(file, elem, opts, callback)
27}
28
29function renderMedia (file: any, elem: HTMLVideoElement, opts: RenderMediaOptions, callback: (err: Error, renderer?: any) => void) {
30 const extension = extname(file.name).toLowerCase()
31 let preparedElem: any
32 let currentTime = 0
33 let renderer: any
34
35 try {
36 if (VIDEOSTREAM_EXTS.includes(extension)) {
37 renderer = useVideostream()
38 } else {
39 renderer = useMediaSource()
40 }
41 } catch (err) {
42 return callback(err)
43 }
44
45 function useVideostream () {
46 prepareElem()
47 preparedElem.addEventListener('error', function onError (err: Error) {
48 preparedElem.removeEventListener('error', onError)
49
50 return callback(err)
51 })
52 preparedElem.addEventListener('loadstart', onLoadStart)
53 return new Videostream(file, preparedElem)
54 }
55
56 function useMediaSource (useVP9 = false) {
57 const codecs = getCodec(file.name, useVP9)
58
59 prepareElem()
60 preparedElem.addEventListener('error', function onError (err: Error) {
61 preparedElem.removeEventListener('error', onError)
62
63 // Try with vp9 before returning an error
64 if (codecs.includes('vp8')) return fallbackToMediaSource(true)
65
66 return callback(err)
67 })
68 preparedElem.addEventListener('loadstart', onLoadStart)
69
70 const wrapper = new MediaElementWrapper(preparedElem)
71 const writable = wrapper.createWriteStream(codecs)
72 file.createReadStream().pipe(writable)
73
74 if (currentTime) preparedElem.currentTime = currentTime
75
76 return wrapper
77 }
78
79 function fallbackToMediaSource (useVP9 = false) {
80 if (useVP9 === true) console.log('Falling back to media source with VP9 enabled.')
81 else console.log('Falling back to media source..')
82
83 useMediaSource(useVP9)
84 }
85
86 function prepareElem () {
87 if (preparedElem === undefined) {
88 preparedElem = elem
89
90 preparedElem.addEventListener('progress', function () {
91 currentTime = elem.currentTime
92 })
93 }
94 }
95
96 function onLoadStart () {
97 preparedElem.removeEventListener('loadstart', onLoadStart)
98 if (opts.autoplay) preparedElem.play()
99
100 callback(null, renderer)
101 }
102}
103
104function validateFile (file: any) {
105 if (file == null) {
106 throw new Error('file cannot be null or undefined')
107 }
108 if (typeof file.name !== 'string') {
109 throw new Error('missing or invalid file.name property')
110 }
111 if (typeof file.createReadStream !== 'function') {
112 throw new Error('missing or invalid file.createReadStream property')
113 }
114}
115
116function getCodec (name: string, useVP9 = false) {
117 const ext = extname(name).toLowerCase()
118 if (ext === '.mp4') {
119 return 'video/mp4; codecs="avc1.640029, mp4a.40.5"'
120 }
121
122 if (ext === '.webm') {
123 if (useVP9 === true) return 'video/webm; codecs="vp9, opus"'
124
125 return 'video/webm; codecs="vp8, vorbis"'
126 }
127
128 return undefined
129}
130
131export {
132 renderVideo
133}
diff --git a/client/src/assets/player/shared/webtorrent/webtorrent-plugin.ts b/client/src/assets/player/shared/webtorrent/webtorrent-plugin.ts
new file mode 100644
index 000000000..b48203148
--- /dev/null
+++ b/client/src/assets/player/shared/webtorrent/webtorrent-plugin.ts
@@ -0,0 +1,641 @@
1import videojs from 'video.js'
2import * as WebTorrent from 'webtorrent'
3import { isIOS } from '@root-helpers/web-browser'
4import { timeToInt } from '@shared/core-utils'
5import { VideoFile } from '@shared/models'
6import { getAverageBandwidthInStore, getStoredMute, getStoredVolume, saveAverageBandwidth } from '../../peertube-player-local-storage'
7import { PeerTubeResolution, PlayerNetworkInfo, WebtorrentPluginOptions } from '../../types'
8import { getRtcConfig, videoFileMaxByResolution, videoFileMinByResolution } from '../common'
9import { PeertubeChunkStore } from './peertube-chunk-store'
10import { renderVideo } from './video-renderer'
11
12const CacheChunkStore = require('cache-chunk-store')
13
14type PlayOptions = {
15 forcePlay?: boolean
16 seek?: number
17 delay?: number
18}
19
20const Plugin = videojs.getPlugin('plugin')
21
22class WebTorrentPlugin extends Plugin {
23 readonly videoFiles: VideoFile[]
24
25 private readonly playerElement: HTMLVideoElement
26
27 private readonly autoplay: boolean = false
28 private readonly startTime: number = 0
29 private readonly savePlayerSrcFunction: videojs.Player['src']
30 private readonly videoDuration: number
31 private readonly CONSTANTS = {
32 INFO_SCHEDULER: 1000, // Don't change this
33 AUTO_QUALITY_SCHEDULER: 3000, // Check quality every 3 seconds
34 AUTO_QUALITY_THRESHOLD_PERCENT: 30, // Bandwidth should be 30% more important than a resolution bitrate to change to it
35 AUTO_QUALITY_OBSERVATION_TIME: 10000, // Wait 10 seconds after having change the resolution before another check
36 AUTO_QUALITY_HIGHER_RESOLUTION_DELAY: 5000, // Buffering higher resolution during 5 seconds
37 BANDWIDTH_AVERAGE_NUMBER_OF_VALUES: 5 // Last 5 seconds to build average bandwidth
38 }
39
40 private readonly webtorrent = new WebTorrent({
41 tracker: {
42 rtcConfig: getRtcConfig()
43 },
44 dht: false
45 })
46
47 private currentVideoFile: VideoFile
48 private torrent: WebTorrent.Torrent
49
50 private renderer: any
51 private fakeRenderer: any
52 private destroyingFakeRenderer = false
53
54 private autoResolution = true
55 private autoResolutionPossible = true
56 private isAutoResolutionObservation = false
57 private playerRefusedP2P = false
58
59 private torrentInfoInterval: any
60 private autoQualityInterval: any
61 private addTorrentDelay: any
62 private qualityObservationTimer: any
63 private runAutoQualitySchedulerTimer: any
64
65 private downloadSpeeds: number[] = []
66
67 constructor (player: videojs.Player, options?: WebtorrentPluginOptions) {
68 super(player)
69
70 this.startTime = timeToInt(options.startTime)
71
72 // Custom autoplay handled by webtorrent because we lazy play the video
73 this.autoplay = options.autoplay
74
75 this.playerRefusedP2P = options.playerRefusedP2P
76
77 this.videoFiles = options.videoFiles
78 this.videoDuration = options.videoDuration
79
80 this.savePlayerSrcFunction = this.player.src
81 this.playerElement = options.playerElement
82
83 this.player.ready(() => {
84 const playerOptions = this.player.options_
85
86 const volume = getStoredVolume()
87 if (volume !== undefined) this.player.volume(volume)
88
89 const muted = playerOptions.muted !== undefined ? playerOptions.muted : getStoredMute()
90 if (muted !== undefined) this.player.muted(muted)
91
92 this.player.duration(options.videoDuration)
93
94 this.initializePlayer()
95 this.runTorrentInfoScheduler()
96
97 this.player.one('play', () => {
98 // Don't run immediately scheduler, wait some seconds the TCP connections are made
99 this.runAutoQualitySchedulerTimer = setTimeout(() => this.runAutoQualityScheduler(), this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
100 })
101 })
102 }
103
104 dispose () {
105 clearTimeout(this.addTorrentDelay)
106 clearTimeout(this.qualityObservationTimer)
107 clearTimeout(this.runAutoQualitySchedulerTimer)
108
109 clearInterval(this.torrentInfoInterval)
110 clearInterval(this.autoQualityInterval)
111
112 // Don't need to destroy renderer, video player will be destroyed
113 this.flushVideoFile(this.currentVideoFile, false)
114
115 this.destroyFakeRenderer()
116 }
117
118 getCurrentResolutionId () {
119 return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
120 }
121
122 updateVideoFile (
123 videoFile?: VideoFile,
124 options: {
125 forcePlay?: boolean
126 seek?: number
127 delay?: number
128 } = {},
129 done: () => void = () => { /* empty */ }
130 ) {
131 // Automatically choose the adapted video file
132 if (!videoFile) {
133 const savedAverageBandwidth = getAverageBandwidthInStore()
134 videoFile = savedAverageBandwidth
135 ? this.getAppropriateFile(savedAverageBandwidth)
136 : this.pickAverageVideoFile()
137 }
138
139 if (!videoFile) {
140 throw Error(`Can't update video file since videoFile is undefined.`)
141 }
142
143 // Don't add the same video file once again
144 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
145 return
146 }
147
148 // Do not display error to user because we will have multiple fallback
149 this.player.peertube().hideFatalError();
150
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
154 (this.player as any).src = () => true
155 const oldPlaybackRate = this.player.playbackRate()
156
157 const previousVideoFile = this.currentVideoFile
158 this.currentVideoFile = videoFile
159
160 // Don't try on iOS that does not support MediaSource
161 // Or don't use P2P if webtorrent is disabled
162 if (isIOS() || this.playerRefusedP2P) {
163 return this.fallbackToHttp(options, () => {
164 this.player.playbackRate(oldPlaybackRate)
165 return done()
166 })
167 }
168
169 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, options, () => {
170 this.player.playbackRate(oldPlaybackRate)
171 return done()
172 })
173
174 this.selectAppropriateResolution(true)
175 }
176
177 updateEngineResolution (resolutionId: number, delay = 0) {
178 // Remember player state
179 const currentTime = this.player.currentTime()
180 const isPaused = this.player.paused()
181
182 // Hide bigPlayButton
183 if (!isPaused) {
184 this.player.bigPlayButton.hide()
185 }
186
187 // Audio-only (resolutionId === 0) gets special treatment
188 if (resolutionId === 0) {
189 // Audio-only: show poster, do not auto-hide controls
190 this.player.addClass('vjs-playing-audio-only-content')
191 this.player.posterImage.show()
192 } else {
193 // Hide poster to have black background
194 this.player.removeClass('vjs-playing-audio-only-content')
195 this.player.posterImage.hide()
196 }
197
198 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
199 const options = {
200 forcePlay: false,
201 delay,
202 seek: currentTime + (delay / 1000)
203 }
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
217 disableAutoResolution () {
218 this.autoResolution = false
219 this.autoResolutionPossible = false
220 this.player.peertubeResolutions().disableAutoResolution()
221 }
222
223 isAutoResolutionPossible () {
224 return this.autoResolutionPossible
225 }
226
227 getTorrent () {
228 return this.torrent
229 }
230
231 getCurrentVideoFile () {
232 return this.currentVideoFile
233 }
234
235 changeQuality (id: number) {
236 if (id === -1) {
237 if (this.autoResolutionPossible === true) {
238 this.autoResolution = true
239
240 this.selectAppropriateResolution(false)
241 }
242
243 return
244 }
245
246 this.autoResolution = false
247 this.updateEngineResolution(id)
248 this.selectAppropriateResolution(false)
249 }
250
251 private addTorrent (
252 magnetOrTorrentUrl: string,
253 previousVideoFile: VideoFile,
254 options: PlayOptions,
255 done: (err?: Error) => void
256 ) {
257 if (!magnetOrTorrentUrl) return this.fallbackToHttp(options, done)
258
259 console.log('Adding ' + magnetOrTorrentUrl + '.')
260
261 const oldTorrent = this.torrent
262 const torrentOptions = {
263 // Don't use arrow function: it breaks webtorrent (that uses `new` keyword)
264 store: function (chunkLength: number, storeOpts: any) {
265 return new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
266 max: 100
267 })
268 }
269 }
270
271 this.torrent = this.webtorrent.add(magnetOrTorrentUrl, torrentOptions, torrent => {
272 console.log('Added ' + magnetOrTorrentUrl + '.')
273
274 if (oldTorrent) {
275 // Pause the old torrent
276 this.stopTorrent(oldTorrent)
277
278 // We use a fake renderer so we download correct pieces of the next file
279 if (options.delay) this.renderFileInFakeElement(torrent.files[0], options.delay)
280 }
281
282 // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
283 this.addTorrentDelay = setTimeout(() => {
284 // We don't need the fake renderer anymore
285 this.destroyFakeRenderer()
286
287 const paused = this.player.paused()
288
289 this.flushVideoFile(previousVideoFile)
290
291 // Update progress bar (just for the UI), do not wait rendering
292 if (options.seek) this.player.currentTime(options.seek)
293
294 const renderVideoOptions = { autoplay: false, controls: true }
295 renderVideo(torrent.files[0], this.playerElement, renderVideoOptions, (err, renderer) => {
296 this.renderer = renderer
297
298 if (err) return this.fallbackToHttp(options, done)
299
300 return this.tryToPlay(err => {
301 if (err) return done(err)
302
303 if (options.seek) this.seek(options.seek)
304 if (options.forcePlay === false && paused === true) this.player.pause()
305
306 return done()
307 })
308 })
309 }, options.delay || 0)
310 })
311
312 this.torrent.on('error', (err: any) => console.error(err))
313
314 this.torrent.on('warning', (err: any) => {
315 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
316 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
317
318 // Users don't care about issues with WebRTC, but developers do so log it in the console
319 if (err.message.indexOf('Ice connection failed') !== -1) {
320 console.log(err)
321 return
322 }
323
324 // Magnet hash is not up to date with the torrent file, add directly the torrent file
325 if (err.message.indexOf('incorrect info hash') !== -1) {
326 console.error('Incorrect info hash detected, falling back to torrent file.')
327 const newOptions = { forcePlay: true, seek: options.seek }
328 return this.addTorrent(this.torrent['xs'], previousVideoFile, newOptions, done)
329 }
330
331 // Remote instance is down
332 if (err.message.indexOf('from xs param') !== -1) {
333 this.handleError(err)
334 }
335
336 console.warn(err)
337 })
338 }
339
340 private tryToPlay (done?: (err?: Error) => void) {
341 if (!done) done = function () { /* empty */ }
342
343 const playPromise = this.player.play()
344 if (playPromise !== undefined) {
345 return playPromise.then(() => done())
346 .catch((err: Error) => {
347 if (err.message.includes('The play() request was interrupted by a call to pause()')) {
348 return
349 }
350
351 console.error(err)
352 this.player.pause()
353 this.player.posterImage.show()
354 this.player.removeClass('vjs-has-autoplay')
355 this.player.removeClass('vjs-has-big-play-button-clicked')
356 this.player.removeClass('vjs-playing-audio-only-content')
357
358 return done()
359 })
360 }
361
362 return done()
363 }
364
365 private seek (time: number) {
366 this.player.currentTime(time)
367 this.player.handleTechSeeked_()
368 }
369
370 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
371 if (this.videoFiles === undefined) return undefined
372 if (this.videoFiles.length === 1) return this.videoFiles[0]
373
374 const files = this.videoFiles.filter(f => f.resolution.id !== 0)
375 if (files.length === 0) return undefined
376
377 // Don't change the torrent if the player ended
378 if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
379
380 if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
381
382 // Limit resolution according to player height
383 const playerHeight = this.playerElement.offsetHeight
384
385 // We take the first resolution just above the player height
386 // Example: player height is 530px, we want the 720p file instead of 480p
387 let maxResolution = files[0].resolution.id
388 for (let i = files.length - 1; i >= 0; i--) {
389 const resolutionId = files[i].resolution.id
390 if (resolutionId !== 0 && resolutionId >= playerHeight) {
391 maxResolution = resolutionId
392 break
393 }
394 }
395
396 // Filter videos we can play according to our screen resolution and bandwidth
397 const filteredFiles = files.filter(f => f.resolution.id <= maxResolution)
398 .filter(f => {
399 const fileBitrate = (f.size / this.videoDuration)
400 let threshold = fileBitrate
401
402 // If this is for a higher resolution or an initial load: add a margin
403 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
404 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
405 }
406
407 return averageDownloadSpeed > threshold
408 })
409
410 // If the download speed is too bad, return the lowest resolution we have
411 if (filteredFiles.length === 0) return videoFileMinByResolution(files)
412
413 return videoFileMaxByResolution(filteredFiles)
414 }
415
416 private getAndSaveActualDownloadSpeed () {
417 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
418 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
419 if (lastDownloadSpeeds.length === 0) return -1
420
421 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
422 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
423
424 // Save the average bandwidth for future use
425 saveAverageBandwidth(averageBandwidth)
426
427 return averageBandwidth
428 }
429
430 private initializePlayer () {
431 this.buildQualities()
432
433 if (this.autoplay) {
434 this.player.posterImage.hide()
435
436 return this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
437 }
438
439 // Proxy first play
440 const oldPlay = this.player.play.bind(this.player);
441 (this.player as any).play = () => {
442 this.player.addClass('vjs-has-big-play-button-clicked')
443 this.player.play = oldPlay
444
445 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
446 }
447 }
448
449 private runAutoQualityScheduler () {
450 this.autoQualityInterval = setInterval(() => {
451
452 // Not initialized or in HTTP fallback
453 if (this.torrent === undefined || this.torrent === null) return
454 if (this.autoResolution === false) return
455 if (this.isAutoResolutionObservation === true) return
456
457 const file = this.getAppropriateFile()
458 let changeResolution = false
459 let changeResolutionDelay = 0
460
461 // Lower resolution
462 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
463 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
464 changeResolution = true
465 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
466 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
467 changeResolution = true
468 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
469 }
470
471 if (changeResolution === true) {
472 this.updateEngineResolution(file.resolution.id, changeResolutionDelay)
473
474 // Wait some seconds in observation of our new resolution
475 this.isAutoResolutionObservation = true
476
477 this.qualityObservationTimer = setTimeout(() => {
478 this.isAutoResolutionObservation = false
479 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
480 }
481 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
482 }
483
484 private isPlayerWaiting () {
485 return this.player?.hasClass('vjs-waiting')
486 }
487
488 private runTorrentInfoScheduler () {
489 this.torrentInfoInterval = setInterval(() => {
490 // Not initialized yet
491 if (this.torrent === undefined) return
492
493 // Http fallback
494 if (this.torrent === null) return this.player.trigger('p2pInfo', false)
495
496 // this.webtorrent.downloadSpeed because we need to take into account the potential old torrent too
497 if (this.webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(this.webtorrent.downloadSpeed)
498
499 return this.player.trigger('p2pInfo', {
500 source: 'webtorrent',
501 http: {
502 downloadSpeed: 0,
503 uploadSpeed: 0,
504 downloaded: 0,
505 uploaded: 0
506 },
507 p2p: {
508 downloadSpeed: this.torrent.downloadSpeed,
509 numPeers: this.torrent.numPeers,
510 uploadSpeed: this.torrent.uploadSpeed,
511 downloaded: this.torrent.downloaded,
512 uploaded: this.torrent.uploaded
513 },
514 bandwidthEstimate: this.webtorrent.downloadSpeed
515 } as PlayerNetworkInfo)
516 }, this.CONSTANTS.INFO_SCHEDULER)
517 }
518
519 private fallbackToHttp (options: PlayOptions, done?: (err?: Error) => void) {
520 const paused = this.player.paused()
521
522 this.disableAutoResolution()
523
524 this.flushVideoFile(this.currentVideoFile, true)
525 this.torrent = null
526
527 // Enable error display now this is our last fallback
528 this.player.one('error', () => this.player.peertube().displayFatalError())
529
530 const httpUrl = this.currentVideoFile.fileUrl
531 this.player.src = this.savePlayerSrcFunction
532 this.player.src(httpUrl)
533
534 this.selectAppropriateResolution(true)
535
536 // We changed the source, so reinit captions
537 this.player.trigger('sourcechange')
538
539 return this.tryToPlay(err => {
540 if (err && done) return done(err)
541
542 if (options.seek) this.seek(options.seek)
543 if (options.forcePlay === false && paused === true) this.player.pause()
544
545 if (done) return done()
546 })
547 }
548
549 private handleError (err: Error | string) {
550 return this.player.trigger('customError', { err })
551 }
552
553 private pickAverageVideoFile () {
554 if (this.videoFiles.length === 1) return this.videoFiles[0]
555
556 const files = this.videoFiles.filter(f => f.resolution.id !== 0)
557 return files[Math.floor(files.length / 2)]
558 }
559
560 private stopTorrent (torrent: WebTorrent.Torrent) {
561 torrent.pause()
562 // Pause does not remove actual peers (in particular the webseed peer)
563 torrent.removePeer(torrent['ws'])
564 }
565
566 private renderFileInFakeElement (file: WebTorrent.TorrentFile, delay: number) {
567 this.destroyingFakeRenderer = false
568
569 const fakeVideoElem = document.createElement('video')
570 renderVideo(file, fakeVideoElem, { autoplay: false, controls: false }, (err, renderer) => {
571 this.fakeRenderer = renderer
572
573 // The renderer returns an error when we destroy it, so skip them
574 if (this.destroyingFakeRenderer === false && err) {
575 console.error('Cannot render new torrent in fake video element.', err)
576 }
577
578 // Load the future file at the correct time (in delay MS - 2 seconds)
579 fakeVideoElem.currentTime = this.player.currentTime() + (delay - 2000)
580 })
581 }
582
583 private destroyFakeRenderer () {
584 if (this.fakeRenderer) {
585 this.destroyingFakeRenderer = true
586
587 if (this.fakeRenderer.destroy) {
588 try {
589 this.fakeRenderer.destroy()
590 } catch (err) {
591 console.log('Cannot destroy correctly fake renderer.', err)
592 }
593 }
594 this.fakeRenderer = undefined
595 }
596 }
597
598 private buildQualities () {
599 const resolutions: PeerTubeResolution[] = this.videoFiles.map(file => ({
600 id: file.resolution.id,
601 label: this.buildQualityLabel(file),
602 height: file.resolution.id,
603 selected: false,
604 selectCallback: () => this.changeQuality(file.resolution.id)
605 }))
606
607 resolutions.push({
608 id: -1,
609 label: this.player.localize('Auto'),
610 selected: true,
611 selectCallback: () => this.changeQuality(-1)
612 })
613
614 this.player.peertubeResolutions().add(resolutions)
615 }
616
617 private buildQualityLabel (file: VideoFile) {
618 let label = file.resolution.label
619
620 if (file.fps && file.fps >= 50) {
621 label += file.fps
622 }
623
624 return label
625 }
626
627 private selectAppropriateResolution (byEngine: boolean) {
628 const resolution = this.autoResolution
629 ? -1
630 : this.getCurrentResolutionId()
631
632 const autoResolutionChosen = this.autoResolution
633 ? this.getCurrentResolutionId()
634 : undefined
635
636 this.player.peertubeResolutions().select({ id: resolution, autoResolutionChosenId: autoResolutionChosen, byEngine })
637 }
638}
639
640videojs.registerPlugin('webtorrent', WebTorrentPlugin)
641export { WebTorrentPlugin }