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