@videojs/hlsjs-video 10.2.0 → 10.3.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.
- package/dist/default/adapter.js +8 -1
- package/dist/default/cap-level.js +8 -17
- package/dist/default/hls-js-only.js +3 -0
- package/dist/default/media-tracks.js +20 -10
- package/dist/default/preload.js +12 -2
- package/dist/default/request-credentials.js +3 -3
- package/dist/default/text-tracks.js +38 -13
- package/dist/dev/adapter.d.ts +5 -0
- package/dist/dev/adapter.js +8 -1
- package/dist/dev/adapter.js.map +1 -1
- package/dist/dev/cap-level.js +8 -17
- package/dist/dev/cap-level.js.map +1 -1
- package/dist/dev/hls-js-only.js +3 -0
- package/dist/dev/hls-js-only.js.map +1 -1
- package/dist/dev/media-tracks.js +20 -10
- package/dist/dev/media-tracks.js.map +1 -1
- package/dist/dev/preload.js +12 -2
- package/dist/dev/preload.js.map +1 -1
- package/dist/dev/request-credentials.js +3 -3
- package/dist/dev/request-credentials.js.map +1 -1
- package/dist/dev/text-tracks.js +38 -13
- package/dist/dev/text-tracks.js.map +1 -1
- package/package.json +6 -6
package/dist/default/adapter.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { HlsJsOnlyAdapter } from "./hls-js-only.js";
|
|
2
2
|
import { MediaStreamTypes, bridgeEvents } from "@videojs/media";
|
|
3
|
-
import { HTMLVideoAdapter } from "@videojs/media/dom";
|
|
3
|
+
import { HTMLVideoAdapter, getMediaEngineName } from "@videojs/media/dom";
|
|
4
4
|
import { NativeHlsAdapter } from "@videojs/native-hls-video";
|
|
5
5
|
import { deepEqual } from "@videojs/utils/object";
|
|
6
6
|
import Hls$1 from "hls.js";
|
|
@@ -89,6 +89,13 @@ var HlsJsAdapter = class HlsJsAdapter extends HTMLVideoAdapter {
|
|
|
89
89
|
get engine() {
|
|
90
90
|
return this.#delegate?.engine ?? null;
|
|
91
91
|
}
|
|
92
|
+
/**
|
|
93
|
+
* Engine this media is playing through, reported to analytics such as Mux Data: `hlsjs` via MSE, `browser` for native
|
|
94
|
+
* HLS, or `undefined` until a source loads. Read from the instance because the engine is picked per source.
|
|
95
|
+
*/
|
|
96
|
+
get engineName() {
|
|
97
|
+
return getMediaEngineName(this.#delegate);
|
|
98
|
+
}
|
|
92
99
|
get error() {
|
|
93
100
|
return this.#delegate?.error ?? null;
|
|
94
101
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import Hls from "hls.js";
|
|
1
|
+
import Hls, { CapLevelController } from "hls.js";
|
|
2
2
|
//#region src/cap-level.ts
|
|
3
3
|
/**
|
|
4
4
|
* Floor applied to the player-size cap unless a source names another.
|
|
@@ -65,22 +65,21 @@ function levelIndexAtOrAbove(levels, resolution) {
|
|
|
65
65
|
/**
|
|
66
66
|
* Build the `capLevelController` class to hand to the hls.js constructor.
|
|
67
67
|
*
|
|
68
|
-
* `hls.autoLevelCapping`
|
|
69
|
-
* interval for as long as `capLevelToPlayerSize` is on — and it is on by
|
|
70
|
-
* outside is undone
|
|
71
|
-
* with it.
|
|
68
|
+
* `hls.autoLevelCapping` is rewritten by hls.js's own `CapLevelController` whenever the element resizes (or on a
|
|
69
|
+
* one-second interval where `ResizeObserver` is missing) for as long as `capLevelToPlayerSize` is on — and it is on by
|
|
70
|
+
* default here. Assigning the property from outside is undone on the next measurement, so a cap has to be applied from
|
|
71
|
+
* inside the controller rather than in competition with it.
|
|
72
72
|
*
|
|
73
73
|
* The only seam hls.js offers is `getMaxLevel()`, which every value the capping loop writes passes through. Overriding
|
|
74
|
-
* it makes the requested ceiling part of the same
|
|
74
|
+
* it makes the requested ceiling part of the same computation.
|
|
75
75
|
*
|
|
76
76
|
* @param policy - Live cap inputs, re-read on every evaluation.
|
|
77
77
|
* @param BaseController - Controller to layer on top of, so a controller passed through
|
|
78
78
|
* `source.engine.capLevelController` keeps its behavior.
|
|
79
79
|
*/
|
|
80
|
-
function createCapLevelController(policy, BaseController = Hls.DefaultConfig.capLevelController) {
|
|
80
|
+
function createCapLevelController(policy, BaseController = Hls.DefaultConfig.capLevelController ?? CapLevelController) {
|
|
81
81
|
return class RenditionCapLevelController extends BaseController {
|
|
82
82
|
#hls;
|
|
83
|
-
#capping = false;
|
|
84
83
|
#measuringWithoutSize = false;
|
|
85
84
|
constructor(hls) {
|
|
86
85
|
super(hls);
|
|
@@ -95,14 +94,6 @@ function createCapLevelController(policy, BaseController = Hls.DefaultConfig.cap
|
|
|
95
94
|
if (policy.controller === this) policy.controller = void 0;
|
|
96
95
|
super.destroy();
|
|
97
96
|
}
|
|
98
|
-
startCapping() {
|
|
99
|
-
this.#capping = true;
|
|
100
|
-
super.startCapping();
|
|
101
|
-
}
|
|
102
|
-
stopCapping() {
|
|
103
|
-
this.#capping = false;
|
|
104
|
-
super.stopCapping();
|
|
105
|
-
}
|
|
106
97
|
/**
|
|
107
98
|
* Hls.js derives its player-size ceiling from these two, so reporting an unbounded measurement is how
|
|
108
99
|
* `capToPlayerSize: false` switches that ceiling off while leaving the rest of the base controller intact.
|
|
@@ -163,7 +154,7 @@ function createCapLevelController(policy, BaseController = Hls.DefaultConfig.cap
|
|
|
163
154
|
this.#applyResolutionCap();
|
|
164
155
|
}
|
|
165
156
|
apply() {
|
|
166
|
-
if (this.#
|
|
157
|
+
if (this.#hls.config.capLevelToPlayerSize) {
|
|
167
158
|
this.detectPlayerSize();
|
|
168
159
|
return;
|
|
169
160
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import Hls from "hls.js";
|
|
2
2
|
//#region src/media-tracks.ts
|
|
3
|
-
function
|
|
4
|
-
return `${
|
|
3
|
+
function getRenditionKey(width, height, codec, bitrate) {
|
|
4
|
+
return `${width}x${height}|${codec}|${bitrate}`;
|
|
5
5
|
}
|
|
6
6
|
function getAudioTrackKind(audioTrack) {
|
|
7
7
|
return audioTrack.default ? "main" : "alternative";
|
|
@@ -15,7 +15,6 @@ function getAudioTrackKind(audioTrack) {
|
|
|
15
15
|
*/
|
|
16
16
|
function HlsJsMediaTracksMixin(BaseClass) {
|
|
17
17
|
class HlsJsMediaTracks extends BaseClass {
|
|
18
|
-
#levelIdMap = /* @__PURE__ */ new Map();
|
|
19
18
|
#currentVideoTrack = null;
|
|
20
19
|
constructor(...args) {
|
|
21
20
|
super(...args);
|
|
@@ -33,13 +32,11 @@ function HlsJsMediaTracksMixin(BaseClass) {
|
|
|
33
32
|
}
|
|
34
33
|
#onManifestParsed = (_event, data) => {
|
|
35
34
|
this.#removeAllMediaTracks();
|
|
36
|
-
this.#levelIdMap.clear();
|
|
37
35
|
const videoTrack = this.addVideoTrack("main");
|
|
38
36
|
this.#currentVideoTrack = videoTrack;
|
|
39
37
|
videoTrack.selected = true;
|
|
40
38
|
for (const [id, level] of data.levels.entries()) {
|
|
41
39
|
const rendition = videoTrack.addRendition(level.url[0] ?? "", level.width, level.height, level.videoCodec, level.bitrate);
|
|
42
|
-
this.#levelIdMap.set(getLevelKey(level), `${id}`);
|
|
43
40
|
rendition.id = `${id}`;
|
|
44
41
|
}
|
|
45
42
|
};
|
|
@@ -75,9 +72,22 @@ function HlsJsMediaTracksMixin(BaseClass) {
|
|
|
75
72
|
for (const track of enabledTracks) if (track !== selectedTrack) track.enabled = false;
|
|
76
73
|
};
|
|
77
74
|
#onLevelsUpdated = (_event, data) => {
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
75
|
+
const videoTrack = this.#currentVideoTrack;
|
|
76
|
+
if (!videoTrack) return;
|
|
77
|
+
const renditionsByKey = /* @__PURE__ */ new Map();
|
|
78
|
+
for (const rendition of this.videoRenditions) {
|
|
79
|
+
const key = getRenditionKey(rendition.width, rendition.height, rendition.codec, rendition.bitrate);
|
|
80
|
+
renditionsByKey.set(key, [...renditionsByKey.get(key) ?? [], rendition]);
|
|
81
|
+
}
|
|
82
|
+
const current = /* @__PURE__ */ new Set();
|
|
83
|
+
for (const [index, level] of data.levels.entries()) {
|
|
84
|
+
const key = getRenditionKey(level.width, level.height, level.videoCodec, level.bitrate);
|
|
85
|
+
const rendition = renditionsByKey.get(key)?.shift() ?? videoTrack.addRendition(level.url[0] ?? "", level.width, level.height, level.videoCodec, level.bitrate);
|
|
86
|
+
rendition.id = `${index}`;
|
|
87
|
+
current.add(rendition);
|
|
88
|
+
}
|
|
89
|
+
for (const rendition of [...this.videoRenditions]) if (rendition.id && !current.has(rendition)) videoTrack.removeRendition(rendition);
|
|
90
|
+
this.#switchRendition();
|
|
81
91
|
};
|
|
82
92
|
#onLevelSwitched = (_event, data) => {
|
|
83
93
|
const activeId = `${data.level}`;
|
|
@@ -86,7 +96,8 @@ function HlsJsMediaTracksMixin(BaseClass) {
|
|
|
86
96
|
#switchRendition = () => {
|
|
87
97
|
const { engine } = this;
|
|
88
98
|
if (!engine) return;
|
|
89
|
-
const
|
|
99
|
+
const selected = this.videoRenditions[this.videoRenditions.selectedIndex];
|
|
100
|
+
const level = selected?.id ? Number(selected.id) : this.videoRenditions.selectedIndex;
|
|
90
101
|
if (level !== engine.manualLevel) engine.nextLevel = level;
|
|
91
102
|
};
|
|
92
103
|
#teardown = () => {
|
|
@@ -101,7 +112,6 @@ function HlsJsMediaTracksMixin(BaseClass) {
|
|
|
101
112
|
this.audioTracks.removeEventListener("change", this.#switchAudioTrack);
|
|
102
113
|
this.videoRenditions.removeEventListener("change", this.#switchRendition);
|
|
103
114
|
this.#removeAllMediaTracks();
|
|
104
|
-
this.#levelIdMap.clear();
|
|
105
115
|
this.#currentVideoTrack = null;
|
|
106
116
|
};
|
|
107
117
|
#removeAllMediaTracks() {
|
package/dist/default/preload.js
CHANGED
|
@@ -4,10 +4,13 @@ import Hls from "hls.js";
|
|
|
4
4
|
* Manages HLS preload behavior by mapping the media element's `preload` attribute to hls.js `startLoad` / buffer-limit
|
|
5
5
|
* configuration.
|
|
6
6
|
*
|
|
7
|
-
* - `'auto'` or already playing → full buffer limits, immediate start.
|
|
7
|
+
* - `'auto'`, `autoplay`, or already playing → full buffer limits, immediate start.
|
|
8
8
|
* - `'metadata'` → minimal buffer (1 byte / 1 second), limits raised on play.
|
|
9
9
|
* - `'none'` / `''` → no start, deferred load on play.
|
|
10
10
|
*
|
|
11
|
+
* `autoplay` overrides `preload`, as it does for a native `<video>`: the browser only starts it once enough has loaded,
|
|
12
|
+
* so a load deferred until `play` would never begin.
|
|
13
|
+
*
|
|
11
14
|
* Loading is started at most once per source. Widening the limits afterwards is a plain config write, never a second
|
|
12
15
|
* `startLoad()`.
|
|
13
16
|
*/
|
|
@@ -35,6 +38,13 @@ function HlsJsPreloadMixin(BaseClass) {
|
|
|
35
38
|
this.#preload = value;
|
|
36
39
|
this.#init();
|
|
37
40
|
}
|
|
41
|
+
get autoplay() {
|
|
42
|
+
return super.autoplay;
|
|
43
|
+
}
|
|
44
|
+
set autoplay(value) {
|
|
45
|
+
super.autoplay = value;
|
|
46
|
+
this.#init();
|
|
47
|
+
}
|
|
38
48
|
#destroy() {
|
|
39
49
|
this.#preloadAbort?.abort();
|
|
40
50
|
this.#preloadAbort = null;
|
|
@@ -71,7 +81,7 @@ function HlsJsPreloadMixin(BaseClass) {
|
|
|
71
81
|
this.#loadStarted = true;
|
|
72
82
|
engine.startLoad();
|
|
73
83
|
};
|
|
74
|
-
if (this.preload === "auto" || !target.paused) {
|
|
84
|
+
if (this.preload === "auto" || target.autoplay || !target.paused) {
|
|
75
85
|
load();
|
|
76
86
|
return;
|
|
77
87
|
}
|
|
@@ -18,13 +18,13 @@ function isCredentialed(crossOrigin) {
|
|
|
18
18
|
function withRequestCredentials(config, crossOrigin) {
|
|
19
19
|
const { xhrSetup, fetchSetup } = config;
|
|
20
20
|
return {
|
|
21
|
-
async xhrSetup(xhr, url) {
|
|
21
|
+
async xhrSetup(xhr, url, context) {
|
|
22
22
|
if (isCredentialed(crossOrigin())) xhr.withCredentials = true;
|
|
23
|
-
await xhrSetup?.(xhr, url);
|
|
23
|
+
await xhrSetup?.call(this, xhr, url, context);
|
|
24
24
|
},
|
|
25
25
|
fetchSetup(context, initParams) {
|
|
26
26
|
if (isCredentialed(crossOrigin())) initParams.credentials = "include";
|
|
27
|
-
return fetchSetup ? fetchSetup(context, initParams) : new Request(context.url, initParams);
|
|
27
|
+
return fetchSetup ? fetchSetup.call(this, context, initParams) : new Request(context.url, initParams);
|
|
28
28
|
}
|
|
29
29
|
};
|
|
30
30
|
}
|
|
@@ -3,6 +3,8 @@ import { isCaptionOrSubtitleTrack, listen } from "@videojs/utils/dom";
|
|
|
3
3
|
//#region src/text-tracks.ts
|
|
4
4
|
/** Marks the `<track>` elements created here for hls.js's own text tracks. */
|
|
5
5
|
const HLS_TRACK_ATTR = "data-removeondestroy";
|
|
6
|
+
/** Marks the subset created from hls.js's CEA-608/708 announcements, which are announced one track at a time. */
|
|
7
|
+
const CC_TRACK_ATTR = "data-cc";
|
|
6
8
|
/** `HTMLTrackElement.LOADED` — the element parsed its resource and will not parse it again. */
|
|
7
9
|
const TRACK_LOADED = 2;
|
|
8
10
|
/**
|
|
@@ -99,15 +101,20 @@ function HlsJsTextTracksMixin(BaseClass) {
|
|
|
99
101
|
const { engine } = this;
|
|
100
102
|
if (!engine || !this.target) return;
|
|
101
103
|
const media = this.target;
|
|
104
|
+
const trackIdFor = ({ _id, default: isDefault, subtitleTrack }) => _id ?? (isDefault ? "default" : `subtitles${subtitleTrack?.id}`);
|
|
102
105
|
const onTracksFound = (_event, data) => {
|
|
103
|
-
|
|
106
|
+
const incomingIds = new Set(data.tracks.map(trackIdFor));
|
|
107
|
+
const ccBatch = data.tracks.every((trackObj) => trackObj._id != null);
|
|
108
|
+
for (const trackEl of media.querySelectorAll(`track[${HLS_TRACK_ATTR}]`)) {
|
|
109
|
+
const replaced = incomingIds.has(trackEl.id);
|
|
110
|
+
const ccOwned = trackEl.hasAttribute(CC_TRACK_ATTR);
|
|
111
|
+
if (!replaced && (ccBatch || ccOwned)) continue;
|
|
112
|
+
trackEl.track.mode = "disabled";
|
|
113
|
+
trackEl.remove();
|
|
114
|
+
}
|
|
104
115
|
for (const trackObj of data.tracks) {
|
|
105
116
|
const baseTrackObj = trackObj.subtitleTrack ?? trackObj.closedCaptions;
|
|
106
|
-
|
|
107
|
-
return lang === baseTrackObj?.lang && name === trackObj.label && type.toLowerCase() === trackObj.kind;
|
|
108
|
-
});
|
|
109
|
-
const id = trackObj._id ?? trackObj.default ? "default" : `${trackObj.kind}${idx}`;
|
|
110
|
-
addTextTrack(media, trackObj.kind, trackObj.label, baseTrackObj?.lang, id, trackObj.default);
|
|
117
|
+
addTextTrack(media, trackObj.kind, trackObj.label, baseTrackObj?.lang, trackIdFor(trackObj), trackObj.default, trackObj._id != null);
|
|
111
118
|
}
|
|
112
119
|
};
|
|
113
120
|
const onCuesParsed = (_event, { track, cues }) => {
|
|
@@ -121,12 +128,16 @@ function HlsJsTextTracksMixin(BaseClass) {
|
|
|
121
128
|
});
|
|
122
129
|
if (disabled) textTrack.mode = "disabled";
|
|
123
130
|
};
|
|
131
|
+
let lastShowingTrack;
|
|
124
132
|
const onTextTrackChange = () => {
|
|
125
|
-
if (!engine.subtitleTracks.length) return;
|
|
126
133
|
const showingTrack = Array.from(media.textTracks).find((textTrack) => {
|
|
127
134
|
return textTrack.id && textTrack.mode === "showing" && isCaptionOrSubtitleTrack(textTrack);
|
|
128
135
|
});
|
|
136
|
+
const showingChanged = showingTrack !== lastShowingTrack;
|
|
137
|
+
lastShowingTrack = showingTrack;
|
|
129
138
|
if (!showingTrack) return;
|
|
139
|
+
if (showingChanged && isHlsTextTrack(media, showingTrack)) refreshCues(showingTrack);
|
|
140
|
+
if (!engine.subtitleTracks.length) return;
|
|
130
141
|
const currentHlsTrack = engine.subtitleTracks[engine.subtitleTrack];
|
|
131
142
|
const hlsTrackId = !currentHlsTrack ? void 0 : currentHlsTrack.default ? "default" : `${engine.subtitleTracks[engine.subtitleTrack]?.type.toLowerCase()}${engine.subtitleTrack}`;
|
|
132
143
|
if (engine.subtitleTrack < 0 || showingTrack?.id !== hlsTrackId) {
|
|
@@ -135,11 +146,6 @@ function HlsJsTextTracksMixin(BaseClass) {
|
|
|
135
146
|
});
|
|
136
147
|
engine.subtitleTrack = idx;
|
|
137
148
|
}
|
|
138
|
-
if (showingTrack?.id === hlsTrackId) {
|
|
139
|
-
if (showingTrack.cues) Array.from(showingTrack.cues).forEach((cue) => {
|
|
140
|
-
showingTrack.addCue(cue);
|
|
141
|
-
});
|
|
142
|
-
}
|
|
143
149
|
};
|
|
144
150
|
engine.on(Hls.Events.NON_NATIVE_TEXT_TRACKS_FOUND, onTracksFound);
|
|
145
151
|
engine.on(Hls.Events.CUES_PARSED, onCuesParsed);
|
|
@@ -152,7 +158,25 @@ function HlsJsTextTracksMixin(BaseClass) {
|
|
|
152
158
|
}
|
|
153
159
|
return HlsJsTextTracks;
|
|
154
160
|
}
|
|
155
|
-
function
|
|
161
|
+
function isHlsTextTrack(media, track) {
|
|
162
|
+
const trackEls = media.querySelectorAll(`track[${HLS_TRACK_ATTR}]`);
|
|
163
|
+
return Array.from(trackEls).some((trackEl) => trackEl.track === track);
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Makes the media element render the cues of a track that just became the showing one.
|
|
167
|
+
*
|
|
168
|
+
* The `<track>` elements created here have no `src`, so their load fails. WebKit only hands a re-enabled track's cues
|
|
169
|
+
* back to the media element when its `<track>` loaded, so a track turned off and on again lists its cues but renders
|
|
170
|
+
* none; Chrome has a similar rendering bug. Adding a cue that is already on the track is a no-op in WebKit, so each cue
|
|
171
|
+
* is removed before it is added back.
|
|
172
|
+
*/
|
|
173
|
+
function refreshCues(track) {
|
|
174
|
+
for (const cue of Array.from(track.cues ?? [])) {
|
|
175
|
+
track.removeCue(cue);
|
|
176
|
+
track.addCue(cue);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
function addTextTrack(mediaEl, kind, label, lang, id, defaultTrack, ccOwned) {
|
|
156
180
|
const trackEl = document.createElement("track");
|
|
157
181
|
trackEl.kind = kind;
|
|
158
182
|
trackEl.label = label;
|
|
@@ -161,6 +185,7 @@ function addTextTrack(mediaEl, kind, label, lang, id, defaultTrack) {
|
|
|
161
185
|
if (defaultTrack) trackEl.default = true;
|
|
162
186
|
trackEl.track.mode = isCaptionOrSubtitleTrack({ kind }) ? "disabled" : "hidden";
|
|
163
187
|
trackEl.setAttribute(HLS_TRACK_ATTR, "");
|
|
188
|
+
if (ccOwned) trackEl.setAttribute(CC_TRACK_ATTR, "");
|
|
164
189
|
mediaEl.append(trackEl);
|
|
165
190
|
return trackEl.track;
|
|
166
191
|
}
|
package/dist/dev/adapter.d.ts
CHANGED
|
@@ -147,6 +147,11 @@ export declare class HlsJsAdapter extends HTMLVideoAdapter implements HlsJsAdapt
|
|
|
147
147
|
* hatch for direct engine access; normal playback is driven through this element's own properties and methods.
|
|
148
148
|
*/
|
|
149
149
|
get engine(): Hls$1 | null;
|
|
150
|
+
/**
|
|
151
|
+
* Engine this media is playing through, reported to analytics such as Mux Data: `hlsjs` via MSE, `browser` for native
|
|
152
|
+
* HLS, or `undefined` until a source loads. Read from the instance because the engine is picked per source.
|
|
153
|
+
*/
|
|
154
|
+
get engineName(): string | undefined;
|
|
150
155
|
get error(): (import("@videojs/media").ErrorLike & import("@videojs/media").MediaError) | null;
|
|
151
156
|
/** Populated only while the hls.js (MSE) engine is active; otherwise `undefined`. */
|
|
152
157
|
get videoTracks(): import("@videojs/media").VideoTrackListLike | undefined;
|
package/dist/dev/adapter.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { HlsJsOnlyAdapter } from "./hls-js-only.js";
|
|
2
2
|
import { KeySystems, MediaStreamTypes, bridgeEvents } from "@videojs/media";
|
|
3
|
-
import { HTMLVideoAdapter } from "@videojs/media/dom";
|
|
3
|
+
import { HTMLVideoAdapter, getMediaEngineName } from "@videojs/media/dom";
|
|
4
4
|
import { NativeHlsAdapter } from "@videojs/native-hls-video";
|
|
5
5
|
import { deepEqual } from "@videojs/utils/object";
|
|
6
6
|
import Hls$1 from "hls.js";
|
|
@@ -89,6 +89,13 @@ var HlsJsAdapter = class HlsJsAdapter extends HTMLVideoAdapter {
|
|
|
89
89
|
get engine() {
|
|
90
90
|
return this.#delegate?.engine ?? null;
|
|
91
91
|
}
|
|
92
|
+
/**
|
|
93
|
+
* Engine this media is playing through, reported to analytics such as Mux Data: `hlsjs` via MSE, `browser` for native
|
|
94
|
+
* HLS, or `undefined` until a source loads. Read from the instance because the engine is picked per source.
|
|
95
|
+
*/
|
|
96
|
+
get engineName() {
|
|
97
|
+
return getMediaEngineName(this.#delegate);
|
|
98
|
+
}
|
|
92
99
|
get error() {
|
|
93
100
|
return this.#delegate?.error ?? null;
|
|
94
101
|
}
|
package/dist/dev/adapter.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adapter.js","names":["Hls"],"sources":["../../src/adapter.ts"],"sourcesContent":["import {\n bridgeEvents,\n type DrmSystemsConfig,\n KeySystems,\n type MediaResolution,\n type MediaStreamType,\n MediaStreamTypes,\n} from '@videojs/media';\nimport { HTMLVideoAdapter } from '@videojs/media/dom';\nimport { type NativeHlsConfig, NativeHlsAdapter, type NativeHlsSource } from '@videojs/native-hls-video';\nimport { deepEqual } from '@videojs/utils/object';\nimport Hls, { type HlsConfig as HlsJsConfig } from 'hls.js';\n\nimport { HlsJsOnlyAdapter } from './hls-js-only';\n\nexport type PreloadType = '' | 'none' | 'metadata' | 'auto';\n\nexport type { MediaResolution };\n\nexport { Hls };\n\n/** How hls.js plays a source: through Media Source Extensions, or the browser's native HLS support. */\nexport type PlaybackType = 'mse' | 'native' | (string & {});\n/** A source's MIME type, such as `application/vnd.apple.mpegurl` for HLS or `video/mp4`. */\nexport type SourceType = 'application/vnd.apple.mpegurl' | 'video/mp4' | (string & {});\nexport type StreamType = MediaStreamType;\n\n/** @internal */\nexport const PlaybackTypes = {\n MSE: 'mse',\n NATIVE: 'native',\n};\n\n/** @internal */\nexport const ContentTypes = {\n M3U8: 'application/vnd.apple.mpegurl',\n MP4: 'video/mp4',\n};\n\n/**\n * Every MIME type that means HLS in the wild, lowercased. `application/vnd.apple.mpegurl` is the registered one, but\n * `application/x-mpegURL` predates it and is what most servers, CDNs, and older Video.js guides hand out, so a source\n * naming any of these has to reach hls.js rather than fall through to native playback.\n */\nconst HLS_CONTENT_TYPES: ReadonlySet<string> = new Set([\n ContentTypes.M3U8,\n 'application/x-mpegurl',\n 'application/mpegurl',\n 'audio/mpegurl',\n 'audio/x-mpegurl',\n]);\n\nconst MP4_CONTENT_TYPES: ReadonlySet<string> = new Set([ContentTypes.MP4]);\n\n/** @internal */\nexport const StreamTypes = MediaStreamTypes;\n\nexport interface HlsJsAdapterProps {\n src: string;\n source: HlsSource | null;\n preload: PreloadType;\n streamType: StreamType;\n disableRemotePlayback: boolean;\n}\n\n/**\n * Structured HLS source: which source to play, plus how to play it.\n *\n * Playback options are namespaced by engine. There are two paths here — hls.js and the browser's own HLS support — and\n * only one of them runs, so a source describes both without either engine reading the other's options.\n *\n * `preferPlayback` and the engine options are all read when the engine is constructed, so changing any of them\n * recreates it.\n */\nexport interface HlsSource {\n /** Manifest URL. Mirrors the host's `src` property. */\n src?: string | undefined;\n /**\n * MIME type of the source. Takes precedence over inference from `src`.\n *\n * Matched case-insensitively, and the legacy HLS spellings (`application/x-mpegURL`, `audio/mpegurl`, …) count as\n * `application/vnd.apple.mpegurl`. Anything unrecognized is treated as a URL the browser plays on its own.\n */\n type?: SourceType | undefined;\n /**\n * Preferred playback path: `'mse'` for hls.js, `'native'` for the browser's own HLS support. Ignored when the\n * preferred path cannot play the source.\n */\n preferPlayback?: PlaybackType | undefined;\n /**\n * License servers for protected content, keyed by EME key system id.\n *\n * Engine neutral, because which engine plays is decided later: hls.js is handed every system named here (with EME\n * switched on), and native playback negotiates the `com.apple.fps` entry itself. Name every system you hold a license\n * server for — which one is used is the browser's choice.\n */\n drm?: DrmSystemsConfig | undefined;\n /**\n * Highest resolution adaptive bitrate selection may choose on its own.\n *\n * A ceiling on automatic selection, not a filter on what is available: renditions above it stay in `videoRenditions`\n * and can still be selected by hand. Matching is by pixel area, so a `'720p'` cap admits any rendition at or below\n * 1280×720 worth of pixels. When every rendition sits above the cap, the smallest one is used.\n *\n * Applied live — changing it never rebuilds the playback engine. Requires the hls.js (MSE) engine; native HLS\n * playback ignores it.\n *\n * For Mux sources this is distinct from `playback.maxResolution`, which asks Mux to leave higher renditions out of\n * the manifest altogether.\n */\n maxAutoResolution?: MediaResolution | undefined;\n /**\n * Whether the element's rendered size caps automatic selection. Defaults to `true`.\n *\n * A 400px-wide player has no use for a 4K rendition, so selection is held to the smallest rendition that still covers\n * the element, measured in device pixels — a `2` device pixel ratio asks for twice what a CSS measurement would. The\n * cap follows the element as it resizes, and `minAutoResolution` bounds how far down it can go. Set it to `false` for\n * a player whose layout size understates what it needs, such as one that goes fullscreen without a resize.\n *\n * Which rendition covers the element is hls.js's own judgement, weighed on the largest dimension rather than pixel\n * area, so it can land elsewhere than `maxAutoResolution` would for the same ladder.\n *\n * Applied live — changing it never rebuilds the playback engine. Requires the hls.js (MSE) engine; native HLS\n * playback ignores it. Setting hls.js's own `capLevelToPlayerSize` through `source.engine.hlsJs` is a different\n * thing: it stops the loop _every_ cap here is evaluated on, and takes a rebuild.\n */\n capRenditionToPlayerSize?: boolean | undefined;\n /**\n * Lowest resolution `capRenditionToPlayerSize` may cap down to. Defaults to `'720p'`.\n *\n * Not a quality floor. It bounds the size-derived cap and nothing else: when bandwidth is poor, adaptive selection\n * still drops below it, because the cap is a ceiling and selection stays free underneath. Nor does it raise an\n * explicit `maxAutoResolution` — asking for at most `'360p'` alongside a `'720p'` floor yields `'360p'`.\n *\n * The default exists because the low rungs of a ladder are there for poor network conditions, and capping a small\n * player to them looks worse than its size suggests. Name a lower rung to weaken the floor, or `'270p'` to lift it\n * for any real ladder.\n *\n * Applied live — changing it never rebuilds the playback engine. Requires the hls.js (MSE) engine; native HLS\n * playback ignores it.\n */\n minAutoResolution?: MediaResolution | undefined;\n /**\n * Playback options, keyed by the engine that reads them. Only one of the two engines below ends up playing, and each\n * reads only its own key.\n */\n engine?: HlsEngineConfig | undefined;\n}\n\n/** The engines an HLS source can configure. */\nexport interface HlsEngineConfig {\n /**\n * Hls.js's own configuration, passed through untouched. A `drmSystems` of its own replaces `source.drm` for hls.js —\n * an escape hatch for licensing MSE playback differently, or for the parts of hls.js's DRM configuration `source.drm`\n * does not cover.\n */\n hlsJs?: Partial<HlsJsConfig> | undefined;\n /**\n * Options for the browser's own HLS playback, used whenever the native path is the one taken. Its `drmSystems`\n * replaces `source.drm` for that path in the same way.\n */\n nativeHls?: NativeHlsConfig | undefined;\n}\n\nclass HlsMediaEvent extends Event {}\n\n/**\n * @fires sourcechange - Fired when `source` changes, either directly or by resolving a new `src`. Read `source` for the\n * new value.\n * @fires streamtypechange - Fired when the detected stream type changes. Read `streamType` for the new value.\n * @fires targetlivewindowchange - Fired when the target live window changes. Read `targetLiveWindow` for the new value.\n */\nexport class HlsJsAdapter extends HTMLVideoAdapter implements HlsJsAdapterProps {\n static readonly defaultProps: HlsJsAdapterProps = {\n src: '',\n source: null,\n preload: 'metadata',\n streamType: MediaStreamTypes.UNKNOWN,\n disableRemotePlayback: false,\n };\n\n #delegate: HlsJsOnlyAdapter | NativeHlsAdapter | null = null;\n #mediaElement: HTMLVideoElement | null = null;\n #src = HlsJsAdapter.defaultProps.src;\n #source: HlsSource | null = HlsJsAdapter.defaultProps.source;\n #preload = HlsJsAdapter.defaultProps.preload;\n #streamType: StreamType = HlsJsAdapter.defaultProps.streamType;\n #isUserStreamType = false;\n #loadRequested?: Promise<void> | null;\n #prevEngineConfigKey?: Record<string, any> | null;\n /**\n * The author's `disableRemotePlayback`, not the element's current value. Tracked because engines (hls.js or SPF) may\n * alter the value internally. Cached here for cases where this value is set before the delegate is created so it can\n * later be forwarded.\n */\n #authorDisableRemotePlayback?: boolean;\n\n constructor() {\n super();\n // Cancel the native loadstart event, it's handled in the load method.\n this.addEventListener('loadstart', this.#stopTargetLoadStartEvent);\n }\n\n attach(target: HTMLVideoElement) {\n this.#mediaElement = target;\n super.attach(target);\n this.#delegate?.attach(target);\n }\n\n detach() {\n this.#delegate?.detach();\n super.detach();\n this.#mediaElement = null;\n }\n\n destroy() {\n this.detach();\n this.#engineDestroy();\n super.destroy();\n this.removeEventListener('loadstart', this.#stopTargetLoadStartEvent);\n }\n\n /**\n * Underlying playback engine — the hls.js `Hls` instance when playing via MSE, otherwise `null`. An advanced escape\n * hatch for direct engine access; normal playback is driven through this element's own properties and methods.\n */\n get engine() {\n return this.#delegate?.engine ?? null;\n }\n\n get error() {\n return this.#delegate?.error ?? null;\n }\n\n /** Populated only while the hls.js (MSE) engine is active; otherwise `undefined`. */\n get videoTracks() {\n return this.#delegate instanceof HlsJsOnlyAdapter ? this.#delegate.videoTracks : undefined;\n }\n\n /** Populated only while the hls.js (MSE) engine is active; otherwise `undefined`. */\n get audioTracks() {\n return this.#delegate instanceof HlsJsOnlyAdapter ? this.#delegate.audioTracks : undefined;\n }\n\n /** Selectable quality levels, populated only while the hls.js (MSE) engine is active; otherwise `undefined`. */\n get videoRenditions() {\n return this.#delegate instanceof HlsJsOnlyAdapter ? this.#delegate.videoRenditions : undefined;\n }\n\n /** Selectable audio variants, populated only while the hls.js (MSE) engine is active; otherwise `undefined`. */\n get audioRenditions() {\n return this.#delegate instanceof HlsJsOnlyAdapter ? this.#delegate.audioRenditions : undefined;\n }\n\n /**\n * Media source URL. Assigning it replaces the identity half of `source` and leaves `type` and the engine options\n * intact, so changing the URL never disturbs engine configuration.\n */\n get src() {\n return this.#src;\n }\n\n set src(src: string) {\n // `src` says which source to play; every other field says how to play it, so\n // they carry over.\n const { type, preferPlayback, drm, engine, maxAutoResolution, capRenditionToPlayerSize, minAutoResolution } =\n this.#source ?? {};\n const next: HlsSource = {\n ...(type && { type }),\n ...(preferPlayback && { preferPlayback }),\n ...(drm && { drm }),\n ...(engine && { engine }),\n ...(maxAutoResolution && { maxAutoResolution }),\n // Definedness, not truthiness: `false` is the value worth naming, and the\n // falsy one, so the neighbors' pattern would drop it.\n ...(capRenditionToPlayerSize !== undefined && { capRenditionToPlayerSize }),\n ...(minAutoResolution && { minAutoResolution }),\n ...(src && { src }),\n };\n\n // Everything happens in the `source` setter, so there is one path for storing\n // it, deciding on a load, and dispatching `sourcechange`.\n this.source = Object.keys(next).length > 0 ? next : null;\n }\n\n /**\n * Structured source: what to play (`src`, an optional `type`) plus how to play it (`preferPlayback`, `engine`).\n * Assigning it derives `src`.\n *\n * Sources are compared structurally, so reassigning an equivalent object is a no-op. Only a change to the engine\n * options (or to the resolved content type) recreates the playback engine.\n */\n get source(): HlsSource | null {\n return this.#source;\n }\n\n set source(value: HlsSource | null) {\n const source = value ?? null;\n // Changing anything takes a new object, so handing the same one back costs\n // nothing.\n if (source === this.#source) return;\n\n const src = source?.src ?? '';\n const srcChanged = this.#src !== src;\n\n this.#source = source;\n this.#src = src;\n\n // Deliberately outside the engine config key below, so it reaches the engine\n // already running.\n this.#applyRenditionCaps();\n\n // Assigning is always a source change, so it is always announced.\n this.dispatchEvent(new Event('sourcechange'));\n\n // Only reload for something playback depends on. Subclasses add params that\n // describe images rather than the stream — Mux's `poster` and `storyboard` —\n // and changing one of those must not restart what is already playing.\n if (srcChanged || this.#shouldEngineUpdate(this.#engineConfigKey())) this.#requestLoad();\n }\n\n /** Preload type (`'none'` / `'metadata'` / `'auto'`). */\n get preload() {\n return this.#preload;\n }\n\n set preload(value) {\n this.#preload = value;\n\n if (this.#delegate) {\n this.#delegate.preload = value;\n }\n }\n\n /** Whether remote playback (AirPlay, Google Cast) is disabled for this media. */\n get disableRemotePlayback() {\n return super.disableRemotePlayback;\n }\n\n set disableRemotePlayback(value: boolean) {\n this.#authorDisableRemotePlayback = value;\n super.disableRemotePlayback = value;\n\n if (this.#delegate instanceof HlsJsOnlyAdapter) {\n this.#delegate.disableRemotePlayback = value;\n }\n }\n\n /** Current stream type (`'on-demand'` / `'live'` / `'unknown'`). */\n get streamType(): StreamType {\n return this.#delegate?.streamType ?? this.#streamType;\n }\n\n set streamType(value: StreamType) {\n this.#isUserStreamType = value !== StreamTypes.UNKNOWN;\n\n if (this.#delegate) {\n this.#delegate.streamType = value;\n this.#streamType = this.#delegate.streamType;\n return;\n }\n\n if (this.#streamType === value) return;\n\n this.#streamType = value;\n this.dispatchEvent(new HlsMediaEvent('streamtypechange'));\n }\n\n /**\n * Presentation time marking the start of the Live Edge Window.\n *\n * Derived from the delegate on every read; `NaN` when no delegate is attached or the stream is not live.\n */\n get liveEdgeStart() {\n return this.#delegate?.liveEdgeStart ?? Number.NaN;\n }\n\n /**\n * Seekable range size for live content. `0` for standard live, `Infinity` for DVR, `NaN` for on-demand or unknown.\n * Fires `targetlivewindowchange` when the value changes (bridged from the delegate).\n */\n get targetLiveWindow() {\n return this.#delegate?.targetLiveWindow ?? Number.NaN;\n }\n\n async load() {\n this.#loadRequested = null;\n\n if (this.remote.state === 'connected') {\n this.dispatchEvent(new HlsMediaEvent('loadstart'));\n return super.load();\n }\n\n if (this.#shouldEngineUpdate(this.#engineConfigKey())) {\n this.#engineDestroy();\n this.#prevEngineConfigKey = this.#engineConfigKey();\n\n // Read the stored source, not the `source` getter: subclasses override the\n // getter to return what was assigned to them, while the fields below come\n // from what they resolved and handed down (Mux fills in the DRM options).\n const { type, preferPlayback, drm, engine, maxAutoResolution, capRenditionToPlayerSize, minAutoResolution } =\n this.#source ?? {};\n const { hlsJs, nativeHls } = engine ?? {};\n const contentType = resolveContentType(type, this.src);\n const useMse = Hls.isSupported() && contentType === ContentTypes.M3U8 && preferPlayback !== PlaybackTypes.NATIVE;\n\n if (__DEV__ && type && !contentType) {\n console.warn(\n `[vjs-media] Unrecognized \\`source.type\\` \"${type}\". HLS sources should use \\`${ContentTypes.M3U8}\\` (or \\`application/x-mpegURL\\`); the browser is being handed this source to play natively, so hls.js features such as quality selection are unavailable.`\n );\n }\n\n if (__DEV__ && !useMse) {\n const ignored = Object.entries({ maxAutoResolution, capRenditionToPlayerSize, minAutoResolution })\n .filter(([, value]) => value !== undefined)\n .map(([key]) => `\\`${key}\\``);\n\n if (ignored.length > 0) {\n const [verb, pronoun] = ignored.length > 1 ? ['require', 'them'] : ['requires', 'it'];\n\n console.warn(\n `[vjs-media] ${ignored.join(', ')} ${verb} the hls.js (MSE) engine; native HLS playback ignores ${pronoun}.`\n );\n }\n }\n\n this.#delegate = useMse\n ? new HlsJsOnlyAdapter({ config: withDrmSystems(hlsJs, drm) })\n : this.#createNativeDelegate(drm, nativeHls, hlsJs);\n\n bridgeEvents(this.#delegate, this);\n\n // Apply user `streamType` before `attach()` so native delegates do not run\n // synchronous duration-based detection first and emit a transient value.\n if (this.#isUserStreamType) {\n this.#delegate.streamType = this.#streamType;\n }\n\n this.#delegate.preload = this.preload;\n this.#applyRenditionCaps();\n\n // Forward the author intent to the delegate, in case it was captured before it existed.\n if (this.#authorDisableRemotePlayback !== undefined && this.#delegate instanceof HlsJsOnlyAdapter) {\n this.#delegate.disableRemotePlayback = this.#authorDisableRemotePlayback;\n }\n\n if (this.#mediaElement) {\n this.#delegate.attach(this.#mediaElement);\n }\n }\n\n if (this.#delegate) {\n this.dispatchEvent(new HlsMediaEvent('loadstart'));\n this.#delegate.src = this.src;\n }\n }\n\n /**\n * A native delegate carrying the native half of the source — the DRM configuration and the native engine options,\n * which it applies the same precedence to. Its `src` is assigned separately, once the delegate is wired up, and\n * carries what is set here forward.\n */\n #createNativeDelegate(\n drm: DrmSystemsConfig | undefined,\n nativeHls: NativeHlsConfig | undefined,\n hlsJs: Partial<HlsJsConfig> | undefined\n ) {\n if (__DEV__) {\n // The delegate applies the same precedence, so the warning has to read — and\n // name — whatever it will end up licensing against. An escape hatch replaces\n // `source.drm` rather than adding to it, so pointing at the wrong one of the\n // two would send a reader looking in a field that is already correct.\n const drmSystems = nativeHls?.drmSystems ?? drm;\n const field = nativeHls?.drmSystems ? 'source.engine.nativeHls.drmSystems' : 'source.drm';\n const isProtected = hlsJs?.emeEnabled || hlsJs?.drmSystems || Object.keys(drmSystems ?? {}).length > 0;\n\n if (isProtected && !drmSystems?.[KeySystems.FAIRPLAY]) {\n console.warn(\n `[vjs-drm] Native HLS playback negotiates FairPlay itself and never sees the hls.js DRM configuration, and no \\`${KeySystems.FAIRPLAY}\\` license server is named in \\`${field}\\`. DRM-protected media will not play.`\n );\n }\n }\n\n const media = new NativeHlsAdapter();\n const source: NativeHlsSource = {\n ...(drm && { drm }),\n ...(nativeHls && { engine: { nativeHls } }),\n };\n\n if (Object.keys(source).length > 0) media.source = source;\n\n return media;\n }\n\n /** Push the source's rendition caps down; only the hls.js engine has a lever. */\n #applyRenditionCaps() {\n if (this.#delegate instanceof HlsJsOnlyAdapter) {\n this.#delegate.maxAutoResolution = this.#source?.maxAutoResolution;\n this.#delegate.capRenditionToPlayerSize = this.#source?.capRenditionToPlayerSize;\n this.#delegate.minAutoResolution = this.#source?.minAutoResolution;\n }\n }\n\n #stopTargetLoadStartEvent = (event: Event) => {\n if (!(event instanceof HlsMediaEvent)) event.stopImmediatePropagation();\n };\n\n async #requestLoad() {\n if (this.#loadRequested) return;\n\n await (this.#loadRequested = Promise.resolve());\n this.#loadRequested = null;\n this.load();\n }\n\n #shouldEngineUpdate(nextEngineConfigKey: Record<string, any>) {\n return !deepEqual(this.#prevEngineConfigKey, nextEngineConfigKey);\n }\n\n /**\n * Every value the engine is constructed from. Compared structurally, so equivalent engine options never trigger a\n * rebuild — including nested ones like `drmSystems`, which a flat comparison would see as changed whenever the object\n * identity did.\n */\n #engineConfigKey() {\n const { type, preferPlayback, drm, engine } = this.#source ?? {};\n\n return { drm, engine, preferPlayback, contentType: resolveContentType(type, this.src) };\n }\n\n #engineDestroy() {\n this.#delegate?.destroy();\n this.#delegate = null;\n this.#prevEngineConfigKey = null;\n this.#loadRequested = null;\n\n // Delegate teardown already emits `streamtypechange` (bridged); only sync cache.\n if (!this.#isUserStreamType) this.#streamType = StreamTypes.UNKNOWN;\n }\n}\n\n/**\n * Hls.js configuration with the source's DRM licensing folded in. hls.js takes `drmSystems` in the same shape as\n * `source.drm`, so the standardized config is what it plays from unless `engine.hlsJs` names servers of its own.\n *\n * Hls.js runs key exchange only while `emeEnabled` is set, so configured DRM switches it on — short of an explicit\n * `emeEnabled: false`, which stays a way to describe a source's licensing without acting on it.\n */\nfunction withDrmSystems(\n hlsJs: Partial<HlsJsConfig> | undefined,\n drm: DrmSystemsConfig | undefined\n): Partial<HlsJsConfig> {\n const drmSystems = hlsJs?.drmSystems ?? drm;\n if (!drmSystems || Object.keys(drmSystems).length === 0) return { ...hlsJs };\n\n // hls.js declares `serverCertificateUrl` without `undefined`, which an\n // omittable property here is allowed to carry. The values are the same.\n return { emeEnabled: true, ...hlsJs, drmSystems: drmSystems as HlsJsConfig['drmSystems'] };\n}\n\n/**\n * The canonical content type the engine decision is made on: an explicit `type` folded onto its canonical spelling, or\n * what the URL suggests when there is none. An explicit type nobody recognizes resolves to `undefined` rather than\n * falling back to inference — the author said what the source is, and guessing over them would make `type` mean\n * different things depending on its value.\n */\nfunction resolveContentType(type: string | undefined, src: string): SourceType | undefined {\n if (!type) return inferContentType(src);\n\n // Parameters (`; charset=...`) and case carry no meaning for the engine choice.\n const normalized = (type.split(';')[0] ?? '').trim().toLowerCase();\n if (HLS_CONTENT_TYPES.has(normalized)) return ContentTypes.M3U8;\n\n if (MP4_CONTENT_TYPES.has(normalized)) return ContentTypes.MP4;\n\n return undefined;\n}\n\nfunction inferContentType(src: string): SourceType {\n const path = src.split(/[?#]/)[0] ?? '';\n if (path.endsWith('.mp4')) return ContentTypes.MP4;\n\n return ContentTypes.M3U8;\n}\n"],"mappings":";;;;;;;;AA4BA,MAAa,gBAAgB;CAC3B,KAAK;CACL,QAAQ;AACV;;AAGA,MAAa,eAAe;CAC1B,MAAM;CACN,KAAK;AACP;;;;;;AAOA,MAAM,oCAAyC,IAAI,IAAI;CACrD,aAAa;CACb;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,oCAAyC,IAAI,IAAI,CAAC,aAAa,GAAG,C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,OAAO,aAAa;AAG7D;AAEA,SAAS,iBAAiB,KAAyB;CAEjD,KADa,IAAI,MAAM,MAAM,CAAC,CAAC,MAAM,GAAA,CAC5B,SAAS,MAAM,GAAG,OAAO,aAAa;CAE/C,OAAO,aAAa;AACtB"}
|
|
1
|
+
{"version":3,"file":"adapter.js","names":["Hls"],"sources":["../../src/adapter.ts"],"sourcesContent":["import {\n bridgeEvents,\n type DrmSystemsConfig,\n KeySystems,\n type MediaResolution,\n type MediaStreamType,\n MediaStreamTypes,\n} from '@videojs/media';\nimport { getMediaEngineName, HTMLVideoAdapter } from '@videojs/media/dom';\nimport { type NativeHlsConfig, NativeHlsAdapter, type NativeHlsSource } from '@videojs/native-hls-video';\nimport { deepEqual } from '@videojs/utils/object';\nimport Hls, { type HlsConfig as HlsJsConfig } from 'hls.js';\n\nimport { HlsJsOnlyAdapter } from './hls-js-only';\n\nexport type PreloadType = '' | 'none' | 'metadata' | 'auto';\n\nexport type { MediaResolution };\n\nexport { Hls };\n\n/** How hls.js plays a source: through Media Source Extensions, or the browser's native HLS support. */\nexport type PlaybackType = 'mse' | 'native' | (string & {});\n/** A source's MIME type, such as `application/vnd.apple.mpegurl` for HLS or `video/mp4`. */\nexport type SourceType = 'application/vnd.apple.mpegurl' | 'video/mp4' | (string & {});\nexport type StreamType = MediaStreamType;\n\n/** @internal */\nexport const PlaybackTypes = {\n MSE: 'mse',\n NATIVE: 'native',\n};\n\n/** @internal */\nexport const ContentTypes = {\n M3U8: 'application/vnd.apple.mpegurl',\n MP4: 'video/mp4',\n};\n\n/**\n * Every MIME type that means HLS in the wild, lowercased. `application/vnd.apple.mpegurl` is the registered one, but\n * `application/x-mpegURL` predates it and is what most servers, CDNs, and older Video.js guides hand out, so a source\n * naming any of these has to reach hls.js rather than fall through to native playback.\n */\nconst HLS_CONTENT_TYPES: ReadonlySet<string> = new Set([\n ContentTypes.M3U8,\n 'application/x-mpegurl',\n 'application/mpegurl',\n 'audio/mpegurl',\n 'audio/x-mpegurl',\n]);\n\nconst MP4_CONTENT_TYPES: ReadonlySet<string> = new Set([ContentTypes.MP4]);\n\n/** @internal */\nexport const StreamTypes = MediaStreamTypes;\n\nexport interface HlsJsAdapterProps {\n src: string;\n source: HlsSource | null;\n preload: PreloadType;\n streamType: StreamType;\n disableRemotePlayback: boolean;\n}\n\n/**\n * Structured HLS source: which source to play, plus how to play it.\n *\n * Playback options are namespaced by engine. There are two paths here — hls.js and the browser's own HLS support — and\n * only one of them runs, so a source describes both without either engine reading the other's options.\n *\n * `preferPlayback` and the engine options are all read when the engine is constructed, so changing any of them\n * recreates it.\n */\nexport interface HlsSource {\n /** Manifest URL. Mirrors the host's `src` property. */\n src?: string | undefined;\n /**\n * MIME type of the source. Takes precedence over inference from `src`.\n *\n * Matched case-insensitively, and the legacy HLS spellings (`application/x-mpegURL`, `audio/mpegurl`, …) count as\n * `application/vnd.apple.mpegurl`. Anything unrecognized is treated as a URL the browser plays on its own.\n */\n type?: SourceType | undefined;\n /**\n * Preferred playback path: `'mse'` for hls.js, `'native'` for the browser's own HLS support. Ignored when the\n * preferred path cannot play the source.\n */\n preferPlayback?: PlaybackType | undefined;\n /**\n * License servers for protected content, keyed by EME key system id.\n *\n * Engine neutral, because which engine plays is decided later: hls.js is handed every system named here (with EME\n * switched on), and native playback negotiates the `com.apple.fps` entry itself. Name every system you hold a license\n * server for — which one is used is the browser's choice.\n */\n drm?: DrmSystemsConfig | undefined;\n /**\n * Highest resolution adaptive bitrate selection may choose on its own.\n *\n * A ceiling on automatic selection, not a filter on what is available: renditions above it stay in `videoRenditions`\n * and can still be selected by hand. Matching is by pixel area, so a `'720p'` cap admits any rendition at or below\n * 1280×720 worth of pixels. When every rendition sits above the cap, the smallest one is used.\n *\n * Applied live — changing it never rebuilds the playback engine. Requires the hls.js (MSE) engine; native HLS\n * playback ignores it.\n *\n * For Mux sources this is distinct from `playback.maxResolution`, which asks Mux to leave higher renditions out of\n * the manifest altogether.\n */\n maxAutoResolution?: MediaResolution | undefined;\n /**\n * Whether the element's rendered size caps automatic selection. Defaults to `true`.\n *\n * A 400px-wide player has no use for a 4K rendition, so selection is held to the smallest rendition that still covers\n * the element, measured in device pixels — a `2` device pixel ratio asks for twice what a CSS measurement would. The\n * cap follows the element as it resizes, and `minAutoResolution` bounds how far down it can go. Set it to `false` for\n * a player whose layout size understates what it needs, such as one that goes fullscreen without a resize.\n *\n * Which rendition covers the element is hls.js's own judgement, weighed on the largest dimension rather than pixel\n * area, so it can land elsewhere than `maxAutoResolution` would for the same ladder.\n *\n * Applied live — changing it never rebuilds the playback engine. Requires the hls.js (MSE) engine; native HLS\n * playback ignores it. Setting hls.js's own `capLevelToPlayerSize` through `source.engine.hlsJs` is a different\n * thing: it stops the loop _every_ cap here is evaluated on, and takes a rebuild.\n */\n capRenditionToPlayerSize?: boolean | undefined;\n /**\n * Lowest resolution `capRenditionToPlayerSize` may cap down to. Defaults to `'720p'`.\n *\n * Not a quality floor. It bounds the size-derived cap and nothing else: when bandwidth is poor, adaptive selection\n * still drops below it, because the cap is a ceiling and selection stays free underneath. Nor does it raise an\n * explicit `maxAutoResolution` — asking for at most `'360p'` alongside a `'720p'` floor yields `'360p'`.\n *\n * The default exists because the low rungs of a ladder are there for poor network conditions, and capping a small\n * player to them looks worse than its size suggests. Name a lower rung to weaken the floor, or `'270p'` to lift it\n * for any real ladder.\n *\n * Applied live — changing it never rebuilds the playback engine. Requires the hls.js (MSE) engine; native HLS\n * playback ignores it.\n */\n minAutoResolution?: MediaResolution | undefined;\n /**\n * Playback options, keyed by the engine that reads them. Only one of the two engines below ends up playing, and each\n * reads only its own key.\n */\n engine?: HlsEngineConfig | undefined;\n}\n\n/** The engines an HLS source can configure. */\nexport interface HlsEngineConfig {\n /**\n * Hls.js's own configuration, passed through untouched. A `drmSystems` of its own replaces `source.drm` for hls.js —\n * an escape hatch for licensing MSE playback differently, or for the parts of hls.js's DRM configuration `source.drm`\n * does not cover.\n */\n hlsJs?: Partial<HlsJsConfig> | undefined;\n /**\n * Options for the browser's own HLS playback, used whenever the native path is the one taken. Its `drmSystems`\n * replaces `source.drm` for that path in the same way.\n */\n nativeHls?: NativeHlsConfig | undefined;\n}\n\nclass HlsMediaEvent extends Event {}\n\n/**\n * @fires sourcechange - Fired when `source` changes, either directly or by resolving a new `src`. Read `source` for the\n * new value.\n * @fires streamtypechange - Fired when the detected stream type changes. Read `streamType` for the new value.\n * @fires targetlivewindowchange - Fired when the target live window changes. Read `targetLiveWindow` for the new value.\n */\nexport class HlsJsAdapter extends HTMLVideoAdapter implements HlsJsAdapterProps {\n static readonly defaultProps: HlsJsAdapterProps = {\n src: '',\n source: null,\n preload: 'metadata',\n streamType: MediaStreamTypes.UNKNOWN,\n disableRemotePlayback: false,\n };\n\n #delegate: HlsJsOnlyAdapter | NativeHlsAdapter | null = null;\n #mediaElement: HTMLVideoElement | null = null;\n #src = HlsJsAdapter.defaultProps.src;\n #source: HlsSource | null = HlsJsAdapter.defaultProps.source;\n #preload = HlsJsAdapter.defaultProps.preload;\n #streamType: StreamType = HlsJsAdapter.defaultProps.streamType;\n #isUserStreamType = false;\n #loadRequested?: Promise<void> | null;\n #prevEngineConfigKey?: Record<string, any> | null;\n /**\n * The author's `disableRemotePlayback`, not the element's current value. Tracked because engines (hls.js or SPF) may\n * alter the value internally. Cached here for cases where this value is set before the delegate is created so it can\n * later be forwarded.\n */\n #authorDisableRemotePlayback?: boolean;\n\n constructor() {\n super();\n // Cancel the native loadstart event, it's handled in the load method.\n this.addEventListener('loadstart', this.#stopTargetLoadStartEvent);\n }\n\n attach(target: HTMLVideoElement) {\n this.#mediaElement = target;\n super.attach(target);\n this.#delegate?.attach(target);\n }\n\n detach() {\n this.#delegate?.detach();\n super.detach();\n this.#mediaElement = null;\n }\n\n destroy() {\n this.detach();\n this.#engineDestroy();\n super.destroy();\n this.removeEventListener('loadstart', this.#stopTargetLoadStartEvent);\n }\n\n /**\n * Underlying playback engine — the hls.js `Hls` instance when playing via MSE, otherwise `null`. An advanced escape\n * hatch for direct engine access; normal playback is driven through this element's own properties and methods.\n */\n get engine() {\n return this.#delegate?.engine ?? null;\n }\n\n /**\n * Engine this media is playing through, reported to analytics such as Mux Data: `hlsjs` via MSE, `browser` for native\n * HLS, or `undefined` until a source loads. Read from the instance because the engine is picked per source.\n */\n get engineName(): string | undefined {\n return getMediaEngineName(this.#delegate);\n }\n\n get error() {\n return this.#delegate?.error ?? null;\n }\n\n /** Populated only while the hls.js (MSE) engine is active; otherwise `undefined`. */\n get videoTracks() {\n return this.#delegate instanceof HlsJsOnlyAdapter ? this.#delegate.videoTracks : undefined;\n }\n\n /** Populated only while the hls.js (MSE) engine is active; otherwise `undefined`. */\n get audioTracks() {\n return this.#delegate instanceof HlsJsOnlyAdapter ? this.#delegate.audioTracks : undefined;\n }\n\n /** Selectable quality levels, populated only while the hls.js (MSE) engine is active; otherwise `undefined`. */\n get videoRenditions() {\n return this.#delegate instanceof HlsJsOnlyAdapter ? this.#delegate.videoRenditions : undefined;\n }\n\n /** Selectable audio variants, populated only while the hls.js (MSE) engine is active; otherwise `undefined`. */\n get audioRenditions() {\n return this.#delegate instanceof HlsJsOnlyAdapter ? this.#delegate.audioRenditions : undefined;\n }\n\n /**\n * Media source URL. Assigning it replaces the identity half of `source` and leaves `type` and the engine options\n * intact, so changing the URL never disturbs engine configuration.\n */\n get src() {\n return this.#src;\n }\n\n set src(src: string) {\n // `src` says which source to play; every other field says how to play it, so\n // they carry over.\n const { type, preferPlayback, drm, engine, maxAutoResolution, capRenditionToPlayerSize, minAutoResolution } =\n this.#source ?? {};\n const next: HlsSource = {\n ...(type && { type }),\n ...(preferPlayback && { preferPlayback }),\n ...(drm && { drm }),\n ...(engine && { engine }),\n ...(maxAutoResolution && { maxAutoResolution }),\n // Definedness, not truthiness: `false` is the value worth naming, and the\n // falsy one, so the neighbors' pattern would drop it.\n ...(capRenditionToPlayerSize !== undefined && { capRenditionToPlayerSize }),\n ...(minAutoResolution && { minAutoResolution }),\n ...(src && { src }),\n };\n\n // Everything happens in the `source` setter, so there is one path for storing\n // it, deciding on a load, and dispatching `sourcechange`.\n this.source = Object.keys(next).length > 0 ? next : null;\n }\n\n /**\n * Structured source: what to play (`src`, an optional `type`) plus how to play it (`preferPlayback`, `engine`).\n * Assigning it derives `src`.\n *\n * Sources are compared structurally, so reassigning an equivalent object is a no-op. Only a change to the engine\n * options (or to the resolved content type) recreates the playback engine.\n */\n get source(): HlsSource | null {\n return this.#source;\n }\n\n set source(value: HlsSource | null) {\n const source = value ?? null;\n // Changing anything takes a new object, so handing the same one back costs\n // nothing.\n if (source === this.#source) return;\n\n const src = source?.src ?? '';\n const srcChanged = this.#src !== src;\n\n this.#source = source;\n this.#src = src;\n\n // Deliberately outside the engine config key below, so it reaches the engine\n // already running.\n this.#applyRenditionCaps();\n\n // Assigning is always a source change, so it is always announced.\n this.dispatchEvent(new Event('sourcechange'));\n\n // Only reload for something playback depends on. Subclasses add params that\n // describe images rather than the stream — Mux's `poster` and `storyboard` —\n // and changing one of those must not restart what is already playing.\n if (srcChanged || this.#shouldEngineUpdate(this.#engineConfigKey())) this.#requestLoad();\n }\n\n /** Preload type (`'none'` / `'metadata'` / `'auto'`). */\n get preload() {\n return this.#preload;\n }\n\n set preload(value) {\n this.#preload = value;\n\n if (this.#delegate) {\n this.#delegate.preload = value;\n }\n }\n\n /** Whether remote playback (AirPlay, Google Cast) is disabled for this media. */\n get disableRemotePlayback() {\n return super.disableRemotePlayback;\n }\n\n set disableRemotePlayback(value: boolean) {\n this.#authorDisableRemotePlayback = value;\n super.disableRemotePlayback = value;\n\n if (this.#delegate instanceof HlsJsOnlyAdapter) {\n this.#delegate.disableRemotePlayback = value;\n }\n }\n\n /** Current stream type (`'on-demand'` / `'live'` / `'unknown'`). */\n get streamType(): StreamType {\n return this.#delegate?.streamType ?? this.#streamType;\n }\n\n set streamType(value: StreamType) {\n this.#isUserStreamType = value !== StreamTypes.UNKNOWN;\n\n if (this.#delegate) {\n this.#delegate.streamType = value;\n this.#streamType = this.#delegate.streamType;\n return;\n }\n\n if (this.#streamType === value) return;\n\n this.#streamType = value;\n this.dispatchEvent(new HlsMediaEvent('streamtypechange'));\n }\n\n /**\n * Presentation time marking the start of the Live Edge Window.\n *\n * Derived from the delegate on every read; `NaN` when no delegate is attached or the stream is not live.\n */\n get liveEdgeStart() {\n return this.#delegate?.liveEdgeStart ?? Number.NaN;\n }\n\n /**\n * Seekable range size for live content. `0` for standard live, `Infinity` for DVR, `NaN` for on-demand or unknown.\n * Fires `targetlivewindowchange` when the value changes (bridged from the delegate).\n */\n get targetLiveWindow() {\n return this.#delegate?.targetLiveWindow ?? Number.NaN;\n }\n\n async load() {\n this.#loadRequested = null;\n\n if (this.remote.state === 'connected') {\n this.dispatchEvent(new HlsMediaEvent('loadstart'));\n return super.load();\n }\n\n if (this.#shouldEngineUpdate(this.#engineConfigKey())) {\n this.#engineDestroy();\n this.#prevEngineConfigKey = this.#engineConfigKey();\n\n // Read the stored source, not the `source` getter: subclasses override the\n // getter to return what was assigned to them, while the fields below come\n // from what they resolved and handed down (Mux fills in the DRM options).\n const { type, preferPlayback, drm, engine, maxAutoResolution, capRenditionToPlayerSize, minAutoResolution } =\n this.#source ?? {};\n const { hlsJs, nativeHls } = engine ?? {};\n const contentType = resolveContentType(type, this.src);\n const useMse = Hls.isSupported() && contentType === ContentTypes.M3U8 && preferPlayback !== PlaybackTypes.NATIVE;\n\n if (__DEV__ && type && !contentType) {\n console.warn(\n `[vjs-media] Unrecognized \\`source.type\\` \"${type}\". HLS sources should use \\`${ContentTypes.M3U8}\\` (or \\`application/x-mpegURL\\`); the browser is being handed this source to play natively, so hls.js features such as quality selection are unavailable.`\n );\n }\n\n if (__DEV__ && !useMse) {\n const ignored = Object.entries({ maxAutoResolution, capRenditionToPlayerSize, minAutoResolution })\n .filter(([, value]) => value !== undefined)\n .map(([key]) => `\\`${key}\\``);\n\n if (ignored.length > 0) {\n const [verb, pronoun] = ignored.length > 1 ? ['require', 'them'] : ['requires', 'it'];\n\n console.warn(\n `[vjs-media] ${ignored.join(', ')} ${verb} the hls.js (MSE) engine; native HLS playback ignores ${pronoun}.`\n );\n }\n }\n\n this.#delegate = useMse\n ? new HlsJsOnlyAdapter({ config: withDrmSystems(hlsJs, drm) })\n : this.#createNativeDelegate(drm, nativeHls, hlsJs);\n\n bridgeEvents(this.#delegate, this);\n\n // Apply user `streamType` before `attach()` so native delegates do not run\n // synchronous duration-based detection first and emit a transient value.\n if (this.#isUserStreamType) {\n this.#delegate.streamType = this.#streamType;\n }\n\n this.#delegate.preload = this.preload;\n this.#applyRenditionCaps();\n\n // Forward the author intent to the delegate, in case it was captured before it existed.\n if (this.#authorDisableRemotePlayback !== undefined && this.#delegate instanceof HlsJsOnlyAdapter) {\n this.#delegate.disableRemotePlayback = this.#authorDisableRemotePlayback;\n }\n\n if (this.#mediaElement) {\n this.#delegate.attach(this.#mediaElement);\n }\n }\n\n if (this.#delegate) {\n this.dispatchEvent(new HlsMediaEvent('loadstart'));\n this.#delegate.src = this.src;\n }\n }\n\n /**\n * A native delegate carrying the native half of the source — the DRM configuration and the native engine options,\n * which it applies the same precedence to. Its `src` is assigned separately, once the delegate is wired up, and\n * carries what is set here forward.\n */\n #createNativeDelegate(\n drm: DrmSystemsConfig | undefined,\n nativeHls: NativeHlsConfig | undefined,\n hlsJs: Partial<HlsJsConfig> | undefined\n ) {\n if (__DEV__) {\n // The delegate applies the same precedence, so the warning has to read — and\n // name — whatever it will end up licensing against. An escape hatch replaces\n // `source.drm` rather than adding to it, so pointing at the wrong one of the\n // two would send a reader looking in a field that is already correct.\n const drmSystems = nativeHls?.drmSystems ?? drm;\n const field = nativeHls?.drmSystems ? 'source.engine.nativeHls.drmSystems' : 'source.drm';\n const isProtected = hlsJs?.emeEnabled || hlsJs?.drmSystems || Object.keys(drmSystems ?? {}).length > 0;\n\n if (isProtected && !drmSystems?.[KeySystems.FAIRPLAY]) {\n console.warn(\n `[vjs-drm] Native HLS playback negotiates FairPlay itself and never sees the hls.js DRM configuration, and no \\`${KeySystems.FAIRPLAY}\\` license server is named in \\`${field}\\`. DRM-protected media will not play.`\n );\n }\n }\n\n const media = new NativeHlsAdapter();\n const source: NativeHlsSource = {\n ...(drm && { drm }),\n ...(nativeHls && { engine: { nativeHls } }),\n };\n\n if (Object.keys(source).length > 0) media.source = source;\n\n return media;\n }\n\n /** Push the source's rendition caps down; only the hls.js engine has a lever. */\n #applyRenditionCaps() {\n if (this.#delegate instanceof HlsJsOnlyAdapter) {\n this.#delegate.maxAutoResolution = this.#source?.maxAutoResolution;\n this.#delegate.capRenditionToPlayerSize = this.#source?.capRenditionToPlayerSize;\n this.#delegate.minAutoResolution = this.#source?.minAutoResolution;\n }\n }\n\n #stopTargetLoadStartEvent = (event: Event) => {\n if (!(event instanceof HlsMediaEvent)) event.stopImmediatePropagation();\n };\n\n async #requestLoad() {\n if (this.#loadRequested) return;\n\n await (this.#loadRequested = Promise.resolve());\n this.#loadRequested = null;\n this.load();\n }\n\n #shouldEngineUpdate(nextEngineConfigKey: Record<string, any>) {\n return !deepEqual(this.#prevEngineConfigKey, nextEngineConfigKey);\n }\n\n /**\n * Every value the engine is constructed from. Compared structurally, so equivalent engine options never trigger a\n * rebuild — including nested ones like `drmSystems`, which a flat comparison would see as changed whenever the object\n * identity did.\n */\n #engineConfigKey() {\n const { type, preferPlayback, drm, engine } = this.#source ?? {};\n\n return { drm, engine, preferPlayback, contentType: resolveContentType(type, this.src) };\n }\n\n #engineDestroy() {\n this.#delegate?.destroy();\n this.#delegate = null;\n this.#prevEngineConfigKey = null;\n this.#loadRequested = null;\n\n // Delegate teardown already emits `streamtypechange` (bridged); only sync cache.\n if (!this.#isUserStreamType) this.#streamType = StreamTypes.UNKNOWN;\n }\n}\n\n/**\n * Hls.js configuration with the source's DRM licensing folded in. hls.js takes `drmSystems` in the same shape as\n * `source.drm`, so the standardized config is what it plays from unless `engine.hlsJs` names servers of its own.\n *\n * Hls.js runs key exchange only while `emeEnabled` is set, so configured DRM switches it on — short of an explicit\n * `emeEnabled: false`, which stays a way to describe a source's licensing without acting on it.\n */\nfunction withDrmSystems(\n hlsJs: Partial<HlsJsConfig> | undefined,\n drm: DrmSystemsConfig | undefined\n): Partial<HlsJsConfig> {\n const drmSystems = hlsJs?.drmSystems ?? drm;\n if (!drmSystems || Object.keys(drmSystems).length === 0) return { ...hlsJs };\n\n // hls.js declares `serverCertificateUrl` without `undefined`, which an\n // omittable property here is allowed to carry. The values are the same.\n return { emeEnabled: true, ...hlsJs, drmSystems: drmSystems as HlsJsConfig['drmSystems'] };\n}\n\n/**\n * The canonical content type the engine decision is made on: an explicit `type` folded onto its canonical spelling, or\n * what the URL suggests when there is none. An explicit type nobody recognizes resolves to `undefined` rather than\n * falling back to inference — the author said what the source is, and guessing over them would make `type` mean\n * different things depending on its value.\n */\nfunction resolveContentType(type: string | undefined, src: string): SourceType | undefined {\n if (!type) return inferContentType(src);\n\n // Parameters (`; charset=...`) and case carry no meaning for the engine choice.\n const normalized = (type.split(';')[0] ?? '').trim().toLowerCase();\n if (HLS_CONTENT_TYPES.has(normalized)) return ContentTypes.M3U8;\n\n if (MP4_CONTENT_TYPES.has(normalized)) return ContentTypes.MP4;\n\n return undefined;\n}\n\nfunction inferContentType(src: string): SourceType {\n const path = src.split(/[?#]/)[0] ?? '';\n if (path.endsWith('.mp4')) return ContentTypes.MP4;\n\n return ContentTypes.M3U8;\n}\n"],"mappings":";;;;;;;;AA4BA,MAAa,gBAAgB;CAC3B,KAAK;CACL,QAAQ;AACV;;AAGA,MAAa,eAAe;CAC1B,MAAM;CACN,KAAK;AACP;;;;;;AAOA,MAAM,oCAAyC,IAAI,IAAI;CACrD,aAAa;CACb;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,oCAAyC,IAAI,IAAI,CAAC,aAAa,GAAG,CAAC;;AAGzE,MAAa,cAAc;AA6G3B,IAAM,gBAAN,cAA4B,MAAM,CAAC;;;;;;;AAQnC,IAAa,eAAb,MAAa,qBAAqB,iBAA8C;;EAC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ADa,IAAI,MAAM,MAAM,CAAC,CAAC,MAAM,GAAA,CAC5B,SAAS,MAAM,GAAG,OAAO,aAAa;CAE/C,OAAO,aAAa;AACtB"}
|
package/dist/dev/cap-level.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import Hls from "hls.js";
|
|
1
|
+
import Hls, { CapLevelController } from "hls.js";
|
|
2
2
|
//#region src/cap-level.ts
|
|
3
3
|
/**
|
|
4
4
|
* Floor applied to the player-size cap unless a source names another.
|
|
@@ -65,22 +65,21 @@ function levelIndexAtOrAbove(levels, resolution) {
|
|
|
65
65
|
/**
|
|
66
66
|
* Build the `capLevelController` class to hand to the hls.js constructor.
|
|
67
67
|
*
|
|
68
|
-
* `hls.autoLevelCapping`
|
|
69
|
-
* interval for as long as `capLevelToPlayerSize` is on — and it is on by
|
|
70
|
-
* outside is undone
|
|
71
|
-
* with it.
|
|
68
|
+
* `hls.autoLevelCapping` is rewritten by hls.js's own `CapLevelController` whenever the element resizes (or on a
|
|
69
|
+
* one-second interval where `ResizeObserver` is missing) for as long as `capLevelToPlayerSize` is on — and it is on by
|
|
70
|
+
* default here. Assigning the property from outside is undone on the next measurement, so a cap has to be applied from
|
|
71
|
+
* inside the controller rather than in competition with it.
|
|
72
72
|
*
|
|
73
73
|
* The only seam hls.js offers is `getMaxLevel()`, which every value the capping loop writes passes through. Overriding
|
|
74
|
-
* it makes the requested ceiling part of the same
|
|
74
|
+
* it makes the requested ceiling part of the same computation.
|
|
75
75
|
*
|
|
76
76
|
* @param policy - Live cap inputs, re-read on every evaluation.
|
|
77
77
|
* @param BaseController - Controller to layer on top of, so a controller passed through
|
|
78
78
|
* `source.engine.capLevelController` keeps its behavior.
|
|
79
79
|
*/
|
|
80
|
-
function createCapLevelController(policy, BaseController = Hls.DefaultConfig.capLevelController) {
|
|
80
|
+
function createCapLevelController(policy, BaseController = Hls.DefaultConfig.capLevelController ?? CapLevelController) {
|
|
81
81
|
return class RenditionCapLevelController extends BaseController {
|
|
82
82
|
#hls;
|
|
83
|
-
#capping = false;
|
|
84
83
|
#measuringWithoutSize = false;
|
|
85
84
|
constructor(hls) {
|
|
86
85
|
super(hls);
|
|
@@ -95,14 +94,6 @@ function createCapLevelController(policy, BaseController = Hls.DefaultConfig.cap
|
|
|
95
94
|
if (policy.controller === this) policy.controller = void 0;
|
|
96
95
|
super.destroy();
|
|
97
96
|
}
|
|
98
|
-
startCapping() {
|
|
99
|
-
this.#capping = true;
|
|
100
|
-
super.startCapping();
|
|
101
|
-
}
|
|
102
|
-
stopCapping() {
|
|
103
|
-
this.#capping = false;
|
|
104
|
-
super.stopCapping();
|
|
105
|
-
}
|
|
106
97
|
/**
|
|
107
98
|
* Hls.js derives its player-size ceiling from these two, so reporting an unbounded measurement is how
|
|
108
99
|
* `capToPlayerSize: false` switches that ceiling off while leaving the rest of the base controller intact.
|
|
@@ -163,7 +154,7 @@ function createCapLevelController(policy, BaseController = Hls.DefaultConfig.cap
|
|
|
163
154
|
this.#applyResolutionCap();
|
|
164
155
|
}
|
|
165
156
|
apply() {
|
|
166
|
-
if (this.#
|
|
157
|
+
if (this.#hls.config.capLevelToPlayerSize) {
|
|
167
158
|
this.detectPlayerSize();
|
|
168
159
|
return;
|
|
169
160
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cap-level.js","names":[],"sources":["../../src/cap-level.ts"],"sourcesContent":["import type { MediaResolution } from '@videojs/media';\nimport Hls, { type Level } from 'hls.js';\n\n/**\n * Live cap inputs the installed cap-level controller reads on every evaluation.\n *\n * Hls.js fixes `capLevelController` when the engine is constructed, so the class cannot carry values that change during\n * playback. The media element owns this object and mutates it in place instead, which is what lets a cap change skip\n * rebuilding the engine.\n */\nexport interface RenditionCapPolicy {\n /** Highest resolution ABR may auto-select, or `undefined` for no cap. */\n maxAutoResolution: MediaResolution | undefined;\n /** Whether the element's rendered size caps automatic selection. */\n capToPlayerSize: boolean;\n /** Lowest resolution {@link capToPlayerSize} may cap down to, or `undefined` for no floor. */\n minAutoResolution: MediaResolution | undefined;\n /** Registered by the controller's own constructor. */\n controller?: RenditionCapController | undefined;\n}\n\n/**\n * Floor applied to the player-size cap unless a source names another.\n *\n * The low rungs of a ladder are there for bad network conditions, and at that end the relationship between resolution\n * and perceived quality stops holding: a small player capped to 360p looks worse than its size alone suggests. No\n * reliable signal exists to key that on, so a fixed floor stands in for one.\n */\nexport const DEFAULT_MIN_AUTO_RESOLUTION: MediaResolution = '720p';\n\nexport interface RenditionCapController {\n /** Re-evaluate the policy now rather than on hls.js's next tick. */\n apply(): void;\n}\n\n/**\n * Pixel area of a resolution shorthand, assuming 16:9 — `'720p'` is `1280 × 720`, or `921_600`.\n *\n * Renditions are matched on area rather than literal height so anamorphic variants are judged by how many pixels they\n * actually carry: a 2560×1080 ultrawide rendition costs more than 16:9 1080p and is capped accordingly.\n *\n * Rounds the 16:9 width up so every standard rendition fits its own cap. For `'480p'`, the exact width is 853.33, while\n * ladders ship 854×480. The exact area would put that rendition over its own cap; rounding admits it while still\n * excluding wider renditions.\n */\nexport function resolutionToPixelArea(resolution: MediaResolution | undefined): number {\n if (resolution === undefined) return Number.POSITIVE_INFINITY;\n\n const height = Number.parseInt(resolution, 10);\n if (!(Number.isFinite(height) && height > 0)) return Number.POSITIVE_INFINITY;\n\n return Math.ceil((height * 16) / 9) * height;\n}\n\n/**\n * Highest level index that keeps automatic selection at or below `resolution`.\n *\n * `autoLevelCapping` is a ceiling on the _index_, so every level at or below it stays eligible. That makes the answer\n * the end of the leading run that fits the budget, not the single best match: hls.js orders levels by height, so a\n * wider rendition can exceed the pixel budget from a lower index, and capping at the best match would leave it\n * selectable.\n *\n * Falls back to index `0` when even the lowest rung is over budget — playing something over-spec beats refusing to\n * adapt.\n *\n * Returns `undefined` when there is nothing to cap: no resolution requested, or no levels to choose from.\n */\nexport function levelIndexAtOrBelow(\n levels: readonly Level[],\n resolution: MediaResolution | undefined\n): number | undefined {\n const maxPixelArea = resolutionToPixelArea(resolution);\n if (maxPixelArea === Number.POSITIVE_INFINITY || levels.length === 0) return undefined;\n\n const overBudget = levels.findIndex((level) => (level.width ?? 0) * (level.height ?? 0) > maxPixelArea);\n\n // Everything fits: the whole ladder is eligible. Otherwise stop one short of\n // the first level that does not, and never below index 0.\n return overBudget === -1 ? levels.length - 1 : Math.max(0, overBudget - 1);\n}\n\n/**\n * Lowest level index that keeps a rendition at or above `resolution` eligible.\n *\n * The complement of {@link levelIndexAtOrBelow}, for raising a ceiling rather than lowering one, and reasoned the same\n * way: `autoLevelCapping` is a ceiling on the _index_, so the cheapest ceiling that still admits the floor is the first\n * index that reaches it. Every rung below stays eligible either way, which is what keeps this a bound on capping rather\n * than a quality minimum.\n *\n * Falls back to the top of the ladder when no rendition reaches the floor — a floor nothing can satisfy has no cap to\n * raise.\n *\n * Returns `undefined` when there is no floor to apply: no resolution requested, or no levels to choose from.\n */\nexport function levelIndexAtOrAbove(\n levels: readonly Level[],\n resolution: MediaResolution | undefined\n): number | undefined {\n const minPixelArea = resolutionToPixelArea(resolution);\n if (minPixelArea === Number.POSITIVE_INFINITY || levels.length === 0) return undefined;\n\n const atFloor = levels.findIndex((level) => (level.width ?? 0) * (level.height ?? 0) >= minPixelArea);\n\n return atFloor === -1 ? levels.length - 1 : atFloor;\n}\n\ntype CapLevelControllerClass = typeof Hls.DefaultConfig.capLevelController;\n\n/**\n * Build the `capLevelController` class to hand to the hls.js constructor.\n *\n * `hls.autoLevelCapping` has exactly one writer: hls.js's own `CapLevelController`, which rewrites it on a one-second\n * interval for as long as `capLevelToPlayerSize` is on — and it is on by default here. Assigning the property from\n * outside is undone within a second, so a cap has to be applied from inside the controller rather than in competition\n * with it.\n *\n * The only seam hls.js offers is `getMaxLevel()`, which every value the capping loop writes passes through. Overriding\n * it makes the requested ceiling part of the same single-writer computation.\n *\n * @param policy - Live cap inputs, re-read on every evaluation.\n * @param BaseController - Controller to layer on top of, so a controller passed through\n * `source.engine.capLevelController` keeps its behavior.\n */\nexport function createCapLevelController(\n policy: RenditionCapPolicy,\n BaseController: CapLevelControllerClass = Hls.DefaultConfig.capLevelController\n): CapLevelControllerClass {\n return class RenditionCapLevelController extends BaseController {\n #hls: Hls;\n #capping = false;\n #measuringWithoutSize = false;\n\n constructor(hls: Hls) {\n super(hls);\n this.#hls = hls;\n policy.controller = this;\n\n // hls.js re-evaluates on both of these itself, but only while its capping\n // loop runs. These cover the case where it never starts.\n hls.on(Hls.Events.MANIFEST_PARSED, this.#onLevelsChanged);\n hls.on(Hls.Events.LEVELS_UPDATED, this.#onLevelsChanged);\n }\n\n destroy() {\n this.#hls.off(Hls.Events.MANIFEST_PARSED, this.#onLevelsChanged);\n this.#hls.off(Hls.Events.LEVELS_UPDATED, this.#onLevelsChanged);\n\n if (policy.controller === this) policy.controller = undefined;\n\n super.destroy();\n }\n\n // hls.js keeps the interval handle private, so the loop is tracked through\n // the public start/stop pair instead of reaching into it.\n startCapping() {\n this.#capping = true;\n super.startCapping();\n }\n\n stopCapping() {\n this.#capping = false;\n super.stopCapping();\n }\n\n /**\n * Hls.js derives its player-size ceiling from these two, so reporting an unbounded measurement is how\n * `capToPlayerSize: false` switches that ceiling off while leaving the rest of the base controller intact.\n *\n * Returning early from `getMaxLevel()` instead would be the obvious way to skip the size cap, and it would also\n * skip the levels `capLevelOnFPSDrop` has restricted: those are filtered inside the same `super.getMaxLevel()`\n * call, and `restrictedLevels` is private, so there is no way to reapply them afterwards. Neutralizing the input\n * keeps one path for both.\n */\n get mediaWidth(): number {\n return this.#sizeApplies ? super.mediaWidth : Number.POSITIVE_INFINITY;\n }\n\n get mediaHeight(): number {\n return this.#sizeApplies ? super.mediaHeight : Number.POSITIVE_INFINITY;\n }\n\n get #sizeApplies(): boolean {\n return policy.capToPlayerSize && !this.#measuringWithoutSize;\n }\n\n /**\n * What `super` allows with player size out of the picture — the ladder minus whatever `capLevelOnFPSDrop` has\n * restricted. Reached through the same unbounded-measurement seam the toggle uses, since `restrictedLevels` is\n * private and not readable any other way.\n */\n #topAllowedLevel(capLevelIndex: number): number {\n this.#measuringWithoutSize = true;\n\n try {\n return super.getMaxLevel(capLevelIndex);\n } finally {\n this.#measuringWithoutSize = false;\n }\n }\n\n /**\n * Intersect hls.js's player-size ceiling with the requested one. Deferring to `super` first keeps the behavior it\n * owns — notably the level restrictions `capLevelOnFPSDrop` accumulates.\n *\n * The translation from resolution to level index happens here, not when the policy is set, because levels arrive\n * after the option does and shift whenever hls.js drops one.\n */\n getMaxLevel(capLevelIndex: number): number {\n const { levels } = this.#hls;\n let ceiling = super.getMaxLevel(capLevelIndex);\n\n // Only where there is a size ceiling to lift: `super` reports `-1` when no\n // level is available at all, and player size is no reason to overrule that.\n if (policy.capToPlayerSize && ceiling >= 0) {\n const floor = levelIndexAtOrAbove(levels, policy.minAutoResolution);\n\n // A floor says \"do not cap this small player that far down\", not \"decode\n // what this device can't\", so it stops at the top allowed level.\n if (floor !== undefined) ceiling = Math.min(Math.max(ceiling, floor), this.#topAllowedLevel(capLevelIndex));\n }\n\n // Narrowing after the floor is what subordinates it: a caller asking for\n // at most 360p gets 360p, however high the floor sits.\n const byResolution = levelIndexAtOrBelow(levels, policy.maxAutoResolution);\n\n if (byResolution !== undefined) ceiling = Math.min(ceiling, byResolution);\n\n // A floor can push past the top of the ladder; `capLevelIndex` is the real bound.\n return Math.min(ceiling, capLevelIndex);\n }\n\n /**\n * Hls.js measures the element here and writes the ceiling it derives. It backs out entirely when the element has no\n * measurable size — sensible for a cap that _is_ the element's size, but a requested resolution ceiling does not\n * depend on layout. A player that is hidden, detached, or not laid out yet still has to honor it.\n */\n detectPlayerSize() {\n super.detectPlayerSize();\n\n // Through the base getters: the overrides above report an unbounded size\n // while the cap is off, which would pass for a measurable element.\n if (super.mediaWidth > 0 && super.mediaHeight > 0) return;\n\n this.#applyResolutionCap();\n }\n\n apply() {\n // While the loop runs it owns the slot, so go through its own path;\n // everything it writes already passes through `getMaxLevel()`.\n if (this.#capping) {\n this.detectPlayerSize();\n return;\n }\n\n this.#applyResolutionCap();\n }\n\n /**\n * The ceiling on its own, for when the size measurement is unavailable.\n *\n * Neither `capToPlayerSize` nor `minAutoResolution` reaches this path, and neither has anything to do here: both\n * describe a cap derived from the element's size, and this is precisely the case where no such cap exists — there\n * is none to switch off, and none for a floor to lift.\n */\n #applyResolutionCap() {\n const { levels } = this.#hls;\n if (!levels?.length) return;\n\n // `-1` is how hls.js spells \"uncapped\".\n this.#hls.autoLevelCapping = levelIndexAtOrBelow(levels, policy.maxAutoResolution) ?? -1;\n }\n\n #onLevelsChanged = () => this.apply();\n };\n}\n"],"mappings":";;;;;;;;;AA4BA,MAAa,8BAA+C;;;;;;;;;;;AAiB5D,SAAgB,sBAAsB,YAAiD;CACrF,IAAI,eAAe,KAAA,GAAW,OAAO,OAAO;CAE5C,MAAM,SAAS,OAAO,SAAS,YAAY,EAAE;CAC7C,IAAI,EAAE,OAAO,SAAS,MAAM,KAAK,SAAS,IAAI,OAAO,OAAO;CAE5D,OAAO,KAAK,KAAM,SAAS,KAAM,CAAC,IAAI;AACxC;;;;;;;;;;;;;;AAeA,SAAgB,oBACd,QACA,YACoB;CACpB,MAAM,eAAe,sBAAsB,UAAU;CACrD,IAAI,iBAAiB,OAAO,qBAAqB,OAAO,WAAW,GAAG,OAAO,KAAA;CAE7E,MAAM,aAAa,OAAO,WAAW,WAAW,MAAM,SAAS,MAAM,MAAM,UAAU,KAAK,YAAY;CAItG,OAAO,eAAe,KAAK,OAAO,SAAS,IAAI,KAAK,IAAI,GAAG,aAAa,CAAC;AAC3E;;;;;;;;;;;;;;AAeA,SAAgB,oBACd,QACA,YACoB;CACpB,MAAM,eAAe,sBAAsB,UAAU;CACrD,IAAI,iBAAiB,OAAO,qBAAqB,OAAO,WAAW,GAAG,OAAO,KAAA;CAE7E,MAAM,UAAU,OAAO,WAAW,WAAW,MAAM,SAAS,MAAM,MAAM,UAAU,MAAM,YAAY;CAEpG,OAAO,YAAY,KAAK,OAAO,SAAS,IAAI;AAC9C;;;;;;;;;;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K,iBAAiB,aAAa,CAAC;GAC5G;GAIA,MAAM,eAAe,oBAAoB,QAAQ,OAAO,iBAAiB;GAEzE,IAAI,iBAAiB,KAAA,GAAW,UAAU,KAAK,IAAI,SAAS,YAAY;GAGxE,OAAO,KAAK,IAAI,SAAS,aAAa;EACxC;;;;;;EAOA,mBAAmB;GACjB,MAAM,iBAAiB;GAIvB,IAAI,MAAM,aAAa,KAAK,MAAM,cAAc,GAAG;GAEnD,KAAK,oBAAoB;EAC3B;EAEA,QAAQ;GAGN,IAAI,KAAK,UAAU;IACjB,KAAK,iBAAiB;IACtB;GACF;GAEA,KAAK,oBAAoB;EAC3B;;;;;;;;EASA,sBAAsB;GACpB,MAAM,EAAE,WAAW,KAAK;GACxB,IAAI,CAAC,QAAQ,QAAQ;GAGrB,KAAK,KAAK,mBAAmB,oBAAoB,QAAQ,OAAO,iBAAiB,KAAK;EACxF;EAEA,yBAAyB,KAAK,MAAM;CACtC;AACF"}
|
|
1
|
+
{"version":3,"file":"cap-level.js","names":[],"sources":["../../src/cap-level.ts"],"sourcesContent":["import type { MediaResolution } from '@videojs/media';\nimport Hls, { CapLevelController, type Level } from 'hls.js';\n\n/**\n * Live cap inputs the installed cap-level controller reads on every evaluation.\n *\n * Hls.js fixes `capLevelController` when the engine is constructed, so the class cannot carry values that change during\n * playback. The media element owns this object and mutates it in place instead, which is what lets a cap change skip\n * rebuilding the engine.\n */\nexport interface RenditionCapPolicy {\n /** Highest resolution ABR may auto-select, or `undefined` for no cap. */\n maxAutoResolution: MediaResolution | undefined;\n /** Whether the element's rendered size caps automatic selection. */\n capToPlayerSize: boolean;\n /** Lowest resolution {@link capToPlayerSize} may cap down to, or `undefined` for no floor. */\n minAutoResolution: MediaResolution | undefined;\n /** Registered by the controller's own constructor. */\n controller?: RenditionCapController | undefined;\n}\n\n/**\n * Floor applied to the player-size cap unless a source names another.\n *\n * The low rungs of a ladder are there for bad network conditions, and at that end the relationship between resolution\n * and perceived quality stops holding: a small player capped to 360p looks worse than its size alone suggests. No\n * reliable signal exists to key that on, so a fixed floor stands in for one.\n */\nexport const DEFAULT_MIN_AUTO_RESOLUTION: MediaResolution = '720p';\n\nexport interface RenditionCapController {\n /** Re-evaluate the policy now rather than when hls.js next measures the element. */\n apply(): void;\n}\n\n/**\n * Pixel area of a resolution shorthand, assuming 16:9 — `'720p'` is `1280 × 720`, or `921_600`.\n *\n * Renditions are matched on area rather than literal height so anamorphic variants are judged by how many pixels they\n * actually carry: a 2560×1080 ultrawide rendition costs more than 16:9 1080p and is capped accordingly.\n *\n * Rounds the 16:9 width up so every standard rendition fits its own cap. For `'480p'`, the exact width is 853.33, while\n * ladders ship 854×480. The exact area would put that rendition over its own cap; rounding admits it while still\n * excluding wider renditions.\n */\nexport function resolutionToPixelArea(resolution: MediaResolution | undefined): number {\n if (resolution === undefined) return Number.POSITIVE_INFINITY;\n\n const height = Number.parseInt(resolution, 10);\n if (!(Number.isFinite(height) && height > 0)) return Number.POSITIVE_INFINITY;\n\n return Math.ceil((height * 16) / 9) * height;\n}\n\n/**\n * Highest level index that keeps automatic selection at or below `resolution`.\n *\n * `autoLevelCapping` is a ceiling on the _index_, so every level at or below it stays eligible. That makes the answer\n * the end of the leading run that fits the budget, not the single best match: hls.js orders levels by height, so a\n * wider rendition can exceed the pixel budget from a lower index, and capping at the best match would leave it\n * selectable.\n *\n * Falls back to index `0` when even the lowest rung is over budget — playing something over-spec beats refusing to\n * adapt.\n *\n * Returns `undefined` when there is nothing to cap: no resolution requested, or no levels to choose from.\n */\nexport function levelIndexAtOrBelow(\n levels: readonly Level[],\n resolution: MediaResolution | undefined\n): number | undefined {\n const maxPixelArea = resolutionToPixelArea(resolution);\n if (maxPixelArea === Number.POSITIVE_INFINITY || levels.length === 0) return undefined;\n\n const overBudget = levels.findIndex((level) => (level.width ?? 0) * (level.height ?? 0) > maxPixelArea);\n\n // Everything fits: the whole ladder is eligible. Otherwise stop one short of\n // the first level that does not, and never below index 0.\n return overBudget === -1 ? levels.length - 1 : Math.max(0, overBudget - 1);\n}\n\n/**\n * Lowest level index that keeps a rendition at or above `resolution` eligible.\n *\n * The complement of {@link levelIndexAtOrBelow}, for raising a ceiling rather than lowering one, and reasoned the same\n * way: `autoLevelCapping` is a ceiling on the _index_, so the cheapest ceiling that still admits the floor is the first\n * index that reaches it. Every rung below stays eligible either way, which is what keeps this a bound on capping rather\n * than a quality minimum.\n *\n * Falls back to the top of the ladder when no rendition reaches the floor — a floor nothing can satisfy has no cap to\n * raise.\n *\n * Returns `undefined` when there is no floor to apply: no resolution requested, or no levels to choose from.\n */\nexport function levelIndexAtOrAbove(\n levels: readonly Level[],\n resolution: MediaResolution | undefined\n): number | undefined {\n const minPixelArea = resolutionToPixelArea(resolution);\n if (minPixelArea === Number.POSITIVE_INFINITY || levels.length === 0) return undefined;\n\n const atFloor = levels.findIndex((level) => (level.width ?? 0) * (level.height ?? 0) >= minPixelArea);\n\n return atFloor === -1 ? levels.length - 1 : atFloor;\n}\n\ntype CapLevelControllerClass = typeof CapLevelController;\n\n/**\n * Build the `capLevelController` class to hand to the hls.js constructor.\n *\n * `hls.autoLevelCapping` is rewritten by hls.js's own `CapLevelController` whenever the element resizes (or on a\n * one-second interval where `ResizeObserver` is missing) for as long as `capLevelToPlayerSize` is on — and it is on by\n * default here. Assigning the property from outside is undone on the next measurement, so a cap has to be applied from\n * inside the controller rather than in competition with it.\n *\n * The only seam hls.js offers is `getMaxLevel()`, which every value the capping loop writes passes through. Overriding\n * it makes the requested ceiling part of the same computation.\n *\n * @param policy - Live cap inputs, re-read on every evaluation.\n * @param BaseController - Controller to layer on top of, so a controller passed through\n * `source.engine.capLevelController` keeps its behavior.\n */\nexport function createCapLevelController(\n policy: RenditionCapPolicy,\n BaseController: CapLevelControllerClass = Hls.DefaultConfig.capLevelController ?? CapLevelController\n): CapLevelControllerClass {\n return class RenditionCapLevelController extends BaseController {\n #hls: Hls;\n #measuringWithoutSize = false;\n\n constructor(hls: Hls) {\n super(hls);\n this.#hls = hls;\n policy.controller = this;\n\n // hls.js re-evaluates on both of these itself, but only while its capping\n // loop runs. These cover the case where it never starts.\n hls.on(Hls.Events.MANIFEST_PARSED, this.#onLevelsChanged);\n hls.on(Hls.Events.LEVELS_UPDATED, this.#onLevelsChanged);\n }\n\n destroy() {\n this.#hls.off(Hls.Events.MANIFEST_PARSED, this.#onLevelsChanged);\n this.#hls.off(Hls.Events.LEVELS_UPDATED, this.#onLevelsChanged);\n\n if (policy.controller === this) policy.controller = undefined;\n\n super.destroy();\n }\n\n /**\n * Hls.js derives its player-size ceiling from these two, so reporting an unbounded measurement is how\n * `capToPlayerSize: false` switches that ceiling off while leaving the rest of the base controller intact.\n *\n * Returning early from `getMaxLevel()` instead would be the obvious way to skip the size cap, and it would also\n * skip the levels `capLevelOnFPSDrop` has restricted: those are filtered inside the same `super.getMaxLevel()`\n * call, and `restrictedLevels` is private, so there is no way to reapply them afterwards. Neutralizing the input\n * keeps one path for both.\n */\n get mediaWidth(): number {\n return this.#sizeApplies ? super.mediaWidth : Number.POSITIVE_INFINITY;\n }\n\n get mediaHeight(): number {\n return this.#sizeApplies ? super.mediaHeight : Number.POSITIVE_INFINITY;\n }\n\n get #sizeApplies(): boolean {\n return policy.capToPlayerSize && !this.#measuringWithoutSize;\n }\n\n /**\n * What `super` allows with player size out of the picture — the ladder minus whatever `capLevelOnFPSDrop` has\n * restricted. Reached through the same unbounded-measurement seam the toggle uses, since `restrictedLevels` is\n * private and not readable any other way.\n */\n #topAllowedLevel(capLevelIndex: number): number {\n this.#measuringWithoutSize = true;\n\n try {\n return super.getMaxLevel(capLevelIndex);\n } finally {\n this.#measuringWithoutSize = false;\n }\n }\n\n /**\n * Intersect hls.js's player-size ceiling with the requested one. Deferring to `super` first keeps the behavior it\n * owns — notably the level restrictions `capLevelOnFPSDrop` accumulates.\n *\n * The translation from resolution to level index happens here, not when the policy is set, because levels arrive\n * after the option does and shift whenever hls.js drops one.\n */\n getMaxLevel(capLevelIndex: number): number {\n const { levels } = this.#hls;\n let ceiling = super.getMaxLevel(capLevelIndex);\n\n // Only where there is a size ceiling to lift: `super` reports `-1` when no\n // level is available at all, and player size is no reason to overrule that.\n if (policy.capToPlayerSize && ceiling >= 0) {\n const floor = levelIndexAtOrAbove(levels, policy.minAutoResolution);\n\n // A floor says \"do not cap this small player that far down\", not \"decode\n // what this device can't\", so it stops at the top allowed level.\n if (floor !== undefined) ceiling = Math.min(Math.max(ceiling, floor), this.#topAllowedLevel(capLevelIndex));\n }\n\n // Narrowing after the floor is what subordinates it: a caller asking for\n // at most 360p gets 360p, however high the floor sits.\n const byResolution = levelIndexAtOrBelow(levels, policy.maxAutoResolution);\n\n if (byResolution !== undefined) ceiling = Math.min(ceiling, byResolution);\n\n // A floor can push past the top of the ladder; `capLevelIndex` is the real bound.\n return Math.min(ceiling, capLevelIndex);\n }\n\n /**\n * Hls.js measures the element here and writes the ceiling it derives. It backs out entirely when the element has no\n * measurable size — sensible for a cap that _is_ the element's size, but a requested resolution ceiling does not\n * depend on layout. A player that is hidden, detached, or not laid out yet still has to honor it.\n */\n detectPlayerSize() {\n super.detectPlayerSize();\n\n // Through the base getters: the overrides above report an unbounded size\n // while the cap is off, which would pass for a measurable element.\n if (super.mediaWidth > 0 && super.mediaHeight > 0) return;\n\n this.#applyResolutionCap();\n }\n\n apply() {\n // With size capping on, measuring owns the slot: everything it writes\n // passes through `getMaxLevel()`, and an unmeasurable element falls back\n // to the resolution cap. Whether hls.js's own loop is running is not\n // tracked, since it starts measuring on attach without `startCapping()`.\n if (this.#hls.config.capLevelToPlayerSize) {\n this.detectPlayerSize();\n return;\n }\n\n this.#applyResolutionCap();\n }\n\n /**\n * The ceiling on its own, for when the size measurement is unavailable.\n *\n * Neither `capToPlayerSize` nor `minAutoResolution` reaches this path, and neither has anything to do here: both\n * describe a cap derived from the element's size, and this is precisely the case where no such cap exists — there\n * is none to switch off, and none for a floor to lift.\n */\n #applyResolutionCap() {\n const { levels } = this.#hls;\n if (!levels?.length) return;\n\n // `-1` is how hls.js spells \"uncapped\".\n this.#hls.autoLevelCapping = levelIndexAtOrBelow(levels, policy.maxAutoResolution) ?? -1;\n }\n\n #onLevelsChanged = () => this.apply();\n };\n}\n"],"mappings":";;;;;;;;;AA4BA,MAAa,8BAA+C;;;;;;;;;;;AAiB5D,SAAgB,sBAAsB,YAAiD;CACrF,IAAI,eAAe,KAAA,GAAW,OAAO,OAAO;CAE5C,MAAM,SAAS,OAAO,SAAS,YAAY,EAAE;CAC7C,IAAI,EAAE,OAAO,SAAS,MAAM,KAAK,SAAS,IAAI,OAAO,OAAO;CAE5D,OAAO,KAAK,KAAM,SAAS,KAAM,CAAC,IAAI;AACxC;;;;;;;;;;;;;;AAeA,SAAgB,oBACd,QACA,YACoB;CACpB,MAAM,eAAe,sBAAsB,UAAU;CACrD,IAAI,iBAAiB,OAAO,qBAAqB,OAAO,WAAW,GAAG,OAAO,KAAA;CAE7E,MAAM,aAAa,OAAO,WAAW,WAAW,MAAM,SAAS,MAAM,MAAM,UAAU,KAAK,YAAY;CAItG,OAAO,eAAe,KAAK,OAAO,SAAS,IAAI,KAAK,IAAI,GAAG,aAAa,CAAC;AAC3E;;;;;;;;;;;;;;AAeA,SAAgB,oBACd,QACA,YACoB;CACpB,MAAM,eAAe,sBAAsB,UAAU;CACrD,IAAI,iBAAiB,OAAO,qBAAqB,OAAO,WAAW,GAAG,OAAO,KAAA;CAE7E,MAAM,UAAU,OAAO,WAAW,WAAW,MAAM,SAAS,MAAM,MAAM,UAAU,MAAM,YAAY;CAEpG,OAAO,YAAY,KAAK,OAAO,SAAS,IAAI;AAC9C;;;;;;;;;;;;;;;;AAmBA,SAAgB,yBACd,QACA,iBAA0C,IAAI,cAAc,sBAAsB,oBACzD;CACzB,OAAO,MAAM,oCAAoC,eAAe;EAC9D;EACA,wBAAwB;EAExB,YAAY,KAAU;GACpB,MAAM,GAAG;GACT,KAAK,OAAO;GACZ,OAAO,aAAa;GAIpB,IAAI,GAAG,IAAI,OAAO,iBAAiB,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OAAO,sBAAsB;IACzC,KAAK,iBAAiB;IACtB;GACF;GAEA,KAAK,oBAAoB;EAC3B;;;;;;;;EASA,sBAAsB;GACpB,MAAM,EAAE,WAAW,KAAK;GACxB,IAAI,CAAC,QAAQ,QAAQ;GAGrB,KAAK,KAAK,mBAAmB,oBAAoB,QAAQ,OAAO,iBAAiB,KAAK;EACxF;EAEA,yBAAyB,KAAK,MAAM;CACtC;AACF"}
|
package/dist/dev/hls-js-only.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hls-js-only.js","names":[],"sources":["../../src/hls-js-only.ts"],"sourcesContent":["import type {\n EngineAdapter,\n MediaError,\n MediaLiveCapability,\n MediaResolution,\n MediaSourceCapability,\n MediaStreamTypeCapability,\n} from '@videojs/media';\nimport { HTMLVideoAdapter } from '@videojs/media/dom';\nimport { MediaTracksMixin, type WithMediaTracks } from '@videojs/media/media-tracks';\nimport type { MixinReturn } from '@videojs/utils/types';\nimport Hls, { type HlsConfig } from 'hls.js';\n\nimport { HlsJsAirPlayMixin } from './airplay-bridge';\nimport { createCapLevelController, DEFAULT_MIN_AUTO_RESOLUTION, type RenditionCapPolicy } from './cap-level';\nimport { HlsJsChaptersMixin } from './chapters';\nimport { setupDrm } from './drm';\nimport { HlsJsErrorsMixin } from './errors';\nimport { HlsJsLiveMixin } from './live';\nimport { HlsJsMediaTracksMixin } from './media-tracks';\nimport { HlsJsMetadataTracksMixin } from './metadata-tracks';\nimport { HlsJsPreloadMixin } from './preload';\nimport { withRequestCredentials } from './request-credentials';\nimport { HlsJsStreamTypeMixin } from './stream-type';\nimport { HlsJsTextTracksMixin, withPreservedTextTracks } from './text-tracks';\n\nconst defaultHlsConfig: Partial<HlsConfig> = {\n backBufferLength: 30,\n renderTextTracksNatively: false,\n liveDurationInfinity: true,\n // Runs hls.js's capping loop, which every rendition cap is evaluated on, not\n // only the one named after it. `capRenditionToPlayerSize` is the live switch.\n capLevelToPlayerSize: true,\n capLevelOnFPSDrop: true,\n autoStartLoad: false,\n};\n\nexport interface HlsJsOnlyMediaParams {\n /** Options forwarded to the hls.js constructor, merged over {@link defaultHlsConfig}. */\n config: Partial<HlsConfig>;\n}\n\nclass HlsJsOnlyAdapterCore extends HTMLVideoAdapter implements EngineAdapter<Hls, HTMLVideoElement> {\n #engine: Hls | null = null;\n #capPolicy: RenditionCapPolicy = {\n maxAutoResolution: undefined,\n capToPlayerSize: true,\n minAutoResolution: DEFAULT_MIN_AUTO_RESOLUTION,\n };\n\n constructor(params: HlsJsOnlyMediaParams) {\n super();\n const config = { ...defaultHlsConfig, ...params.config };\n\n this.#engine = new Hls({\n ...config,\n // Layered over whatever controller the config already names, so a\n // `capLevelController` passed through `source.engine` keeps working.\n capLevelController: createCapLevelController(this.#capPolicy, config.capLevelController),\n // Likewise layered over the config's own loader hooks: the element's\n // `crossorigin=\"use-credentials\"` sends cookies with every request.\n ...withRequestCredentials(config, () => this.target?.crossOrigin),\n });\n\n setupDrm(this.#engine);\n }\n\n get engine() {\n return this.#engine;\n }\n\n /** Ceiling on automatic rendition selection. See `HlsSource.maxAutoResolution`. */\n get maxAutoResolution(): MediaResolution | undefined {\n return this.#capPolicy.maxAutoResolution;\n }\n\n set maxAutoResolution(value: MediaResolution | undefined) {\n if (this.#capPolicy.maxAutoResolution === value) return;\n\n this.#capPolicy.maxAutoResolution = value;\n this.#capPolicy.controller?.apply();\n }\n\n /** Whether the rendered size caps selection. See `HlsSource.capRenditionToPlayerSize`. */\n get capRenditionToPlayerSize(): boolean {\n return this.#capPolicy.capToPlayerSize;\n }\n\n set capRenditionToPlayerSize(value: boolean | undefined) {\n // Defaults resolve here rather than in the caller, so the getters report the\n // cap that is actually in force instead of what a source happened to name.\n const next = value ?? true;\n if (this.#capPolicy.capToPlayerSize === next) return;\n\n this.#capPolicy.capToPlayerSize = next;\n this.#capPolicy.controller?.apply();\n }\n\n /** Floor on the player-size cap. See `HlsSource.minAutoResolution`. */\n get minAutoResolution(): MediaResolution {\n return this.#capPolicy.minAutoResolution ?? DEFAULT_MIN_AUTO_RESOLUTION;\n }\n\n set minAutoResolution(value: MediaResolution | undefined) {\n const next = value ?? DEFAULT_MIN_AUTO_RESOLUTION;\n if (this.#capPolicy.minAutoResolution === next) return;\n\n this.#capPolicy.minAutoResolution = next;\n this.#capPolicy.controller?.apply();\n }\n\n get src() {\n return this.#engine?.url ?? '';\n }\n\n set src(src: string) {\n // Attaching, detaching, and loading a source each reset every text track on\n // the element, sideloaded ones included. See `withPreservedTextTracks`.\n withPreservedTextTracks(this.target as HTMLVideoElement | null, () => this.#engine?.loadSource(src));\n }\n\n attach(target: HTMLVideoElement) {\n super.attach(target);\n withPreservedTextTracks(target, () => this.#engine?.attachMedia(target));\n }\n\n detach() {\n withPreservedTextTracks(this.target as HTMLVideoElement | null, () => this.#engine?.detachMedia());\n super.detach();\n }\n\n destroy() {\n this.detach();\n this.#engine?.destroy();\n this.#engine = null;\n }\n}\n\ninterface HlsJsMediaCapabilities\n extends MediaStreamTypeCapability, MediaLiveCapability, Pick<MediaSourceCapability, 'preload'> {\n readonly error: MediaError | null;\n}\n\nconst HlsJsOnlyAdapterComposed = HlsJsAirPlayMixin(\n HlsJsPreloadMixin(\n HlsJsLiveMixin(\n HlsJsStreamTypeMixin(\n HlsJsMediaTracksMixin(\n HlsJsChaptersMixin(\n HlsJsMetadataTracksMixin(HlsJsTextTracksMixin(HlsJsErrorsMixin(MediaTracksMixin(HlsJsOnlyAdapterCore))))\n )\n )\n )\n )\n )\n) as unknown as MixinReturn<WithMediaTracks<typeof HlsJsOnlyAdapterCore>, HlsJsMediaCapabilities>;\n\nexport class HlsJsOnlyAdapter extends HlsJsOnlyAdapterComposed {}\n"],"mappings":";;;;;;;;;;;;;;;;AA0BA,MAAM,mBAAuC;CAC3C,kBAAkB;CAClB,0BAA0B;CAC1B,sBAAsB;CAGtB,sBAAsB;CACtB,mBAAmB;CACnB,eAAe;AACjB;AAOA,IAAM,uBAAN,cAAmC,iBAAiE
|
|
1
|
+
{"version":3,"file":"hls-js-only.js","names":[],"sources":["../../src/hls-js-only.ts"],"sourcesContent":["import type {\n EngineAdapter,\n MediaError,\n MediaLiveCapability,\n MediaResolution,\n MediaSourceCapability,\n MediaStreamTypeCapability,\n} from '@videojs/media';\nimport { HTMLVideoAdapter } from '@videojs/media/dom';\nimport { MediaTracksMixin, type WithMediaTracks } from '@videojs/media/media-tracks';\nimport type { MixinReturn } from '@videojs/utils/types';\nimport Hls, { type HlsConfig } from 'hls.js';\n\nimport { HlsJsAirPlayMixin } from './airplay-bridge';\nimport { createCapLevelController, DEFAULT_MIN_AUTO_RESOLUTION, type RenditionCapPolicy } from './cap-level';\nimport { HlsJsChaptersMixin } from './chapters';\nimport { setupDrm } from './drm';\nimport { HlsJsErrorsMixin } from './errors';\nimport { HlsJsLiveMixin } from './live';\nimport { HlsJsMediaTracksMixin } from './media-tracks';\nimport { HlsJsMetadataTracksMixin } from './metadata-tracks';\nimport { HlsJsPreloadMixin } from './preload';\nimport { withRequestCredentials } from './request-credentials';\nimport { HlsJsStreamTypeMixin } from './stream-type';\nimport { HlsJsTextTracksMixin, withPreservedTextTracks } from './text-tracks';\n\nconst defaultHlsConfig: Partial<HlsConfig> = {\n backBufferLength: 30,\n renderTextTracksNatively: false,\n liveDurationInfinity: true,\n // Runs hls.js's capping loop, which every rendition cap is evaluated on, not\n // only the one named after it. `capRenditionToPlayerSize` is the live switch.\n capLevelToPlayerSize: true,\n capLevelOnFPSDrop: true,\n autoStartLoad: false,\n};\n\nexport interface HlsJsOnlyMediaParams {\n /** Options forwarded to the hls.js constructor, merged over {@link defaultHlsConfig}. */\n config: Partial<HlsConfig>;\n}\n\nclass HlsJsOnlyAdapterCore extends HTMLVideoAdapter implements EngineAdapter<Hls, HTMLVideoElement> {\n /** Engine this media plays through, reported to analytics such as Mux Data. */\n static readonly engineName: string = 'hlsjs';\n\n #engine: Hls | null = null;\n #capPolicy: RenditionCapPolicy = {\n maxAutoResolution: undefined,\n capToPlayerSize: true,\n minAutoResolution: DEFAULT_MIN_AUTO_RESOLUTION,\n };\n\n constructor(params: HlsJsOnlyMediaParams) {\n super();\n const config = { ...defaultHlsConfig, ...params.config };\n\n this.#engine = new Hls({\n ...config,\n // Layered over whatever controller the config already names, so a\n // `capLevelController` passed through `source.engine` keeps working.\n capLevelController: createCapLevelController(this.#capPolicy, config.capLevelController),\n // Likewise layered over the config's own loader hooks: the element's\n // `crossorigin=\"use-credentials\"` sends cookies with every request.\n ...withRequestCredentials(config, () => this.target?.crossOrigin),\n });\n\n setupDrm(this.#engine);\n }\n\n get engine() {\n return this.#engine;\n }\n\n /** Ceiling on automatic rendition selection. See `HlsSource.maxAutoResolution`. */\n get maxAutoResolution(): MediaResolution | undefined {\n return this.#capPolicy.maxAutoResolution;\n }\n\n set maxAutoResolution(value: MediaResolution | undefined) {\n if (this.#capPolicy.maxAutoResolution === value) return;\n\n this.#capPolicy.maxAutoResolution = value;\n this.#capPolicy.controller?.apply();\n }\n\n /** Whether the rendered size caps selection. See `HlsSource.capRenditionToPlayerSize`. */\n get capRenditionToPlayerSize(): boolean {\n return this.#capPolicy.capToPlayerSize;\n }\n\n set capRenditionToPlayerSize(value: boolean | undefined) {\n // Defaults resolve here rather than in the caller, so the getters report the\n // cap that is actually in force instead of what a source happened to name.\n const next = value ?? true;\n if (this.#capPolicy.capToPlayerSize === next) return;\n\n this.#capPolicy.capToPlayerSize = next;\n this.#capPolicy.controller?.apply();\n }\n\n /** Floor on the player-size cap. See `HlsSource.minAutoResolution`. */\n get minAutoResolution(): MediaResolution {\n return this.#capPolicy.minAutoResolution ?? DEFAULT_MIN_AUTO_RESOLUTION;\n }\n\n set minAutoResolution(value: MediaResolution | undefined) {\n const next = value ?? DEFAULT_MIN_AUTO_RESOLUTION;\n if (this.#capPolicy.minAutoResolution === next) return;\n\n this.#capPolicy.minAutoResolution = next;\n this.#capPolicy.controller?.apply();\n }\n\n get src() {\n return this.#engine?.url ?? '';\n }\n\n set src(src: string) {\n // Attaching, detaching, and loading a source each reset every text track on\n // the element, sideloaded ones included. See `withPreservedTextTracks`.\n withPreservedTextTracks(this.target as HTMLVideoElement | null, () => this.#engine?.loadSource(src));\n }\n\n attach(target: HTMLVideoElement) {\n super.attach(target);\n withPreservedTextTracks(target, () => this.#engine?.attachMedia(target));\n }\n\n detach() {\n withPreservedTextTracks(this.target as HTMLVideoElement | null, () => this.#engine?.detachMedia());\n super.detach();\n }\n\n destroy() {\n this.detach();\n this.#engine?.destroy();\n this.#engine = null;\n }\n}\n\ninterface HlsJsMediaCapabilities\n extends MediaStreamTypeCapability, MediaLiveCapability, Pick<MediaSourceCapability, 'preload'> {\n readonly error: MediaError | null;\n}\n\nconst HlsJsOnlyAdapterComposed = HlsJsAirPlayMixin(\n HlsJsPreloadMixin(\n HlsJsLiveMixin(\n HlsJsStreamTypeMixin(\n HlsJsMediaTracksMixin(\n HlsJsChaptersMixin(\n HlsJsMetadataTracksMixin(HlsJsTextTracksMixin(HlsJsErrorsMixin(MediaTracksMixin(HlsJsOnlyAdapterCore))))\n )\n )\n )\n )\n )\n) as unknown as MixinReturn<WithMediaTracks<typeof HlsJsOnlyAdapterCore>, HlsJsMediaCapabilities>;\n\nexport class HlsJsOnlyAdapter extends HlsJsOnlyAdapterComposed {}\n"],"mappings":";;;;;;;;;;;;;;;;AA0BA,MAAM,mBAAuC;CAC3C,kBAAkB;CAClB,0BAA0B;CAC1B,sBAAsB;CAGtB,sBAAsB;CACtB,mBAAmB;CACnB,eAAe;AACjB;AAOA,IAAM,uBAAN,cAAmC,iBAAiE;;EAE7D,KAAA,aAAA;;CAErC,UAAsB;CACtB,aAAiC;EAC/B,mBAAmB,KAAA;EACnB,iBAAiB;EACjB,mBAAmB;CACrB;CAEA,YAAY,QAA8B;EACxC,MAAM;EACN,MAAM,SAAS;GAAE,GAAG;GAAkB,GAAG,OAAO;EAAO;EAEvD,KAAK,UAAU,IAAI,IAAI;GACrB,GAAG;GAGH,oBAAoB,yBAAyB,KAAK,YAA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iBAAiB,iBAAiB,oBAAoB,CAAC,CAAC,CAAC,CACzG,CACF,CACF,CACF,CACF,CACF;AAEA,IAAa,mBAAb,cAAsC,yBAAyB,CAAC"}
|
package/dist/dev/media-tracks.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import Hls from "hls.js";
|
|
2
2
|
//#region src/media-tracks.ts
|
|
3
|
-
function
|
|
4
|
-
return `${
|
|
3
|
+
function getRenditionKey(width, height, codec, bitrate) {
|
|
4
|
+
return `${width}x${height}|${codec}|${bitrate}`;
|
|
5
5
|
}
|
|
6
6
|
function getAudioTrackKind(audioTrack) {
|
|
7
7
|
return audioTrack.default ? "main" : "alternative";
|
|
@@ -15,7 +15,6 @@ function getAudioTrackKind(audioTrack) {
|
|
|
15
15
|
*/
|
|
16
16
|
function HlsJsMediaTracksMixin(BaseClass) {
|
|
17
17
|
class HlsJsMediaTracks extends BaseClass {
|
|
18
|
-
#levelIdMap = /* @__PURE__ */ new Map();
|
|
19
18
|
#currentVideoTrack = null;
|
|
20
19
|
constructor(...args) {
|
|
21
20
|
super(...args);
|
|
@@ -33,13 +32,11 @@ function HlsJsMediaTracksMixin(BaseClass) {
|
|
|
33
32
|
}
|
|
34
33
|
#onManifestParsed = (_event, data) => {
|
|
35
34
|
this.#removeAllMediaTracks();
|
|
36
|
-
this.#levelIdMap.clear();
|
|
37
35
|
const videoTrack = this.addVideoTrack("main");
|
|
38
36
|
this.#currentVideoTrack = videoTrack;
|
|
39
37
|
videoTrack.selected = true;
|
|
40
38
|
for (const [id, level] of data.levels.entries()) {
|
|
41
39
|
const rendition = videoTrack.addRendition(level.url[0] ?? "", level.width, level.height, level.videoCodec, level.bitrate);
|
|
42
|
-
this.#levelIdMap.set(getLevelKey(level), `${id}`);
|
|
43
40
|
rendition.id = `${id}`;
|
|
44
41
|
}
|
|
45
42
|
};
|
|
@@ -75,9 +72,22 @@ function HlsJsMediaTracksMixin(BaseClass) {
|
|
|
75
72
|
for (const track of enabledTracks) if (track !== selectedTrack) track.enabled = false;
|
|
76
73
|
};
|
|
77
74
|
#onLevelsUpdated = (_event, data) => {
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
75
|
+
const videoTrack = this.#currentVideoTrack;
|
|
76
|
+
if (!videoTrack) return;
|
|
77
|
+
const renditionsByKey = /* @__PURE__ */ new Map();
|
|
78
|
+
for (const rendition of this.videoRenditions) {
|
|
79
|
+
const key = getRenditionKey(rendition.width, rendition.height, rendition.codec, rendition.bitrate);
|
|
80
|
+
renditionsByKey.set(key, [...renditionsByKey.get(key) ?? [], rendition]);
|
|
81
|
+
}
|
|
82
|
+
const current = /* @__PURE__ */ new Set();
|
|
83
|
+
for (const [index, level] of data.levels.entries()) {
|
|
84
|
+
const key = getRenditionKey(level.width, level.height, level.videoCodec, level.bitrate);
|
|
85
|
+
const rendition = renditionsByKey.get(key)?.shift() ?? videoTrack.addRendition(level.url[0] ?? "", level.width, level.height, level.videoCodec, level.bitrate);
|
|
86
|
+
rendition.id = `${index}`;
|
|
87
|
+
current.add(rendition);
|
|
88
|
+
}
|
|
89
|
+
for (const rendition of [...this.videoRenditions]) if (rendition.id && !current.has(rendition)) videoTrack.removeRendition(rendition);
|
|
90
|
+
this.#switchRendition();
|
|
81
91
|
};
|
|
82
92
|
#onLevelSwitched = (_event, data) => {
|
|
83
93
|
const activeId = `${data.level}`;
|
|
@@ -86,7 +96,8 @@ function HlsJsMediaTracksMixin(BaseClass) {
|
|
|
86
96
|
#switchRendition = () => {
|
|
87
97
|
const { engine } = this;
|
|
88
98
|
if (!engine) return;
|
|
89
|
-
const
|
|
99
|
+
const selected = this.videoRenditions[this.videoRenditions.selectedIndex];
|
|
100
|
+
const level = selected?.id ? Number(selected.id) : this.videoRenditions.selectedIndex;
|
|
90
101
|
if (level !== engine.manualLevel) engine.nextLevel = level;
|
|
91
102
|
};
|
|
92
103
|
#teardown = () => {
|
|
@@ -101,7 +112,6 @@ function HlsJsMediaTracksMixin(BaseClass) {
|
|
|
101
112
|
this.audioTracks.removeEventListener("change", this.#switchAudioTrack);
|
|
102
113
|
this.videoRenditions.removeEventListener("change", this.#switchRendition);
|
|
103
114
|
this.#removeAllMediaTracks();
|
|
104
|
-
this.#levelIdMap.clear();
|
|
105
115
|
this.#currentVideoTrack = null;
|
|
106
116
|
};
|
|
107
117
|
#removeAllMediaTracks() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"media-tracks.js","names":[],"sources":["../../src/media-tracks.ts"],"sourcesContent":["import type {\n MediaAudioTrackCapability,\n MediaVideoRenditionCapability,\n MediaVideoTrackCapability,\n VideoTrackLike,\n} from '@videojs/media';\nimport type { Constructor } from '@videojs/utils/types';\nimport Hls from 'hls.js';\n\nimport type { HlsEngineHost } from './types';\n\ntype MediaTracksHost = HlsEngineHost &\n MediaVideoTrackCapability &\n MediaAudioTrackCapability &\n MediaVideoRenditionCapability;\n\ntype HlsJsMediaTrackLevel = {\n url: string[];\n width?: number | undefined;\n height?: number | undefined;\n videoCodec?: string | undefined;\n bitrate?: number | undefined;\n};\n\ntype HlsJsMediaAudioTrack = {\n id: number;\n default?: boolean | undefined;\n name?: string | undefined;\n lang?: string | undefined;\n};\n\n// hls.js may rebuild its levels array with new object references between\n// events, so key levels by their identifying attributes instead of identity.\nfunction getLevelKey(level: HlsJsMediaTrackLevel): string {\n return `${level.url[0] ?? ''}|${level.width}x${level.height}|${level.videoCodec}|${level.bitrate}`;\n}\n\nfunction getAudioTrackKind(audioTrack: HlsJsMediaAudioTrack): string {\n return audioTrack.default ? 'main' : 'alternative';\n}\n\n/**\n * Mirrors hls.js manifest levels and alternate audio into the media element's `videoRenditions` / `audioTracks` lists,\n * and wires user selection back to `engine.nextLevel` and `engine.audioTrack`.\n *\n * Requires the media-tracks mixin (track-list infrastructure) to be applied earlier in the chain so the host exposes\n * `addVideoTrack`, `videoRenditions`, and friends.\n */\nexport function HlsJsMediaTracksMixin<Base extends Constructor<MediaTracksHost>>(BaseClass: Base) {\n class HlsJsMediaTracks extends (BaseClass as Constructor<MediaTracksHost>) {\n #levelIdMap = new Map<string, string>();\n #currentVideoTrack: VideoTrackLike | null = null;\n\n constructor(...args: any[]) {\n super(...args);\n\n const { engine } = this;\n if (!engine) return;\n\n engine.on(Hls.Events.MANIFEST_PARSED, this.#onManifestParsed);\n engine.on(Hls.Events.AUDIO_TRACKS_UPDATED, this.#onAudioTracksUpdated);\n engine.on(Hls.Events.AUDIO_TRACK_SWITCHING, this.#onAudioTrackSwitch);\n engine.on(Hls.Events.AUDIO_TRACK_SWITCHED, this.#onAudioTrackSwitch);\n engine.on(Hls.Events.LEVELS_UPDATED, this.#onLevelsUpdated);\n engine.on(Hls.Events.LEVEL_SWITCHED, this.#onLevelSwitched);\n engine.once(Hls.Events.DESTROYING, this.#teardown);\n\n this.audioTracks.addEventListener('change', this.#switchAudioTrack);\n this.videoRenditions.addEventListener('change', this.#switchRendition);\n }\n\n #onManifestParsed = (_event: string, data: { levels: HlsJsMediaTrackLevel[] }) => {\n this.#removeAllMediaTracks();\n this.#levelIdMap.clear();\n\n const videoTrack = this.addVideoTrack('main');\n\n this.#currentVideoTrack = videoTrack;\n videoTrack.selected = true;\n\n for (const [id, level] of data.levels.entries()) {\n const rendition = videoTrack.addRendition(\n level.url[0] ?? '',\n level.width,\n level.height,\n level.videoCodec,\n level.bitrate\n );\n\n this.#levelIdMap.set(getLevelKey(level), `${id}`);\n rendition.id = `${id}`;\n }\n };\n\n // hls.js re-emits this whenever the active audio group changes, which a\n // rendition switch can trigger mid-playback. Skip the rebuild when the set\n // is unchanged so the list (and its selection) survives the group switch.\n #onAudioTracksUpdated = (_event: string, data: { audioTracks: HlsJsMediaAudioTrack[] }) => {\n if (this.#audioTracksMatch(data.audioTracks)) return;\n\n this.#removeAudioTracks();\n\n for (const hlsAudioTrack of data.audioTracks) {\n const audioTrack = this.addAudioTrack(getAudioTrackKind(hlsAudioTrack), hlsAudioTrack.name, hlsAudioTrack.lang);\n\n audioTrack.id = `${hlsAudioTrack.id}`;\n }\n };\n\n // `enabled` is owned by the engine's switch events rather than seeded from\n // `.default`, because hls.js already carries a selection across audio groups\n // and re-announces it here.\n #onAudioTrackSwitch = (_event: string, data: { id: number }) => {\n const selectedId = `${data.id}`;\n\n for (const audioTrack of this.audioTracks) {\n audioTrack.enabled = audioTrack.id === selectedId;\n }\n };\n\n // hls.js reindexes track ids per audio group, so compare the identifying\n // attributes rather than relying on object identity or ids alone.\n #audioTracksMatch(hlsAudioTracks: HlsJsMediaAudioTrack[]): boolean {\n const currentTracks = [...this.audioTracks];\n if (currentTracks.length !== hlsAudioTracks.length) return false;\n\n return hlsAudioTracks.every((hlsAudioTrack, index) => {\n const audioTrack = currentTracks[index];\n\n return (\n audioTrack?.id === `${hlsAudioTrack.id}` &&\n audioTrack.kind === getAudioTrackKind(hlsAudioTrack) &&\n audioTrack.label === (hlsAudioTrack.name ?? '') &&\n audioTrack.language === (hlsAudioTrack.lang ?? '')\n );\n });\n }\n\n #switchAudioTrack = () => {\n const { engine } = this;\n if (!engine) return;\n\n // `enabled` is not exclusive like video `selected`, so prefer a newly\n // enabled track over the one that is already playing.\n const enabledTracks = [...this.audioTracks].filter((track) => track.enabled);\n const selectedTrack = enabledTracks.find((track) => Number(track.id) !== engine.audioTrack) ?? enabledTracks[0];\n if (!selectedTrack?.id) return;\n\n const audioTrackId = Number(selectedTrack.id);\n const availableIds = engine.audioTracks.map((track) => track.id);\n\n if (audioTrackId !== engine.audioTrack && availableIds.includes(audioTrackId)) {\n engine.audioTrack = audioTrackId;\n }\n\n // Disable the rest so future change events resolve unambiguously.\n for (const track of enabledTracks) {\n if (track !== selectedTrack) track.enabled = false;\n }\n };\n\n #onLevelsUpdated = (_event: string, data: { levels: HlsJsMediaTrackLevel[] }) => {\n if (!this.#currentVideoTrack) return;\n\n const levelIds = data.levels.map((level) => this.#levelIdMap.get(getLevelKey(level)));\n\n for (const rendition of this.videoRenditions) {\n if (rendition.id && !levelIds.includes(rendition.id)) {\n this.#currentVideoTrack.removeRendition(rendition);\n }\n }\n };\n\n #onLevelSwitched = (_event: string, data: { level: number }) => {\n const activeId = `${data.level}`;\n\n for (const rendition of this.videoRenditions) {\n rendition.active = rendition.id === activeId;\n }\n };\n\n #switchRendition = () => {\n const { engine } = this;\n if (!engine) return;\n\n const level = this.videoRenditions.selectedIndex;\n\n // The `nextLevel` getter reports the next buffered fragment's level, not\n // the requested one, so compare against `manualLevel` (-1 in auto mode).\n if (level !== engine.manualLevel) engine.nextLevel = level;\n };\n\n #teardown = () => {\n const { engine } = this;\n\n engine?.off(Hls.Events.MANIFEST_PARSED, this.#onManifestParsed);\n engine?.off(Hls.Events.AUDIO_TRACKS_UPDATED, this.#onAudioTracksUpdated);\n engine?.off(Hls.Events.AUDIO_TRACK_SWITCHING, this.#onAudioTrackSwitch);\n engine?.off(Hls.Events.AUDIO_TRACK_SWITCHED, this.#onAudioTrackSwitch);\n engine?.off(Hls.Events.LEVELS_UPDATED, this.#onLevelsUpdated);\n engine?.off(Hls.Events.LEVEL_SWITCHED, this.#onLevelSwitched);\n engine?.off(Hls.Events.DESTROYING, this.#teardown);\n\n this.audioTracks.removeEventListener('change', this.#switchAudioTrack);\n this.videoRenditions.removeEventListener('change', this.#switchRendition);\n\n this.#removeAllMediaTracks();\n this.#levelIdMap.clear();\n this.#currentVideoTrack = null;\n };\n\n #removeAllMediaTracks() {\n this.#removeVideoTracks();\n this.#removeAudioTracks();\n }\n\n #removeVideoTracks() {\n for (const videoTrack of this.videoTracks) {\n this.removeVideoTrack(videoTrack);\n }\n }\n\n #removeAudioTracks() {\n for (const audioTrack of this.audioTracks) {\n this.removeAudioTrack(audioTrack);\n }\n }\n }\n\n return HlsJsMediaTracks as unknown as Base;\n}\n"],"mappings":";;AAiCA,SAAS,YAAY,OAAqC;CACxD,OAAO,GAAG,MAAM,IAAI,MAAM,GAAG,GAAG,MAAM,MAAM,GAAG,MAAM,OAAO,GAAG,MAAM,WAAW,GAAG,MAAM;AAC3F;AAEA,SA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pC;CACF;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"media-tracks.js","names":[],"sources":["../../src/media-tracks.ts"],"sourcesContent":["import type {\n MediaAudioTrackCapability,\n MediaVideoRenditionCapability,\n MediaVideoTrackCapability,\n VideoRenditionLike,\n VideoTrackLike,\n} from '@videojs/media';\nimport type { Constructor } from '@videojs/utils/types';\nimport Hls from 'hls.js';\n\nimport type { HlsEngineHost } from './types';\n\ntype MediaTracksHost = HlsEngineHost &\n MediaVideoTrackCapability &\n MediaAudioTrackCapability &\n MediaVideoRenditionCapability;\n\ntype HlsJsMediaTrackLevel = {\n url: string[];\n width?: number | undefined;\n height?: number | undefined;\n videoCodec?: string | undefined;\n bitrate?: number | undefined;\n};\n\ntype HlsJsMediaAudioTrack = {\n id: number;\n default?: boolean | undefined;\n name?: string | undefined;\n lang?: string | undefined;\n};\n\n// hls.js rebuilds its levels array with new object references between events, and a content-steering pathway switch\n// replaces every URL, so a level is matched to its rendition by the encoding attributes both of them carry.\nfunction getRenditionKey(width?: number, height?: number, codec?: string, bitrate?: number): string {\n return `${width}x${height}|${codec}|${bitrate}`;\n}\n\nfunction getAudioTrackKind(audioTrack: HlsJsMediaAudioTrack): string {\n return audioTrack.default ? 'main' : 'alternative';\n}\n\n/**\n * Mirrors hls.js manifest levels and alternate audio into the media element's `videoRenditions` / `audioTracks` lists,\n * and wires user selection back to `engine.nextLevel` and `engine.audioTrack`.\n *\n * Requires the media-tracks mixin (track-list infrastructure) to be applied earlier in the chain so the host exposes\n * `addVideoTrack`, `videoRenditions`, and friends.\n */\nexport function HlsJsMediaTracksMixin<Base extends Constructor<MediaTracksHost>>(BaseClass: Base) {\n class HlsJsMediaTracks extends (BaseClass as Constructor<MediaTracksHost>) {\n #currentVideoTrack: VideoTrackLike | null = null;\n\n constructor(...args: any[]) {\n super(...args);\n\n const { engine } = this;\n if (!engine) return;\n\n engine.on(Hls.Events.MANIFEST_PARSED, this.#onManifestParsed);\n engine.on(Hls.Events.AUDIO_TRACKS_UPDATED, this.#onAudioTracksUpdated);\n engine.on(Hls.Events.AUDIO_TRACK_SWITCHING, this.#onAudioTrackSwitch);\n engine.on(Hls.Events.AUDIO_TRACK_SWITCHED, this.#onAudioTrackSwitch);\n engine.on(Hls.Events.LEVELS_UPDATED, this.#onLevelsUpdated);\n engine.on(Hls.Events.LEVEL_SWITCHED, this.#onLevelSwitched);\n engine.once(Hls.Events.DESTROYING, this.#teardown);\n\n this.audioTracks.addEventListener('change', this.#switchAudioTrack);\n this.videoRenditions.addEventListener('change', this.#switchRendition);\n }\n\n #onManifestParsed = (_event: string, data: { levels: HlsJsMediaTrackLevel[] }) => {\n this.#removeAllMediaTracks();\n\n const videoTrack = this.addVideoTrack('main');\n\n this.#currentVideoTrack = videoTrack;\n videoTrack.selected = true;\n\n for (const [id, level] of data.levels.entries()) {\n const rendition = videoTrack.addRendition(\n level.url[0] ?? '',\n level.width,\n level.height,\n level.videoCodec,\n level.bitrate\n );\n\n rendition.id = `${id}`;\n }\n };\n\n // hls.js re-emits this whenever the active audio group changes, which a\n // rendition switch can trigger mid-playback. Skip the rebuild when the set\n // is unchanged so the list (and its selection) survives the group switch.\n #onAudioTracksUpdated = (_event: string, data: { audioTracks: HlsJsMediaAudioTrack[] }) => {\n if (this.#audioTracksMatch(data.audioTracks)) return;\n\n this.#removeAudioTracks();\n\n for (const hlsAudioTrack of data.audioTracks) {\n const audioTrack = this.addAudioTrack(getAudioTrackKind(hlsAudioTrack), hlsAudioTrack.name, hlsAudioTrack.lang);\n\n audioTrack.id = `${hlsAudioTrack.id}`;\n }\n };\n\n // `enabled` is owned by the engine's switch events rather than seeded from\n // `.default`, because hls.js already carries a selection across audio groups\n // and re-announces it here.\n #onAudioTrackSwitch = (_event: string, data: { id: number }) => {\n const selectedId = `${data.id}`;\n\n for (const audioTrack of this.audioTracks) {\n audioTrack.enabled = audioTrack.id === selectedId;\n }\n };\n\n // hls.js reindexes track ids per audio group, so compare the identifying\n // attributes rather than relying on object identity or ids alone.\n #audioTracksMatch(hlsAudioTracks: HlsJsMediaAudioTrack[]): boolean {\n const currentTracks = [...this.audioTracks];\n if (currentTracks.length !== hlsAudioTracks.length) return false;\n\n return hlsAudioTracks.every((hlsAudioTrack, index) => {\n const audioTrack = currentTracks[index];\n\n return (\n audioTrack?.id === `${hlsAudioTrack.id}` &&\n audioTrack.kind === getAudioTrackKind(hlsAudioTrack) &&\n audioTrack.label === (hlsAudioTrack.name ?? '') &&\n audioTrack.language === (hlsAudioTrack.lang ?? '')\n );\n });\n }\n\n #switchAudioTrack = () => {\n const { engine } = this;\n if (!engine) return;\n\n // `enabled` is not exclusive like video `selected`, so prefer a newly\n // enabled track over the one that is already playing.\n const enabledTracks = [...this.audioTracks].filter((track) => track.enabled);\n const selectedTrack = enabledTracks.find((track) => Number(track.id) !== engine.audioTrack) ?? enabledTracks[0];\n if (!selectedTrack?.id) return;\n\n const audioTrackId = Number(selectedTrack.id);\n const availableIds = engine.audioTracks.map((track) => track.id);\n\n if (audioTrackId !== engine.audioTrack && availableIds.includes(audioTrackId)) {\n engine.audioTrack = audioTrackId;\n }\n\n // Disable the rest so future change events resolve unambiguously.\n for (const track of enabledTracks) {\n if (track !== selectedTrack) track.enabled = false;\n }\n };\n\n // hls.js renumbers its levels whenever the set changes, so the ids seeded at MANIFEST_PARSED go stale the moment\n // it does. Rebuild from the incoming levels so LEVEL_SWITCHED and rendition ids keep speaking one numbering.\n #onLevelsUpdated = (_event: string, data: { levels: HlsJsMediaTrackLevel[] }) => {\n const videoTrack = this.#currentVideoTrack;\n if (!videoTrack) return;\n\n // A queue per key, so levels that share every attribute each claim a rendition of their own.\n const renditionsByKey = new Map<string, VideoRenditionLike[]>();\n\n for (const rendition of this.videoRenditions) {\n const key = getRenditionKey(rendition.width, rendition.height, rendition.codec, rendition.bitrate);\n\n renditionsByKey.set(key, [...(renditionsByKey.get(key) ?? []), rendition]);\n }\n\n const current = new Set<VideoRenditionLike>();\n\n for (const [index, level] of data.levels.entries()) {\n const key = getRenditionKey(level.width, level.height, level.videoCodec, level.bitrate);\n\n // Reusing the rendition carries its `selected` and `active` flags over, including across a pathway switch,\n // where hls.js keeps the level index and so fires no LEVEL_SWITCHED to restore `active`.\n const rendition =\n renditionsByKey.get(key)?.shift() ??\n videoTrack.addRendition(level.url[0] ?? '', level.width, level.height, level.videoCodec, level.bitrate);\n\n rendition.id = `${index}`;\n current.add(rendition);\n }\n\n // Snapshot first: removeRendition mutates the collection being walked.\n for (const rendition of [...this.videoRenditions]) {\n if (rendition.id && !current.has(rendition)) videoTrack.removeRendition(rendition);\n }\n\n // hls.js rewrites its own manualLevelIndex when it drops a level, so the selection is re-asserted against the\n // new numbering. Removing the picked rendition fires no `change`, and this is what returns the engine to auto.\n this.#switchRendition();\n };\n\n #onLevelSwitched = (_event: string, data: { level: number }) => {\n const activeId = `${data.level}`;\n\n for (const rendition of this.videoRenditions) {\n rendition.active = rendition.id === activeId;\n }\n };\n\n #switchRendition = () => {\n const { engine } = this;\n if (!engine) return;\n\n // The id carries the hls.js level index, which only coincides with the list position while the two are in step.\n const selected = this.videoRenditions[this.videoRenditions.selectedIndex];\n const level = selected?.id ? Number(selected.id) : this.videoRenditions.selectedIndex;\n\n // The `nextLevel` getter reports the next buffered fragment's level, not\n // the requested one, so compare against `manualLevel` (-1 in auto mode).\n if (level !== engine.manualLevel) engine.nextLevel = level;\n };\n\n #teardown = () => {\n const { engine } = this;\n\n engine?.off(Hls.Events.MANIFEST_PARSED, this.#onManifestParsed);\n engine?.off(Hls.Events.AUDIO_TRACKS_UPDATED, this.#onAudioTracksUpdated);\n engine?.off(Hls.Events.AUDIO_TRACK_SWITCHING, this.#onAudioTrackSwitch);\n engine?.off(Hls.Events.AUDIO_TRACK_SWITCHED, this.#onAudioTrackSwitch);\n engine?.off(Hls.Events.LEVELS_UPDATED, this.#onLevelsUpdated);\n engine?.off(Hls.Events.LEVEL_SWITCHED, this.#onLevelSwitched);\n engine?.off(Hls.Events.DESTROYING, this.#teardown);\n\n this.audioTracks.removeEventListener('change', this.#switchAudioTrack);\n this.videoRenditions.removeEventListener('change', this.#switchRendition);\n\n this.#removeAllMediaTracks();\n this.#currentVideoTrack = null;\n };\n\n #removeAllMediaTracks() {\n this.#removeVideoTracks();\n this.#removeAudioTracks();\n }\n\n #removeVideoTracks() {\n for (const videoTrack of this.videoTracks) {\n this.removeVideoTrack(videoTrack);\n }\n }\n\n #removeAudioTracks() {\n for (const audioTrack of this.audioTracks) {\n this.removeAudioTrack(audioTrack);\n }\n }\n }\n\n return HlsJsMediaTracks as unknown as Base;\n}\n"],"mappings":";;AAkCA,SAAS,gBAAgB,OAAgB,QAAiB,OAAgB,SAA0B;CAClG,OAAO,GAAG,MAAM,GAAG,OAAO,GAAG,MAAM,GAAG;AACxC;AAEA,SAAS,kBAAkB,YAA0C;CACnE,OAAO,WAAW,UAAU,SAAS;AACvC;;;;;;;;AASA,SAAgB,sBAAiE,WAAiB;CAChG,MAAM,yBAA0B,UAA2C;EACzE,qBAA4C;EAE5C,YAAY,GAAG,MAAa;GAC1B,MAAM,GAAG,IAAI;GAEb,MAAM,EAAE,WAAW;GACnB,IAAI,CAAC,QAAQ;GAEb,OAAO,GAAG,IAAI,OAAO,iBAAiB,KAAK,iBAAiB;GAC5D,OAAO,GAAG,IAAI,OAAO,sBAAsB,KAAK,qBAAqB;GACrE,OAAO,GAAG,IAAI,OAAO,uBAAuB,KAAK,mBAAmB;GACpE,OAAO,GAAG,IAAI,OAAO,sBAAsB,KAAK,mBAAmB;GACnE,OAAO,GAAG,IAAI,OAAO,gBAAgB,KAAK,gBAAgB;GAC1D,OAAO,GAAG,IAAI,OAAO,gBAAgB,KAAK,gBAAgB;GAC1D,OAAO,KAAK,IAAI,OAAO,YAAY,KAAK,SAAS;GAEjD,KAAK,YAAY,iBAAiB,UAAU,KAAK,iBAAiB;GAClE,KAAK,gBAAgB,iBAAiB,UAAU,KAAK,gBAAgB;EACvE;EAEA,qBAAqB,QAAgB,SAA6C;GACh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OAAO;EAExC;EAEA,yBAAyB;GACvB,MAAM,EAAE,WAAW;GACnB,IAAI,CAAC,QAAQ;GAGb,MAAM,WAAW,KAAK,gBAAgB,KAAK,gBAAgB;GAC3D,MAAM,QAAQ,UAAU,KAAK,OAAO,SAAS,EAAE,IAAI,KAAK,gBAAgB;GAIxE,IAAI,UAAU,OAAO,aAAa,OAAO,YAAY;EACvD;EAEA,kBAAkB;GAChB,MAAM,EAAE,WAAW;GAEnB,QAAQ,IAAI,IAAI,OAAO,iBAAiB,KAAK,iBAAiB;GAC9D,QAAQ,IAAI,IAAI,OAAO,sBAAsB,KAAK,qBAAqB;GACvE,QAAQ,IAAI,IAAI,OAAO,uBAAuB,KAAK,mBAAmB;GACtE,QAAQ,IAAI,IAAI,OAAO,sBAAsB,KAAK,mBAAmB;GACrE,QAAQ,IAAI,IAAI,OAAO,gBAAgB,KAAK,gBAAgB;GAC5D,QAAQ,IAAI,IAAI,OAAO,gBAAgB,KAAK,gBAAgB;GAC5D,QAAQ,IAAI,IAAI,OAAO,YAAY,KAAK,SAAS;GAEjD,KAAK,YAAY,oBAAoB,UAAU,KAAK,iBAAiB;GACrE,KAAK,gBAAgB,oBAAoB,UAAU,KAAK,gBAAgB;GAExE,KAAK,sBAAsB;GAC3B,KAAK,qBAAqB;EAC5B;EAEA,wBAAwB;GACtB,KAAK,mBAAmB;GACxB,KAAK,mBAAmB;EAC1B;EAEA,qBAAqB;GACnB,KAAK,MAAM,cAAc,KAAK,aAC5B,KAAK,iBAAiB,UAAU;EAEpC;EAEA,qBAAqB;GACnB,KAAK,MAAM,cAAc,KAAK,aAC5B,KAAK,iBAAiB,UAAU;EAEpC;CACF;CAEA,OAAO;AACT"}
|
package/dist/dev/preload.js
CHANGED
|
@@ -4,10 +4,13 @@ import Hls from "hls.js";
|
|
|
4
4
|
* Manages HLS preload behavior by mapping the media element's `preload` attribute to hls.js `startLoad` / buffer-limit
|
|
5
5
|
* configuration.
|
|
6
6
|
*
|
|
7
|
-
* - `'auto'` or already playing → full buffer limits, immediate start.
|
|
7
|
+
* - `'auto'`, `autoplay`, or already playing → full buffer limits, immediate start.
|
|
8
8
|
* - `'metadata'` → minimal buffer (1 byte / 1 second), limits raised on play.
|
|
9
9
|
* - `'none'` / `''` → no start, deferred load on play.
|
|
10
10
|
*
|
|
11
|
+
* `autoplay` overrides `preload`, as it does for a native `<video>`: the browser only starts it once enough has loaded,
|
|
12
|
+
* so a load deferred until `play` would never begin.
|
|
13
|
+
*
|
|
11
14
|
* Loading is started at most once per source. Widening the limits afterwards is a plain config write, never a second
|
|
12
15
|
* `startLoad()`.
|
|
13
16
|
*/
|
|
@@ -35,6 +38,13 @@ function HlsJsPreloadMixin(BaseClass) {
|
|
|
35
38
|
this.#preload = value;
|
|
36
39
|
this.#init();
|
|
37
40
|
}
|
|
41
|
+
get autoplay() {
|
|
42
|
+
return super.autoplay;
|
|
43
|
+
}
|
|
44
|
+
set autoplay(value) {
|
|
45
|
+
super.autoplay = value;
|
|
46
|
+
this.#init();
|
|
47
|
+
}
|
|
38
48
|
#destroy() {
|
|
39
49
|
this.#preloadAbort?.abort();
|
|
40
50
|
this.#preloadAbort = null;
|
|
@@ -71,7 +81,7 @@ function HlsJsPreloadMixin(BaseClass) {
|
|
|
71
81
|
this.#loadStarted = true;
|
|
72
82
|
engine.startLoad();
|
|
73
83
|
};
|
|
74
|
-
if (this.preload === "auto" || !target.paused) {
|
|
84
|
+
if (this.preload === "auto" || target.autoplay || !target.paused) {
|
|
75
85
|
load();
|
|
76
86
|
return;
|
|
77
87
|
}
|
package/dist/dev/preload.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"preload.js","names":[],"sources":["../../src/preload.ts"],"sourcesContent":["import type { Constructor } from '@videojs/utils/types';\nimport Hls from 'hls.js';\n\nimport type { HlsEngineHost } from './types';\n\nexport type PreloadType = '' | 'none' | 'metadata' | 'auto';\n\n/**\n * Manages HLS preload behavior by mapping the media element's `preload` attribute to hls.js `startLoad` / buffer-limit\n * configuration.\n *\n * - `'auto'` or already playing → full buffer limits, immediate start.\n * - `'metadata'` → minimal buffer (1 byte / 1 second), limits raised on play.\n * - `'none'` / `''` → no start, deferred load on play.\n *\n * Loading is started at most once per source. Widening the limits afterwards is a plain config write, never a second\n * `startLoad()`.\n */\nexport function HlsJsPreloadMixin<Base extends Constructor<HlsEngineHost>>(BaseClass: Base) {\n class HlsJsPreload extends (BaseClass as Constructor<HlsEngineHost>) {\n #preloadAbort: AbortController | null = null;\n #preload: PreloadType = 'metadata';\n #defaultMaxBufferLength: number | undefined;\n #defaultMaxBufferSize: number | undefined;\n #loadStarted = false;\n\n constructor(...args: any[]) {\n super(...args);\n\n this.engine?.on(Hls.Events.MANIFEST_LOADING, () => {\n // `loadSource()` stops loading before announcing the manifest, so the\n // next start for this source has to be a real `startLoad()` again.\n this.#loadStarted = false;\n this.#init();\n });\n this.engine?.on(Hls.Events.MEDIA_ATTACHED, () => this.#init());\n this.engine?.on(Hls.Events.MEDIA_DETACHED, () => this.#destroy());\n this.engine?.on(Hls.Events.DESTROYING, () => this.#destroy());\n }\n\n get preload(): PreloadType {\n return this.#preload;\n }\n\n set preload(value: PreloadType) {\n this.#preload = value;\n this.#init();\n }\n\n #destroy(): void {\n this.#preloadAbort?.abort();\n this.#preloadAbort = null;\n this.#loadStarted = false;\n }\n\n #init(): void {\n this.#preloadAbort?.abort();\n\n const target = this.target as HTMLVideoElement | null;\n if (!target) return;\n\n // Sync stored preload to the native element (may have been set before attach)\n if (target.preload !== this.preload) {\n target.preload = this.preload;\n }\n\n const { engine } = this;\n if (!engine) return;\n\n this.#defaultMaxBufferLength ??= engine.config.maxBufferLength;\n this.#defaultMaxBufferSize ??= engine.config.maxBufferSize;\n\n const defaultLength = this.#defaultMaxBufferLength;\n const defaultSize = this.#defaultMaxBufferSize;\n\n /**\n * Applies buffer limits, and starts loading only if this source has not been started yet.\n *\n * Once loading is under way, writing the limits is enough: hls.js reads both off `config` on every tick and its\n * ticker is already armed. A second `startLoad()` would open with hls.js's own `stopLoad()`, which aborts the\n * in-flight segment — and that abort resets the controller to IDLE a task later, so the next tick re-requests and\n * re-aborts, forever.\n */\n const load = (length?: number, size?: number) => {\n const { engine } = this;\n if (!engine) return;\n\n engine.config.maxBufferLength = length ?? defaultLength;\n engine.config.maxBufferSize = size ?? defaultSize;\n\n if (this.#loadStarted) {\n // No-op unless something paused buffering; ManagedMediaSource does,\n // on `endstreaming`.\n engine.resumeBuffering?.();\n return;\n }\n\n this.#loadStarted = true;\n engine.startLoad();\n };\n\n if (this.preload === 'auto' || !target.paused) {\n load();\n return;\n }\n\n if (this.preload === 'metadata') {\n load(1, 1);\n }\n\n this.#preloadAbort = new AbortController();\n target.addEventListener('play', () => load(), {\n signal: this.#preloadAbort.signal,\n once: true,\n });\n }\n }\n\n return HlsJsPreload as unknown as Base & Constructor<{ preload: PreloadType }>;\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"preload.js","names":[],"sources":["../../src/preload.ts"],"sourcesContent":["import type { Constructor } from '@videojs/utils/types';\nimport Hls from 'hls.js';\n\nimport type { HlsEngineHost } from './types';\n\nexport type PreloadType = '' | 'none' | 'metadata' | 'auto';\n\n/**\n * Manages HLS preload behavior by mapping the media element's `preload` attribute to hls.js `startLoad` / buffer-limit\n * configuration.\n *\n * - `'auto'`, `autoplay`, or already playing → full buffer limits, immediate start.\n * - `'metadata'` → minimal buffer (1 byte / 1 second), limits raised on play.\n * - `'none'` / `''` → no start, deferred load on play.\n *\n * `autoplay` overrides `preload`, as it does for a native `<video>`: the browser only starts it once enough has loaded,\n * so a load deferred until `play` would never begin.\n *\n * Loading is started at most once per source. Widening the limits afterwards is a plain config write, never a second\n * `startLoad()`.\n */\nexport function HlsJsPreloadMixin<Base extends Constructor<HlsEngineHost>>(BaseClass: Base) {\n class HlsJsPreload extends (BaseClass as Constructor<HlsEngineHost>) {\n #preloadAbort: AbortController | null = null;\n #preload: PreloadType = 'metadata';\n #defaultMaxBufferLength: number | undefined;\n #defaultMaxBufferSize: number | undefined;\n #loadStarted = false;\n\n constructor(...args: any[]) {\n super(...args);\n\n this.engine?.on(Hls.Events.MANIFEST_LOADING, () => {\n // `loadSource()` stops loading before announcing the manifest, so the\n // next start for this source has to be a real `startLoad()` again.\n this.#loadStarted = false;\n this.#init();\n });\n this.engine?.on(Hls.Events.MEDIA_ATTACHED, () => this.#init());\n this.engine?.on(Hls.Events.MEDIA_DETACHED, () => this.#destroy());\n this.engine?.on(Hls.Events.DESTROYING, () => this.#destroy());\n }\n\n get preload(): PreloadType {\n return this.#preload;\n }\n\n set preload(value: PreloadType) {\n this.#preload = value;\n this.#init();\n }\n\n override get autoplay(): boolean {\n return super.autoplay;\n }\n\n // Set after the source as often as before it, so turning it on starts a load that `preload` deferred.\n override set autoplay(value: boolean) {\n super.autoplay = value;\n this.#init();\n }\n\n #destroy(): void {\n this.#preloadAbort?.abort();\n this.#preloadAbort = null;\n this.#loadStarted = false;\n }\n\n #init(): void {\n this.#preloadAbort?.abort();\n\n const target = this.target as HTMLVideoElement | null;\n if (!target) return;\n\n // Sync stored preload to the native element (may have been set before attach)\n if (target.preload !== this.preload) {\n target.preload = this.preload;\n }\n\n const { engine } = this;\n if (!engine) return;\n\n this.#defaultMaxBufferLength ??= engine.config.maxBufferLength;\n this.#defaultMaxBufferSize ??= engine.config.maxBufferSize;\n\n const defaultLength = this.#defaultMaxBufferLength;\n const defaultSize = this.#defaultMaxBufferSize;\n\n /**\n * Applies buffer limits, and starts loading only if this source has not been started yet.\n *\n * Once loading is under way, writing the limits is enough: hls.js reads both off `config` on every tick and its\n * ticker is already armed. A second `startLoad()` would open with hls.js's own `stopLoad()`, which aborts the\n * in-flight segment — and that abort resets the controller to IDLE a task later, so the next tick re-requests and\n * re-aborts, forever.\n */\n const load = (length?: number, size?: number) => {\n const { engine } = this;\n if (!engine) return;\n\n engine.config.maxBufferLength = length ?? defaultLength;\n engine.config.maxBufferSize = size ?? defaultSize;\n\n if (this.#loadStarted) {\n // No-op unless something paused buffering; ManagedMediaSource does,\n // on `endstreaming`.\n engine.resumeBuffering?.();\n return;\n }\n\n this.#loadStarted = true;\n engine.startLoad();\n };\n\n if (this.preload === 'auto' || target.autoplay || !target.paused) {\n load();\n return;\n }\n\n if (this.preload === 'metadata') {\n load(1, 1);\n }\n\n this.#preloadAbort = new AbortController();\n target.addEventListener('play', () => load(), {\n signal: this.#preloadAbort.signal,\n once: true,\n });\n }\n }\n\n return HlsJsPreload as unknown as Base & Constructor<{ preload: PreloadType }>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAqBA,SAAgB,kBAA2D,WAAiB;CAC1F,MAAM,qBAAsB,UAAyC;EACnE,gBAAwC;EACxC,WAAwB;EACxB;EACA;EACA,eAAe;EAEf,YAAY,GAAG,MAAa;GAC1B,MAAM,GAAG,IAAI;GAEb,KAAK,QAAQ,GAAG,IAAI,OAAO,wBAAwB;IAGjD,KAAK,eAAe;IACpB,KAAK,MAAM;GACb,CAAC;GACD,KAAK,QAAQ,GAAG,IAAI,OAAO,sBAAsB,KAAK,MAAM,CAAC;GAC7D,KAAK,QAAQ,GAAG,IAAI,OAAO,sBAAsB,KAAK,SAAS,CAAC;GAChE,KAAK,QAAQ,GAAG,IAAI,OAAO,kBAAkB,KAAK,SAAS,CAAC;EAC9D;EAEA,IAAI,UAAuB;GACzB,OAAO,KAAK;EACd;EAEA,IAAI,QAAQ,OAAoB;GAC9B,KAAK,WAAW;GAChB,KAAK,MAAM;EACb;EAEA,IAAa,WAAoB;GAC/B,OAAO,MAAM;EACf;EAGA,IAAa,SAAS,OAAgB;GACpC,MAAM,WAAW;GACjB,KAAK,MAAM;EACb;EAEA,WAAiB;GACf,KAAK,eAAe,MAAM;GAC1B,KAAK,gBAAgB;GACrB,KAAK,eAAe;EACtB;EAEA,QAAc;GACZ,KAAK,eAAe,MAAM;GAE1B,MAAM,SAAS,KAAK;GACpB,IAAI,CAAC,QAAQ;GAGb,IAAI,OAAO,YAAY,KAAK,SAC1B,OAAO,UAAU,KAAK;GAGxB,MAAM,EAAE,WAAW;GACnB,IAAI,CAAC,QAAQ;GAEb,KAAK,4BAA4B,OAAO,OAAO;GAC/C,KAAK,0BAA0B,OAAO,OAAO;GAE7C,MAAM,gBAAgB,KAAK;GAC3B,MAAM,cAAc,KAAK;;;;;;;;;GAUzB,MAAM,QAAQ,QAAiB,SAAkB;IAC/C,MAAM,EAAE,WAAW;IACnB,IAAI,CAAC,QAAQ;IAEb,OAAO,OAAO,kBAAkB,UAAU;IAC1C,OAAO,OAAO,gBAAgB,QAAQ;IAEtC,IAAI,KAAK,cAAc;KAGrB,OAAO,kBAAkB;KACzB;IACF;IAEA,KAAK,eAAe;IACpB,OAAO,UAAU;GACnB;GAEA,IAAI,KAAK,YAAY,UAAU,OAAO,YAAY,CAAC,OAAO,QAAQ;IAChE,KAAK;IACL;GACF;GAEA,IAAI,KAAK,YAAY,YACnB,KAAK,GAAG,CAAC;GAGX,KAAK,gBAAgB,IAAI,gBAAgB;GACzC,OAAO,iBAAiB,cAAc,KAAK,GAAG;IAC5C,QAAQ,KAAK,cAAc;IAC3B,MAAM;GACR,CAAC;EACH;CACF;CAEA,OAAO;AACT"}
|
|
@@ -18,13 +18,13 @@ function isCredentialed(crossOrigin) {
|
|
|
18
18
|
function withRequestCredentials(config, crossOrigin) {
|
|
19
19
|
const { xhrSetup, fetchSetup } = config;
|
|
20
20
|
return {
|
|
21
|
-
async xhrSetup(xhr, url) {
|
|
21
|
+
async xhrSetup(xhr, url, context) {
|
|
22
22
|
if (isCredentialed(crossOrigin())) xhr.withCredentials = true;
|
|
23
|
-
await xhrSetup?.(xhr, url);
|
|
23
|
+
await xhrSetup?.call(this, xhr, url, context);
|
|
24
24
|
},
|
|
25
25
|
fetchSetup(context, initParams) {
|
|
26
26
|
if (isCredentialed(crossOrigin())) initParams.credentials = "include";
|
|
27
|
-
return fetchSetup ? fetchSetup(context, initParams) : new Request(context.url, initParams);
|
|
27
|
+
return fetchSetup ? fetchSetup.call(this, context, initParams) : new Request(context.url, initParams);
|
|
28
28
|
}
|
|
29
29
|
};
|
|
30
30
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request-credentials.js","names":[],"sources":["../../src/request-credentials.ts"],"sourcesContent":["import type { HlsConfig } from 'hls.js';\n\n/** The media element's `crossOrigin`, read at request time — hls.js is built before the element is attached. */\nexport type CrossOriginSource = () => string | null | undefined;\n\n/** Whether the element's CORS-settings attribute asks for cookies on its resource fetches. */\nexport function isCredentialed(crossOrigin: string | null | undefined): boolean {\n return crossOrigin?.toLowerCase() === 'use-credentials';\n}\n\n/**\n * Layer the media element's `crossorigin` onto hls.js's loader hooks so `use-credentials` sends cookies with every\n * manifest, playlist, and segment request, the way the browser does under native playback.\n *\n * Both hooks are covered because hls.js picks one loader per configuration: `xhrSetup` for the default `XhrLoader`\n * (`withCredentials`), `fetchSetup` for `FetchLoader` (`credentials: 'include'`). A hook the config already names runs\n * after ours, on the same request, so a consumer's own setup keeps working and can still override the mode. Anything\n * but `use-credentials` — `anonymous`, an empty value, no attribute — leaves hls.js's default (`same-origin`).\n *\n * The attribute is read per request rather than at construction: the engine exists before the element is attached, and\n * an author can change the attribute afterwards.\n */\nexport function withRequestCredentials(\n config: Partial<HlsConfig>,\n crossOrigin: CrossOriginSource\n): Pick<HlsConfig, 'xhrSetup' | 'fetchSetup'> {\n const { xhrSetup, fetchSetup } = config;\n\n return {\n async xhrSetup(xhr, url) {\n if (isCredentialed(crossOrigin())) xhr.withCredentials = true;\n\n await xhrSetup?.(xhr, url);\n },\n fetchSetup(context, initParams) {\n if (isCredentialed(crossOrigin())) initParams.credentials = 'include';\n\n return fetchSetup ? fetchSetup(context, initParams) : new Request(context.url, initParams);\n },\n };\n}\n"],"mappings":";;AAMA,SAAgB,eAAe,aAAiD;CAC9E,OAAO,aAAa,YAAY,MAAM;AACxC;;;;;;;;;;;;;AAcA,SAAgB,uBACd,QACA,aAC4C;CAC5C,MAAM,EAAE,UAAU,eAAe;CAEjC,OAAO;
|
|
1
|
+
{"version":3,"file":"request-credentials.js","names":[],"sources":["../../src/request-credentials.ts"],"sourcesContent":["import type { HlsConfig } from 'hls.js';\n\n/** The media element's `crossOrigin`, read at request time — hls.js is built before the element is attached. */\nexport type CrossOriginSource = () => string | null | undefined;\n\n/** Whether the element's CORS-settings attribute asks for cookies on its resource fetches. */\nexport function isCredentialed(crossOrigin: string | null | undefined): boolean {\n return crossOrigin?.toLowerCase() === 'use-credentials';\n}\n\n/**\n * Layer the media element's `crossorigin` onto hls.js's loader hooks so `use-credentials` sends cookies with every\n * manifest, playlist, and segment request, the way the browser does under native playback.\n *\n * Both hooks are covered because hls.js picks one loader per configuration: `xhrSetup` for the default `XhrLoader`\n * (`withCredentials`), `fetchSetup` for `FetchLoader` (`credentials: 'include'`). A hook the config already names runs\n * after ours, on the same request, so a consumer's own setup keeps working and can still override the mode. Anything\n * but `use-credentials` — `anonymous`, an empty value, no attribute — leaves hls.js's default (`same-origin`).\n *\n * The attribute is read per request rather than at construction: the engine exists before the element is attached, and\n * an author can change the attribute afterwards.\n */\nexport function withRequestCredentials(\n config: Partial<HlsConfig>,\n crossOrigin: CrossOriginSource\n): Pick<HlsConfig, 'xhrSetup' | 'fetchSetup'> {\n const { xhrSetup, fetchSetup } = config;\n\n return {\n // hls.js calls both hooks with the loader as `this`; pass it on.\n async xhrSetup(xhr, url, context) {\n if (isCredentialed(crossOrigin())) xhr.withCredentials = true;\n\n await xhrSetup?.call(this, xhr, url, context);\n },\n fetchSetup(context, initParams) {\n if (isCredentialed(crossOrigin())) initParams.credentials = 'include';\n\n return fetchSetup ? fetchSetup.call(this, context, initParams) : new Request(context.url, initParams);\n },\n };\n}\n"],"mappings":";;AAMA,SAAgB,eAAe,aAAiD;CAC9E,OAAO,aAAa,YAAY,MAAM;AACxC;;;;;;;;;;;;;AAcA,SAAgB,uBACd,QACA,aAC4C;CAC5C,MAAM,EAAE,UAAU,eAAe;CAEjC,OAAO;EAEL,MAAM,SAAS,KAAK,KAAK,SAAS;GAChC,IAAI,eAAe,YAAY,CAAC,GAAG,IAAI,kBAAkB;GAEzD,MAAM,UAAU,KAAK,MAAM,KAAK,KAAK,OAAO;EAC9C;EACA,WAAW,SAAS,YAAY;GAC9B,IAAI,eAAe,YAAY,CAAC,GAAG,WAAW,cAAc;GAE5D,OAAO,aAAa,WAAW,KAAK,MAAM,SAAS,UAAU,IAAI,IAAI,QAAQ,QAAQ,KAAK,UAAU;EACtG;CACF;AACF"}
|
package/dist/dev/text-tracks.js
CHANGED
|
@@ -3,6 +3,8 @@ import { isCaptionOrSubtitleTrack, listen } from "@videojs/utils/dom";
|
|
|
3
3
|
//#region src/text-tracks.ts
|
|
4
4
|
/** Marks the `<track>` elements created here for hls.js's own text tracks. */
|
|
5
5
|
const HLS_TRACK_ATTR = "data-removeondestroy";
|
|
6
|
+
/** Marks the subset created from hls.js's CEA-608/708 announcements, which are announced one track at a time. */
|
|
7
|
+
const CC_TRACK_ATTR = "data-cc";
|
|
6
8
|
/** `HTMLTrackElement.LOADED` — the element parsed its resource and will not parse it again. */
|
|
7
9
|
const TRACK_LOADED = 2;
|
|
8
10
|
/**
|
|
@@ -99,15 +101,20 @@ function HlsJsTextTracksMixin(BaseClass) {
|
|
|
99
101
|
const { engine } = this;
|
|
100
102
|
if (!engine || !this.target) return;
|
|
101
103
|
const media = this.target;
|
|
104
|
+
const trackIdFor = ({ _id, default: isDefault, subtitleTrack }) => _id ?? (isDefault ? "default" : `subtitles${subtitleTrack?.id}`);
|
|
102
105
|
const onTracksFound = (_event, data) => {
|
|
103
|
-
|
|
106
|
+
const incomingIds = new Set(data.tracks.map(trackIdFor));
|
|
107
|
+
const ccBatch = data.tracks.every((trackObj) => trackObj._id != null);
|
|
108
|
+
for (const trackEl of media.querySelectorAll(`track[${HLS_TRACK_ATTR}]`)) {
|
|
109
|
+
const replaced = incomingIds.has(trackEl.id);
|
|
110
|
+
const ccOwned = trackEl.hasAttribute(CC_TRACK_ATTR);
|
|
111
|
+
if (!replaced && (ccBatch || ccOwned)) continue;
|
|
112
|
+
trackEl.track.mode = "disabled";
|
|
113
|
+
trackEl.remove();
|
|
114
|
+
}
|
|
104
115
|
for (const trackObj of data.tracks) {
|
|
105
116
|
const baseTrackObj = trackObj.subtitleTrack ?? trackObj.closedCaptions;
|
|
106
|
-
|
|
107
|
-
return lang === baseTrackObj?.lang && name === trackObj.label && type.toLowerCase() === trackObj.kind;
|
|
108
|
-
});
|
|
109
|
-
const id = trackObj._id ?? trackObj.default ? "default" : `${trackObj.kind}${idx}`;
|
|
110
|
-
addTextTrack(media, trackObj.kind, trackObj.label, baseTrackObj?.lang, id, trackObj.default);
|
|
117
|
+
addTextTrack(media, trackObj.kind, trackObj.label, baseTrackObj?.lang, trackIdFor(trackObj), trackObj.default, trackObj._id != null);
|
|
111
118
|
}
|
|
112
119
|
};
|
|
113
120
|
const onCuesParsed = (_event, { track, cues }) => {
|
|
@@ -121,12 +128,16 @@ function HlsJsTextTracksMixin(BaseClass) {
|
|
|
121
128
|
});
|
|
122
129
|
if (disabled) textTrack.mode = "disabled";
|
|
123
130
|
};
|
|
131
|
+
let lastShowingTrack;
|
|
124
132
|
const onTextTrackChange = () => {
|
|
125
|
-
if (!engine.subtitleTracks.length) return;
|
|
126
133
|
const showingTrack = Array.from(media.textTracks).find((textTrack) => {
|
|
127
134
|
return textTrack.id && textTrack.mode === "showing" && isCaptionOrSubtitleTrack(textTrack);
|
|
128
135
|
});
|
|
136
|
+
const showingChanged = showingTrack !== lastShowingTrack;
|
|
137
|
+
lastShowingTrack = showingTrack;
|
|
129
138
|
if (!showingTrack) return;
|
|
139
|
+
if (showingChanged && isHlsTextTrack(media, showingTrack)) refreshCues(showingTrack);
|
|
140
|
+
if (!engine.subtitleTracks.length) return;
|
|
130
141
|
const currentHlsTrack = engine.subtitleTracks[engine.subtitleTrack];
|
|
131
142
|
const hlsTrackId = !currentHlsTrack ? void 0 : currentHlsTrack.default ? "default" : `${engine.subtitleTracks[engine.subtitleTrack]?.type.toLowerCase()}${engine.subtitleTrack}`;
|
|
132
143
|
if (engine.subtitleTrack < 0 || showingTrack?.id !== hlsTrackId) {
|
|
@@ -135,11 +146,6 @@ function HlsJsTextTracksMixin(BaseClass) {
|
|
|
135
146
|
});
|
|
136
147
|
engine.subtitleTrack = idx;
|
|
137
148
|
}
|
|
138
|
-
if (showingTrack?.id === hlsTrackId) {
|
|
139
|
-
if (showingTrack.cues) Array.from(showingTrack.cues).forEach((cue) => {
|
|
140
|
-
showingTrack.addCue(cue);
|
|
141
|
-
});
|
|
142
|
-
}
|
|
143
149
|
};
|
|
144
150
|
engine.on(Hls.Events.NON_NATIVE_TEXT_TRACKS_FOUND, onTracksFound);
|
|
145
151
|
engine.on(Hls.Events.CUES_PARSED, onCuesParsed);
|
|
@@ -152,7 +158,25 @@ function HlsJsTextTracksMixin(BaseClass) {
|
|
|
152
158
|
}
|
|
153
159
|
return HlsJsTextTracks;
|
|
154
160
|
}
|
|
155
|
-
function
|
|
161
|
+
function isHlsTextTrack(media, track) {
|
|
162
|
+
const trackEls = media.querySelectorAll(`track[${HLS_TRACK_ATTR}]`);
|
|
163
|
+
return Array.from(trackEls).some((trackEl) => trackEl.track === track);
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Makes the media element render the cues of a track that just became the showing one.
|
|
167
|
+
*
|
|
168
|
+
* The `<track>` elements created here have no `src`, so their load fails. WebKit only hands a re-enabled track's cues
|
|
169
|
+
* back to the media element when its `<track>` loaded, so a track turned off and on again lists its cues but renders
|
|
170
|
+
* none; Chrome has a similar rendering bug. Adding a cue that is already on the track is a no-op in WebKit, so each cue
|
|
171
|
+
* is removed before it is added back.
|
|
172
|
+
*/
|
|
173
|
+
function refreshCues(track) {
|
|
174
|
+
for (const cue of Array.from(track.cues ?? [])) {
|
|
175
|
+
track.removeCue(cue);
|
|
176
|
+
track.addCue(cue);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
function addTextTrack(mediaEl, kind, label, lang, id, defaultTrack, ccOwned) {
|
|
156
180
|
const trackEl = document.createElement("track");
|
|
157
181
|
trackEl.kind = kind;
|
|
158
182
|
trackEl.label = label;
|
|
@@ -161,6 +185,7 @@ function addTextTrack(mediaEl, kind, label, lang, id, defaultTrack) {
|
|
|
161
185
|
if (defaultTrack) trackEl.default = true;
|
|
162
186
|
trackEl.track.mode = isCaptionOrSubtitleTrack({ kind }) ? "disabled" : "hidden";
|
|
163
187
|
trackEl.setAttribute(HLS_TRACK_ATTR, "");
|
|
188
|
+
if (ccOwned) trackEl.setAttribute(CC_TRACK_ATTR, "");
|
|
164
189
|
mediaEl.append(trackEl);
|
|
165
190
|
return trackEl.track;
|
|
166
191
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"text-tracks.js","names":[],"sources":["../../src/text-tracks.ts"],"sourcesContent":["import type { HTMLMediaTargetLike } from '@videojs/media/dom';\nimport { isCaptionOrSubtitleTrack, listen } from '@videojs/utils/dom';\nimport type { Constructor } from '@videojs/utils/types';\nimport type { CuesParsedData, NonNativeTextTracksData } from 'hls.js';\nimport Hls from 'hls.js';\n\nimport type { HlsEngineHost } from './types';\n\n/** Marks the `<track>` elements created here for hls.js's own text tracks. */\nconst HLS_TRACK_ATTR = 'data-removeondestroy';\n\n/** `HTMLTrackElement.LOADED` — the element parsed its resource and will not parse it again. */\nconst TRACK_LOADED = 2;\n\ninterface TextTrackSnapshot {\n track: TextTrack;\n mode: TextTrackMode;\n cues: TextTrackCue[];\n}\n\n/**\n * Runs an hls.js call that attaches, detaches, or loads a source, leaving the `<track>` children hls.js does not own\n * the way it found them.\n *\n * Hls.js resets _every_ text track on the media element at those points: it clears the cues of all of them and disables\n * the ones it takes for subtitles, without checking which tracks it created. Tracks sideloaded from `<track>` elements\n * are collateral damage, and losing their cues is permanent — an element that finished loading is never parsed again,\n * so the track keeps reporting `showing` while rendering nothing. It surfaces whenever a `<track>` outlives a source\n * assignment, most visibly when `src` arrives after the element connected and its default track already loaded.\n *\n * Cues are the objects the browser parsed, so putting back the ones hls.js took restores the track without refetching\n * its resource.\n */\nexport function withPreservedTextTracks(media: HTMLMediaElement | null, action: () => void): void {\n const snapshots = media ? snapshotTextTracks(media) : [];\n\n try {\n action();\n } finally {\n for (const snapshot of snapshots) restoreTextTrack(snapshot);\n }\n}\n\n/** Disables and removes every text track created for the current hls.js source. */\nexport function removeHlsTextTracks(media: HTMLMediaTargetLike | null): void {\n const trackEls = media?.querySelectorAll<HTMLTrackElement>(`track[${HLS_TRACK_ATTR}]`) ?? [];\n\n for (const trackEl of trackEls) {\n trackEl.track.mode = 'disabled';\n trackEl.remove();\n }\n}\n\nfunction snapshotTextTracks(media: HTMLMediaElement): TextTrackSnapshot[] {\n const snapshots: TextTrackSnapshot[] = [];\n\n for (const trackEl of media.querySelectorAll('track')) {\n // Tracks created for hls.js are rebuilt from the manifest on every load.\n if (trackEl.hasAttribute(HLS_TRACK_ATTR)) continue;\n\n const { track } = trackEl;\n // A disabled track stays disabled through anything hls.js does, and only\n // holds cues if it was enabled long enough to load them. Skipping the rest\n // keeps the mode juggling below off the common path.\n if (track.mode === 'disabled' && trackEl.readyState !== TRACK_LOADED) continue;\n\n snapshots.push({\n track,\n mode: track.mode,\n cues: withReadableCues(track, () => Array.from(track.cues ?? [])),\n });\n }\n\n return snapshots;\n}\n\nfunction restoreTextTrack({ track, mode, cues }: TextTrackSnapshot): void {\n if (track.mode !== mode) track.mode = mode;\n\n if (!cues.length) return;\n\n withReadableCues(track, () => {\n const present = new Set<TextTrackCue>(track.cues ?? []);\n\n for (const cue of cues) {\n if (!present.has(cue)) track.addCue(cue);\n }\n });\n}\n\n/** Reads or writes cues through a mode that exposes them, leaving the track's own mode intact. */\nfunction withReadableCues<T>(track: TextTrack, action: () => T): T {\n const { mode } = track;\n\n if (mode === 'disabled') track.mode = 'hidden';\n\n try {\n return action();\n } finally {\n if (mode === 'disabled') track.mode = mode;\n }\n}\n\n/**\n * Bridges hls.js non-native text tracks to native `<track>` elements so the rest of the player can treat them like any\n * other text track.\n *\n * When `renderTextTracksNatively: false`, hls.js fires `NON_NATIVE_TEXT_TRACKS_FOUND` with track metadata and\n * `CUES_PARSED` with VTTCues. This mixin creates `<track>` elements on the media target and forwards cues into them. It\n * also syncs user track-mode changes back to hls.js via `engine.subtitleTrack`.\n */\nexport function HlsJsTextTracksMixin<Base extends Constructor<HlsEngineHost>>(BaseClass: Base) {\n class HlsJsTextTracks extends (BaseClass as Constructor<HlsEngineHost>) {\n #disconnect: AbortController | null = null;\n\n constructor(...args: any[]) {\n super(...args);\n\n // A new manifest invalidates the tracks built from the previous one. Attaching media does not: it rebinds the\n // handlers to the element hls.js drives now, and the tracks of the load in progress have to survive it.\n this.engine?.on(Hls.Events.MANIFEST_LOADING, () => {\n removeHlsTextTracks(this.target);\n this.#init();\n });\n this.engine?.on(Hls.Events.MEDIA_ATTACHED, () => this.#init());\n this.engine?.on(Hls.Events.MEDIA_DETACHED, () => this.#destroy());\n this.engine?.on(Hls.Events.DESTROYING, () => this.#destroy());\n }\n\n #destroy(): void {\n this.#disconnect?.abort();\n this.#disconnect = null;\n removeHlsTextTracks(this.target);\n }\n\n #init(): void {\n this.#disconnect?.abort();\n this.#disconnect = new AbortController();\n\n const { signal } = this.#disconnect;\n const { engine } = this;\n if (!engine || !this.target) return;\n\n // The hls.js delegate always binds to the real `<video>` element.\n const media = this.target as HTMLVideoElement;\n\n const onTracksFound = (_event: string, data: NonNativeTextTracksData) => {\n removeHlsTextTracks(this.target);\n\n for (const trackObj of data.tracks) {\n const baseTrackObj = trackObj.subtitleTrack ?? trackObj.closedCaptions;\n const idx = engine.subtitleTracks.findIndex(({ lang, name, type }) => {\n return lang === baseTrackObj?.lang && name === trackObj.label && type.toLowerCase() === trackObj.kind;\n });\n\n // NOTE: Undocumented method for determining identifier by hls.js. Relied on for\n // ensuring CUES_PARSED events can identify and apply cues to the appropriate track (CJP).\n // See: https://github.com/video-dev/hls.js/blob/master/src/controller/timeline-controller.ts#L640\n const id = (trackObj._id ?? trackObj.default) ? 'default' : `${trackObj.kind}${idx}`;\n\n addTextTrack(media, trackObj.kind as TextTrackKind, trackObj.label, baseTrackObj?.lang, id, trackObj.default);\n }\n };\n\n const onCuesParsed = (_event: string, { track, cues }: CuesParsedData) => {\n const textTrack = media.textTracks.getTrackById(track);\n if (!textTrack) return;\n\n const disabled = textTrack.mode === 'disabled';\n\n if (disabled) {\n textTrack.mode = 'hidden';\n }\n\n cues.forEach((cue: VTTCue) => {\n if (textTrack.cues?.getCueById(cue.id)) return;\n\n textTrack.addCue(cue);\n });\n\n if (disabled) {\n textTrack.mode = 'disabled';\n }\n };\n\n const onTextTrackChange = () => {\n if (!engine.subtitleTracks.length) return;\n\n const showingTrack = Array.from(media.textTracks).find((textTrack) => {\n return textTrack.id && textTrack.mode === 'showing' && isCaptionOrSubtitleTrack(textTrack);\n });\n if (!showingTrack) return;\n\n const currentHlsTrack = engine.subtitleTracks[engine.subtitleTrack];\n\n // If hls.subtitleTrack is -1 or its id changed compared to the one that is showing load the new subtitle track.\n const hlsTrackId = !currentHlsTrack\n ? undefined\n : currentHlsTrack.default\n ? 'default'\n : `${engine.subtitleTracks[engine.subtitleTrack]?.type.toLowerCase()}${engine.subtitleTrack}`;\n\n if (engine.subtitleTrack < 0 || showingTrack?.id !== hlsTrackId) {\n const idx = engine.subtitleTracks.findIndex(({ lang, name, type, default: defaultTrack }) => {\n return (\n (showingTrack.id === 'default' && defaultTrack) ||\n (lang === showingTrack.language &&\n name === showingTrack.label &&\n type.toLowerCase() === showingTrack.kind)\n );\n });\n\n // After the subtitleTrack is set here, hls.js will load the playlist and CUES_PARSED events will be fired below.\n engine.subtitleTrack = idx;\n }\n\n if (showingTrack?.id === hlsTrackId) {\n // Refresh the cues after a texttrack mode change to fix a Chrome bug causing the captions not to render.\n if (showingTrack.cues) {\n Array.from(showingTrack.cues).forEach((cue) => {\n showingTrack.addCue(cue);\n });\n }\n }\n };\n\n engine.on(Hls.Events.NON_NATIVE_TEXT_TRACKS_FOUND, onTracksFound);\n engine.on(Hls.Events.CUES_PARSED, onCuesParsed);\n listen(media.textTracks, 'change', onTextTrackChange, { signal });\n\n signal.addEventListener(\n 'abort',\n () => {\n engine.off(Hls.Events.NON_NATIVE_TEXT_TRACKS_FOUND, onTracksFound);\n engine.off(Hls.Events.CUES_PARSED, onCuesParsed);\n },\n { once: true }\n );\n }\n }\n\n return HlsJsTextTracks as unknown as Base;\n}\n\nfunction addTextTrack(\n mediaEl: HTMLMediaElement,\n kind: TextTrackKind,\n label: string,\n lang?: string,\n id?: string,\n defaultTrack?: boolean\n): TextTrack {\n const trackEl = document.createElement('track');\n\n trackEl.kind = kind;\n trackEl.label = label;\n\n if (lang) {\n // This attribute must be present if the element's kind attribute is in the subtitles state.\n trackEl.srclang = lang;\n }\n\n if (id) {\n trackEl.id = id;\n }\n\n if (defaultTrack) {\n trackEl.default = true;\n }\n\n trackEl.track.mode = isCaptionOrSubtitleTrack({ kind }) ? 'disabled' : 'hidden';\n\n // Add data attribute to identify tracks that should be removed when switching sources/destroying hls.js instance.\n trackEl.setAttribute(HLS_TRACK_ATTR, '');\n mediaEl.append(trackEl);\n\n return trackEl.track as TextTrack;\n}\n"],"mappings":";;;;AASA,MAAM,iBAAiB;;AAGvB,MAAM,eAAe;;;;;;;;;;;;;;AAqBrB,SAAgB,wBAAwB,OAAgC,QAA0B;CAChG,MAAM,YAAY,QAAQ,mBAAmB,KAAK,IAAI,CAAC;CAEvD,IAAI;EACF,OAAO;CACT,UAAU;EACR,KAAK,MAAM,YAAY,WAAW,iBAAiB,QAAQ;CAC7D;AACF;;AAGA,SAAgB,oBAAoB,OAAyC;CAC3E,MAAM,WAAW,OAAO,iBAAmC,SAAS,eAAe,EAAE,KAAK,CAAC;CAE3F,KAAK,MAAM,WAAW,UAAU;EAC9B,QAAQ,MAAM,OAAO;EACrB,QAAQ,OAAO;CACjB;AACF;AAEA,SAAS,mBAAmB,OAA8C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a,gBAAgB,EAAE;CACvC,QAAQ,OAAO,OAAO;CAEtB,OAAO,QAAQ;AACjB"}
|
|
1
|
+
{"version":3,"file":"text-tracks.js","names":[],"sources":["../../src/text-tracks.ts"],"sourcesContent":["import type { HTMLMediaTargetLike } from '@videojs/media/dom';\nimport { isCaptionOrSubtitleTrack, listen } from '@videojs/utils/dom';\nimport type { Constructor } from '@videojs/utils/types';\nimport type { CuesParsedData, NonNativeTextTracksData } from 'hls.js';\nimport Hls from 'hls.js';\n\nimport type { HlsEngineHost } from './types';\n\n/** Marks the `<track>` elements created here for hls.js's own text tracks. */\nconst HLS_TRACK_ATTR = 'data-removeondestroy';\n\n/** Marks the subset created from hls.js's CEA-608/708 announcements, which are announced one track at a time. */\nconst CC_TRACK_ATTR = 'data-cc';\n\n/** `HTMLTrackElement.LOADED` — the element parsed its resource and will not parse it again. */\nconst TRACK_LOADED = 2;\n\ninterface TextTrackSnapshot {\n track: TextTrack;\n mode: TextTrackMode;\n cues: TextTrackCue[];\n}\n\n/**\n * Runs an hls.js call that attaches, detaches, or loads a source, leaving the `<track>` children hls.js does not own\n * the way it found them.\n *\n * Hls.js resets _every_ text track on the media element at those points: it clears the cues of all of them and disables\n * the ones it takes for subtitles, without checking which tracks it created. Tracks sideloaded from `<track>` elements\n * are collateral damage, and losing their cues is permanent — an element that finished loading is never parsed again,\n * so the track keeps reporting `showing` while rendering nothing. It surfaces whenever a `<track>` outlives a source\n * assignment, most visibly when `src` arrives after the element connected and its default track already loaded.\n *\n * Cues are the objects the browser parsed, so putting back the ones hls.js took restores the track without refetching\n * its resource.\n */\nexport function withPreservedTextTracks(media: HTMLMediaElement | null, action: () => void): void {\n const snapshots = media ? snapshotTextTracks(media) : [];\n\n try {\n action();\n } finally {\n for (const snapshot of snapshots) restoreTextTrack(snapshot);\n }\n}\n\n/** Disables and removes every text track created for the current hls.js source. */\nexport function removeHlsTextTracks(media: HTMLMediaTargetLike | null): void {\n const trackEls = media?.querySelectorAll<HTMLTrackElement>(`track[${HLS_TRACK_ATTR}]`) ?? [];\n\n for (const trackEl of trackEls) {\n trackEl.track.mode = 'disabled';\n trackEl.remove();\n }\n}\n\nfunction snapshotTextTracks(media: HTMLMediaElement): TextTrackSnapshot[] {\n const snapshots: TextTrackSnapshot[] = [];\n\n for (const trackEl of media.querySelectorAll('track')) {\n // Tracks created for hls.js are rebuilt from the manifest on every load.\n if (trackEl.hasAttribute(HLS_TRACK_ATTR)) continue;\n\n const { track } = trackEl;\n // A disabled track stays disabled through anything hls.js does, and only\n // holds cues if it was enabled long enough to load them. Skipping the rest\n // keeps the mode juggling below off the common path.\n if (track.mode === 'disabled' && trackEl.readyState !== TRACK_LOADED) continue;\n\n snapshots.push({\n track,\n mode: track.mode,\n cues: withReadableCues(track, () => Array.from(track.cues ?? [])),\n });\n }\n\n return snapshots;\n}\n\nfunction restoreTextTrack({ track, mode, cues }: TextTrackSnapshot): void {\n if (track.mode !== mode) track.mode = mode;\n\n if (!cues.length) return;\n\n withReadableCues(track, () => {\n const present = new Set<TextTrackCue>(track.cues ?? []);\n\n for (const cue of cues) {\n if (!present.has(cue)) track.addCue(cue);\n }\n });\n}\n\n/** Reads or writes cues through a mode that exposes them, leaving the track's own mode intact. */\nfunction withReadableCues<T>(track: TextTrack, action: () => T): T {\n const { mode } = track;\n\n if (mode === 'disabled') track.mode = 'hidden';\n\n try {\n return action();\n } finally {\n if (mode === 'disabled') track.mode = mode;\n }\n}\n\n/**\n * Bridges hls.js non-native text tracks to native `<track>` elements so the rest of the player can treat them like any\n * other text track.\n *\n * When `renderTextTracksNatively: false`, hls.js fires `NON_NATIVE_TEXT_TRACKS_FOUND` with track metadata and\n * `CUES_PARSED` with VTTCues. This mixin creates `<track>` elements on the media target and forwards cues into them. It\n * also syncs user track-mode changes back to hls.js via `engine.subtitleTrack`.\n */\nexport function HlsJsTextTracksMixin<Base extends Constructor<HlsEngineHost>>(BaseClass: Base) {\n class HlsJsTextTracks extends (BaseClass as Constructor<HlsEngineHost>) {\n #disconnect: AbortController | null = null;\n\n constructor(...args: any[]) {\n super(...args);\n\n // A new manifest invalidates the tracks built from the previous one. Attaching media does not: it rebinds the\n // handlers to the element hls.js drives now, and the tracks of the load in progress have to survive it.\n this.engine?.on(Hls.Events.MANIFEST_LOADING, () => {\n removeHlsTextTracks(this.target);\n this.#init();\n });\n this.engine?.on(Hls.Events.MEDIA_ATTACHED, () => this.#init());\n this.engine?.on(Hls.Events.MEDIA_DETACHED, () => this.#destroy());\n this.engine?.on(Hls.Events.DESTROYING, () => this.#destroy());\n }\n\n #destroy(): void {\n this.#disconnect?.abort();\n this.#disconnect = null;\n removeHlsTextTracks(this.target);\n }\n\n #init(): void {\n this.#disconnect?.abort();\n this.#disconnect = new AbortController();\n\n const { signal } = this.#disconnect;\n const { engine } = this;\n if (!engine || !this.target) return;\n\n // The hls.js delegate always binds to the real `<video>` element.\n const media = this.target as HTMLVideoElement;\n\n // NOTE: Undocumented identifiers hls.js addresses CUES_PARSED with: `_id` for CEA-608/708 tracks, and\n // `default` or `subtitles` plus the group-local index it stamps on `subtitleTrack.id` for the subtitle set.\n // See: https://github.com/video-dev/hls.js/blob/master/src/controller/timeline-controller.ts\n const trackIdFor = ({ _id, default: isDefault, subtitleTrack }: NonNativeTextTracksData['tracks'][number]) =>\n _id ?? (isDefault ? 'default' : `subtitles${subtitleTrack?.id}`);\n\n const onTracksFound = (_event: string, data: NonNativeTextTracksData) => {\n // The subtitle set arrives in one batch, and each CC track arrives alone once 608 data shows up in the\n // stream. Replace only what is being re-announced, so a CC announcement does not destroy the subtitle set\n // and a fresh subtitle set does not destroy the CC tracks.\n const incomingIds = new Set(data.tracks.map(trackIdFor));\n const ccBatch = data.tracks.every((trackObj) => trackObj._id != null);\n\n for (const trackEl of media.querySelectorAll<HTMLTrackElement>(`track[${HLS_TRACK_ATTR}]`)) {\n const replaced = incomingIds.has(trackEl.id);\n const ccOwned = trackEl.hasAttribute(CC_TRACK_ATTR);\n if (!replaced && (ccBatch || ccOwned)) continue;\n\n trackEl.track.mode = 'disabled';\n trackEl.remove();\n }\n\n for (const trackObj of data.tracks) {\n const baseTrackObj = trackObj.subtitleTrack ?? trackObj.closedCaptions;\n\n addTextTrack(\n media,\n trackObj.kind as TextTrackKind,\n trackObj.label,\n baseTrackObj?.lang,\n trackIdFor(trackObj),\n trackObj.default,\n trackObj._id != null\n );\n }\n };\n\n const onCuesParsed = (_event: string, { track, cues }: CuesParsedData) => {\n const textTrack = media.textTracks.getTrackById(track);\n if (!textTrack) return;\n\n const disabled = textTrack.mode === 'disabled';\n\n if (disabled) {\n textTrack.mode = 'hidden';\n }\n\n cues.forEach((cue: VTTCue) => {\n if (textTrack.cues?.getCueById(cue.id)) return;\n\n textTrack.addCue(cue);\n });\n\n if (disabled) {\n textTrack.mode = 'disabled';\n }\n };\n\n let lastShowingTrack: TextTrack | undefined;\n\n const onTextTrackChange = () => {\n const showingTrack = Array.from(media.textTracks).find((textTrack) => {\n return textTrack.id && textTrack.mode === 'showing' && isCaptionOrSubtitleTrack(textTrack);\n });\n const showingChanged = showingTrack !== lastShowingTrack;\n\n lastShowingTrack = showingTrack;\n\n if (!showingTrack) return;\n\n // Only on a new showing track: `onCuesParsed` fires `change` for every batch it forwards to a disabled\n // track, and refreshing each time would re-render the active cue several times a second.\n if (showingChanged && isHlsTextTrack(media, showingTrack)) refreshCues(showingTrack);\n\n if (!engine.subtitleTracks.length) return;\n\n const currentHlsTrack = engine.subtitleTracks[engine.subtitleTrack];\n\n // If hls.subtitleTrack is -1 or its id changed compared to the one that is showing load the new subtitle track.\n const hlsTrackId = !currentHlsTrack\n ? undefined\n : currentHlsTrack.default\n ? 'default'\n : `${engine.subtitleTracks[engine.subtitleTrack]?.type.toLowerCase()}${engine.subtitleTrack}`;\n\n if (engine.subtitleTrack < 0 || showingTrack?.id !== hlsTrackId) {\n const idx = engine.subtitleTracks.findIndex(({ lang, name, type, default: defaultTrack }) => {\n return (\n (showingTrack.id === 'default' && defaultTrack) ||\n (lang === showingTrack.language &&\n name === showingTrack.label &&\n type.toLowerCase() === showingTrack.kind)\n );\n });\n\n // After the subtitleTrack is set here, hls.js will load the playlist and CUES_PARSED events will be fired below.\n // A closed-caption track has no entry in `subtitleTracks`, so picking one assigns -1, which only stops\n // subtitle loading: CEA-608 cues come from the video segments.\n engine.subtitleTrack = idx;\n }\n };\n\n engine.on(Hls.Events.NON_NATIVE_TEXT_TRACKS_FOUND, onTracksFound);\n engine.on(Hls.Events.CUES_PARSED, onCuesParsed);\n listen(media.textTracks, 'change', onTextTrackChange, { signal });\n\n signal.addEventListener(\n 'abort',\n () => {\n engine.off(Hls.Events.NON_NATIVE_TEXT_TRACKS_FOUND, onTracksFound);\n engine.off(Hls.Events.CUES_PARSED, onCuesParsed);\n },\n { once: true }\n );\n }\n }\n\n return HlsJsTextTracks as unknown as Base;\n}\n\nfunction isHlsTextTrack(media: HTMLMediaElement, track: TextTrack): boolean {\n const trackEls = media.querySelectorAll<HTMLTrackElement>(`track[${HLS_TRACK_ATTR}]`);\n\n return Array.from(trackEls).some((trackEl) => trackEl.track === track);\n}\n\n/**\n * Makes the media element render the cues of a track that just became the showing one.\n *\n * The `<track>` elements created here have no `src`, so their load fails. WebKit only hands a re-enabled track's cues\n * back to the media element when its `<track>` loaded, so a track turned off and on again lists its cues but renders\n * none; Chrome has a similar rendering bug. Adding a cue that is already on the track is a no-op in WebKit, so each cue\n * is removed before it is added back.\n */\nfunction refreshCues(track: TextTrack): void {\n for (const cue of Array.from(track.cues ?? [])) {\n track.removeCue(cue);\n track.addCue(cue);\n }\n}\n\nfunction addTextTrack(\n mediaEl: HTMLMediaElement,\n kind: TextTrackKind,\n label: string,\n lang?: string,\n id?: string,\n defaultTrack?: boolean,\n ccOwned?: boolean\n): TextTrack {\n const trackEl = document.createElement('track');\n\n trackEl.kind = kind;\n trackEl.label = label;\n\n if (lang) {\n // This attribute must be present if the element's kind attribute is in the subtitles state.\n trackEl.srclang = lang;\n }\n\n if (id) {\n trackEl.id = id;\n }\n\n if (defaultTrack) {\n trackEl.default = true;\n }\n\n trackEl.track.mode = isCaptionOrSubtitleTrack({ kind }) ? 'disabled' : 'hidden';\n\n // Add data attribute to identify tracks that should be removed when switching sources/destroying hls.js instance.\n trackEl.setAttribute(HLS_TRACK_ATTR, '');\n\n if (ccOwned) trackEl.setAttribute(CC_TRACK_ATTR, '');\n\n mediaEl.append(trackEl);\n\n return trackEl.track as TextTrack;\n}\n"],"mappings":";;;;AASA,MAAM,iBAAiB;;AAGvB,MAAM,gBAAgB;;AAGtB,MAAM,eAAe;;;;;;;;;;;;;;AAqBrB,SAAgB,wBAAwB,OAAgC,QAA0B;CAChG,MAAM,YAAY,QAAQ,mBAAmB,KAAK,IAAI,CAAC;CAEvD,IAAI;EACF,OAAO;CACT,UAAU;EACR,KAAK,MAAM,YAAY,WAAW,iBAAiB,QAAQ;CAC7D;AACF;;AAGA,SAAgB,oBAAoB,OAAyC;CAC3E,MAAM,WAAW,OAAO,iBAAmC,SAAS,eAAe,EAAE,KAAK,CAAC;CAE3F,KAAK,MAAM,WAAW,UAAU;EAC9B,QAAQ,MAAM,OAAO;EACrB,QAAQ,OAAO;CACjB;AACF;AAEA,SAAS,mBAAmB,OAA8C;CACxE,MAAM,YAAiC,CAAC;CAExC,KAAK,MAAM,WAAW,MAAM,iBAAiB,OAAO,GAAG;EAErD,IAAI,QAAQ,aAAa,cAAc,GAAG;EAE1C,MAAM,EAAE,UAAU;EAIlB,IAAI,MAAM,SAAS,cAAc,QAAQ,eAAe,cAAc;EAEtE,UAAU,KAAK;GACb;GACA,MAAM,MAAM;GACZ,MAAM,iBAAiB,aAAa,MAAM,KAAK,MAAM,QAAQ,CAAC,CAAC,CAAC;EAClE,CAAC;CACH;CAEA,OAAO;AACT;AAEA,SAAS,iBAAiB,EAAE,OAAO,MAAM,QAAiC;CACxE,IAAI,MAAM,SAAS,MAAM,MAAM,OAAO;CAEtC,IAAI,CAAC,KAAK,QAAQ;CAElB,iBAAiB,aAAa;EAC5B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E,KAAK,CAAC,IAAI,aAAa;CAGvE,QAAQ,aAAa,gBAAgB,EAAE;CAEvC,IAAI,SAAS,QAAQ,aAAa,eAAe,EAAE;CAEnD,QAAQ,OAAO,OAAO;CAEtB,OAAO,QAAQ;AACjB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@videojs/hlsjs-video",
|
|
3
|
-
"version": "10.
|
|
3
|
+
"version": "10.3.0",
|
|
4
4
|
"description": "hls.js playback adapter for Video.js",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"hls",
|
|
@@ -35,11 +35,11 @@
|
|
|
35
35
|
"access": "public"
|
|
36
36
|
},
|
|
37
37
|
"dependencies": {
|
|
38
|
-
"@videojs/media": "10.
|
|
39
|
-
"@videojs/native-hls-video": "10.
|
|
40
|
-
"@videojs/spf": "10.
|
|
41
|
-
"@videojs/utils": "10.
|
|
42
|
-
"hls.js": "1.
|
|
38
|
+
"@videojs/media": "10.3.0",
|
|
39
|
+
"@videojs/native-hls-video": "10.3.0",
|
|
40
|
+
"@videojs/spf": "10.3.0",
|
|
41
|
+
"@videojs/utils": "10.3.0",
|
|
42
|
+
"hls.js": "1.7.3"
|
|
43
43
|
},
|
|
44
44
|
"devDependencies": {
|
|
45
45
|
"jsdom": "^26.1.0",
|