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