]>
Commit | Line | Data |
---|---|---|
83fcadac C |
1 | // Thanks https://github.com/streamroot/videojs-hlsjs-plugin |
2 | // We duplicated this plugin to choose the hls.js version we want, because streamroot only provide a bundled file | |
3 | ||
e367da94 | 4 | import Hlsjs, { ErrorData, HlsConfig, Level, LevelSwitchingData, ManifestParsedData } from 'hls.js' |
512decf3 | 5 | import videojs from 'video.js' |
e367da94 | 6 | import { HlsjsConfigHandlerOptions, PeerTubeResolution, VideoJSTechHLS } from '../peertube-videojs-typings' |
83fcadac C |
7 | |
8 | type ErrorCounts = { | |
9 | [ type: string ]: number | |
10 | } | |
11 | ||
12 | type Metadata = { | |
134006b0 | 13 | levels: Level[] |
83fcadac C |
14 | } |
15 | ||
9df52d66 C |
16 | type HookFn = (player: videojs.Player, hljs: Hlsjs) => void |
17 | ||
83fcadac C |
18 | const registerSourceHandler = function (vjs: typeof videojs) { |
19 | if (!Hlsjs.isSupported()) { | |
20 | console.warn('Hls.js is not supported in this browser!') | |
21 | return | |
22 | } | |
23 | ||
24 | const html5 = vjs.getTech('Html5') | |
25 | ||
26 | if (!html5) { | |
27 | console.error('Not supported version if video.js') | |
28 | return | |
29 | } | |
30 | ||
31 | // FIXME: typings | |
32 | (html5 as any).registerSourceHandler({ | |
33 | canHandleSource: function (source: videojs.Tech.SourceObject) { | |
34 | const hlsTypeRE = /^application\/x-mpegURL|application\/vnd\.apple\.mpegurl$/i | |
35 | const hlsExtRE = /\.m3u8/i | |
36 | ||
37 | if (hlsTypeRE.test(source.type)) return 'probably' | |
38 | if (hlsExtRE.test(source.src)) return 'maybe' | |
39 | ||
40 | return '' | |
41 | }, | |
42 | ||
43 | handleSource: function (source: videojs.Tech.SourceObject, tech: VideoJSTechHLS) { | |
44 | if (tech.hlsProvider) { | |
45 | tech.hlsProvider.dispose() | |
46 | } | |
47 | ||
48 | tech.hlsProvider = new Html5Hlsjs(vjs, source, tech) | |
49 | ||
50 | return tech.hlsProvider | |
51 | } | |
52 | }, 0); | |
53 | ||
54 | // FIXME: typings | |
55 | (vjs as any).Html5Hlsjs = Html5Hlsjs | |
56 | } | |
57 | ||
7e37e111 | 58 | function hlsjsConfigHandler (this: videojs.Player, options: HlsjsConfigHandlerOptions) { |
83fcadac C |
59 | const player = this |
60 | ||
61 | if (!options) return | |
62 | ||
63 | if (!player.srOptions_) { | |
64 | player.srOptions_ = {} | |
65 | } | |
66 | ||
67 | if (!player.srOptions_.hlsjsConfig) { | |
68 | player.srOptions_.hlsjsConfig = options.hlsjsConfig | |
69 | } | |
70 | ||
71 | if (!player.srOptions_.captionConfig) { | |
72 | player.srOptions_.captionConfig = options.captionConfig | |
73 | } | |
74 | ||
75 | if (options.levelLabelHandler && !player.srOptions_.levelLabelHandler) { | |
76 | player.srOptions_.levelLabelHandler = options.levelLabelHandler | |
77 | } | |
78 | } | |
79 | ||
80 | const registerConfigPlugin = function (vjs: typeof videojs) { | |
81 | // Used in Brightcove since we don't pass options directly there | |
82 | const registerVjsPlugin = vjs.registerPlugin || vjs.plugin | |
83 | registerVjsPlugin('hlsjs', hlsjsConfigHandler) | |
84 | } | |
85 | ||
86 | class Html5Hlsjs { | |
9df52d66 | 87 | private static readonly hooks: { [id: string]: HookFn[] } = {} |
83fcadac C |
88 | |
89 | private readonly videoElement: HTMLVideoElement | |
90 | private readonly errorCounts: ErrorCounts = {} | |
7e37e111 | 91 | private readonly player: videojs.Player |
83fcadac C |
92 | private readonly tech: videojs.Tech |
93 | private readonly source: videojs.Tech.SourceObject | |
94 | private readonly vjs: typeof videojs | |
95 | ||
134006b0 C |
96 | private hls: Hlsjs |
97 | private hlsjsConfig: Partial<HlsConfig & { cueHandler: any }> = null | |
83fcadac C |
98 | |
99 | private _duration: number = null | |
100 | private metadata: Metadata = null | |
101 | private isLive: boolean = null | |
102 | private dvrDuration: number = null | |
103 | private edgeMargin: number = null | |
104 | ||
e367da94 C |
105 | private handlers: { [ id in 'play' ]: EventListener } = { |
106 | play: null | |
83fcadac C |
107 | } |
108 | ||
83fcadac C |
109 | constructor (vjs: typeof videojs, source: videojs.Tech.SourceObject, tech: videojs.Tech) { |
110 | this.vjs = vjs | |
111 | this.source = source | |
112 | ||
113 | this.tech = tech; | |
114 | (this.tech as any).name_ = 'Hlsjs' | |
115 | ||
116 | this.videoElement = tech.el() as HTMLVideoElement | |
117 | this.player = vjs((tech.options_ as any).playerId) | |
118 | ||
119 | this.videoElement.addEventListener('error', event => { | |
120 | let errorTxt: string | |
d0dd9813 | 121 | const mediaError = ((event.currentTarget || event.target) as HTMLVideoElement).error |
83fcadac | 122 | |
d0dd9813 C |
123 | if (!mediaError) return |
124 | ||
125 | console.log(mediaError) | |
83fcadac C |
126 | switch (mediaError.code) { |
127 | case mediaError.MEDIA_ERR_ABORTED: | |
128 | errorTxt = 'You aborted the video playback' | |
129 | break | |
130 | case mediaError.MEDIA_ERR_DECODE: | |
9df52d66 C |
131 | errorTxt = 'The video playback was aborted due to a corruption problem or because the video used features ' + |
132 | 'your browser did not support' | |
83fcadac C |
133 | this._handleMediaError(mediaError) |
134 | break | |
135 | case mediaError.MEDIA_ERR_NETWORK: | |
136 | errorTxt = 'A network error caused the video download to fail part-way' | |
137 | break | |
138 | case mediaError.MEDIA_ERR_SRC_NOT_SUPPORTED: | |
139 | errorTxt = 'The video could not be loaded, either because the server or network failed or because the format is not supported' | |
140 | break | |
141 | ||
142 | default: | |
143 | errorTxt = mediaError.message | |
144 | } | |
145 | ||
146 | console.error('MEDIA_ERROR: ', errorTxt) | |
147 | }) | |
148 | ||
149 | this.initialize() | |
150 | } | |
151 | ||
152 | duration () { | |
153 | return this._duration || this.videoElement.duration || 0 | |
154 | } | |
155 | ||
156 | seekable () { | |
157 | if (this.hls.media) { | |
158 | if (!this.isLive) { | |
159 | return this.vjs.createTimeRanges(0, this.hls.media.duration) | |
160 | } | |
161 | ||
162 | // Video.js doesn't seem to like floating point timeranges | |
163 | const startTime = Math.round(this.hls.media.duration - this.dvrDuration) | |
164 | const endTime = Math.round(this.hls.media.duration - this.edgeMargin) | |
165 | ||
166 | return this.vjs.createTimeRanges(startTime, endTime) | |
167 | } | |
168 | ||
169 | return this.vjs.createTimeRanges() | |
170 | } | |
171 | ||
172 | // See comment for `initialize` method. | |
173 | dispose () { | |
174 | this.videoElement.removeEventListener('play', this.handlers.play) | |
83fcadac | 175 | |
83fcadac C |
176 | this.hls.destroy() |
177 | } | |
178 | ||
9df52d66 C |
179 | static addHook (type: string, callback: HookFn) { |
180 | Html5Hlsjs.hooks[type] = this.hooks[type] || [] | |
181 | Html5Hlsjs.hooks[type].push(callback) | |
83fcadac C |
182 | } |
183 | ||
9df52d66 C |
184 | static removeHook (type: string, callback: HookFn) { |
185 | if (Html5Hlsjs.hooks[type] === undefined) return false | |
83fcadac | 186 | |
9df52d66 | 187 | const index = Html5Hlsjs.hooks[type].indexOf(callback) |
83fcadac C |
188 | if (index === -1) return false |
189 | ||
9df52d66 | 190 | Html5Hlsjs.hooks[type].splice(index, 1) |
83fcadac C |
191 | |
192 | return true | |
193 | } | |
194 | ||
195 | private _executeHooksFor (type: string) { | |
9df52d66 | 196 | if (Html5Hlsjs.hooks[type] === undefined) { |
83fcadac C |
197 | return |
198 | } | |
199 | ||
200 | // ES3 and IE < 9 | |
9df52d66 C |
201 | for (let i = 0; i < Html5Hlsjs.hooks[type].length; i++) { |
202 | Html5Hlsjs.hooks[type][i](this.player, this.hls) | |
83fcadac C |
203 | } |
204 | } | |
205 | ||
206 | private _handleMediaError (error: any) { | |
9df52d66 | 207 | if (this.errorCounts[Hlsjs.ErrorTypes.MEDIA_ERROR] === 1) { |
83fcadac C |
208 | console.info('trying to recover media error') |
209 | this.hls.recoverMediaError() | |
210 | return | |
211 | } | |
212 | ||
9df52d66 | 213 | if (this.errorCounts[Hlsjs.ErrorTypes.MEDIA_ERROR] === 2) { |
83fcadac C |
214 | console.info('2nd try to recover media error (by swapping audio codec') |
215 | this.hls.swapAudioCodec() | |
216 | this.hls.recoverMediaError() | |
217 | return | |
218 | } | |
219 | ||
9df52d66 | 220 | if (this.errorCounts[Hlsjs.ErrorTypes.MEDIA_ERROR] > 2) { |
83fcadac | 221 | console.info('bubbling media error up to VIDEOJS') |
adc1f09c | 222 | this.hls.destroy() |
83fcadac C |
223 | this.tech.error = () => error |
224 | this.tech.trigger('error') | |
83fcadac C |
225 | } |
226 | } | |
227 | ||
2d056f66 | 228 | private _handleNetworkError (error: any) { |
9df52d66 | 229 | if (this.errorCounts[Hlsjs.ErrorTypes.NETWORK_ERROR] <= 5) { |
2d056f66 C |
230 | console.info('trying to recover network error') |
231 | ||
232 | // Wait 1 second and retry | |
233 | setTimeout(() => this.hls.startLoad(), 1000) | |
234 | ||
235 | // Reset error count on success | |
236 | this.hls.once(Hlsjs.Events.FRAG_LOADED, () => { | |
9df52d66 | 237 | this.errorCounts[Hlsjs.ErrorTypes.NETWORK_ERROR] = 0 |
2d056f66 C |
238 | }) |
239 | ||
240 | return | |
241 | } | |
242 | ||
243 | console.info('bubbling network error up to VIDEOJS') | |
244 | this.hls.destroy() | |
245 | this.tech.error = () => error | |
246 | this.tech.trigger('error') | |
247 | } | |
248 | ||
134006b0 | 249 | private _onError (_event: any, data: ErrorData) { |
83fcadac C |
250 | const error: { message: string, code?: number } = { |
251 | message: `HLS.js error: ${data.type} - fatal: ${data.fatal} - ${data.details}` | |
252 | } | |
83fcadac C |
253 | |
254 | // increment/set error count | |
9df52d66 C |
255 | if (this.errorCounts[data.type]) this.errorCounts[data.type] += 1 |
256 | else this.errorCounts[data.type] = 1 | |
83fcadac | 257 | |
3e254de8 C |
258 | if (data.fatal) console.warn(error.message) |
259 | else console.error(error.message, data) | |
83fcadac | 260 | |
e25f83ce | 261 | if (data.type === Hlsjs.ErrorTypes.NETWORK_ERROR) { |
e25f83ce | 262 | error.code = 2 |
2d056f66 | 263 | this._handleNetworkError(error) |
3e254de8 | 264 | } else if (data.fatal && data.type === Hlsjs.ErrorTypes.MEDIA_ERROR && data.details !== 'manifestIncompatibleCodecsError') { |
e25f83ce C |
265 | error.code = 3 |
266 | this._handleMediaError(error) | |
3e254de8 | 267 | } else if (data.fatal) { |
e25f83ce C |
268 | this.hls.destroy() |
269 | console.info('bubbling error up to VIDEOJS') | |
270 | this.tech.error = () => error as any | |
271 | this.tech.trigger('error') | |
83fcadac C |
272 | } |
273 | } | |
274 | ||
e367da94 | 275 | private buildLevelLabel (level: Level) { |
83fcadac | 276 | if (this.player.srOptions_.levelLabelHandler) { |
3e254de8 | 277 | return this.player.srOptions_.levelLabelHandler(level as any) |
83fcadac C |
278 | } |
279 | ||
280 | if (level.height) return level.height + 'p' | |
281 | if (level.width) return Math.round(level.width * 9 / 16) + 'p' | |
282 | if (level.bitrate) return (level.bitrate / 1000) + 'kbps' | |
283 | ||
e367da94 | 284 | return '0' |
83fcadac C |
285 | } |
286 | ||
287 | private _notifyVideoQualities () { | |
288 | if (!this.metadata) return | |
83fcadac | 289 | |
e367da94 | 290 | const resolutions: PeerTubeResolution[] = [] |
83fcadac C |
291 | |
292 | this.metadata.levels.forEach((level, index) => { | |
e367da94 | 293 | resolutions.push({ |
83fcadac | 294 | id: index, |
e367da94 C |
295 | height: level.height, |
296 | width: level.width, | |
297 | bitrate: level.bitrate, | |
298 | label: this.buildLevelLabel(level), | |
299 | selected: level.id === this.hls.manualLevel, | |
300 | ||
301 | selectCallback: () => { | |
302 | this.hls.currentLevel = index | |
303 | } | |
304 | }) | |
83fcadac C |
305 | }) |
306 | ||
e367da94 C |
307 | resolutions.push({ |
308 | id: -1, | |
309 | label: this.player.localize('Auto'), | |
310 | selected: true, | |
311 | selectCallback: () => this.hls.currentLevel = -1 | |
312 | }) | |
83fcadac | 313 | |
e367da94 | 314 | this.player.peertubeResolutions().add(resolutions) |
83fcadac C |
315 | } |
316 | ||
317 | private _startLoad () { | |
318 | this.hls.startLoad(-1) | |
319 | this.videoElement.removeEventListener('play', this.handlers.play) | |
320 | } | |
321 | ||
9df52d66 | 322 | private _oneLevelObjClone (obj: { [ id: string ]: any }) { |
83fcadac C |
323 | const result = {} |
324 | const objKeys = Object.keys(obj) | |
325 | for (let i = 0; i < objKeys.length; i++) { | |
9df52d66 | 326 | result[objKeys[i]] = obj[objKeys[i]] |
83fcadac C |
327 | } |
328 | ||
329 | return result | |
330 | } | |
331 | ||
e367da94 | 332 | private _onMetaData (_event: any, data: ManifestParsedData) { |
83fcadac | 333 | // This could arrive before 'loadedqualitydata' handlers is registered, remember it so we can raise it later |
e367da94 C |
334 | this.metadata = data |
335 | this._notifyVideoQualities() | |
83fcadac C |
336 | } |
337 | ||
338 | private _initHlsjs () { | |
339 | const techOptions = this.tech.options_ as HlsjsConfigHandlerOptions | |
340 | const srOptions_ = this.player.srOptions_ | |
341 | ||
9df52d66 | 342 | const hlsjsConfigRef = srOptions_?.hlsjsConfig || techOptions.hlsjsConfig |
83fcadac C |
343 | // Hls.js will write to the reference thus change the object for later streams |
344 | this.hlsjsConfig = hlsjsConfigRef ? this._oneLevelObjClone(hlsjsConfigRef) : {} | |
345 | ||
346 | if ([ '', 'auto' ].includes(this.videoElement.preload) && !this.videoElement.autoplay && this.hlsjsConfig.autoStartLoad === undefined) { | |
347 | this.hlsjsConfig.autoStartLoad = false | |
348 | } | |
349 | ||
83fcadac C |
350 | // If the user explicitly sets autoStartLoad to false, we're not going to enter the if block above |
351 | // That's why we have a separate if block here to set the 'play' listener | |
352 | if (this.hlsjsConfig.autoStartLoad === false) { | |
353 | this.handlers.play = this._startLoad.bind(this) | |
354 | this.videoElement.addEventListener('play', this.handlers.play) | |
355 | } | |
356 | ||
83fcadac C |
357 | this.hls = new Hlsjs(this.hlsjsConfig) |
358 | ||
359 | this._executeHooksFor('beforeinitialize') | |
360 | ||
361 | this.hls.on(Hlsjs.Events.ERROR, (event, data) => this._onError(event, data)) | |
e367da94 | 362 | this.hls.on(Hlsjs.Events.MANIFEST_PARSED, (event, data) => this._onMetaData(event, data)) |
83fcadac C |
363 | this.hls.on(Hlsjs.Events.LEVEL_LOADED, (event, data) => { |
364 | // The DVR plugin will auto seek to "live edge" on start up | |
365 | if (this.hlsjsConfig.liveSyncDuration) { | |
366 | this.edgeMargin = this.hlsjsConfig.liveSyncDuration | |
367 | } else if (this.hlsjsConfig.liveSyncDurationCount) { | |
368 | this.edgeMargin = this.hlsjsConfig.liveSyncDurationCount * data.details.targetduration | |
369 | } | |
370 | ||
371 | this.isLive = data.details.live | |
372 | this.dvrDuration = data.details.totalduration | |
373 | this._duration = this.isLive ? Infinity : data.details.totalduration | |
374 | }) | |
e367da94 | 375 | |
83fcadac C |
376 | this.hls.once(Hlsjs.Events.FRAG_LOADED, () => { |
377 | // Emit custom 'loadedmetadata' event for parity with `videojs-contrib-hls` | |
378 | // Ref: https://github.com/videojs/videojs-contrib-hls#loadedmetadata | |
379 | this.tech.trigger('loadedmetadata') | |
380 | }) | |
381 | ||
e367da94 C |
382 | this.hls.on(Hlsjs.Events.LEVEL_SWITCHING, (_e, data: LevelSwitchingData) => { |
383 | const resolutionId = this.hls.autoLevelEnabled | |
384 | ? -1 | |
385 | : data.level | |
386 | ||
387 | const autoResolutionChosenId = this.hls.autoLevelEnabled | |
388 | ? data.level | |
389 | : -1 | |
390 | ||
391 | this.player.peertubeResolutions().select({ id: resolutionId, autoResolutionChosenId, byEngine: true }) | |
392 | }) | |
393 | ||
83fcadac C |
394 | this.hls.attachMedia(this.videoElement) |
395 | ||
83fcadac C |
396 | this.hls.loadSource(this.source.src) |
397 | } | |
398 | ||
399 | private initialize () { | |
400 | this._initHlsjs() | |
401 | } | |
402 | } | |
403 | ||
404 | export { | |
405 | Html5Hlsjs, | |
406 | registerSourceHandler, | |
407 | registerConfigPlugin | |
408 | } |