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