@clappr/hlsjs-playback 2.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,733 +0,0 @@
1
- (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('@clappr/core'), require('hls.js')) :
3
- typeof define === 'function' && define.amd ? define(['@clappr/core', 'hls.js'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.HlsjsPlayback = factory(global.Clappr, global.Hls));
5
- })(this, (function (core, HLSJS) { 'use strict';
6
-
7
- // Copyright 2014 Globo.com Player authors. All rights reserved.
8
- // Use of this source code is governed by a BSD-style
9
- // license that can be found in the LICENSE file.
10
-
11
- const {
12
- now,
13
- listContainsIgnoreCase
14
- } = core.Utils;
15
- const AUTO = -1;
16
- const DEFAULT_RECOVER_ATTEMPTS = 16;
17
- core.Events.register('PLAYBACK_FRAGMENT_CHANGED');
18
- core.Events.register('PLAYBACK_FRAGMENT_PARSING_METADATA');
19
- class HlsjsPlayback extends core.HTML5Video {
20
- get name() {
21
- return 'hls';
22
- }
23
- get supportedVersion() {
24
- return {
25
- min: "0.14.8"
26
- };
27
- }
28
- get levels() {
29
- return this._levels || [];
30
- }
31
- get currentLevel() {
32
- if (this._currentLevel === null || this._currentLevel === undefined) {
33
- return AUTO;
34
- } else {
35
- return this._currentLevel;
36
- } // 0 is a valid level ID
37
- }
38
- get isReady() {
39
- return this._isReadyState;
40
- }
41
- set currentLevel(id) {
42
- this._currentLevel = id;
43
- this.trigger(core.Events.PLAYBACK_LEVEL_SWITCH_START);
44
- if (this.options.playback.hlsUseNextLevel) {
45
- this._hls.nextLevel = this._currentLevel;
46
- } else {
47
- this._hls.currentLevel = this._currentLevel;
48
- }
49
- }
50
- get latency() {
51
- return this._hls.latency;
52
- }
53
- get liveSyncPosition() {
54
- return this._hls.liveSyncPosition;
55
- }
56
- get currentProgramDateTime() {
57
- return this._hls.playingDate;
58
- }
59
- get _startTime() {
60
- if (this._playbackType === core.Playback.LIVE && this._playlistType !== 'EVENT') {
61
- return this._extrapolatedStartTime;
62
- }
63
- return this._playableRegionStartTime;
64
- }
65
- get _now() {
66
- return now();
67
- }
68
-
69
- // the time in the video element which should represent the start of the sliding window
70
- // extrapolated to increase in real time (instead of jumping as the early segments are removed)
71
- get _extrapolatedStartTime() {
72
- if (!this._localStartTimeCorrelation) {
73
- return this._playableRegionStartTime;
74
- }
75
- const corr = this._localStartTimeCorrelation;
76
- const timePassed = this._now - corr.local;
77
- const extrapolatedWindowStartTime = (corr.remote + timePassed) / 1000;
78
- // cap at the end of the extrapolated window duration
79
- return Math.min(extrapolatedWindowStartTime, this._playableRegionStartTime + this._extrapolatedWindowDuration);
80
- }
81
-
82
- // the time in the video element which should represent the end of the content
83
- // extrapolated to increase in real time (instead of jumping as segments are added)
84
- get _extrapolatedEndTime() {
85
- const actualEndTime = this._playableRegionStartTime + this._playableRegionDuration;
86
- if (!this._localEndTimeCorrelation) return actualEndTime;
87
- const correlation = this._localEndTimeCorrelation;
88
- const timePassed = this._now - correlation.local;
89
- const extrapolatedEndTime = (correlation.remote + timePassed) / 1000;
90
- return Math.max(actualEndTime - this._extrapolatedWindowDuration, Math.min(extrapolatedEndTime, actualEndTime));
91
- }
92
- get _duration() {
93
- return this._extrapolatedEndTime - this._startTime;
94
- }
95
-
96
- // Returns the duration (seconds) of the window that the extrapolated start time is allowed
97
- // to move in before being capped.
98
- // The extrapolated start time should never reach the cap at the end of the window as the
99
- // window should slide as chunks are removed from the start.
100
- // This also applies to the extrapolated end time in the same way.
101
- //
102
- // If chunks aren't being removed for some reason that the start time will reach and remain fixed at
103
- // playableRegionStartTime + extrapolatedWindowDuration
104
- //
105
- // <-- window duration -->
106
- // I.e playableRegionStartTime |-----------------------|
107
- // | --> . . .
108
- // . --> | --> . .
109
- // . . --> | --> .
110
- // . . . --> |
111
- // . . . .
112
- // extrapolatedStartTime
113
- get _extrapolatedWindowDuration() {
114
- if (this._segmentTargetDuration === null) {
115
- return 0;
116
- }
117
- return this._extrapolatedWindowNumSegments * this._segmentTargetDuration;
118
- }
119
- get bandwidthEstimate() {
120
- return this._hls && this._hls.bandwidthEstimate;
121
- }
122
- get defaultOptions() {
123
- return {
124
- preload: true
125
- };
126
- }
127
- get customListeners() {
128
- return this.options.hlsPlayback && this.options.hlsPlayback.customListeners || [];
129
- }
130
- get sourceMedia() {
131
- return this.options.src;
132
- }
133
- get currentTimestamp() {
134
- if (!this._currentFragment) return null;
135
- const startTime = this._currentFragment.programDateTime;
136
- const playbackTime = this.el.currentTime;
137
- const playTimeOffSet = playbackTime - this._currentFragment.start;
138
- const currentTimestampInMs = startTime + playTimeOffSet * 1000;
139
- return currentTimestampInMs / 1000;
140
- }
141
- static get HLSJS() {
142
- return HLSJS;
143
- }
144
- constructor(...args) {
145
- super(...args);
146
- this.options.hlsPlayback = {
147
- ...this.defaultOptions,
148
- ...this.options.hlsPlayback
149
- };
150
- this._timeUpdateThrottleDelay = 200;
151
- this._timeUpdateFiringRate = 0.2;
152
- this._durationChangeMinOffset = 0.5;
153
- this._setInitialState();
154
- }
155
- _setInitialState() {
156
- this._minDvrSize = typeof this.options.hlsMinimumDvrSize === 'undefined' ? 60 : this.options.hlsMinimumDvrSize;
157
- // The size of the start time extrapolation window measured as a multiple of segments.
158
- // Should be 2 or higher, or 0 to disable. Should only need to be increased above 2 if more than one segment is
159
- // removed from the start of the playlist at a time. E.g if the playlist is cached for 10 seconds and new chunks are
160
- // added/removed every 5.
161
- this._extrapolatedWindowNumSegments = !this.options.playback || typeof this.options.playback.extrapolatedWindowNumSegments === 'undefined' ? 2 : this.options.playback.extrapolatedWindowNumSegments;
162
- this._playbackType = core.Playback.VOD;
163
- this._lastTimeUpdate = {
164
- current: 0,
165
- total: 0,
166
- firstFragDateTime: 0
167
- };
168
- this._lastTimeUpdateFiredTime = 0;
169
- this._lastDuration = null;
170
- // for hls streams which have dvr with a sliding window,
171
- // the content at the start of the playlist is removed as new
172
- // content is appended at the end.
173
- // this means the actual playable start time will increase as the
174
- // start content is deleted
175
- // For streams with dvr where the entire recording is kept from the
176
- // beginning this should stay as 0
177
- this._playableRegionStartTime = 0;
178
- // {local, remote} remote is the time in the video element that should represent 0
179
- // local is the system time when the 'remote' measurment took place
180
- this._localStartTimeCorrelation = null;
181
- // {local, remote} remote is the time in the video element that should represents the end
182
- // local is the system time when the 'remote' measurment took place
183
- this._localEndTimeCorrelation = null;
184
- // if content is removed from the beginning then this empty area should
185
- // be ignored. "playableRegionDuration" excludes the empty area
186
- this._playableRegionDuration = 0;
187
- // #EXT-X-PROGRAM-DATE-TIME
188
- this._programDateTime = 0;
189
- // true when the actual duration is longer than hlsjs's live sync point
190
- // when this is false playableRegionDuration will be the actual duration
191
- // when this is true playableRegionDuration will exclude the time after the sync point
192
- this._durationExcludesAfterLiveSyncPoint = false;
193
- // #EXT-X-TARGETDURATION
194
- this._segmentTargetDuration = null;
195
- // #EXT-X-PLAYLIST-TYPE
196
- this._playlistType = null;
197
- this._recoverAttemptsRemaining = this.options.hlsRecoverAttempts || DEFAULT_RECOVER_ATTEMPTS;
198
- }
199
- _setup() {
200
- this._destroyHLSInstance();
201
- this._createHLSInstance();
202
- this._listenHLSEvents();
203
- this._attachHLSMedia();
204
- }
205
- _destroyHLSInstance() {
206
- if (!this._hls) return;
207
- this._manifestLoading = false;
208
- this._ccIsSetup = false;
209
- this._ccTracksUpdated = false;
210
- this._setInitialState();
211
- this._hls.destroy();
212
- this._hls = null;
213
- }
214
- _createHLSInstance() {
215
- const config = {
216
- ...this.options.playback.hlsjsConfig
217
- };
218
- this._hls = new HLSJS(config);
219
- }
220
- _attachHLSMedia() {
221
- if (!this._hls) return;
222
- this._hls.attachMedia(this.el);
223
- }
224
- _listenHLSEvents() {
225
- if (!this._hls) return;
226
- this._hls.once(HLSJS.Events.MEDIA_ATTACHED, () => {
227
- this.options.hlsPlayback.preload && this._hls.loadSource(this.options.src);
228
- });
229
- this._hls.on(HLSJS.Events.MANIFEST_LOADING, () => {
230
- this._manifestLoading = true;
231
- });
232
- this._hls.on(HLSJS.Events.LEVEL_LOADED, (evt, data) => this._updatePlaybackType(evt, data));
233
- this._hls.on(HLSJS.Events.LEVEL_UPDATED, (evt, data) => this._onLevelUpdated(evt, data));
234
- this._hls.on(HLSJS.Events.LEVEL_SWITCHED, (evt, data) => this._onLevelSwitch(evt, data));
235
- this._hls.on(HLSJS.Events.FRAG_CHANGED, (evt, data) => this._onFragmentChanged(evt, data));
236
- this._hls.on(HLSJS.Events.FRAG_LOADED, (evt, data) => this._onFragmentLoaded(evt, data));
237
- this._hls.on(HLSJS.Events.FRAG_BUFFERED, (evt, data) => this._onFragmentBuffered(evt, data));
238
- this._hls.on(HLSJS.Events.FRAG_PARSING_METADATA, (evt, data) => this._onFragmentParsingMetadata(evt, data));
239
- this._hls.on(HLSJS.Events.ERROR, (evt, data) => this._onHLSJSError(evt, data));
240
- this._hls.on(HLSJS.Events.SUBTITLE_TRACK_LOADED, (evt, data) => this._onSubtitleLoaded(evt, data));
241
- this._hls.on(HLSJS.Events.SUBTITLE_TRACKS_UPDATED, () => this._ccTracksUpdated = true);
242
- this.bindCustomListeners();
243
- }
244
- bindCustomListeners() {
245
- this.customListeners.forEach(item => {
246
- const requestedEventName = item.eventName;
247
- const typeOfListener = item.once ? 'once' : 'on';
248
- requestedEventName && this._hls[`${typeOfListener}`](requestedEventName, item.callback);
249
- });
250
- }
251
- unbindCustomListeners() {
252
- this.customListeners.forEach(item => {
253
- const requestedEventName = item.eventName;
254
- requestedEventName && this._hls.off(requestedEventName, item.callback);
255
- });
256
- }
257
- _onFragmentParsingMetadata(evt, data) {
258
- this.trigger(core.Events.Custom.PLAYBACK_FRAGMENT_PARSING_METADATA, {
259
- evt,
260
- data
261
- });
262
- }
263
- render() {
264
- this._ready();
265
- return super.render();
266
- }
267
- _ready() {
268
- if (this._isReadyState) return;
269
- !this._hls && this._setup();
270
- this._isReadyState = true;
271
- this.trigger(core.Events.PLAYBACK_READY, this.name);
272
- }
273
- _recover(evt, data, error) {
274
- if (!this._recoveredDecodingError) {
275
- this._recoveredDecodingError = true;
276
- this._hls.recoverMediaError();
277
- this.play();
278
- } else if (!this._recoveredAudioCodecError) {
279
- this._recoveredAudioCodecError = true;
280
- this._hls.swapAudioCodec();
281
- this._hls.recoverMediaError();
282
- this.play();
283
- } else {
284
- core.Log.error('hlsjs: failed to recover', {
285
- evt,
286
- data
287
- });
288
- error.level = core.PlayerError.Levels.FATAL;
289
- const formattedError = this.createError(error);
290
- this.trigger(core.Events.PLAYBACK_ERROR, formattedError);
291
- this.stop();
292
- }
293
- }
294
-
295
- // override
296
- // this playback manages the src on the video element itself
297
- _setupSrc(srcUrl) {} // eslint-disable-line no-unused-vars
298
-
299
- _startTimeUpdateTimer() {
300
- if (this._timeUpdateTimer) return;
301
- this._timeUpdateTimer = setInterval(() => {
302
- this._onDurationChange();
303
- this._onTimeUpdate();
304
- }, 100);
305
- }
306
- _stopTimeUpdateTimer() {
307
- if (!this._timeUpdateTimer) return;
308
- clearInterval(this._timeUpdateTimer);
309
- this._timeUpdateTimer = null;
310
- }
311
- getProgramDateTime() {
312
- return this._programDateTime;
313
- }
314
-
315
- // the duration on the video element itself should not be used
316
- // as this does not necesarily represent the duration of the stream
317
- // https://github.com/clappr/clappr/issues/668#issuecomment-157036678
318
- getDuration() {
319
- return this._duration;
320
- }
321
-
322
- // the frame rate should be retrieved from the HLS.js level information
323
- // as it is not necessarily exposed directly by the video element
324
- getFrameRate() {
325
- if (this._hls && this._hls.levels && this._hls.currentLevel >= 0) {
326
- const level = this._hls.levels[this._hls.currentLevel];
327
- return level && level.frameRate ? level.frameRate : null;
328
- }
329
- return null;
330
- }
331
- getCurrentTime() {
332
- // e.g. can be < 0 if user pauses near the start
333
- // eventually they will then be kicked to the end by hlsjs if they run out of buffer
334
- // before the official start time
335
- return Math.max(0, this.el.currentTime - this._startTime);
336
- }
337
-
338
- // the time that "0" now represents relative to when playback started
339
- // for a stream with a sliding window this will increase as content is
340
- // removed from the beginning
341
- getStartTimeOffset() {
342
- return this._startTime;
343
- }
344
- seekPercentage(percentage) {
345
- const seekTo = percentage > 0 ? this._duration * (percentage / 100) : this._duration;
346
- this.seek(seekTo);
347
- }
348
- seek(time) {
349
- if (time < 0) {
350
- core.Log.warn('Attempt to seek to a negative time. Resetting to live point. Use seekToLivePoint() to seek to the live point.');
351
- time = this.getDuration();
352
- }
353
- time += this._startTime;
354
- this.el.currentTime = time;
355
- }
356
- seekToLivePoint() {
357
- this.seek(this.getDuration());
358
- }
359
- _updateSettings() {
360
- if (this._playbackType === core.Playback.VOD) {
361
- this.settings.left = ['playpause', 'position', 'duration'];
362
- } else if (this.dvrEnabled) {
363
- this.settings.left = ['playpause'];
364
- } else {
365
- this.settings.left = ['playstop'];
366
- }
367
- this.settings.seekEnabled = this.isSeekEnabled();
368
- this.trigger(core.Events.PLAYBACK_SETTINGSUPDATE);
369
- }
370
- _onHLSJSError(evt, data) {
371
- const error = {
372
- code: `${data.type}_${data.details}`,
373
- description: `${this.name} error: type: ${data.type}, details: ${data.details}`,
374
- raw: data
375
- };
376
- let formattedError;
377
- if (data.response) error.description += `, response: ${JSON.stringify(data.response)}`;
378
- // only report/handle errors if they are fatal
379
- // hlsjs should automatically handle non fatal errors
380
- if (data.fatal) {
381
- if (this._recoverAttemptsRemaining > 0) {
382
- this._recoverAttemptsRemaining -= 1;
383
- switch (data.type) {
384
- case HLSJS.ErrorTypes.NETWORK_ERROR:
385
- switch (data.details) {
386
- // The following network errors cannot be recovered with HLS.startLoad()
387
- // For more details, see https://github.com/video-dev/hls.js/blob/master/doc/design.md#error-detection-and-handling
388
- // For "level load" fatal errors, see https://github.com/video-dev/hls.js/issues/1138
389
- case HLSJS.ErrorDetails.MANIFEST_LOAD_ERROR:
390
- case HLSJS.ErrorDetails.MANIFEST_LOAD_TIMEOUT:
391
- case HLSJS.ErrorDetails.MANIFEST_PARSING_ERROR:
392
- case HLSJS.ErrorDetails.LEVEL_LOAD_ERROR:
393
- case HLSJS.ErrorDetails.LEVEL_LOAD_TIMEOUT:
394
- core.Log.error('hlsjs: unrecoverable network fatal error.', {
395
- evt,
396
- data
397
- });
398
- formattedError = this.createError(error);
399
- this.trigger(core.Events.PLAYBACK_ERROR, formattedError);
400
- this.stop();
401
- break;
402
- default:
403
- core.Log.warn('hlsjs: trying to recover from network error.', {
404
- evt,
405
- data
406
- });
407
- error.level = core.PlayerError.Levels.WARN;
408
- this._hls.startLoad();
409
- break;
410
- }
411
- break;
412
- case HLSJS.ErrorTypes.MEDIA_ERROR:
413
- core.Log.warn('hlsjs: trying to recover from media error.', {
414
- evt,
415
- data
416
- });
417
- error.level = core.PlayerError.Levels.WARN;
418
- this._recover(evt, data, error);
419
- break;
420
- default:
421
- core.Log.error('hlsjs: could not recover from error.', {
422
- evt,
423
- data
424
- });
425
- formattedError = this.createError(error);
426
- this.trigger(core.Events.PLAYBACK_ERROR, formattedError);
427
- this.stop();
428
- break;
429
- }
430
- } else {
431
- core.Log.error('hlsjs: could not recover from error after maximum number of attempts.', {
432
- evt,
433
- data
434
- });
435
- formattedError = this.createError(error);
436
- this.trigger(core.Events.PLAYBACK_ERROR, formattedError);
437
- this.stop();
438
- }
439
- } else {
440
- // Transforms HLSJS.ErrorDetails.KEY_LOAD_ERROR non-fatal error to
441
- // playback fatal error if triggerFatalErrorOnResourceDenied playback
442
- // option is set. HLSJS.ErrorTypes.KEY_SYSTEM_ERROR are fatal errors
443
- // and therefore already handled.
444
- if (this.options.playback.triggerFatalErrorOnResourceDenied && this._keyIsDenied(data)) {
445
- core.Log.error('hlsjs: could not load decrypt key.', {
446
- evt,
447
- data
448
- });
449
- formattedError = this.createError(error);
450
- this.trigger(core.Events.PLAYBACK_ERROR, formattedError);
451
- this.stop();
452
- return;
453
- }
454
- error.level = core.PlayerError.Levels.WARN;
455
- core.Log.warn('hlsjs: non-fatal error occurred', {
456
- evt,
457
- data
458
- });
459
- }
460
- }
461
- _keyIsDenied(data) {
462
- return data.type === HLSJS.ErrorTypes.NETWORK_ERROR && data.details === HLSJS.ErrorDetails.KEY_LOAD_ERROR && data.response && data.response.code >= 400;
463
- }
464
- _onTimeUpdate() {
465
- const update = {
466
- current: this.getCurrentTime(),
467
- total: this.getDuration(),
468
- firstFragDateTime: this.getProgramDateTime()
469
- };
470
- const shouldThrottle = this._shouldThrottleTimeUpdate(update);
471
- if (shouldThrottle) return;
472
- this._lastTimeUpdate = update;
473
- this._lastTimeUpdateFiredTime = this._now;
474
- this.trigger(core.Events.PLAYBACK_TIMEUPDATE, update, this.name);
475
- }
476
- _shouldThrottleTimeUpdate(update) {
477
- const isSameTime = Math.abs(update.current - this._lastTimeUpdate.current) < this._timeUpdateFiringRate;
478
- const isSameDuration = Math.abs(update.total - this._lastTimeUpdate.total) < this._durationChangeMinOffset;
479
- const isSameFirstFragDateTime = update.firstFragDateTime === this._lastTimeUpdate.firstFragDateTime;
480
- const isSameEventPayload = isSameTime && isSameDuration && isSameFirstFragDateTime;
481
- const isThrottled = this._now - this._lastTimeUpdateFiredTime < this._timeUpdateThrottleDelay;
482
- return isSameEventPayload && isThrottled;
483
- }
484
- _onDurationChange() {
485
- const duration = this.getDuration();
486
- const isSameDuration = Math.abs(this._lastDuration - duration) < this._durationChangeMinOffset;
487
- if (isSameDuration) return;
488
- this._lastDuration = duration;
489
- super._onDurationChange();
490
- }
491
- _onProgress() {
492
- if (!this.el.buffered.length) return;
493
- let buffered = [];
494
- let bufferedPos = 0;
495
- for (let i = 0; i < this.el.buffered.length; i++) {
496
- buffered = [...buffered, {
497
- // for a stream with sliding window dvr something that is buffered my slide off the start of the timeline
498
- start: Math.max(0, this.el.buffered.start(i) - this._playableRegionStartTime),
499
- end: Math.max(0, this.el.buffered.end(i) - this._playableRegionStartTime)
500
- }];
501
- if (this.el.currentTime >= buffered[i].start && this.el.currentTime <= buffered[i].end) {
502
- bufferedPos = i;
503
- }
504
- }
505
- const progress = {
506
- start: buffered[bufferedPos].start,
507
- current: buffered[bufferedPos].end,
508
- total: this.getDuration()
509
- };
510
- this.trigger(core.Events.PLAYBACK_PROGRESS, progress, buffered);
511
- }
512
- load(url) {
513
- this._stopTimeUpdateTimer();
514
- this.options.src = url;
515
- this._setup();
516
- }
517
- play() {
518
- !this._hls && this._setup();
519
- !this._manifestLoading && !this.options.hlsPlayback.preload && this._hls.loadSource(this.options.src);
520
- super.play();
521
- this._startTimeUpdateTimer();
522
- }
523
- pause() {
524
- if (!this._hls) return;
525
- this.el.pause();
526
- }
527
- stop() {
528
- this._stopTimeUpdateTimer();
529
- if (this._hls) super.stop();
530
- this._destroyHLSInstance();
531
- }
532
- destroy() {
533
- this._stopTimeUpdateTimer();
534
- this._destroyHLSInstance();
535
- super.destroy();
536
- }
537
- _updatePlaybackType(evt, data) {
538
- this._playbackType = data.details.live ? core.Playback.LIVE : core.Playback.VOD;
539
- this._onLevelUpdated(evt, data);
540
- // Live stream subtitle tracks detection hack (may not immediately available)
541
- if (this._ccTracksUpdated && this._playbackType === core.Playback.LIVE && this.hasClosedCaptionsTracks) {
542
- this._onSubtitleLoaded();
543
- }
544
- }
545
- _fillLevels() {
546
- this._levels = this._hls.levels.map((level, index) => {
547
- return {
548
- id: index,
549
- level: level,
550
- label: `${level.bitrate / 1000}Kbps`
551
- };
552
- });
553
- this.trigger(core.Events.PLAYBACK_LEVELS_AVAILABLE, this._levels);
554
- }
555
- _onLevelUpdated(evt, data) {
556
- this._segmentTargetDuration = data.details.targetduration;
557
- this._playlistType = data.details.type || null;
558
- let startTimeChanged = false;
559
- let durationChanged = false;
560
- const fragments = data.details.fragments;
561
- const previousPlayableRegionStartTime = this._playableRegionStartTime;
562
- const previousPlayableRegionDuration = this._playableRegionDuration;
563
- if (fragments.length === 0) return;
564
- // #EXT-X-PROGRAM-DATE-TIME
565
- if (fragments[0].rawProgramDateTime) {
566
- this._programDateTime = fragments[0].rawProgramDateTime;
567
- }
568
- if (this._playableRegionStartTime !== fragments[0].start) {
569
- startTimeChanged = true;
570
- this._playableRegionStartTime = fragments[0].start;
571
- }
572
- if (startTimeChanged) {
573
- if (!this._localStartTimeCorrelation) {
574
- // set the correlation to map to middle of the extrapolation window
575
- this._localStartTimeCorrelation = {
576
- local: this._now,
577
- remote: (fragments[0].start + this._extrapolatedWindowDuration / 2) * 1000
578
- };
579
- } else {
580
- // check if the correlation still works
581
- const corr = this._localStartTimeCorrelation;
582
- const timePassed = this._now - corr.local;
583
- // this should point to a time within the extrapolation window
584
- const startTime = (corr.remote + timePassed) / 1000;
585
- if (startTime < fragments[0].start) {
586
- // our start time is now earlier than the first chunk
587
- // (maybe the chunk was removed early)
588
- // reset correlation so that it sits at the beginning of the first available chunk
589
- this._localStartTimeCorrelation = {
590
- local: this._now,
591
- remote: fragments[0].start * 1000
592
- };
593
- } else if (startTime > previousPlayableRegionStartTime + this._extrapolatedWindowDuration) {
594
- // start time was past the end of the old extrapolation window (so would have been capped)
595
- // see if now that time would be inside the window, and if it would be set the correlation
596
- // so that it resumes from the time it was at at the end of the old window
597
- // update the correlation so that the time starts counting again from the value it's on now
598
- this._localStartTimeCorrelation = {
599
- local: this._now,
600
- remote: Math.max(fragments[0].start, previousPlayableRegionStartTime + this._extrapolatedWindowDuration) * 1000
601
- };
602
- }
603
- }
604
- }
605
- let newDuration = data.details.totalduration;
606
- // if it's a live stream then shorten the duration to remove access
607
- // to the area after hlsjs's live sync point
608
- // seeks to areas after this point sometimes have issues
609
- if (this._playbackType === core.Playback.LIVE) {
610
- const fragmentTargetDuration = data.details.targetduration;
611
- const hlsjsConfig = this.options.playback.hlsjsConfig || {};
612
- const liveSyncDurationCount = hlsjsConfig.liveSyncDurationCount || HLSJS.DefaultConfig.liveSyncDurationCount;
613
- const hiddenAreaDuration = fragmentTargetDuration * liveSyncDurationCount;
614
- if (hiddenAreaDuration <= newDuration) {
615
- newDuration -= hiddenAreaDuration;
616
- this._durationExcludesAfterLiveSyncPoint = true;
617
- } else {
618
- this._durationExcludesAfterLiveSyncPoint = false;
619
- }
620
- }
621
- if (newDuration !== this._playableRegionDuration) {
622
- durationChanged = true;
623
- this._playableRegionDuration = newDuration;
624
- }
625
- // Note the end time is not the playableRegionDuration
626
- // The end time will always increase even if content is removed from the beginning
627
- const endTime = fragments[0].start + newDuration;
628
- const previousEndTime = previousPlayableRegionStartTime + previousPlayableRegionDuration;
629
- const endTimeChanged = endTime !== previousEndTime;
630
- if (endTimeChanged) {
631
- if (!this._localEndTimeCorrelation) {
632
- // set the correlation to map to the end
633
- this._localEndTimeCorrelation = {
634
- local: this._now,
635
- remote: endTime * 1000
636
- };
637
- } else {
638
- // check if the correlation still works
639
- const corr = this._localEndTimeCorrelation;
640
- const timePassed = this._now - corr.local;
641
- // this should point to a time within the extrapolation window from the end
642
- const extrapolatedEndTime = (corr.remote + timePassed) / 1000;
643
- if (extrapolatedEndTime > endTime) {
644
- this._localEndTimeCorrelation = {
645
- local: this._now,
646
- remote: endTime * 1000
647
- };
648
- } else if (extrapolatedEndTime < endTime - this._extrapolatedWindowDuration) {
649
- // our extrapolated end time is now earlier than the extrapolation window from the actual end time
650
- // (maybe a chunk became available early)
651
- // reset correlation so that it sits at the beginning of the extrapolation window from the end time
652
- this._localEndTimeCorrelation = {
653
- local: this._now,
654
- remote: (endTime - this._extrapolatedWindowDuration) * 1000
655
- };
656
- } else if (extrapolatedEndTime > previousEndTime) {
657
- // end time was past the old end time (so would have been capped)
658
- // set the correlation so that it resumes from the time it was at at the end of the old window
659
- this._localEndTimeCorrelation = {
660
- local: this._now,
661
- remote: previousEndTime * 1000
662
- };
663
- }
664
- }
665
- }
666
-
667
- // now that the values have been updated call any methods that use on them so they get the updated values
668
- // immediately
669
- durationChanged && this._onDurationChange();
670
- startTimeChanged && this._onProgress();
671
- }
672
- _onFragmentChanged(evt, data) {
673
- this._currentFragment = data.frag;
674
- this.trigger(core.Events.Custom.PLAYBACK_FRAGMENT_CHANGED, data);
675
- }
676
- _onFragmentLoaded(evt, data) {
677
- this.trigger(core.Events.PLAYBACK_FRAGMENT_LOADED, data);
678
- }
679
- _onFragmentBuffered(evt, data) {
680
- this.trigger(core.Events.PLAYBACK_FRAGMENT_BUFFERED, data);
681
- }
682
- _onSubtitleLoaded() {
683
- // This event may be triggered multiple times
684
- // Setup CC only once (disable CC by default)
685
- if (!this._ccIsSetup) {
686
- this.trigger(core.Events.PLAYBACK_SUBTITLE_AVAILABLE);
687
- const trackId = this._playbackType === core.Playback.LIVE ? -1 : this.closedCaptionsTrackId;
688
- this.closedCaptionsTrackId = trackId;
689
- this._ccIsSetup = true;
690
- }
691
- }
692
- _onLevelSwitch(evt, data) {
693
- if (!this.levels.length) this._fillLevels();
694
- this.trigger(core.Events.PLAYBACK_LEVEL_SWITCH_END);
695
- this.trigger(core.Events.PLAYBACK_LEVEL_SWITCH, data);
696
- const currentLevel = this._hls.levels[data.level];
697
- if (currentLevel) {
698
- // TODO should highDefinition be private and maybe have a read only accessor if it's used somewhere
699
- this.highDefinition = currentLevel.height >= 720 || currentLevel.bitrate / 1000 >= 2000;
700
- this.trigger(core.Events.PLAYBACK_HIGHDEFINITIONUPDATE, this.highDefinition);
701
- this.trigger(core.Events.PLAYBACK_BITRATE, {
702
- height: currentLevel.height,
703
- width: currentLevel.width,
704
- bandwidth: currentLevel.bitrate,
705
- bitrate: currentLevel.bitrate,
706
- level: data.level
707
- });
708
- }
709
- }
710
- get dvrEnabled() {
711
- // enabled when:
712
- // - the duration does not include content after hlsjs's live sync point
713
- // - the playable region duration is longer than the configured duration to enable dvr after
714
- // - the playback type is LIVE.
715
- return this._durationExcludesAfterLiveSyncPoint && this._duration >= this._minDvrSize && this.getPlaybackType() === core.Playback.LIVE;
716
- }
717
- getPlaybackType() {
718
- return this._playbackType;
719
- }
720
- isSeekEnabled() {
721
- return this._playbackType === core.Playback.VOD || this.dvrEnabled;
722
- }
723
- }
724
- HlsjsPlayback.canPlay = function (resource, mimeType) {
725
- const resourceParts = resource.split('?')[0].match(/.*\.(.*)$/) || [];
726
- const isHls = resourceParts.length > 1 && resourceParts[1].toLowerCase() === 'm3u8' || listContainsIgnoreCase(mimeType, ['application/vnd.apple.mpegurl', 'application/x-mpegURL']);
727
- return !!(HLSJS.isSupported() && isHls);
728
- };
729
-
730
- return HlsjsPlayback;
731
-
732
- }));
733
- //# sourceMappingURL=hlsjs-playback.external.js.map