@videojs/hlsjs-video 10.1.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/live.js +6 -17
- 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/live.js +6 -17
- package/dist/dev/live.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 +8 -9
|
@@ -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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BAAiB,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,KAA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O,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,YAAY,O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AiB,iBAAiB,oBAAoB,CAAC,CAAC,CAAC,CACzG,CACF,CACF,CACF,CACF,CACF;AAEA,IAAa,mBAAb,cAAsC,yBAAyB,CAAC"}
|
package/dist/dev/live.js
CHANGED
|
@@ -4,7 +4,6 @@ import Hls from "hls.js";
|
|
|
4
4
|
function HlsJsLiveMixin(BaseClass) {
|
|
5
5
|
class HlsJsLive extends BaseClass {
|
|
6
6
|
#targetLiveWindow = NaN;
|
|
7
|
-
#liveEdgeStartOffset;
|
|
8
7
|
#seekToLiveAbort = null;
|
|
9
8
|
#seekToLivePending = false;
|
|
10
9
|
constructor(...args) {
|
|
@@ -29,22 +28,18 @@ function HlsJsLiveMixin(BaseClass) {
|
|
|
29
28
|
return this.#targetLiveWindow;
|
|
30
29
|
}
|
|
31
30
|
get liveEdgeStart() {
|
|
32
|
-
if (this.#
|
|
31
|
+
if (Number.isNaN(this.#targetLiveWindow)) return NaN;
|
|
33
32
|
const { target } = this;
|
|
34
|
-
if (!target) return NaN;
|
|
35
|
-
|
|
36
|
-
if (!seekable.length) return NaN;
|
|
37
|
-
return seekable.end(seekable.length - 1) - this.#liveEdgeStartOffset;
|
|
33
|
+
if (!target?.seekable.length) return NaN;
|
|
34
|
+
return this.engine?.liveSyncPosition ?? NaN;
|
|
38
35
|
}
|
|
39
36
|
#derive(details) {
|
|
40
37
|
if (!details.live) return this.#reset();
|
|
41
38
|
const info = getStreamInfoFromHlsjsLevelDetails(details);
|
|
42
|
-
this.#liveEdgeStartOffset = info.liveEdgeStartOffset;
|
|
43
39
|
this.#updateConfig(info);
|
|
44
40
|
this.#setTargetLiveWindow(info.targetLiveWindow);
|
|
45
41
|
}
|
|
46
42
|
#reset() {
|
|
47
|
-
this.#liveEdgeStartOffset = void 0;
|
|
48
43
|
this.#setTargetLiveWindow(NaN);
|
|
49
44
|
}
|
|
50
45
|
#updateConfig({ streamType, lowLatency }) {
|
|
@@ -98,16 +93,10 @@ function HlsJsLiveMixin(BaseClass) {
|
|
|
98
93
|
}
|
|
99
94
|
const getStreamInfoFromHlsjsLevelDetails = (levelDetails) => {
|
|
100
95
|
const playlistType = levelDetails.type;
|
|
101
|
-
const streamType = toStreamTypeFromPlaylistType(playlistType);
|
|
102
|
-
const targetLiveWindow = toTargetLiveWindowFromPlaylistType(playlistType);
|
|
103
|
-
const lowLatency = !!levelDetails.partList?.length;
|
|
104
|
-
let liveEdgeStartOffset;
|
|
105
|
-
if (streamType === MediaStreamTypes.LIVE) liveEdgeStartOffset = lowLatency ? levelDetails.partHoldBack || levelDetails.partTarget * 2 : levelDetails.holdBack || levelDetails.targetduration * 3;
|
|
106
96
|
return {
|
|
107
|
-
streamType,
|
|
108
|
-
targetLiveWindow,
|
|
109
|
-
|
|
110
|
-
lowLatency
|
|
97
|
+
streamType: toStreamTypeFromPlaylistType(playlistType),
|
|
98
|
+
targetLiveWindow: toTargetLiveWindowFromPlaylistType(playlistType),
|
|
99
|
+
lowLatency: !!levelDetails.partList?.length
|
|
111
100
|
};
|
|
112
101
|
};
|
|
113
102
|
const toStreamTypeFromPlaylistType = (playlistType) => {
|
package/dist/dev/live.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"live.js","names":[],"sources":["../../src/live.ts"],"sourcesContent":["import { MediaStreamTypes } from '@videojs/media';\nimport type { Constructor } from '@videojs/utils/types';\nimport type { LevelLoadedData } from 'hls.js';\nimport Hls from 'hls.js';\n\nimport type { HlsEngineHost, HlsPlaylistTypes } from './types';\n\nexport function HlsJsLiveMixin<Base extends Constructor<HlsEngineHost>>(BaseClass: Base) {\n class HlsJsLive extends (BaseClass as Constructor<HlsEngineHost>) {\n #targetLiveWindow = Number.NaN;\n #
|
|
1
|
+
{"version":3,"file":"live.js","names":[],"sources":["../../src/live.ts"],"sourcesContent":["import { MediaStreamTypes } from '@videojs/media';\nimport type { Constructor } from '@videojs/utils/types';\nimport type { LevelLoadedData } from 'hls.js';\nimport Hls from 'hls.js';\n\nimport type { HlsEngineHost, HlsPlaylistTypes } from './types';\n\nexport function HlsJsLiveMixin<Base extends Constructor<HlsEngineHost>>(BaseClass: Base) {\n class HlsJsLive extends (BaseClass as Constructor<HlsEngineHost>) {\n #targetLiveWindow = Number.NaN;\n #seekToLiveAbort: AbortController | null = null;\n #seekToLivePending = false;\n\n constructor(...args: any[]) {\n super(...args);\n\n const { engine } = this;\n\n engine?.on(Hls.Events.MANIFEST_LOADING, () => {\n this.#reset();\n this.#armSeekToLive();\n });\n engine?.on(Hls.Events.MEDIA_ATTACHED, () => this.#armSeekToLive());\n engine?.on(Hls.Events.MEDIA_DETACHED, () => this.#disarmSeekToLive());\n engine?.on(Hls.Events.DESTROYING, () => {\n this.#reset();\n this.#disarmSeekToLive();\n });\n engine?.on(Hls.Events.LEVEL_LOADED, (_event: string, data: LevelLoadedData) => {\n this.#derive(data.details);\n\n // For `preload=\"none\"`/`\"metadata\"` the manifest only loads after the\n // first play, so retry the seek once `liveEdgeStart` becomes finite.\n if (this.#seekToLivePending) this.#trySeekToLive();\n });\n }\n\n get targetLiveWindow() {\n return this.#targetLiveWindow;\n }\n\n // Read from hls.js at read time. No cached state, no event. hls.js applies the playlist hold-back, the\n // `liveSyncDuration` / `liveSyncDurationCount` config and `lowLatencyMode`, so this is where hls.js itself plays.\n get liveEdgeStart() {\n if (Number.isNaN(this.#targetLiveWindow)) return Number.NaN;\n\n // Keep `NaN` until the media has a seekable range, so the first-play seek does not run before the media can seek.\n const { target } = this;\n if (!target?.seekable.length) return Number.NaN;\n\n return this.engine?.liveSyncPosition ?? Number.NaN;\n }\n\n #derive(details: LevelLoadedData['details']) {\n if (!details.live) return this.#reset();\n\n const info = getStreamInfoFromHlsjsLevelDetails(details);\n\n this.#updateConfig(info);\n this.#setTargetLiveWindow(info.targetLiveWindow);\n }\n\n #reset() {\n this.#setTargetLiveWindow(Number.NaN);\n }\n\n #updateConfig({ streamType, lowLatency }: StreamInfo) {\n if (streamType === MediaStreamTypes.LIVE) {\n // Update hls.js config for live/ll-live\n const hls = this.engine;\n if (!hls) return;\n\n if (lowLatency) {\n hls.config.backBufferLength = hls.userConfig.backBufferLength ?? 4;\n hls.config.maxFragLookUpTolerance = hls.userConfig.maxFragLookUpTolerance ?? 0.001;\n // For ll-hls, ensure that up switches are weighted the same as down switches to mitigate\n // cases of getting stuck at lower bitrates.\n hls.config.abrBandWidthUpFactor = hls.userConfig.abrBandWidthUpFactor ?? hls.config.abrBandWidthFactor;\n } else {\n hls.config.backBufferLength = hls.userConfig.backBufferLength ?? 8;\n }\n }\n }\n\n #setTargetLiveWindow(value: number) {\n if (Object.is(this.#targetLiveWindow, value)) return;\n\n this.#targetLiveWindow = value;\n this.dispatchEvent(new Event('targetlivewindowchange'));\n }\n\n /**\n * Arm a one-shot seek-to-live on the first user-initiated `play`. Skipped when `autoplay` is set, since hls.js\n * positions at the live edge during its own startup sequence and a programmatic seek would race that.\n */\n #armSeekToLive() {\n this.#disarmSeekToLive();\n\n const target = this.target as HTMLVideoElement | null;\n if (!target || target.autoplay) return;\n\n this.#seekToLiveAbort = new AbortController();\n target.addEventListener(\n 'play',\n () => {\n this.#seekToLivePending = true;\n this.#trySeekToLive();\n },\n { signal: this.#seekToLiveAbort.signal, once: true }\n );\n }\n\n #disarmSeekToLive() {\n this.#seekToLiveAbort?.abort();\n this.#seekToLiveAbort = null;\n this.#seekToLivePending = false;\n }\n\n #trySeekToLive() {\n const target = this.target as HTMLVideoElement | null;\n if (!target) return;\n\n const { liveEdgeStart } = this;\n if (!Number.isFinite(liveEdgeStart)) return;\n\n if (target.currentTime < liveEdgeStart) {\n target.currentTime = liveEdgeStart;\n }\n\n this.#seekToLivePending = false;\n }\n }\n\n return HlsJsLive as unknown as Base &\n Constructor<{ readonly liveEdgeStart: number; readonly targetLiveWindow: number }>;\n}\n\ntype StreamInfo = ReturnType<typeof getStreamInfoFromHlsjsLevelDetails>;\n\nconst getStreamInfoFromHlsjsLevelDetails = (levelDetails: LevelLoadedData['details']) => {\n const playlistType: HlsPlaylistTypes = levelDetails.type as HlsPlaylistTypes;\n const streamType = toStreamTypeFromPlaylistType(playlistType);\n const targetLiveWindow = toTargetLiveWindowFromPlaylistType(playlistType);\n const lowLatency = !!levelDetails.partList?.length;\n\n return {\n streamType,\n targetLiveWindow,\n lowLatency,\n };\n};\n\nconst toStreamTypeFromPlaylistType = (playlistType: HlsPlaylistTypes) => {\n return playlistType === 'VOD' ? MediaStreamTypes.ON_DEMAND : MediaStreamTypes.LIVE;\n};\n\nconst toTargetLiveWindowFromPlaylistType = (playlistType: HlsPlaylistTypes) => {\n if (playlistType === 'EVENT') return Number.POSITIVE_INFINITY;\n\n if (playlistType === 'VOD') return Number.NaN;\n\n return 0;\n};\n"],"mappings":";;;AAOA,SAAgB,eAAwD,WAAiB;CACvF,MAAM,kBAAmB,UAAyC;EAChE,oBAAoB;EACpB,mBAA2C;EAC3C,qBAAqB;EAErB,YAAY,GAAG,MAAa;GAC1B,MAAM,GAAG,IAAI;GAEb,MAAM,EAAE,WAAW;GAEnB,QAAQ,GAAG,IAAI,OAAO,wBAAwB;IAC5C,KAAK,OAAO;IACZ,KAAK,eAAe;GACtB,CAAC;GACD,QAAQ,GAAG,IAAI,OAAO,sBAAsB,KAAK,eAAe,CAAC;GACjE,QAAQ,GAAG,IAAI,OAAO,sBAAsB,KAAK,kBAAkB,CAAC;GACpE,QAAQ,GAAG,IAAI,OAAO,kBAAkB;IACtC,KAAK,OAAO;IACZ,KAAK,kBAAkB;GACzB,CAAC;GACD,QAAQ,GAAG,IAAI,OAAO,eAAe,QAAgB,SAA0B;IAC7E,KAAK,QAAQ,KAAK,OAAO;IAIzB,IAAI,KAAK,oBAAoB,KAAK,eAAe;GACnD,CAAC;EACH;EAEA,IAAI,mBAAmB;GACrB,OAAO,KAAK;EACd;EAIA,IAAI,gBAAgB;GAClB,IAAI,OAAO,MAAM,KAAK,iBAAiB,GAAG,OAAO;GAGjD,MAAM,EAAE,WAAW;GACnB,IAAI,CAAC,QAAQ,SAAS,QAAQ,OAA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AAG;GAErC,IAAI,OAAO,cAAc,eACvB,OAAO,cAAc;GAGvB,KAAK,qBAAqB;EAC5B;CACF;CAEA,OAAO;AAET;AAIA,MAAM,sCAAsC,iBAA6C;CACvF,MAAM,eAAiC,aAAa;CAKpD,OAAO;EACL,YALiB,6BAA6B,YAKrC;EACT,kBALuB,mCAAmC,YAK3C;EACf,YAAA,CALkB,CAAC,aAAa,UAAU;CAM5C;AACF;AAEA,MAAM,gCAAgC,iBAAmC;CACvE,OAAO,iBAAiB,QAAQ,iBAAiB,YAAY,iBAAiB;AAChF;AAEA,MAAM,sCAAsC,iBAAmC;CAC7E,IAAI,iBAAiB,SAAS,OAAO,OAAO;CAE5C,IAAI,iBAAiB,OAAO,OAAO;CAEnC,OAAO;AACT"}
|
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,SAAS,kBAAkB,YAA0C;CACnE,OAAO,WAAW,UAAU,SAAS;AACvC;;;;;;;;AASA,SAAgB,sBAAiE,WAAiB;CAChG,MAAM,yBAA0B,UAA2C;EACzE,8BAAc,IAAI,IAAoB;EACtC,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;GAChF,KAAK,sBAAsB;GAC3B,KAAK,YAAY,MAAM;GAEvB,MAAM,aAAa,KAAK,cAAc,MAAM;GAE5C,KAAK,qBAAqB;GAC1B,W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U,KAAK,iBAAiB;GACrE,KAAK,gBAAgB,oBAAoB,UAAU,KAAK,gBAAgB;GAExE,KAAK,sBAAsB;GAC3B,KAAK,YAAY,MAAM;GACvB,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"}
|
|
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,KA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,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
|
}
|