@videojs/spf 10.0.0-beta.2 → 10.0.0-beta.21

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.
Files changed (264) hide show
  1. package/README.md +16 -40
  2. package/dist/default/core/abr/bandwidth-estimator.js +95 -0
  3. package/dist/default/core/abr/bandwidth-estimator.js.map +1 -0
  4. package/dist/default/core/abr/ewma.js +71 -0
  5. package/dist/default/core/abr/ewma.js.map +1 -0
  6. package/dist/default/core/abr/quality-selection.js +53 -0
  7. package/dist/default/core/abr/quality-selection.js.map +1 -0
  8. package/dist/default/core/buffer/back-buffer.js +46 -0
  9. package/dist/default/core/buffer/back-buffer.js.map +1 -0
  10. package/dist/default/core/buffer/forward-buffer.js +73 -0
  11. package/dist/default/core/buffer/forward-buffer.js.map +1 -0
  12. package/dist/default/core/create-machine-actor.js +91 -0
  13. package/dist/default/core/create-machine-actor.js.map +1 -0
  14. package/dist/default/core/create-machine-reactor.js +83 -0
  15. package/dist/default/core/create-machine-reactor.js.map +1 -0
  16. package/dist/default/core/create-transition-actor.js +46 -0
  17. package/dist/default/core/create-transition-actor.js.map +1 -0
  18. package/dist/default/core/features/calculate-presentation-duration.js +53 -0
  19. package/dist/default/core/features/calculate-presentation-duration.js.map +1 -0
  20. package/dist/default/core/features/quality-switching.js +69 -0
  21. package/dist/default/core/features/quality-switching.js.map +1 -0
  22. package/dist/default/core/features/resolve-presentation.js +73 -0
  23. package/dist/default/core/features/resolve-presentation.js.map +1 -0
  24. package/dist/default/core/features/resolve-track.js +66 -0
  25. package/dist/default/core/features/resolve-track.js.map +1 -0
  26. package/dist/default/core/features/select-tracks.js +130 -0
  27. package/dist/default/core/features/select-tracks.js.map +1 -0
  28. package/dist/default/core/features/sync-preload-attribute.js +26 -0
  29. package/dist/default/core/features/sync-preload-attribute.js.map +1 -0
  30. package/dist/default/core/hls/parse-attributes.js +134 -0
  31. package/dist/default/core/hls/parse-attributes.js.map +1 -0
  32. package/dist/default/core/hls/parse-media-playlist.js +82 -0
  33. package/dist/default/core/hls/parse-media-playlist.js.map +1 -0
  34. package/dist/default/core/hls/parse-multivariant.js +214 -0
  35. package/dist/default/core/hls/parse-multivariant.js.map +1 -0
  36. package/dist/default/core/hls/resolve-url.js +11 -0
  37. package/dist/default/core/hls/resolve-url.js.map +1 -0
  38. package/dist/default/core/machine.js +26 -0
  39. package/dist/default/core/machine.js.map +1 -0
  40. package/dist/default/core/signals/effect.js +41 -0
  41. package/dist/default/core/signals/effect.js.map +1 -0
  42. package/dist/default/core/signals/primitives.js +32 -0
  43. package/dist/default/core/signals/primitives.js.map +1 -0
  44. package/dist/default/core/task.js +191 -0
  45. package/dist/default/core/task.js.map +1 -0
  46. package/dist/default/core/types/index.js +15 -0
  47. package/dist/default/core/types/index.js.map +1 -0
  48. package/dist/default/core/utils/generate-id.js +21 -0
  49. package/dist/default/core/utils/generate-id.js.map +1 -0
  50. package/dist/default/core/utils/track-selection.js +39 -0
  51. package/dist/default/core/utils/track-selection.js.map +1 -0
  52. package/dist/default/dom/features/end-of-stream.js +145 -0
  53. package/dist/default/dom/features/end-of-stream.js.map +1 -0
  54. package/dist/default/dom/features/load-segments.js +192 -0
  55. package/dist/default/dom/features/load-segments.js.map +1 -0
  56. package/dist/default/dom/features/load-text-track-cues.js +104 -0
  57. package/dist/default/dom/features/load-text-track-cues.js.map +1 -0
  58. package/dist/default/dom/features/segment-loader-actor.js +243 -0
  59. package/dist/default/dom/features/segment-loader-actor.js.map +1 -0
  60. package/dist/default/dom/features/setup-mediasource.js +48 -0
  61. package/dist/default/dom/features/setup-mediasource.js.map +1 -0
  62. package/dist/default/dom/features/setup-sourcebuffer.js +78 -0
  63. package/dist/default/dom/features/setup-sourcebuffer.js.map +1 -0
  64. package/dist/default/dom/features/sync-text-tracks.js +95 -0
  65. package/dist/default/dom/features/sync-text-tracks.js.map +1 -0
  66. package/dist/default/dom/features/text-track-segment-loader-actor.js +55 -0
  67. package/dist/default/dom/features/text-track-segment-loader-actor.js.map +1 -0
  68. package/dist/default/dom/features/text-tracks-actor.js +42 -0
  69. package/dist/default/dom/features/text-tracks-actor.js.map +1 -0
  70. package/dist/default/dom/features/track-current-time.js +49 -0
  71. package/dist/default/dom/features/track-current-time.js.map +1 -0
  72. package/dist/default/dom/features/track-playback-initiated.js +66 -0
  73. package/dist/default/dom/features/track-playback-initiated.js.map +1 -0
  74. package/dist/default/dom/features/track-playback-rate.js +32 -0
  75. package/dist/default/dom/features/track-playback-rate.js.map +1 -0
  76. package/dist/default/dom/features/update-duration.js +78 -0
  77. package/dist/default/dom/features/update-duration.js.map +1 -0
  78. package/dist/default/dom/media/append-segment.js +60 -0
  79. package/dist/default/dom/media/append-segment.js.map +1 -0
  80. package/dist/default/dom/media/buffer-flusher.js +55 -0
  81. package/dist/default/dom/media/buffer-flusher.js.map +1 -0
  82. package/dist/default/dom/media/mediasource-setup.js +146 -0
  83. package/dist/default/dom/media/mediasource-setup.js.map +1 -0
  84. package/dist/default/dom/media/source-buffer-actor.js +137 -0
  85. package/dist/default/dom/media/source-buffer-actor.js.map +1 -0
  86. package/dist/default/dom/network/chunked-stream-iterable.js +49 -0
  87. package/dist/default/dom/network/chunked-stream-iterable.js.map +1 -0
  88. package/dist/default/dom/network/fetch.js +54 -0
  89. package/dist/default/dom/network/fetch.js.map +1 -0
  90. package/dist/default/dom/playback-engine/adapter.js +100 -0
  91. package/dist/default/dom/playback-engine/adapter.js.map +1 -0
  92. package/dist/default/dom/playback-engine/engine.js +142 -0
  93. package/dist/default/dom/playback-engine/engine.js.map +1 -0
  94. package/dist/default/dom/playback-engine.js +4 -0
  95. package/dist/default/dom/text/parse-vtt-segment.js +56 -0
  96. package/dist/default/dom/text/parse-vtt-segment.js.map +1 -0
  97. package/dist/default/dom.js +10 -0
  98. package/dist/{src-DRsS_H80.js → default/index.js} +3 -3
  99. package/dist/default/index.js.map +1 -0
  100. package/dist/dev/core/abr/bandwidth-estimator.d.ts +35 -0
  101. package/dist/dev/core/abr/bandwidth-estimator.d.ts.map +1 -0
  102. package/dist/dev/core/abr/bandwidth-estimator.js +95 -0
  103. package/dist/dev/core/abr/bandwidth-estimator.js.map +1 -0
  104. package/dist/dev/core/abr/ewma.js +71 -0
  105. package/dist/dev/core/abr/ewma.js.map +1 -0
  106. package/dist/dev/core/abr/quality-selection.js +53 -0
  107. package/dist/dev/core/abr/quality-selection.js.map +1 -0
  108. package/dist/dev/core/actor.d.ts +27 -0
  109. package/dist/dev/core/actor.d.ts.map +1 -0
  110. package/dist/dev/core/buffer/back-buffer.js +46 -0
  111. package/dist/dev/core/buffer/back-buffer.js.map +1 -0
  112. package/dist/dev/core/buffer/forward-buffer.js +73 -0
  113. package/dist/dev/core/buffer/forward-buffer.js.map +1 -0
  114. package/dist/dev/core/create-machine-actor.d.ts +12 -0
  115. package/dist/dev/core/create-machine-actor.d.ts.map +1 -0
  116. package/dist/dev/core/create-machine-actor.js +91 -0
  117. package/dist/dev/core/create-machine-actor.js.map +1 -0
  118. package/dist/dev/core/create-machine-reactor.d.ts +8 -0
  119. package/dist/dev/core/create-machine-reactor.d.ts.map +1 -0
  120. package/dist/dev/core/create-machine-reactor.js +83 -0
  121. package/dist/dev/core/create-machine-reactor.js.map +1 -0
  122. package/dist/dev/core/create-transition-actor.d.ts +23 -0
  123. package/dist/dev/core/create-transition-actor.d.ts.map +1 -0
  124. package/dist/dev/core/create-transition-actor.js +46 -0
  125. package/dist/dev/core/create-transition-actor.js.map +1 -0
  126. package/dist/dev/core/features/calculate-presentation-duration.js +53 -0
  127. package/dist/dev/core/features/calculate-presentation-duration.js.map +1 -0
  128. package/dist/dev/core/features/quality-switching.js +69 -0
  129. package/dist/dev/core/features/quality-switching.js.map +1 -0
  130. package/dist/dev/core/features/resolve-presentation.js +73 -0
  131. package/dist/dev/core/features/resolve-presentation.js.map +1 -0
  132. package/dist/dev/core/features/resolve-track.js +66 -0
  133. package/dist/dev/core/features/resolve-track.js.map +1 -0
  134. package/dist/dev/core/features/select-tracks.js +130 -0
  135. package/dist/dev/core/features/select-tracks.js.map +1 -0
  136. package/dist/dev/core/features/sync-preload-attribute.js +26 -0
  137. package/dist/dev/core/features/sync-preload-attribute.js.map +1 -0
  138. package/dist/dev/core/hls/parse-attributes.js +134 -0
  139. package/dist/dev/core/hls/parse-attributes.js.map +1 -0
  140. package/dist/dev/core/hls/parse-media-playlist.js +82 -0
  141. package/dist/dev/core/hls/parse-media-playlist.js.map +1 -0
  142. package/dist/dev/core/hls/parse-multivariant.js +214 -0
  143. package/dist/dev/core/hls/parse-multivariant.js.map +1 -0
  144. package/dist/dev/core/hls/resolve-url.js +11 -0
  145. package/dist/dev/core/hls/resolve-url.js.map +1 -0
  146. package/dist/dev/core/machine.d.ts +21 -0
  147. package/dist/dev/core/machine.d.ts.map +1 -0
  148. package/dist/dev/core/machine.js +26 -0
  149. package/dist/dev/core/machine.js.map +1 -0
  150. package/dist/dev/core/signals/effect.d.ts +15 -0
  151. package/dist/dev/core/signals/effect.d.ts.map +1 -0
  152. package/dist/dev/core/signals/effect.js +41 -0
  153. package/dist/dev/core/signals/effect.js.map +1 -0
  154. package/dist/dev/core/signals/primitives.d.ts +10 -0
  155. package/dist/dev/core/signals/primitives.d.ts.map +1 -0
  156. package/dist/dev/core/signals/primitives.js +32 -0
  157. package/dist/dev/core/signals/primitives.js.map +1 -0
  158. package/dist/dev/core/task.js +191 -0
  159. package/dist/dev/core/task.js.map +1 -0
  160. package/dist/dev/core/types/index.d.ts +166 -0
  161. package/dist/dev/core/types/index.d.ts.map +1 -0
  162. package/dist/dev/core/types/index.js +15 -0
  163. package/dist/dev/core/types/index.js.map +1 -0
  164. package/dist/dev/core/utils/generate-id.js +21 -0
  165. package/dist/dev/core/utils/generate-id.js.map +1 -0
  166. package/dist/dev/core/utils/track-selection.d.ts +16 -0
  167. package/dist/dev/core/utils/track-selection.d.ts.map +1 -0
  168. package/dist/dev/core/utils/track-selection.js +39 -0
  169. package/dist/dev/core/utils/track-selection.js.map +1 -0
  170. package/dist/dev/dom/features/end-of-stream.js +145 -0
  171. package/dist/dev/dom/features/end-of-stream.js.map +1 -0
  172. package/dist/dev/dom/features/load-segments.d.ts +72 -0
  173. package/dist/dev/dom/features/load-segments.d.ts.map +1 -0
  174. package/dist/dev/dom/features/load-segments.js +192 -0
  175. package/dist/dev/dom/features/load-segments.js.map +1 -0
  176. package/dist/dev/dom/features/load-text-track-cues.d.ts +85 -0
  177. package/dist/dev/dom/features/load-text-track-cues.d.ts.map +1 -0
  178. package/dist/dev/dom/features/load-text-track-cues.js +104 -0
  179. package/dist/dev/dom/features/load-text-track-cues.js.map +1 -0
  180. package/dist/dev/dom/features/segment-loader-actor.d.ts +1 -0
  181. package/dist/dev/dom/features/segment-loader-actor.js +243 -0
  182. package/dist/dev/dom/features/segment-loader-actor.js.map +1 -0
  183. package/dist/dev/dom/features/setup-mediasource.js +48 -0
  184. package/dist/dev/dom/features/setup-mediasource.js.map +1 -0
  185. package/dist/dev/dom/features/setup-sourcebuffer.d.ts +9 -0
  186. package/dist/dev/dom/features/setup-sourcebuffer.d.ts.map +1 -0
  187. package/dist/dev/dom/features/setup-sourcebuffer.js +78 -0
  188. package/dist/dev/dom/features/setup-sourcebuffer.js.map +1 -0
  189. package/dist/dev/dom/features/sync-text-tracks.js +95 -0
  190. package/dist/dev/dom/features/sync-text-tracks.js.map +1 -0
  191. package/dist/dev/dom/features/text-track-segment-loader-actor.d.ts +12 -0
  192. package/dist/dev/dom/features/text-track-segment-loader-actor.d.ts.map +1 -0
  193. package/dist/dev/dom/features/text-track-segment-loader-actor.js +55 -0
  194. package/dist/dev/dom/features/text-track-segment-loader-actor.js.map +1 -0
  195. package/dist/dev/dom/features/text-tracks-actor.d.ts +31 -0
  196. package/dist/dev/dom/features/text-tracks-actor.d.ts.map +1 -0
  197. package/dist/dev/dom/features/text-tracks-actor.js +42 -0
  198. package/dist/dev/dom/features/text-tracks-actor.js.map +1 -0
  199. package/dist/dev/dom/features/track-current-time.d.ts +40 -0
  200. package/dist/dev/dom/features/track-current-time.d.ts.map +1 -0
  201. package/dist/dev/dom/features/track-current-time.js +49 -0
  202. package/dist/dev/dom/features/track-current-time.js.map +1 -0
  203. package/dist/dev/dom/features/track-playback-initiated.d.ts +46 -0
  204. package/dist/dev/dom/features/track-playback-initiated.d.ts.map +1 -0
  205. package/dist/dev/dom/features/track-playback-initiated.js +66 -0
  206. package/dist/dev/dom/features/track-playback-initiated.js.map +1 -0
  207. package/dist/dev/dom/features/track-playback-rate.d.ts +34 -0
  208. package/dist/dev/dom/features/track-playback-rate.d.ts.map +1 -0
  209. package/dist/dev/dom/features/track-playback-rate.js +32 -0
  210. package/dist/dev/dom/features/track-playback-rate.js.map +1 -0
  211. package/dist/dev/dom/features/update-duration.js +78 -0
  212. package/dist/dev/dom/features/update-duration.js.map +1 -0
  213. package/dist/dev/dom/media/append-segment.d.ts +24 -0
  214. package/dist/dev/dom/media/append-segment.d.ts.map +1 -0
  215. package/dist/dev/dom/media/append-segment.js +60 -0
  216. package/dist/dev/dom/media/append-segment.js.map +1 -0
  217. package/dist/dev/dom/media/buffer-flusher.d.ts +24 -0
  218. package/dist/dev/dom/media/buffer-flusher.d.ts.map +1 -0
  219. package/dist/dev/dom/media/buffer-flusher.js +55 -0
  220. package/dist/dev/dom/media/buffer-flusher.js.map +1 -0
  221. package/dist/dev/dom/media/mediasource-setup.js +146 -0
  222. package/dist/dev/dom/media/mediasource-setup.js.map +1 -0
  223. package/dist/dev/dom/media/source-buffer-actor.d.ts +62 -0
  224. package/dist/dev/dom/media/source-buffer-actor.d.ts.map +1 -0
  225. package/dist/dev/dom/media/source-buffer-actor.js +137 -0
  226. package/dist/dev/dom/media/source-buffer-actor.js.map +1 -0
  227. package/dist/dev/dom/network/chunked-stream-iterable.js +49 -0
  228. package/dist/dev/dom/network/chunked-stream-iterable.js.map +1 -0
  229. package/dist/dev/dom/network/fetch.js +54 -0
  230. package/dist/dev/dom/network/fetch.js.map +1 -0
  231. package/dist/dev/dom/playback-engine/adapter.d.ts +40 -0
  232. package/dist/dev/dom/playback-engine/adapter.d.ts.map +1 -0
  233. package/dist/dev/dom/playback-engine/adapter.js +100 -0
  234. package/dist/dev/dom/playback-engine/adapter.js.map +1 -0
  235. package/dist/dev/dom/playback-engine/engine.d.ts +124 -0
  236. package/dist/dev/dom/playback-engine/engine.d.ts.map +1 -0
  237. package/dist/dev/dom/playback-engine/engine.js +142 -0
  238. package/dist/dev/dom/playback-engine/engine.js.map +1 -0
  239. package/dist/dev/dom/playback-engine.d.ts +4 -0
  240. package/dist/dev/dom/playback-engine.js +4 -0
  241. package/dist/dev/dom/text/parse-vtt-segment.d.ts +12 -0
  242. package/dist/dev/dom/text/parse-vtt-segment.d.ts.map +1 -0
  243. package/dist/dev/dom/text/parse-vtt-segment.js +56 -0
  244. package/dist/dev/dom/text/parse-vtt-segment.js.map +1 -0
  245. package/dist/dev/dom.d.ts +10 -0
  246. package/dist/dev/dom.js +10 -0
  247. package/dist/dev/index.d.ts.map +1 -0
  248. package/dist/dev/index.js +14 -0
  249. package/dist/dev/index.js.map +1 -0
  250. package/package.json +26 -24
  251. package/dist/adapter-CMw-rvbk.js +0 -3512
  252. package/dist/adapter-CMw-rvbk.js.map +0 -1
  253. package/dist/adapter-l8iJN_GI.d.ts +0 -689
  254. package/dist/adapter-l8iJN_GI.d.ts.map +0 -1
  255. package/dist/dom/index.d.ts +0 -243
  256. package/dist/dom/index.d.ts.map +0 -1
  257. package/dist/dom/index.js +0 -38
  258. package/dist/dom/index.js.map +0 -1
  259. package/dist/dom/playback-engine/index.d.ts +0 -2
  260. package/dist/dom/playback-engine/index.js +0 -4
  261. package/dist/index.d.ts.map +0 -1
  262. package/dist/index.js +0 -3
  263. package/dist/src-DRsS_H80.js.map +0 -1
  264. /package/dist/{index.d.ts → dev/index.d.ts} +0 -0
@@ -1,3512 +0,0 @@
1
- import { listen } from "@videojs/utils/dom";
2
- import { isNil, isUndefined } from "@videojs/utils/predicate";
3
-
4
- //#region src/core/state/create-state.ts
5
- /**
6
- * Reactive state container with selectors, custom equality, and batched updates.
7
- *
8
- * Manages both immutable state values and mutable object references (e.g., HTMLMediaElement).
9
- */
10
- const STATE_SYMBOL = Symbol("@videojs/spf/state");
11
- /**
12
- * Default equality function using Object.is.
13
- */
14
- function defaultEquality(a, b) {
15
- return Object.is(a, b);
16
- }
17
- /**
18
- * State container implementation.
19
- */
20
- var StateContainer = class {
21
- [STATE_SYMBOL] = true;
22
- #current;
23
- #pending = null;
24
- #pendingFlush = false;
25
- #equalityFn;
26
- #listeners = /* @__PURE__ */ new Set();
27
- #selectorListeners = /* @__PURE__ */ new Set();
28
- constructor(initial, config) {
29
- this.#current = typeof initial === "object" && initial !== null ? { ...initial } : initial;
30
- this.#equalityFn = config?.equalityFn ?? defaultEquality;
31
- }
32
- get current() {
33
- return this.#pending ?? this.#current;
34
- }
35
- patch(partial) {
36
- const base = this.#pending ?? this.#current;
37
- if (typeof base !== "object" || base === null) {
38
- const value = partial;
39
- if (!Object.is(base, value)) {
40
- this.#pending = value;
41
- this.#scheduleFlush();
42
- }
43
- return;
44
- }
45
- const next = { ...base };
46
- let changed = false;
47
- for (const key in partial) {
48
- if (!Object.hasOwn(partial, key)) continue;
49
- const value = partial[key];
50
- if (!Object.is(base[key], value)) {
51
- next[key] = value;
52
- changed = true;
53
- }
54
- }
55
- if (changed) {
56
- this.#pending = next;
57
- this.#scheduleFlush();
58
- }
59
- }
60
- subscribe(selectorOrListener, maybeListener, options) {
61
- if (maybeListener === void 0) {
62
- const listener$1 = selectorOrListener;
63
- this.#listeners.add(listener$1);
64
- listener$1(this.current);
65
- return () => {
66
- this.#listeners.delete(listener$1);
67
- };
68
- }
69
- const selector = selectorOrListener;
70
- const listener = maybeListener;
71
- const entry = {
72
- selector,
73
- listener,
74
- options: options ?? {}
75
- };
76
- this.#selectorListeners.add(entry);
77
- listener(selector(this.current));
78
- return () => {
79
- this.#selectorListeners.delete(entry);
80
- };
81
- }
82
- flush() {
83
- if (this.#pending === null) return;
84
- const prev = this.#current;
85
- const next = this.#pending;
86
- this.#pending = null;
87
- this.#pendingFlush = false;
88
- if (this.#equalityFn(prev, next)) return;
89
- this.#current = next;
90
- for (const listener of this.#listeners) listener(this.#current);
91
- for (const entry of this.#selectorListeners) {
92
- const prevSelected = entry.selector(prev);
93
- const nextSelected = entry.selector(this.#current);
94
- if (!(entry.options.equalityFn ?? Object.is)(prevSelected, nextSelected)) entry.listener(nextSelected);
95
- }
96
- }
97
- #scheduleFlush() {
98
- if (this.#pendingFlush) return;
99
- this.#pendingFlush = true;
100
- queueMicrotask(() => this.flush());
101
- }
102
- };
103
- /**
104
- * Create a reactive state container.
105
- *
106
- * @example
107
- * ```typescript
108
- * const state = createState({ count: 0 });
109
- *
110
- * // Subscribe to changes
111
- * state.subscribe((current, prev) => {
112
- * console.log('Changed:', prev, '->', current);
113
- * });
114
- *
115
- * // Updates are batched
116
- * state.patch({ count: 1 });
117
- * state.patch({ count: 2 });
118
- * // Only one notification fires (with count: 2)
119
- * ```
120
- *
121
- * @example Selector subscriptions
122
- * ```typescript
123
- * const state = createState({ count: 0, name: 'test' });
124
- *
125
- * // Only notified when count changes
126
- * state.subscribe(
127
- * s => s.count,
128
- * (current, prev) => console.log(current, prev)
129
- * );
130
- * ```
131
- *
132
- * @example Custom equality
133
- * ```typescript
134
- * const state = createState(
135
- * { count: 0, name: 'test' },
136
- * { equalityFn: (a, b) => a.count === b.count }
137
- * );
138
- * ```
139
- */
140
- function createState(initial, config) {
141
- return new StateContainer(initial, config);
142
- }
143
-
144
- //#endregion
145
- //#region src/core/hls/parse-attributes.ts
146
- /**
147
- * Parse HLS attribute list from a tag line.
148
- * Handles both quoted and unquoted values.
149
- */
150
- function parseAttributeList(line) {
151
- const attributes = /* @__PURE__ */ new Map();
152
- for (const match of line.matchAll(/([A-Z0-9-]+)=(?:"([^"]*)"|([^,]*))/g)) {
153
- const key = match[1];
154
- const value = match[2] ?? match[3] ?? "";
155
- if (key) attributes.set(key, value);
156
- }
157
- return attributes;
158
- }
159
- /**
160
- * Parse RESOLUTION attribute value (WIDTHxHEIGHT).
161
- */
162
- function parseResolution(value) {
163
- const match = /^(\d+)x(\d+)$/.exec(value);
164
- if (!match) return null;
165
- return {
166
- width: Number.parseInt(match[1], 10),
167
- height: Number.parseInt(match[2], 10)
168
- };
169
- }
170
- /**
171
- * Parse FRAME-RATE attribute to rational frame rate.
172
- */
173
- function parseFrameRate(value) {
174
- const fps = Number.parseFloat(value);
175
- if (Number.isNaN(fps) || fps <= 0) return void 0;
176
- if (Math.abs(fps - 23.976) < .01) return {
177
- frameRateNumerator: 24e3,
178
- frameRateDenominator: 1001
179
- };
180
- if (Math.abs(fps - 29.97) < .01) return {
181
- frameRateNumerator: 3e4,
182
- frameRateDenominator: 1001
183
- };
184
- if (Math.abs(fps - 59.94) < .01) return {
185
- frameRateNumerator: 6e4,
186
- frameRateDenominator: 1001
187
- };
188
- if (fps % 1 === 0) return { frameRateNumerator: Math.round(fps) };
189
- return { frameRateNumerator: Math.round(fps) };
190
- }
191
- /**
192
- * Parse CODECS attribute into separate video and audio codecs.
193
- */
194
- function parseCodecs(codecs) {
195
- const parts = codecs.split(",").map((s) => s.trim());
196
- const result = {};
197
- for (const codec of parts) if (codec.startsWith("avc1.") || codec.startsWith("hvc1.") || codec.startsWith("hev1.")) result.video = codec;
198
- else if (codec.startsWith("mp4a.")) result.audio = codec;
199
- return result;
200
- }
201
- /**
202
- * Parse #EXTINF duration value.
203
- */
204
- function parseExtInfDuration(value) {
205
- const durationPart = value.split(",")[0] ?? value;
206
- const duration = Number.parseFloat(durationPart);
207
- return Number.isNaN(duration) ? 0 : duration;
208
- }
209
- /**
210
- * Parse BYTERANGE attribute value.
211
- * Format: "length[@offset]"
212
- * If offset is omitted, it continues from the previous byte range end.
213
- */
214
- function parseByteRange(value, previousEnd) {
215
- const match = /^(\d+)(?:@(\d+))?$/.exec(value);
216
- if (!match) return null;
217
- const length = Number.parseInt(match[1], 10);
218
- if (Number.isNaN(length)) return null;
219
- let start;
220
- if (match[2] !== void 0) {
221
- start = Number.parseInt(match[2], 10);
222
- if (Number.isNaN(start)) return null;
223
- } else if (previousEnd !== void 0) start = previousEnd;
224
- else return null;
225
- return {
226
- start,
227
- end: start + length - 1
228
- };
229
- }
230
- /**
231
- * Create AttributeList from raw attribute string.
232
- */
233
- function createAttributeList(line) {
234
- const map = parseAttributeList(line);
235
- return {
236
- get(key) {
237
- return map.get(key);
238
- },
239
- getInt(key, defaultValue) {
240
- const value = map.get(key);
241
- if (value === void 0) return defaultValue;
242
- const parsed = Number.parseInt(value, 10);
243
- return Number.isNaN(parsed) ? defaultValue : parsed;
244
- },
245
- getFloat(key, defaultValue) {
246
- const value = map.get(key);
247
- if (value === void 0) return defaultValue;
248
- const parsed = Number.parseFloat(value);
249
- return Number.isNaN(parsed) ? defaultValue : parsed;
250
- },
251
- getBool(key) {
252
- return map.get(key) === "YES";
253
- },
254
- getResolution(key) {
255
- const value = map.get(key);
256
- if (!value) return void 0;
257
- return parseResolution(value) ?? void 0;
258
- },
259
- getFrameRate(key) {
260
- const value = map.get(key);
261
- if (!value) return void 0;
262
- return parseFrameRate(value);
263
- }
264
- };
265
- }
266
- /**
267
- * Match a tag and extract its attributes.
268
- * Returns null if the line doesn't match the tag.
269
- */
270
- function matchTag(line, tag) {
271
- const prefix = `#${tag}:`;
272
- if (!line.startsWith(prefix)) return null;
273
- return createAttributeList(line.slice(prefix.length));
274
- }
275
-
276
- //#endregion
277
- //#region src/core/hls/resolve-url.ts
278
- /**
279
- * Resolve a potentially relative URL against a base URL using native URL API.
280
- */
281
- function resolveUrl(url, baseUrl) {
282
- return new URL(url, baseUrl).href;
283
- }
284
-
285
- //#endregion
286
- //#region src/core/hls/parse-media-playlist.ts
287
- /**
288
- * Parse HLS media playlist and resolve track with segments.
289
- *
290
- * Takes an unresolved track (from multivariant playlist) and media playlist text,
291
- * returns a HAM-compliant resolved track with segments.
292
- *
293
- * @param text - Media playlist text content
294
- * @param unresolved - Unresolved track from parseMultivariantPlaylist
295
- * @returns Resolved track with segments (type inferred from input)
296
- */
297
- function parseMediaPlaylist(text, unresolved) {
298
- const lines = text.split(/\r?\n/);
299
- const baseUrl = unresolved.url;
300
- const segments = [];
301
- let initSegmentUrl;
302
- let initSegmentByteRange;
303
- let currentDuration = 0;
304
- let currentByteRange;
305
- let currentTime = 0;
306
- let segmentIndex = 0;
307
- let previousByteRangeEnd;
308
- for (const line of lines) {
309
- const trimmed = line.trim();
310
- if (!trimmed || trimmed.startsWith("#") && !trimmed.startsWith("#EXT")) continue;
311
- if (trimmed === "#EXTM3U" || trimmed.startsWith("#EXT-X-VERSION:") || trimmed.startsWith("#EXT-X-TARGETDURATION:") || trimmed.startsWith("#EXT-X-PLAYLIST-TYPE:") || trimmed.startsWith("#EXT-X-INDEPENDENT-SEGMENTS")) continue;
312
- const mapAttrs = matchTag(trimmed, "EXT-X-MAP");
313
- if (mapAttrs) {
314
- const uri = mapAttrs.get("URI");
315
- if (uri) {
316
- initSegmentUrl = resolveUrl(uri, baseUrl);
317
- const byteRangeStr = mapAttrs.get("BYTERANGE");
318
- if (byteRangeStr) initSegmentByteRange = parseByteRange(byteRangeStr, 0) ?? void 0;
319
- }
320
- continue;
321
- }
322
- if (trimmed.startsWith("#EXTINF:")) {
323
- currentDuration = parseExtInfDuration(trimmed.slice(8));
324
- continue;
325
- }
326
- if (trimmed.startsWith("#EXT-X-BYTERANGE:")) {
327
- currentByteRange = parseByteRange(trimmed.slice(17), previousByteRangeEnd) ?? void 0;
328
- continue;
329
- }
330
- if (trimmed === "#EXT-X-ENDLIST") continue;
331
- if (!trimmed.startsWith("#") && currentDuration > 0) {
332
- const segment = {
333
- id: `segment-${segmentIndex}`,
334
- url: resolveUrl(trimmed, baseUrl),
335
- duration: currentDuration,
336
- startTime: currentTime
337
- };
338
- if (currentByteRange) {
339
- segment.byteRange = currentByteRange;
340
- previousByteRangeEnd = currentByteRange.end + 1;
341
- } else previousByteRangeEnd = void 0;
342
- segments.push(segment);
343
- currentTime += currentDuration;
344
- segmentIndex++;
345
- currentDuration = 0;
346
- currentByteRange = void 0;
347
- }
348
- }
349
- const totalDuration = currentTime;
350
- const initialization = unresolved.type === "text" && !initSegmentUrl ? void 0 : initSegmentUrl ? {
351
- url: initSegmentUrl,
352
- ...initSegmentByteRange ? { byteRange: initSegmentByteRange } : {}
353
- } : { url: "" };
354
- return {
355
- ...unresolved,
356
- startTime: 0,
357
- duration: totalDuration,
358
- segments,
359
- initialization
360
- };
361
- }
362
-
363
- //#endregion
364
- //#region src/core/utils/generate-id.ts
365
- /**
366
- * Generate unique ID for HAM objects.
367
- *
368
- * Uses timestamp + random number for sufficient uniqueness.
369
- * IDs are strings without decimals.
370
- *
371
- * @returns Unique string ID in format: timestamp-random
372
- *
373
- * @example
374
- * ```ts
375
- * const id = generateId(); // "1738423156789-542891"
376
- * ```
377
- */
378
- function generateId() {
379
- return `${Date.now()}-${Math.floor(Math.random() * 1e6)}`;
380
- }
381
-
382
- //#endregion
383
- //#region src/core/hls/parse-multivariant.ts
384
- /**
385
- * Parse HLS multivariant playlist into a Presentation.
386
- *
387
- * Returns Presentation with partially resolved tracks (no segment information).
388
- * Tracks contain metadata from multivariant playlist (bandwidth, resolution, codecs)
389
- * but segment information is added when media playlists are fetched.
390
- *
391
- * @param text - Raw playlist text content
392
- * @param unresolved - Unresolved presentation (contains URL for base URL resolution)
393
- * @returns Presentation with partially resolved tracks (duration is undefined)
394
- */
395
- function parseMultivariantPlaylist(text, unresolved) {
396
- const baseUrl = unresolved.url;
397
- const lines = text.split(/\r?\n/);
398
- const streams = [];
399
- const audioRenditions = [];
400
- const subtitleRenditions = [];
401
- let pendingStreamInfo = null;
402
- for (const line of lines) {
403
- const trimmed = line.trim();
404
- if (!trimmed || trimmed.startsWith("#") && !trimmed.startsWith("#EXT")) continue;
405
- if (trimmed === "#EXTM3U" || trimmed.startsWith("#EXT-X-VERSION:") || trimmed.startsWith("#EXT-X-INDEPENDENT-SEGMENTS")) continue;
406
- const mediaAttrs = matchTag(trimmed, "EXT-X-MEDIA");
407
- if (mediaAttrs) {
408
- const type = mediaAttrs.get("TYPE");
409
- const groupId = mediaAttrs.get("GROUP-ID");
410
- const name = mediaAttrs.get("NAME");
411
- if (type === "AUDIO" && groupId && name) {
412
- const uri = mediaAttrs.get("URI");
413
- audioRenditions.push({
414
- groupId,
415
- name,
416
- language: mediaAttrs.get("LANGUAGE"),
417
- uri: uri ? resolveUrl(uri, baseUrl) : void 0,
418
- default: mediaAttrs.getBool("DEFAULT"),
419
- autoselect: mediaAttrs.getBool("AUTOSELECT")
420
- });
421
- }
422
- if (type === "SUBTITLES" && groupId && name) {
423
- const uri = mediaAttrs.get("URI");
424
- if (uri) subtitleRenditions.push({
425
- groupId,
426
- name,
427
- language: mediaAttrs.get("LANGUAGE"),
428
- uri: resolveUrl(uri, baseUrl),
429
- default: mediaAttrs.getBool("DEFAULT"),
430
- autoselect: mediaAttrs.getBool("AUTOSELECT"),
431
- forced: mediaAttrs.getBool("FORCED")
432
- });
433
- }
434
- continue;
435
- }
436
- const streamInfAttrs = matchTag(trimmed, "EXT-X-STREAM-INF");
437
- if (streamInfAttrs) {
438
- pendingStreamInfo = {
439
- bandwidth: streamInfAttrs.getInt("BANDWIDTH", 0),
440
- resolution: streamInfAttrs.getResolution("RESOLUTION"),
441
- codecs: streamInfAttrs.get("CODECS"),
442
- frameRate: streamInfAttrs.getFrameRate("FRAME-RATE"),
443
- audioGroupId: streamInfAttrs.get("AUDIO")
444
- };
445
- continue;
446
- }
447
- if (!trimmed.startsWith("#") && pendingStreamInfo) {
448
- streams.push({
449
- ...pendingStreamInfo,
450
- uri: resolveUrl(trimmed, baseUrl)
451
- });
452
- pendingStreamInfo = null;
453
- }
454
- }
455
- const videoStreams = [];
456
- const audioOnlyStreams = [];
457
- for (const stream of streams) {
458
- if (!stream.codecs) {
459
- videoStreams.push(stream);
460
- continue;
461
- }
462
- const parsedCodecs = parseCodecs(stream.codecs);
463
- if (stream.codecs.split(",").length === 1) if (parsedCodecs.audio && !parsedCodecs.video) audioOnlyStreams.push(stream);
464
- else videoStreams.push(stream);
465
- else videoStreams.push(stream);
466
- }
467
- const videoTracks = videoStreams.map((stream) => {
468
- const codecs = stream.codecs ? parseCodecs(stream.codecs) : void 0;
469
- const track = {
470
- type: "video",
471
- id: generateId(),
472
- url: stream.uri,
473
- bandwidth: stream.bandwidth,
474
- mimeType: "video/mp4",
475
- codecs: []
476
- };
477
- if (stream.resolution?.width !== void 0) track.width = stream.resolution.width;
478
- if (stream.resolution?.height !== void 0) track.height = stream.resolution.height;
479
- if (codecs?.video) track.codecs = [codecs.video];
480
- if (stream.frameRate) track.frameRate = stream.frameRate;
481
- if (stream.audioGroupId) track.audioGroupId = stream.audioGroupId;
482
- return track;
483
- });
484
- const audioOnlyTracks = audioOnlyStreams.map((stream) => {
485
- const codecs = stream.codecs ? parseCodecs(stream.codecs) : void 0;
486
- return {
487
- type: "audio",
488
- id: generateId(),
489
- url: stream.uri,
490
- bandwidth: stream.bandwidth,
491
- mimeType: "audio/mp4",
492
- codecs: codecs?.audio ? [codecs.audio] : [],
493
- groupId: stream.audioGroupId || "default",
494
- name: "Default",
495
- sampleRate: 48e3,
496
- channels: 2
497
- };
498
- });
499
- const audioTracks = [...audioRenditions.map((rendition) => {
500
- let audioCodecs;
501
- for (const stream of streams) if (stream.audioGroupId === rendition.groupId && stream.codecs) {
502
- const codecs = parseCodecs(stream.codecs);
503
- if (codecs.audio) {
504
- audioCodecs = [codecs.audio];
505
- break;
506
- }
507
- }
508
- const track = {
509
- type: "audio",
510
- id: generateId(),
511
- url: rendition.uri ?? "",
512
- groupId: rendition.groupId,
513
- name: rendition.name,
514
- mimeType: "audio/mp4",
515
- bandwidth: 0,
516
- sampleRate: 48e3,
517
- channels: 2,
518
- codecs: []
519
- };
520
- if (rendition.language) track.language = rendition.language;
521
- if (audioCodecs) track.codecs = audioCodecs;
522
- if (rendition.default) track.default = rendition.default;
523
- if (rendition.autoselect) track.autoselect = rendition.autoselect;
524
- return track;
525
- }), ...audioOnlyTracks];
526
- const textTracks = subtitleRenditions.map((rendition) => {
527
- const track = {
528
- type: "text",
529
- id: generateId(),
530
- url: rendition.uri,
531
- groupId: rendition.groupId,
532
- label: rendition.name,
533
- kind: "subtitles",
534
- mimeType: "text/vtt",
535
- bandwidth: 0
536
- };
537
- if (rendition.language) track.language = rendition.language;
538
- if (rendition.default && rendition.autoselect) track.default = true;
539
- if (rendition.autoselect) track.autoselect = rendition.autoselect;
540
- if (rendition.forced) track.forced = rendition.forced;
541
- return track;
542
- });
543
- const selectionSets = [];
544
- if (videoTracks.length > 0) {
545
- const videoSwitchingSet = {
546
- id: generateId(),
547
- type: "video",
548
- tracks: videoTracks
549
- };
550
- const videoSelectionSet = {
551
- id: generateId(),
552
- type: "video",
553
- switchingSets: [videoSwitchingSet]
554
- };
555
- selectionSets.push(videoSelectionSet);
556
- }
557
- if (audioTracks.length > 0) {
558
- const audioSwitchingSet = {
559
- id: generateId(),
560
- type: "audio",
561
- tracks: audioTracks
562
- };
563
- const audioSelectionSet = {
564
- id: generateId(),
565
- type: "audio",
566
- switchingSets: [audioSwitchingSet]
567
- };
568
- selectionSets.push(audioSelectionSet);
569
- }
570
- if (textTracks.length > 0) {
571
- const textSwitchingSet = {
572
- id: generateId(),
573
- type: "text",
574
- tracks: textTracks
575
- };
576
- const textSelectionSet = {
577
- id: generateId(),
578
- type: "text",
579
- switchingSets: [textSwitchingSet]
580
- };
581
- selectionSets.push(textSelectionSet);
582
- }
583
- return {
584
- id: generateId(),
585
- url: unresolved.url,
586
- startTime: 0,
587
- selectionSets
588
- };
589
- }
590
-
591
- //#endregion
592
- //#region src/core/abr/ewma.ts
593
- /**
594
- * Exponentially Weighted Moving Average (EWMA)
595
- *
596
- * Pure functional implementation of EWMA calculations.
597
- * Based on Shaka Player's EWMA algorithm.
598
- */
599
- /**
600
- * Calculate alpha (decay factor) from half-life.
601
- *
602
- * Alpha determines how quickly old data "expires":
603
- * - alpha close to 1 = slow decay (long memory)
604
- * - alpha close to 0 = fast decay (short memory)
605
- *
606
- * @param halfLife - The quantity of prior samples (by weight) that make up
607
- * half of the new estimate. Must be positive.
608
- * @returns Alpha value between 0 and 1
609
- *
610
- * @example
611
- * const alpha = calculateAlpha(2); // ≈ 0.7071 for 2-second half-life
612
- */
613
- function calculateAlpha(halfLife) {
614
- return Math.exp(Math.log(.5) / halfLife);
615
- }
616
- /**
617
- * Calculate exponentially weighted moving average.
618
- *
619
- * Updates an estimate by blending a new value with the previous estimate,
620
- * weighted by the sample duration. Longer samples have more influence.
621
- *
622
- * @param prevEstimate - Previous EWMA estimate
623
- * @param value - New sample value to incorporate
624
- * @param weight - Sample weight (typically duration in seconds)
625
- * @param halfLife - Half-life for decay (typically 2-5 seconds)
626
- * @returns Updated EWMA estimate
627
- *
628
- * @example
629
- * let estimate = 0;
630
- * estimate = calculateEwma(estimate, 1_000_000, 1, 2); // First sample
631
- * estimate = calculateEwma(estimate, 2_000_000, 1, 2); // Second sample
632
- */
633
- function calculateEwma(prevEstimate, value, weight, halfLife) {
634
- const adjAlpha = calculateAlpha(halfLife) ** weight;
635
- return value * (1 - adjAlpha) + adjAlpha * prevEstimate;
636
- }
637
- /**
638
- * Apply zero-factor correction to EWMA estimate.
639
- *
640
- * The zero-factor correction compensates for bias when starting from zero.
641
- * Without this correction, early estimates would be artificially low.
642
- *
643
- * As totalWeight increases, the correction factor approaches 1, meaning
644
- * the estimate becomes more reliable and needs less correction.
645
- *
646
- * @param estimate - Raw EWMA estimate (uncorrected)
647
- * @param totalWeight - Accumulated weight from all samples
648
- * @param halfLife - Half-life used in EWMA calculation
649
- * @returns Corrected estimate, or 0 if totalWeight is 0
650
- *
651
- * @example
652
- * const raw = calculateEwma(0, 1_000_000, 1, 2);
653
- * const corrected = applyZeroFactor(raw, 1, 2); // ≈ 1_000_000
654
- */
655
- function applyZeroFactor(estimate, totalWeight, halfLife) {
656
- if (totalWeight === 0) return 0;
657
- return estimate / (1 - calculateAlpha(halfLife) ** totalWeight);
658
- }
659
-
660
- //#endregion
661
- //#region src/core/abr/bandwidth-estimator.ts
662
- /**
663
- * Default bandwidth estimator configuration.
664
- *
665
- * Values match Shaka Player defaults based on experimentation.
666
- */
667
- const DEFAULT_BANDWIDTH_CONFIG = {
668
- fastHalfLife: 2,
669
- slowHalfLife: 5,
670
- minTotalBytes: 128e3,
671
- minBytes: 16e3,
672
- minDuration: 5
673
- };
674
- /**
675
- * Add a bandwidth sample from a segment download.
676
- *
677
- * Samples are filtered based on:
678
- * - Minimum bytes (filters TTFB-dominated small segments)
679
- * - Minimum duration (filters cached responses)
680
- *
681
- * Valid samples update both fast and slow EWMA estimates.
682
- *
683
- * @param state - Current estimator state
684
- * @param durationMs - Download duration in milliseconds
685
- * @param numBytes - Number of bytes downloaded
686
- * @param config - Optional estimator configuration (uses defaults if not provided)
687
- * @returns New estimator state with sample incorporated (or unchanged if filtered)
688
- *
689
- * @example
690
- * let state = { fastEstimate: 0, fastTotalWeight: 0, ... };
691
- * // Sample: 1MB in 1 second
692
- * state = sampleBandwidth(state, 1000, 1_000_000);
693
- */
694
- function sampleBandwidth(state, durationMs, numBytes, config = DEFAULT_BANDWIDTH_CONFIG) {
695
- const updatedBytesSampled = state.bytesSampled + numBytes;
696
- if (numBytes < config.minBytes) return {
697
- ...state,
698
- bytesSampled: updatedBytesSampled
699
- };
700
- if (durationMs < config.minDuration) return {
701
- ...state,
702
- bytesSampled: updatedBytesSampled
703
- };
704
- const bandwidth = 8e3 * numBytes / durationMs;
705
- const weight = durationMs / 1e3;
706
- return {
707
- fastEstimate: calculateEwma(state.fastEstimate, bandwidth, weight, config.fastHalfLife),
708
- fastTotalWeight: state.fastTotalWeight + weight,
709
- slowEstimate: calculateEwma(state.slowEstimate, bandwidth, weight, config.slowHalfLife),
710
- slowTotalWeight: state.slowTotalWeight + weight,
711
- bytesSampled: updatedBytesSampled
712
- };
713
- }
714
- /**
715
- * Get the current bandwidth estimate.
716
- *
717
- * Returns the **minimum** of the fast and slow EWMA estimates.
718
- * This provides the key asymmetric behavior:
719
- * - When bandwidth drops, fast EWMA reacts first and dominates (quick adaptation)
720
- * - When bandwidth rises, slow EWMA lags behind and dominates (slow adaptation)
721
- *
722
- * Uses default estimate until enough data has been sampled.
723
- *
724
- * @param state - Current estimator state
725
- * @param defaultEstimate - Fallback estimate before sufficient samples (bps)
726
- * @param config - Optional estimator configuration (uses defaults if not provided)
727
- * @returns Bandwidth estimate in bits per second
728
- *
729
- * @example
730
- * const estimate = getBandwidthEstimate(state, 5_000_000); // 5 Mbps default
731
- */
732
- function getBandwidthEstimate(state, defaultEstimate, config = DEFAULT_BANDWIDTH_CONFIG) {
733
- if (state.bytesSampled < config.minTotalBytes) return defaultEstimate;
734
- const fastEstimate = applyZeroFactor(state.fastEstimate, state.fastTotalWeight, config.fastHalfLife);
735
- const slowEstimate = applyZeroFactor(state.slowEstimate, state.slowTotalWeight, config.slowHalfLife);
736
- return Math.min(fastEstimate, slowEstimate);
737
- }
738
-
739
- //#endregion
740
- //#region src/core/abr/quality-selection.ts
741
- /**
742
- * Default quality selection configuration.
743
- * Values match Shaka Player upgrade threshold (0.85 = 15% headroom).
744
- */
745
- const DEFAULT_QUALITY_CONFIG = { safetyMargin: .85 };
746
- /**
747
- * Select the best video track based on current bandwidth estimate.
748
- *
749
- * Selects the highest quality track where bandwidth is sufficient with safety margin:
750
- * - currentBandwidth >= track.bandwidth / safetyMargin
751
- * - Default safetyMargin 0.85 means track uses ≤85% of bandwidth (15% headroom)
752
- * - At same bandwidth, prefers higher resolution
753
- *
754
- * @param tracks - Available video tracks (can be unsorted)
755
- * @param currentBandwidth - Current bandwidth estimate in bits per second
756
- * @param config - Optional quality selection configuration
757
- * @returns Selected track, or undefined if no tracks available
758
- *
759
- * @example
760
- * const tracks = [
761
- * { id: '360p', bandwidth: 500_000, ... },
762
- * { id: '720p', bandwidth: 2_000_000, ... },
763
- * { id: '1080p', bandwidth: 4_000_000, ... },
764
- * ];
765
- *
766
- * // With 2.5 Mbps, selects 720p (1080p needs 4M/0.85 = 4.7 Mbps)
767
- * const selected = selectQuality(tracks, 2_500_000);
768
- */
769
- function selectQuality(tracks, currentBandwidth, config = DEFAULT_QUALITY_CONFIG) {
770
- if (tracks.length === 0) return;
771
- const sortedTracks = tracks.slice().sort((a, b) => a.bandwidth - b.bandwidth);
772
- let chosen;
773
- for (const track of sortedTracks) if (currentBandwidth >= track.bandwidth / config.safetyMargin) {
774
- if (!chosen || track.bandwidth > chosen.bandwidth || track.bandwidth === chosen.bandwidth && hasHigherResolution(track, chosen)) chosen = track;
775
- }
776
- return chosen ?? sortedTracks[0];
777
- }
778
- /**
779
- * Check if track A has higher resolution than track B.
780
- * Compares by total pixel count (width × height).
781
- *
782
- * @param trackA - First track to compare
783
- * @param trackB - Second track to compare
784
- * @returns True if trackA has more pixels than trackB
785
- */
786
- function hasHigherResolution(trackA, trackB) {
787
- return (trackA.width ?? 0) * (trackA.height ?? 0) > (trackB.width ?? 0) * (trackB.height ?? 0);
788
- }
789
-
790
- //#endregion
791
- //#region src/core/buffer/back-buffer.ts
792
- /**
793
- * Default back buffer configuration.
794
- */
795
- const DEFAULT_BACK_BUFFER_CONFIG = { keepSegments: 2 };
796
- /**
797
- * Calculate back buffer flush point.
798
- *
799
- * Determines where to flush old segments from the back buffer.
800
- * Keeps a fixed number of segments behind the current playback position.
801
- *
802
- * Algorithm:
803
- * 1. Find segments before currentTime
804
- * 2. Count back N segments (keepSegments)
805
- * 3. Return startTime of segment N+1 back (flush everything before this)
806
- *
807
- * @param segments - Available segments (should be sorted by startTime)
808
- * @param currentTime - Current playback position in seconds
809
- * @param config - Optional back buffer configuration
810
- * @returns Time in seconds to flush up to (flush range: [0, flushEnd))
811
- *
812
- * @example
813
- * const segments = [
814
- * { startTime: 0, duration: 6, ... },
815
- * { startTime: 6, duration: 6, ... },
816
- * { startTime: 12, duration: 6, ... },
817
- * { startTime: 18, duration: 6, ... },
818
- * ];
819
- *
820
- * // Playing at 18s, keep 2 segments
821
- * const flushEnd = calculateBackBufferFlushPoint(segments, 18);
822
- * // Returns 6 (flush [0, 6), keep [6-18))
823
- */
824
- function calculateBackBufferFlushPoint(segments, currentTime, config = DEFAULT_BACK_BUFFER_CONFIG) {
825
- if (segments.length === 0) return 0;
826
- const segmentsBefore = segments.filter((seg) => seg.startTime < currentTime);
827
- if (segmentsBefore.length === 0) return 0;
828
- const segmentsToFlush = segmentsBefore.length - config.keepSegments;
829
- if (segmentsToFlush <= 0) return 0;
830
- if (segmentsToFlush >= segmentsBefore.length) return currentTime;
831
- return segmentsBefore[segmentsToFlush].startTime;
832
- }
833
-
834
- //#endregion
835
- //#region src/core/buffer/forward-buffer.ts
836
- /**
837
- * Default forward buffer configuration.
838
- */
839
- const DEFAULT_FORWARD_BUFFER_CONFIG = { bufferDuration: 30 };
840
- /**
841
- * Get segments that need to be loaded for forward buffer.
842
- *
843
- * Determines which segments to load to maintain target buffer duration.
844
- * Handles discontiguous buffering (gaps after seeks).
845
- *
846
- * Algorithm:
847
- * 1. Calculate target time: currentTime + bufferDuration
848
- * 2. Find all segments in range [currentTime, targetTime)
849
- * 3. Filter out segments already buffered at that time position
850
- * 4. Return segments to load (fills gaps + extends to target)
851
- *
852
- * @param segments - All available segments from playlist
853
- * @param bufferedSegments - Segments already buffered (ordered by startTime)
854
- * @param currentTime - Current playback position in seconds
855
- * @param config - Optional forward buffer configuration
856
- * @returns Array of segments to load (empty if buffer is sufficient)
857
- *
858
- * @example
859
- * // After seek: buffered [0-12, 18-30], playing at 7s
860
- * const toLoad = getSegmentsToLoad(segments, buffered, 7, { bufferDuration: 24 });
861
- * // Returns [seg-12, seg-30] (fills gap, extends to target 31s)
862
- */
863
- /**
864
- * Calculate the start time from which to flush forward buffer content.
865
- *
866
- * Content that starts at or beyond `currentTime + bufferDuration` is no
867
- * longer needed for the current playback position and should be removed
868
- * from the SourceBuffer. This prevents unbounded accumulation of scattered
869
- * SourceBuffer content after seeks, which can cause QuotaExceededError on
870
- * long-form content.
871
- *
872
- * Returns `Infinity` when nothing needs flushing (no buffered segments
873
- * exist beyond the threshold).
874
- *
875
- * @param bufferedSegments - Segments currently tracked in the buffer model
876
- * @param currentTime - Current playback position in seconds
877
- * @param config - Optional forward buffer configuration
878
- * @returns Start time to flush from (flush range: [flushStart, Infinity)),
879
- * or Infinity if no flush is needed
880
- *
881
- * @example
882
- * // Playing at 0s, buffered [0,6,12,18,24,30,36], bufferDuration=30
883
- * const flushStart = calculateForwardFlushPoint(segments, 0);
884
- * // Returns 30 — flush [30, Infinity), keep [0, 30)
885
- */
886
- function calculateForwardFlushPoint(bufferedSegments, currentTime, config = DEFAULT_FORWARD_BUFFER_CONFIG) {
887
- if (bufferedSegments.length === 0) return Infinity;
888
- const threshold = currentTime + config.bufferDuration;
889
- const beyond = bufferedSegments.filter((seg) => seg.startTime >= threshold);
890
- if (beyond.length === 0) return Infinity;
891
- return Math.min(...beyond.map((seg) => seg.startTime));
892
- }
893
- function getSegmentsToLoad(segments, bufferedSegments, currentTime, config = DEFAULT_FORWARD_BUFFER_CONFIG) {
894
- if (segments.length === 0) return [];
895
- const targetTime = currentTime + config.bufferDuration;
896
- const bufferedStartTimes = new Set(bufferedSegments.map((seg) => seg.startTime));
897
- return segments.filter((seg) => {
898
- const segmentEnd = seg.startTime + seg.duration;
899
- const isInRange = seg.startTime < targetTime && segmentEnd > currentTime;
900
- const isNotBuffered = !bufferedStartTimes.has(seg.startTime);
901
- return isInRange && isNotBuffered;
902
- });
903
- }
904
-
905
- //#endregion
906
- //#region src/core/types/index.ts
907
- function isResolvedTrack(track) {
908
- return "segments" in track;
909
- }
910
- /**
911
- * Check if a presentation has duration (at least one track resolved).
912
- * Narrows type to include required duration.
913
- */
914
- function hasPresentationDuration(presentation) {
915
- return presentation.duration !== void 0;
916
- }
917
-
918
- //#endregion
919
- //#region src/dom/media/mediasource-setup.ts
920
- /**
921
- * MediaSource Setup
922
- *
923
- * Utilities for creating and configuring MediaSource/ManagedMediaSource
924
- * for MSE (Media Source Extensions) playback.
925
- *
926
- * Global ManagedMediaSource types are defined in ./mediasource.d.ts
927
- */
928
- /**
929
- * Check if MediaSource API is supported.
930
- */
931
- function supportsMediaSource() {
932
- return typeof MediaSource !== "undefined";
933
- }
934
- /**
935
- * Check if ManagedMediaSource API is supported.
936
- * ManagedMediaSource is a newer Safari API with better lifecycle management.
937
- */
938
- function supportsManagedMediaSource() {
939
- return typeof ManagedMediaSource !== "undefined";
940
- }
941
- /**
942
- * Create a MediaSource or ManagedMediaSource instance.
943
- *
944
- * @param options - Creation options
945
- * @returns A MediaSource or ManagedMediaSource instance
946
- * @throws Error if no MediaSource API is available
947
- *
948
- * @example
949
- * const mediaSource = createMediaSource();
950
- * const mediaElement = document.querySelector('video');
951
- * attachMediaSource(mediaSource, mediaElement);
952
- */
953
- function createMediaSource(options = {}) {
954
- const { preferManaged = false } = options;
955
- if (preferManaged && supportsManagedMediaSource()) return new ManagedMediaSource();
956
- if (supportsMediaSource()) return new MediaSource();
957
- throw new Error("MediaSource API is not supported");
958
- }
959
- /**
960
- * Attach a MediaSource to an HTMLMediaElement.
961
- *
962
- * Uses srcObject for ManagedMediaSource (Safari), or createObjectURL for regular MediaSource.
963
- *
964
- * @param mediaSource - The MediaSource to attach
965
- * @param mediaElement - The media element to attach to
966
- * @returns Object with URL and detach function
967
- *
968
- * @example
969
- * const mediaSource = createMediaSource();
970
- * const { detach } = attachMediaSource(mediaSource, videoElement);
971
- * await waitForSourceOpen(mediaSource);
972
- * // Use mediaSource...
973
- * // Later, to clean up:
974
- * detach();
975
- */
976
- function attachMediaSource(mediaSource, mediaElement) {
977
- if (supportsManagedMediaSource() && mediaSource instanceof ManagedMediaSource) {
978
- mediaElement.disableRemotePlayback = true;
979
- mediaElement.srcObject = mediaSource;
980
- const detach$1 = () => {
981
- mediaElement.srcObject = null;
982
- mediaElement.load();
983
- };
984
- return {
985
- url: "",
986
- detach: detach$1
987
- };
988
- }
989
- const url = URL.createObjectURL(mediaSource);
990
- mediaElement.src = url;
991
- const detach = () => {
992
- mediaElement.removeAttribute("src");
993
- mediaElement.load();
994
- URL.revokeObjectURL(url);
995
- };
996
- return {
997
- url,
998
- detach
999
- };
1000
- }
1001
- /**
1002
- * Wait for a MediaSource to reach the 'open' state.
1003
- * Resolves immediately if already open.
1004
- *
1005
- * @param mediaSource - The MediaSource to wait for
1006
- * @param signal - Optional AbortSignal for cancellation
1007
- * @returns Promise that resolves when the MediaSource is open
1008
- *
1009
- * @example
1010
- * const mediaSource = createMediaSource();
1011
- * attachMediaSource(mediaSource, videoElement);
1012
- * await waitForSourceOpen(mediaSource);
1013
- * // MediaSource is now ready for SourceBuffer creation
1014
- */
1015
- function waitForSourceOpen(mediaSource, signal) {
1016
- return new Promise((resolve, reject) => {
1017
- if (mediaSource.readyState === "open") {
1018
- resolve();
1019
- return;
1020
- }
1021
- if (signal?.aborted) {
1022
- reject(new DOMException("Aborted", "AbortError"));
1023
- return;
1024
- }
1025
- const controller = new AbortController();
1026
- const options = { signal: controller.signal };
1027
- mediaSource.addEventListener("sourceopen", () => {
1028
- controller.abort();
1029
- resolve();
1030
- }, options);
1031
- signal?.addEventListener("abort", () => {
1032
- controller.abort();
1033
- reject(new DOMException("Aborted", "AbortError"));
1034
- }, options);
1035
- });
1036
- }
1037
- /**
1038
- * Create a SourceBuffer on a MediaSource.
1039
- *
1040
- * @param mediaSource - The MediaSource (must be in 'open' state)
1041
- * @param mimeCodec - MIME type with codecs (e.g., 'video/mp4; codecs="avc1.42E01E"')
1042
- * @returns The created SourceBuffer
1043
- * @throws Error if MediaSource is not open or codec is unsupported
1044
- *
1045
- * @example
1046
- * await waitForSourceOpen(mediaSource);
1047
- * const buffer = createSourceBuffer(mediaSource, 'video/mp4; codecs="avc1.42E01E"');
1048
- */
1049
- function createSourceBuffer(mediaSource, mimeCodec) {
1050
- if (mediaSource.readyState !== "open") throw new Error("MediaSource is not open");
1051
- if (!isCodecSupported(mimeCodec)) throw new Error(`Codec not supported: ${mimeCodec}`);
1052
- return mediaSource.addSourceBuffer(mimeCodec);
1053
- }
1054
- /**
1055
- * Check if a codec is supported.
1056
- *
1057
- * @param mimeCodec - MIME type with codecs string
1058
- * @returns True if the codec is supported
1059
- *
1060
- * @example
1061
- * if (isCodecSupported('video/mp4; codecs="avc1.42E01E"')) {
1062
- * // Create source buffer
1063
- * }
1064
- */
1065
- function isCodecSupported(mimeCodec) {
1066
- if (!supportsMediaSource()) return false;
1067
- return MediaSource.isTypeSupported(mimeCodec);
1068
- }
1069
-
1070
- //#endregion
1071
- //#region src/dom/network/fetch.ts
1072
- /**
1073
- * Fetch resolvable from AddressableObject.
1074
- *
1075
- * Handles byte range requests if byteRange is present.
1076
- * Returns native fetch Response for composability (can extract text, stream, etc.).
1077
- *
1078
- * @param addressable - Resource to fetch (url + optional byteRange)
1079
- * @returns Promise resolving to Response
1080
- *
1081
- * @example
1082
- * const response = await fetchResolvable({ url: 'https://example.com/segment.m4s' });
1083
- * const text = await getResponseText(response);
1084
- *
1085
- * @example
1086
- * // With byte range
1087
- * const response = await fetchResolvable({
1088
- * url: 'https://example.com/file.mp4',
1089
- * byteRange: { start: 1000, end: 1999 }
1090
- * });
1091
- */
1092
- async function fetchResolvable(addressable, options) {
1093
- const headers = new Headers(options?.headers);
1094
- if (addressable.byteRange) {
1095
- const { start, end } = addressable.byteRange;
1096
- headers.set("Range", `bytes=${start}-${end}`);
1097
- }
1098
- const request = new Request(addressable.url, {
1099
- method: "GET",
1100
- headers,
1101
- ...options
1102
- });
1103
- return fetch(request);
1104
- }
1105
- /**
1106
- * Fetch resolvable as bytes.
1107
- *
1108
- * Convenience wrapper around fetchResolvable that resolves the body as an
1109
- * ArrayBuffer. Use this when you need the raw bytes (e.g. segment appends).
1110
- * For text or streaming consumption, use fetchResolvable directly.
1111
- */
1112
- async function fetchResolvableBytes(addressable, options) {
1113
- return (await fetchResolvable(addressable, options)).arrayBuffer();
1114
- }
1115
- /**
1116
- * Extract text from Response.
1117
- *
1118
- * Accepts minimal Response-like object (just needs text() method).
1119
- * Returns promise from response.text().
1120
- *
1121
- * @param response - Response-like object with text() method
1122
- * @returns Promise resolving to text content
1123
- *
1124
- * @example
1125
- * const response = await fetchResolvable(addressable);
1126
- * const text = await getResponseText(response);
1127
- */
1128
- function getResponseText(response) {
1129
- return response.text();
1130
- }
1131
-
1132
- //#endregion
1133
- //#region src/core/events/create-event-stream.ts
1134
- /**
1135
- * Minimal event stream with Observable-like shape.
1136
- *
1137
- * Simple Subject/Observable-like implementation for dispatching discrete events.
1138
- * Events are dispatched synchronously to all subscribers.
1139
- */
1140
- const EVENT_STREAM_SYMBOL = Symbol("@videojs/event-stream");
1141
- /**
1142
- * Creates a minimal event stream for dispatching discrete events.
1143
- *
1144
- * Events are dispatched synchronously to all subscribers.
1145
- * Conforms to Observable-like shape for future compatibility.
1146
- *
1147
- * Events must have a 'type' property for discriminated union type narrowing.
1148
- *
1149
- * @example
1150
- * ```ts
1151
- * type Action = { type: 'PLAY' } | { type: 'PAUSE' };
1152
- * const events = createEventStream<Action>();
1153
- *
1154
- * events.subscribe((action) => {
1155
- * if (action.type === 'PLAY') {
1156
- * // Type narrowed to { type: 'PLAY' }
1157
- * }
1158
- * });
1159
- *
1160
- * events.dispatch({ type: 'PLAY' });
1161
- * ```
1162
- */
1163
- function createEventStream() {
1164
- const subscribers = /* @__PURE__ */ new Set();
1165
- return {
1166
- [EVENT_STREAM_SYMBOL]: true,
1167
- dispatch(event) {
1168
- const current = Array.from(subscribers);
1169
- for (const listener of current) listener(event);
1170
- },
1171
- subscribe(listener) {
1172
- subscribers.add(listener);
1173
- return () => subscribers.delete(listener);
1174
- }
1175
- };
1176
- }
1177
-
1178
- //#endregion
1179
- //#region src/core/reactive/combine-latest.ts
1180
- /**
1181
- * Combines multiple Observable sources into a single Observable.
1182
- *
1183
- * Emits an array of latest values whenever any source emits.
1184
- * Only emits after all sources have emitted at least once.
1185
- *
1186
- * Supports selector-based subscriptions (fires only when the selected value
1187
- * changes, per the optional equalityFn) mirroring the createState API.
1188
- *
1189
- * @param sources - Array of Observable sources
1190
- * @returns Combined Observable
1191
- *
1192
- * @example
1193
- * ```ts
1194
- * const state = createState({ count: 0 });
1195
- * const events = createEventStream<Action>();
1196
- *
1197
- * combineLatest([state, events]).subscribe(([state, event]) => {
1198
- * if (event.type === 'PLAY' && state.count > 0) {
1199
- * // React to event + state condition
1200
- * }
1201
- * });
1202
- * ```
1203
- *
1204
- * @example Selector subscription
1205
- * ```ts
1206
- * combineLatest([state, owners]).subscribe(
1207
- * ([s, o]) => deriveKey(s, o),
1208
- * (key) => { ... },
1209
- * { equalityFn: keyEq }
1210
- * );
1211
- * ```
1212
- */
1213
- function combineLatest(sources) {
1214
- const subscribeToSources = (listener) => {
1215
- const latest = new Array(sources.length);
1216
- const hasValue = new Array(sources.length).fill(false);
1217
- const unsubscribers = [];
1218
- for (let i = 0; i < sources.length; i++) {
1219
- const unsubscribe = sources[i].subscribe((value) => {
1220
- latest[i] = value;
1221
- hasValue[i] = true;
1222
- if (hasValue.every((has) => has)) listener([...latest]);
1223
- });
1224
- unsubscribers.push(unsubscribe);
1225
- }
1226
- return () => {
1227
- for (const unsubscribe of unsubscribers) unsubscribe();
1228
- };
1229
- };
1230
- return { subscribe(listenerOrSelector, maybeListener, options) {
1231
- if (maybeListener === void 0) return subscribeToSources(listenerOrSelector);
1232
- const selector = listenerOrSelector;
1233
- const listener = maybeListener;
1234
- const equalityFn = options?.equalityFn ?? Object.is;
1235
- let prevSelected;
1236
- let initialized = false;
1237
- return subscribeToSources((values) => {
1238
- const nextSelected = selector(values);
1239
- if (!initialized || !equalityFn(prevSelected, nextSelected)) {
1240
- prevSelected = nextSelected;
1241
- initialized = true;
1242
- listener(nextSelected);
1243
- }
1244
- });
1245
- } };
1246
- }
1247
-
1248
- //#endregion
1249
- //#region src/core/features/resolve-presentation.ts
1250
- /**
1251
- * Type guard to check if presentation is unresolved.
1252
- */
1253
- function isUnresolved(presentation) {
1254
- return presentation !== void 0 && "url" in presentation && !("id" in presentation);
1255
- }
1256
- function canResolve$1(state) {
1257
- return isUnresolved(state.presentation);
1258
- }
1259
- /**
1260
- * Determines if resolution conditions are met based on preload policy and event.
1261
- *
1262
- * Resolution conditions:
1263
- * - State-driven: preload is 'auto' or 'metadata'
1264
- * - Event-driven: play event
1265
- *
1266
- * @param state - Current presentation state
1267
- * @param event - Current action/event
1268
- * @returns true if resolution conditions are met
1269
- */
1270
- function shouldResolve$1(state, event) {
1271
- const { preload } = state;
1272
- return ["auto", "metadata"].includes(preload) || event.type === "play";
1273
- }
1274
- /**
1275
- * Syncs preload attribute from mediaElement to state.
1276
- *
1277
- * Watches the owners state for mediaElement changes and copies the
1278
- * preload attribute to the immutable state.
1279
- *
1280
- * @param state - Immutable state container
1281
- * @param owners - Mutable platform objects container
1282
- * @returns Cleanup function to stop syncing
1283
- */
1284
- function syncPreloadAttribute(state, owners) {
1285
- return owners.subscribe((current) => {
1286
- const preload = current.mediaElement?.preload || void 0;
1287
- state.patch({ preload });
1288
- });
1289
- }
1290
- /**
1291
- * Resolves unresolved presentations using reactive composition.
1292
- *
1293
- * Uses combineLatest to compose state + events, enabling both state-driven
1294
- * and event-driven resolution triggers.
1295
- *
1296
- * Triggers resolution when:
1297
- * - State-driven: Unresolved presentation + preload allows (auto/metadata)
1298
- * - Event-driven: PLAY event when preload="none"
1299
- *
1300
- * @example
1301
- * ```ts
1302
- * const state = createState({ presentation: undefined, preload: 'auto' });
1303
- * const events = createEventStream<PresentationAction>();
1304
- *
1305
- * const cleanup = resolvePresentation({ state, events });
1306
- *
1307
- * // State-driven: resolves immediately when preload allows
1308
- * state.patch({ presentation: { url: 'http://example.com/playlist.m3u8' } });
1309
- *
1310
- * // Event-driven: resolves on PLAY when preload="none"
1311
- * state.patch({ preload: 'none', presentation: { url: '...' } });
1312
- * events.dispatch({ type: 'PLAY' });
1313
- * ```
1314
- */
1315
- function resolvePresentation({ state, events }) {
1316
- let resolving = false;
1317
- let abortController = null;
1318
- const cleanup = combineLatest([state, events]).subscribe(async ([currentState, event]) => {
1319
- if (!canResolve$1(currentState) || !shouldResolve$1(currentState, event) || resolving) return;
1320
- try {
1321
- resolving = true;
1322
- abortController = new AbortController();
1323
- const { presentation } = currentState;
1324
- const parsed = parseMultivariantPlaylist(await getResponseText(await fetchResolvable(presentation, { signal: abortController.signal })), presentation);
1325
- state.patch({ presentation: parsed });
1326
- } catch (error) {
1327
- if (error instanceof Error && error.name === "AbortError") return;
1328
- throw error;
1329
- } finally {
1330
- resolving = false;
1331
- abortController = null;
1332
- }
1333
- });
1334
- return () => {
1335
- abortController?.abort();
1336
- cleanup();
1337
- };
1338
- }
1339
-
1340
- //#endregion
1341
- //#region src/core/features/quality-switching.ts
1342
- /**
1343
- * Default quality switching configuration.
1344
- */
1345
- const DEFAULT_SWITCHING_CONFIG = {
1346
- safetyMargin: .85,
1347
- minUpgradeInterval: 8e3,
1348
- defaultBandwidth: 5e6
1349
- };
1350
- /**
1351
- * Get all video tracks from a presentation's first switching set.
1352
- * Returns [] when the presentation is still unresolved (no selectionSets yet).
1353
- */
1354
- function getVideoTracks(presentation) {
1355
- return (presentation.selectionSets?.find((s) => s.type === "video"))?.switchingSets[0]?.tracks ?? [];
1356
- }
1357
- /**
1358
- * Quality switching orchestration (F9).
1359
- *
1360
- * Reacts to bandwidth estimate changes and updates `selectedVideoTrackId`
1361
- * when a different quality is optimal:
1362
- *
1363
- * - **Downgrades** happen immediately to avoid buffering stalls.
1364
- * - **Upgrades** are gated by `minUpgradeInterval` to prevent oscillation.
1365
- * - The first switch (from any track, or no track) is always immediate.
1366
- *
1367
- * Smooth switching is handled downstream: when `selectedVideoTrackId` changes,
1368
- * `resolveTrack` fetches the new playlist and `loadSegments` reloads the init
1369
- * segment, then appends media segments from the current position in the new
1370
- * quality. The browser's SourceBuffer replaces the overlapping buffered range.
1371
- *
1372
- * @example
1373
- * const cleanup = switchQuality({ state });
1374
- * // Later, when done:
1375
- * cleanup();
1376
- */
1377
- function switchQuality({ state }, config = {}) {
1378
- const safetyMargin = config.safetyMargin ?? DEFAULT_SWITCHING_CONFIG.safetyMargin;
1379
- const minUpgradeInterval = config.minUpgradeInterval ?? DEFAULT_SWITCHING_CONFIG.minUpgradeInterval;
1380
- const defaultBandwidth = config.defaultBandwidth ?? DEFAULT_SWITCHING_CONFIG.defaultBandwidth;
1381
- let lastUpgradeTime = Date.now();
1382
- let firstMeaningfulFire = true;
1383
- return state.subscribe((currentState) => {
1384
- const { presentation, bandwidthState, selectedVideoTrackId, abrDisabled } = currentState;
1385
- if (abrDisabled === true) return;
1386
- if (!presentation || !bandwidthState) return;
1387
- const videoTracks = getVideoTracks(presentation);
1388
- if (videoTracks.length === 0) return;
1389
- const isFirst = firstMeaningfulFire;
1390
- firstMeaningfulFire = false;
1391
- const optimal = selectQuality(videoTracks, getBandwidthEstimate(bandwidthState, defaultBandwidth), { safetyMargin });
1392
- if (!optimal || optimal.id === selectedVideoTrackId) return;
1393
- const currentTrack = videoTracks.find((t) => t.id === selectedVideoTrackId);
1394
- if (!currentTrack || optimal.bandwidth > currentTrack.bandwidth) {
1395
- const now = Date.now();
1396
- if (!isFirst && now - lastUpgradeTime < minUpgradeInterval) return;
1397
- lastUpgradeTime = now;
1398
- }
1399
- state.patch({ selectedVideoTrackId: optimal.id });
1400
- });
1401
- }
1402
-
1403
- //#endregion
1404
- //#region src/core/utils/track-selection.ts
1405
- /**
1406
- * Map track type to selected track ID property key in state.
1407
- */
1408
- const SelectedTrackIdKeyByType = {
1409
- video: "selectedVideoTrackId",
1410
- audio: "selectedAudioTrackId",
1411
- text: "selectedTextTrackId"
1412
- };
1413
- /**
1414
- * Map track type to buffer owner property key.
1415
- * Used for SourceBuffer references in owners.
1416
- */
1417
- const BufferKeyByType = {
1418
- video: "videoBuffer",
1419
- audio: "audioBuffer"
1420
- };
1421
- /**
1422
- * Get selected track from state by type.
1423
- * Returns properly typed track (partially or fully resolved) or undefined.
1424
- * Type parameter T is inferred from the type argument.
1425
- *
1426
- * @example
1427
- * const videoTrack = getSelectedTrack(state, 'video');
1428
- * if (videoTrack && isResolvedTrack(videoTrack)) {
1429
- * // videoTrack is VideoTrack
1430
- * }
1431
- */
1432
- function getSelectedTrack(state, type) {
1433
- const { presentation } = state;
1434
- /** @TODO Consider moving and reusing isUnresolved(presentation) (CJP) */
1435
- if (!presentation || !("id" in presentation)) return void 0;
1436
- const trackId = state[SelectedTrackIdKeyByType[type]];
1437
- return presentation.selectionSets.find(({ type: selectionSetType }) => selectionSetType === type)?.switchingSets[0]?.tracks.find(({ id }) => id === trackId);
1438
- }
1439
-
1440
- //#endregion
1441
- //#region src/dom/features/segment-loader-actor.ts
1442
- /**
1443
- * Creates a SegmentLoaderActor for one track type (video or audio).
1444
- *
1445
- * Receives load assignments via `send()` and owns all execution: planning,
1446
- * removes, fetches, and appends. Coordinates with the SourceBufferActor for
1447
- * all physical SourceBuffer operations.
1448
- *
1449
- * Planning (Cases 1–3) happens in `send()` on every incoming message, producing
1450
- * an ordered LoadTask list. The runner drains that list sequentially. When a new
1451
- * message arrives mid-run, send() replans and either continues the in-flight
1452
- * operation (if still needed) or preempts it.
1453
- *
1454
- * @param sourceBufferActor - Shared SourceBufferActor reference (not owned)
1455
- * @param fetchBytes - Tracked fetch closure (owns throughput sampling)
1456
- */
1457
- function createSegmentLoaderActor(sourceBufferActor, fetchBytes) {
1458
- let pendingTasks = null;
1459
- let inFlightInitTrackId = null;
1460
- let inFlightSegmentId = null;
1461
- let abortController = null;
1462
- let running = false;
1463
- let destroyed = false;
1464
- const getBufferedSegments = (allSegments) => {
1465
- const bufferedIds = new Set(sourceBufferActor.snapshot.context.segments.map((s) => s.id));
1466
- return allSegments.filter((s) => bufferedIds.has(s.id));
1467
- };
1468
- /**
1469
- * Translate a load message into an ordered LoadTask list based on committed
1470
- * actor state. In-flight awareness is handled separately in send().
1471
- *
1472
- * @todo Rename alongside LoadTask (e.g. planOps).
1473
- *
1474
- * Case 1 — Removes: forward and back buffer flush points, segment-aligned.
1475
- * No flush on track switch: appending new content overwrites existing buffer
1476
- * ranges, and the actor's time-aligned deduplication keeps the segment model
1477
- * accurate as new segments arrive.
1478
- *
1479
- * Case 2 — Init: schedule if not yet committed for this track.
1480
- *
1481
- * Case 3 — Segments: all segments in the load window not yet committed.
1482
- */
1483
- const planTasks = (message) => {
1484
- const { track, range } = message;
1485
- const actorCtx = sourceBufferActor.snapshot.context;
1486
- const bufferedSegments = getBufferedSegments(track.segments);
1487
- const currentTime = range?.start ?? 0;
1488
- const tasks = [];
1489
- if (range) {
1490
- const forwardFlushStart = calculateForwardFlushPoint(bufferedSegments, currentTime);
1491
- if (forwardFlushStart < Infinity) tasks.push({
1492
- type: "remove",
1493
- start: forwardFlushStart,
1494
- end: Infinity
1495
- });
1496
- const backFlushEnd = calculateBackBufferFlushPoint(bufferedSegments, currentTime);
1497
- if (backFlushEnd > 0) tasks.push({
1498
- type: "remove",
1499
- start: 0,
1500
- end: backFlushEnd
1501
- });
1502
- }
1503
- if (actorCtx.initTrackId !== track.id) tasks.push({
1504
- type: "append-init",
1505
- meta: { trackId: track.id },
1506
- url: track.initialization.url
1507
- });
1508
- if (range) {
1509
- const EPSILON = 1e-4;
1510
- const segmentsToLoad = getSegmentsToLoad(track.segments, bufferedSegments, currentTime).filter((seg) => {
1511
- const existing = actorCtx.segments.find((s) => Math.abs(s.startTime - seg.startTime) < EPSILON);
1512
- if (!existing?.trackBandwidth || !track.bandwidth) return true;
1513
- return track.bandwidth > existing.trackBandwidth;
1514
- });
1515
- for (const segment of segmentsToLoad) tasks.push({
1516
- type: "append-segment",
1517
- meta: {
1518
- id: segment.id,
1519
- startTime: segment.startTime,
1520
- duration: segment.duration,
1521
- trackId: track.id,
1522
- trackBandwidth: track.bandwidth
1523
- },
1524
- url: segment.url
1525
- });
1526
- }
1527
- return tasks;
1528
- };
1529
- /**
1530
- * Execute a single LoadTask: fetch (if needed) then forward to SourceBufferActor.
1531
- * Sets/clears in-flight tracking around async operations so send() can make
1532
- * accurate continue/preempt decisions at any point during execution.
1533
- *
1534
- * @todo Rename alongside LoadTask (e.g. executeOp).
1535
- */
1536
- const executeLoadTask = async (task) => {
1537
- const signal = abortController.signal;
1538
- try {
1539
- if (task.type === "remove") {
1540
- await sourceBufferActor.send(task, signal);
1541
- return;
1542
- }
1543
- if (task.type === "append-init") {
1544
- inFlightInitTrackId = task.meta.trackId;
1545
- if (!signal.aborted) {
1546
- const data = await fetchBytes(task, { signal });
1547
- const isTrackSwitch = pendingTasks?.some((t) => t.type === "append-init" && t.meta.trackId !== task.meta.trackId);
1548
- if (!signal.aborted || !isTrackSwitch) {
1549
- const appendSignal = signal.aborted ? new AbortController().signal : signal;
1550
- await sourceBufferActor.send({
1551
- type: "append-init",
1552
- data,
1553
- meta: task.meta
1554
- }, appendSignal);
1555
- }
1556
- }
1557
- return;
1558
- }
1559
- inFlightSegmentId = task.meta.id;
1560
- if (!signal.aborted) {
1561
- const data = await fetchBytes(task, { signal });
1562
- if (!signal.aborted) await sourceBufferActor.send({
1563
- type: "append-segment",
1564
- data,
1565
- meta: task.meta
1566
- }, signal);
1567
- }
1568
- } finally {
1569
- inFlightInitTrackId = null;
1570
- inFlightSegmentId = null;
1571
- }
1572
- };
1573
- /**
1574
- * Drain the scheduled task list sequentially.
1575
- * After each task completes, checks for a pending replacement plan from send().
1576
- * If the signal was aborted and no new plan arrived, stops immediately.
1577
- */
1578
- const runScheduled = async (initialTasks) => {
1579
- running = true;
1580
- abortController = new AbortController();
1581
- let scheduled = initialTasks;
1582
- while (scheduled.length > 0 && !destroyed) {
1583
- const task = scheduled[0];
1584
- scheduled = scheduled.slice(1);
1585
- try {
1586
- await executeLoadTask(task);
1587
- } catch (error) {
1588
- if (error instanceof Error && error.name === "AbortError") {} else {
1589
- console.error("Unexpected error in segment loader:", error);
1590
- scheduled = [];
1591
- }
1592
- }
1593
- if (pendingTasks !== null) {
1594
- scheduled = pendingTasks;
1595
- pendingTasks = null;
1596
- abortController = new AbortController();
1597
- } else if (abortController.signal.aborted) break;
1598
- }
1599
- abortController = null;
1600
- running = false;
1601
- };
1602
- return {
1603
- send(message) {
1604
- if (destroyed) return;
1605
- const allTasks = planTasks(message);
1606
- if (!running) {
1607
- if (allTasks.length === 0) return;
1608
- runScheduled(allTasks);
1609
- return;
1610
- }
1611
- if (inFlightSegmentId !== null && allTasks.some((t) => t.type === "append-segment" && t.meta.id === inFlightSegmentId) || inFlightInitTrackId !== null && allTasks.some((t) => t.type === "append-init" && t.meta.trackId === inFlightInitTrackId)) pendingTasks = allTasks.filter((t) => !(t.type === "append-segment" && t.meta.id === inFlightSegmentId) && !(t.type === "append-init" && t.meta.trackId === inFlightInitTrackId));
1612
- else {
1613
- pendingTasks = allTasks;
1614
- abortController?.abort();
1615
- }
1616
- },
1617
- destroy() {
1618
- destroyed = true;
1619
- abortController?.abort();
1620
- }
1621
- };
1622
- }
1623
-
1624
- //#endregion
1625
- //#region src/dom/features/load-segments.ts
1626
- const ActorKeyByType$1 = {
1627
- video: "videoBufferActor",
1628
- audio: "audioBufferActor"
1629
- };
1630
- /**
1631
- * Creates a fetch function that transparently samples bandwidth after each
1632
- * completed request. Callers receive bytes; throughput tracking is invisible.
1633
- *
1634
- * `onSample` is an optional callback invoked after each sample is recorded,
1635
- * used for bridging throughput state outward (e.g. migration bridge to global
1636
- * state). A callback is used rather than a subscription so that no immediate
1637
- * fire occurs at setup time — subscriptions fire on registration and would
1638
- * trigger spurious state changes before any work has started.
1639
- */
1640
- function createTrackedFetch(throughput, onSample) {
1641
- return async (addressable, options) => {
1642
- const start = performance.now();
1643
- const data = await fetchResolvableBytes(addressable, options);
1644
- const elapsed = performance.now() - start;
1645
- const next = sampleBandwidth(throughput.current, elapsed, data.byteLength);
1646
- throughput.patch(next);
1647
- throughput.flush();
1648
- onSample?.(next);
1649
- return data;
1650
- };
1651
- }
1652
- function selectLoadingInputs([segmentsCanLoad, state], type) {
1653
- const { playbackInitiated, preload, currentTime } = state;
1654
- return {
1655
- playbackInitiated,
1656
- preload,
1657
- currentTime,
1658
- track: getSelectedTrack(state, type),
1659
- segmentsCanLoad
1660
- };
1661
- }
1662
- /**
1663
- * Equality function encoding the condition hierarchy for relevant changes.
1664
- *
1665
- * Pre-play (!playbackInitiated):
1666
- * Only preload changes matter. currentTime and resolvedTrackId are ignored
1667
- * (track changes not supported pre-play; currentTime value is used at
1668
- * trigger time but changes don't re-trigger).
1669
- *
1670
- * playbackInitiated transition:
1671
- * Always fires (handled in the subscriber; preload='auto' suppression
1672
- * applied there since equality functions have no memory of prior values).
1673
- *
1674
- * Post-play (playbackInitiated):
1675
- * resolvedTrackId changes (track switch or previously-unresolved track
1676
- * resolving) and currentTime changes both trigger. preload is irrelevant.
1677
- */
1678
- const segmentStartFor = (currentTime, track) => {
1679
- if (currentTime == null) return void 0;
1680
- return track?.segments.find(({ startTime, duration }, i, segments) => currentTime >= startTime && (currentTime < startTime + duration || i === segments.length - 1))?.startTime;
1681
- };
1682
- /**
1683
- * Returns true when the inputs are equal (no meaningful change — don't fire).
1684
- * Returns false when the inputs differ in a way that requires a new message.
1685
- *
1686
- * This IS the shouldLoadSegments logic, expressed as an equality function.
1687
- */
1688
- function loadingInputsEq(prevState, curState) {
1689
- if (!curState.segmentsCanLoad) return true;
1690
- if (!curState.playbackInitiated) {
1691
- if (curState.preload === "none") return true;
1692
- return curState.preload === prevState.preload;
1693
- }
1694
- if (!prevState.playbackInitiated && curState.playbackInitiated) {
1695
- if (prevState.preload !== "auto") return false;
1696
- }
1697
- if (!curState.track || !isResolvedTrack(curState.track)) return true;
1698
- if (prevState.track?.id !== curState.track.id && isResolvedTrack(curState.track)) return false;
1699
- return segmentStartFor(prevState.currentTime, curState.track) === segmentStartFor(curState.currentTime, curState.track);
1700
- }
1701
- /**
1702
- * Load segments orchestration — Reactor layer.
1703
- *
1704
- * Sends typed load messages to a SegmentLoaderActor when relevant conditions
1705
- * change. Uses targeted subscriptions rather than broad combineLatest so only
1706
- * meaningful state changes trigger evaluation.
1707
- *
1708
- * Condition hierarchy (see SegmentLoadingKey for detail):
1709
- *
1710
- * !playbackInitiated
1711
- * preload==='none' (or unset) → dormant; no trigger
1712
- * preload==='metadata' → trigger on transition to 'metadata'
1713
- * preload==='auto' → trigger on transition to 'auto'
1714
- *
1715
- * !playbackInitiated → playbackInitiated
1716
- * preload !== 'auto' → trigger (message shape changes)
1717
- * preload === 'auto' → suppressed (was already full-range mode;
1718
- * let segmentStart take over post-play)
1719
- * KNOWN LIMITATION: seek-before-play with
1720
- * preload='auto' is not supported — if the
1721
- * user seeks before pressing play, the
1722
- * first re-send is delayed until the next
1723
- * segment boundary crossing post-play.
1724
- *
1725
- * playbackInitiated
1726
- * resolvedTrackId changes → trigger
1727
- * segmentStart(currentTime) changes → trigger (segment boundary only)
1728
- *
1729
- * @example
1730
- * const cleanup = loadSegments({ state, owners }, { type: 'video' });
1731
- */
1732
- function loadSegments({ state, owners }, config) {
1733
- const { type } = config;
1734
- const actorKey = ActorKeyByType$1[type];
1735
- const initialBandwidth = state.current.bandwidthState;
1736
- const throughput = createState(initialBandwidth ?? {
1737
- fastEstimate: 0,
1738
- fastTotalWeight: 0,
1739
- slowEstimate: 0,
1740
- slowTotalWeight: 0,
1741
- bytesSampled: 0
1742
- });
1743
- const fetchBytes = type === "video" ? createTrackedFetch(throughput, initialBandwidth !== void 0 ? (next) => {
1744
- state.patch({ bandwidthState: next });
1745
- state.flush();
1746
- } : void 0) : fetchResolvableBytes;
1747
- const segmentLoader = createState(void 0);
1748
- const unsubActorLifecycle = owners.subscribe((o) => o[actorKey], (actor) => {
1749
- if (actor) segmentLoader.patch(createSegmentLoaderActor(actor, fetchBytes));
1750
- else if (!actor && segmentLoader.current) {
1751
- segmentLoader.current.destroy();
1752
- segmentLoader.patch(void 0);
1753
- }
1754
- return () => {
1755
- segmentLoader.current?.destroy();
1756
- segmentLoader.patch(void 0);
1757
- };
1758
- });
1759
- const segmentsCanLoad = createState(false);
1760
- const unsubscribeCanLoadSegments = combineLatest([state, segmentLoader]).subscribe(([currentState, currentSegmentLoader]) => {
1761
- const track = getSelectedTrack(currentState, type);
1762
- const trackResolved = !!track && isResolvedTrack(track);
1763
- const segmentLoaderActorExists = !!currentSegmentLoader;
1764
- segmentsCanLoad.patch(trackResolved && segmentLoaderActorExists);
1765
- });
1766
- const unsubscribeShouldLoadSegments = combineLatest([segmentsCanLoad, state]).subscribe(([segmentsCanLoad$1, state$1]) => selectLoadingInputs([segmentsCanLoad$1, state$1], type), ({ preload, playbackInitiated, currentTime, track }) => {
1767
- if (!(preload === "auto" || !!playbackInitiated))
1768
- /** @ts-expect-error */
1769
- segmentLoader.current?.send({
1770
- type: "load",
1771
- track
1772
- });
1773
- else segmentLoader.current?.send({
1774
- type: "load",
1775
- track,
1776
- range: {
1777
- start: currentTime,
1778
- end: currentTime + DEFAULT_FORWARD_BUFFER_CONFIG.bufferDuration
1779
- }
1780
- });
1781
- }, { equalityFn: loadingInputsEq });
1782
- return () => {
1783
- unsubscribeCanLoadSegments();
1784
- unsubscribeShouldLoadSegments();
1785
- unsubActorLifecycle();
1786
- };
1787
- }
1788
-
1789
- //#endregion
1790
- //#region src/dom/text/parse-vtt-segment.ts
1791
- /**
1792
- * Parse a VTT segment using browser's native parser.
1793
- *
1794
- * Creates a dummy video element with a track element to leverage
1795
- * the browser's optimized VTT parsing. Returns parsed VTTCue objects.
1796
- */
1797
- let dummyVideo = null;
1798
- function ensureDummyVideo() {
1799
- if (!dummyVideo) {
1800
- dummyVideo = document.createElement("video");
1801
- dummyVideo.muted = true;
1802
- dummyVideo.preload = "none";
1803
- dummyVideo.style.display = "none";
1804
- dummyVideo.crossOrigin = "anonymous";
1805
- }
1806
- return dummyVideo;
1807
- }
1808
- function parseVttSegment(url) {
1809
- const video = ensureDummyVideo();
1810
- const track = document.createElement("track");
1811
- track.kind = "subtitles";
1812
- track.default = true;
1813
- return new Promise((resolve, reject) => {
1814
- const onLoad = () => {
1815
- const cues = [];
1816
- const textTrack = track.track;
1817
- if (textTrack.cues) for (let i = 0; i < textTrack.cues.length; i++) {
1818
- const cue = textTrack.cues[i];
1819
- if (cue) cues.push(cue);
1820
- }
1821
- cleanup();
1822
- resolve(cues);
1823
- };
1824
- const onError = () => {
1825
- cleanup();
1826
- reject(/* @__PURE__ */ new Error(`Failed to load VTT segment: ${url}`));
1827
- };
1828
- const cleanup = () => {
1829
- track.removeEventListener("load", onLoad);
1830
- track.removeEventListener("error", onError);
1831
- video.removeChild(track);
1832
- };
1833
- track.addEventListener("load", onLoad);
1834
- track.addEventListener("error", onError);
1835
- video.appendChild(track);
1836
- track.src = url;
1837
- });
1838
- }
1839
- function destroyVttParser() {
1840
- dummyVideo = null;
1841
- }
1842
-
1843
- //#endregion
1844
- //#region src/dom/features/load-text-track-cues.ts
1845
- function isDuplicateCue(cue, textTrack) {
1846
- const { cues } = textTrack;
1847
- if (!cues) return false;
1848
- for (let i = 0; i < cues.length; i++) {
1849
- const existing = cues[i];
1850
- if (existing.startTime === cue.startTime && existing.endTime === cue.endTime && existing.text === cue.text) return true;
1851
- }
1852
- return false;
1853
- }
1854
- const loadVttSegmentTask = async ({ segment }, context) => {
1855
- const cues = await parseVttSegment(segment.url);
1856
- for (const cue of cues) if (!isDuplicateCue(cue, context.textTrack)) context.textTrack.addCue(cue);
1857
- };
1858
- /**
1859
- * Load text track cues task (composite - orchestrates VTT segment subtasks).
1860
- */
1861
- const loadTextTrackCuesTask = async ({ currentState }, context) => {
1862
- const track = findSelectedTextTrack(currentState);
1863
- if (!track || !isResolvedTrack(track)) return;
1864
- const { segments } = track;
1865
- if (segments.length === 0) return;
1866
- const trackId = track.id;
1867
- const loadedIds = new Set((currentState.textBufferState?.[trackId]?.segments ?? []).map((s) => s.id));
1868
- const segmentsToLoad = getSegmentsToLoad(segments, segments.filter((s) => loadedIds.has(s.id)), currentState.currentTime ?? 0).filter((s) => !loadedIds.has(s.id));
1869
- if (segmentsToLoad.length === 0) return;
1870
- for (const segment of segmentsToLoad) {
1871
- if (context.signal.aborted) break;
1872
- try {
1873
- await loadVttSegmentTask({ segment }, { textTrack: context.textTrack });
1874
- const latest = context.state.current.textBufferState ?? {};
1875
- const trackState = latest[trackId] ?? { segments: [] };
1876
- context.state.patch({ textBufferState: {
1877
- ...latest,
1878
- [trackId]: { segments: [...trackState.segments, { id: segment.id }] }
1879
- } });
1880
- } catch (error) {
1881
- if (error instanceof Error && error.name === "AbortError") break;
1882
- console.error("Failed to load VTT segment:", error);
1883
- }
1884
- }
1885
- if (context.textTrack.mode === "showing" && context.textTrack.cues) Array.from(context.textTrack.cues).forEach((cue) => {
1886
- context.textTrack.addCue(cue);
1887
- });
1888
- await new Promise((resolve) => requestAnimationFrame(resolve));
1889
- };
1890
- /**
1891
- * Find the selected text track in the presentation.
1892
- */
1893
- function findSelectedTextTrack(state) {
1894
- if (!state.presentation || !state.selectedTextTrackId) return;
1895
- const textSet = state.presentation.selectionSets.find((set) => set.type === "text");
1896
- if (!textSet?.switchingSets?.[0]?.tracks) return;
1897
- return textSet.switchingSets[0].tracks.find((t) => t.id === state.selectedTextTrackId);
1898
- }
1899
- /**
1900
- * Get the browser's TextTrack object for the selected text track.
1901
- *
1902
- * Retrieves the live TextTrack interface from the track element in owners,
1903
- * which is used for adding cues, checking mode, and managing track state.
1904
- *
1905
- * Note: Returns the DOM TextTrack interface (HTMLTrackElement.track),
1906
- * not the presentation Track metadata type.
1907
- *
1908
- * @param state - Current playback state (track selection)
1909
- * @param owners - DOM owners containing track elements map
1910
- * @returns DOM TextTrack interface or undefined if not found
1911
- */
1912
- function getSelectedTextTrackFromOwners(state, owners) {
1913
- const trackId = state.selectedTextTrackId;
1914
- if (!trackId || !owners.textTracks) return;
1915
- return owners.textTracks.get(trackId)?.track;
1916
- }
1917
- /**
1918
- * Check if we can load text track cues.
1919
- *
1920
- * Requires:
1921
- * - Selected text track ID exists
1922
- * - Track elements map exists
1923
- * - Track element exists for selected track
1924
- */
1925
- function canLoadTextTrackCues(state, owners) {
1926
- return !!state.selectedTextTrackId && !!owners.textTracks && owners.textTracks.has(state.selectedTextTrackId);
1927
- }
1928
- /**
1929
- * Check if we should load text track cues.
1930
- *
1931
- * Only load if:
1932
- * - Track is resolved (has segments)
1933
- * - Track has at least one segment
1934
- * - Track element exists
1935
- */
1936
- function shouldLoadTextTrackCues(state, owners) {
1937
- if (!canLoadTextTrackCues(state, owners)) return false;
1938
- const track = findSelectedTextTrack(state);
1939
- if (!track || !isResolvedTrack(track) || track.segments.length === 0) return false;
1940
- if (!getSelectedTextTrackFromOwners(state, owners)) return false;
1941
- return true;
1942
- }
1943
- /**
1944
- * Load text track cues orchestration.
1945
- *
1946
- * Triggers when:
1947
- * - Text track is selected
1948
- * - Track is resolved (has segments)
1949
- * - Track element exists
1950
- *
1951
- * Fetches and parses VTT segments within the forward buffer window, then adds
1952
- * cues to the track incrementally. Continues on segment errors to provide
1953
- * partial subtitles.
1954
- *
1955
- * @example
1956
- * const cleanup = loadTextTrackCues({ state, owners });
1957
- */
1958
- function loadTextTrackCues({ state, owners }) {
1959
- let currentTask = null;
1960
- let abortController = null;
1961
- let lastTrackId;
1962
- const cleanup = combineLatest([state, owners]).subscribe(async ([currentState, currentOwners]) => {
1963
- if (currentState.selectedTextTrackId !== lastTrackId) {
1964
- lastTrackId = currentState.selectedTextTrackId;
1965
- abortController?.abort();
1966
- currentTask = null;
1967
- }
1968
- if (currentTask) return;
1969
- if (!shouldLoadTextTrackCues(currentState, currentOwners)) return;
1970
- const textTrack = getSelectedTextTrackFromOwners(currentState, currentOwners);
1971
- if (!textTrack) return;
1972
- abortController = new AbortController();
1973
- currentTask = loadTextTrackCuesTask({ currentState }, {
1974
- signal: abortController.signal,
1975
- textTrack,
1976
- state
1977
- }).finally(() => {
1978
- currentTask = null;
1979
- });
1980
- });
1981
- return () => {
1982
- abortController?.abort();
1983
- cleanup();
1984
- };
1985
- }
1986
-
1987
- //#endregion
1988
- //#region src/dom/features/track-current-time.ts
1989
- /**
1990
- * Track current playback position from the media element.
1991
- *
1992
- * Mirrors `mediaElement.currentTime` into reactive state on:
1993
- * - `timeupdate` — fires during playback (~4 Hz)
1994
- * - `seeking` — fires when a seek begins; per spec, `currentTime` is
1995
- * already at the new position when this event dispatches, so buffer
1996
- * management can react immediately rather than waiting for `timeupdate`,
1997
- * which does not fire while paused.
1998
- *
1999
- * Also syncs immediately when a media element becomes available.
2000
- *
2001
- * @example
2002
- * const cleanup = trackCurrentTime({ state, owners });
2003
- */
2004
- function trackCurrentTime({ state, owners }) {
2005
- let lastMediaElement;
2006
- let removeListeners = null;
2007
- const unsubscribe = owners.subscribe((currentOwners) => {
2008
- const { mediaElement } = currentOwners;
2009
- if (mediaElement === lastMediaElement) return;
2010
- removeListeners?.();
2011
- removeListeners = null;
2012
- lastMediaElement = mediaElement;
2013
- if (!mediaElement) return;
2014
- state.patch({ currentTime: mediaElement.currentTime });
2015
- const sync = () => state.patch({ currentTime: mediaElement.currentTime });
2016
- const removeTimeupdate = listen(mediaElement, "timeupdate", sync);
2017
- const removeSeeking = listen(mediaElement, "seeking", sync);
2018
- removeListeners = () => {
2019
- removeTimeupdate();
2020
- removeSeeking();
2021
- };
2022
- });
2023
- return () => {
2024
- removeListeners?.();
2025
- unsubscribe();
2026
- };
2027
- }
2028
-
2029
- //#endregion
2030
- //#region src/dom/features/track-playback-initiated.ts
2031
- /**
2032
- * Track whether playback has been initiated by the user.
2033
- *
2034
- * Sets `state.playbackInitiated = true` when the media element fires a `play`
2035
- * event (via `element.play()`, native controls, or autoplay) and simultaneously
2036
- * dispatches `{ type: 'play' }` to the event stream so `resolvePresentation`
2037
- * can react.
2038
- *
2039
- * Resets `state.playbackInitiated = false` when `presentation.url` changes,
2040
- * so a new source with `preload="none"` won't load segments until play is
2041
- * triggered again.
2042
- *
2043
- * This flag is used by `shouldLoadSegments` to allow segment loading after
2044
- * play is initiated regardless of the initial `preload` setting — `preload`
2045
- * is a startup hint, not a runtime gate.
2046
- *
2047
- * @example
2048
- * const cleanup = trackPlaybackInitiated({ state, owners, events });
2049
- */
2050
- function trackPlaybackInitiated({ state, owners, events }) {
2051
- let lastMediaElement;
2052
- let removeListener = null;
2053
- let lastPresentationUrl;
2054
- const unsubscribeState = state.subscribe((currentState) => {
2055
- const url = currentState.presentation?.url;
2056
- if (url !== lastPresentationUrl) {
2057
- if (lastPresentationUrl !== void 0) state.patch({ playbackInitiated: false });
2058
- lastPresentationUrl = url;
2059
- }
2060
- });
2061
- const unsubscribeOwners = owners.subscribe((currentOwners) => {
2062
- const { mediaElement } = currentOwners;
2063
- if (mediaElement === lastMediaElement) return;
2064
- removeListener?.();
2065
- removeListener = null;
2066
- lastMediaElement = mediaElement;
2067
- if (!mediaElement) return;
2068
- removeListener = listen(mediaElement, "play", () => {
2069
- state.patch({ playbackInitiated: true });
2070
- events.dispatch({ type: "play" });
2071
- });
2072
- });
2073
- return () => {
2074
- removeListener?.();
2075
- unsubscribeState();
2076
- unsubscribeOwners();
2077
- };
2078
- }
2079
-
2080
- //#endregion
2081
- //#region src/dom/media/append-segment.ts
2082
- /**
2083
- * Segment appender helper (P11)
2084
- *
2085
- * Appends media segments (ArrayBuffer) to SourceBuffer.
2086
- */
2087
- /**
2088
- * Append a media segment to a SourceBuffer.
2089
- *
2090
- * Waits for the SourceBuffer to be ready (not updating), then appends
2091
- * the segment data. Returns a promise that resolves when append completes.
2092
- *
2093
- * @param sourceBuffer - The SourceBuffer to append to
2094
- * @param segmentData - The segment data as ArrayBuffer
2095
- * @returns Promise that resolves when append completes
2096
- *
2097
- * @example
2098
- * const data = await fetch(segmentUrl).then(r => r.arrayBuffer());
2099
- * await appendSegment(videoSourceBuffer, data);
2100
- */
2101
- async function appendSegment(sourceBuffer, segmentData) {
2102
- if (sourceBuffer.updating) await new Promise((resolve) => {
2103
- const onUpdateEnd = () => {
2104
- sourceBuffer.removeEventListener("updateend", onUpdateEnd);
2105
- resolve();
2106
- };
2107
- sourceBuffer.addEventListener("updateend", onUpdateEnd);
2108
- });
2109
- return new Promise((resolve, reject) => {
2110
- const onUpdateEnd = () => {
2111
- cleanup();
2112
- resolve();
2113
- };
2114
- const onError = (event) => {
2115
- cleanup();
2116
- reject(/* @__PURE__ */ new Error(`SourceBuffer append error: ${event.type}`));
2117
- };
2118
- const cleanup = () => {
2119
- sourceBuffer.removeEventListener("updateend", onUpdateEnd);
2120
- sourceBuffer.removeEventListener("error", onError);
2121
- };
2122
- sourceBuffer.addEventListener("updateend", onUpdateEnd);
2123
- sourceBuffer.addEventListener("error", onError);
2124
- try {
2125
- sourceBuffer.appendBuffer(segmentData);
2126
- } catch (error) {
2127
- cleanup();
2128
- reject(error);
2129
- }
2130
- });
2131
- }
2132
-
2133
- //#endregion
2134
- //#region src/dom/media/buffer-flusher.ts
2135
- /**
2136
- * Buffer flusher helper (P12)
2137
- *
2138
- * Removes a time range from a SourceBuffer to manage memory.
2139
- */
2140
- /**
2141
- * Remove a time range from a SourceBuffer.
2142
- *
2143
- * Waits for the SourceBuffer to be ready (not updating), then removes
2144
- * the specified range. Returns a promise that resolves when removal completes.
2145
- *
2146
- * @param sourceBuffer - The SourceBuffer to remove data from
2147
- * @param start - Start of the time range to remove (seconds)
2148
- * @param end - End of the time range to remove (seconds)
2149
- * @returns Promise that resolves when removal completes
2150
- *
2151
- * @example
2152
- * await flushBuffer(videoSourceBuffer, 0, 30);
2153
- */
2154
- async function flushBuffer(sourceBuffer, start, end) {
2155
- if (sourceBuffer.updating) await new Promise((resolve) => {
2156
- const onUpdateEnd = () => {
2157
- sourceBuffer.removeEventListener("updateend", onUpdateEnd);
2158
- resolve();
2159
- };
2160
- sourceBuffer.addEventListener("updateend", onUpdateEnd);
2161
- });
2162
- return new Promise((resolve, reject) => {
2163
- const onUpdateEnd = () => {
2164
- cleanup();
2165
- resolve();
2166
- };
2167
- const onError = (event) => {
2168
- cleanup();
2169
- reject(/* @__PURE__ */ new Error(`SourceBuffer remove error: ${event.type}`));
2170
- };
2171
- const cleanup = () => {
2172
- sourceBuffer.removeEventListener("updateend", onUpdateEnd);
2173
- sourceBuffer.removeEventListener("error", onError);
2174
- };
2175
- sourceBuffer.addEventListener("updateend", onUpdateEnd);
2176
- sourceBuffer.addEventListener("error", onError);
2177
- try {
2178
- sourceBuffer.remove(start, end);
2179
- } catch (error) {
2180
- cleanup();
2181
- reject(error);
2182
- }
2183
- });
2184
- }
2185
-
2186
- //#endregion
2187
- //#region src/core/features/calculate-presentation-duration.ts
2188
- /**
2189
- * Check if we can calculate presentation duration (have required data).
2190
- */
2191
- function canCalculateDuration(state) {
2192
- if (!state.presentation) return false;
2193
- return !!(state.selectedVideoTrackId || state.selectedAudioTrackId);
2194
- }
2195
- /**
2196
- * Check if we should calculate presentation duration (conditions met).
2197
- */
2198
- function shouldCalculateDuration(state) {
2199
- if (!canCalculateDuration(state)) return false;
2200
- const { presentation } = state;
2201
- if (presentation.duration !== void 0) return false;
2202
- const videoTrack = state.selectedVideoTrackId ? getSelectedTrack(state, "video") : void 0;
2203
- const audioTrack = state.selectedAudioTrackId ? getSelectedTrack(state, "audio") : void 0;
2204
- return !!(videoTrack && isResolvedTrack(videoTrack) || audioTrack && isResolvedTrack(audioTrack));
2205
- }
2206
- /**
2207
- * Get duration from the first resolved track (prefer video, fallback to audio).
2208
- */
2209
- function getDurationFromResolvedTracks(state) {
2210
- const videoTrack = state.selectedVideoTrackId ? getSelectedTrack(state, "video") : void 0;
2211
- if (videoTrack && isResolvedTrack(videoTrack)) return videoTrack.duration;
2212
- const audioTrack = state.selectedAudioTrackId ? getSelectedTrack(state, "audio") : void 0;
2213
- if (audioTrack && isResolvedTrack(audioTrack)) return audioTrack.duration;
2214
- }
2215
- /**
2216
- * Calculate and set presentation duration from resolved tracks.
2217
- */
2218
- function calculatePresentationDuration({ state }) {
2219
- return combineLatest([state]).subscribe(([currentState]) => {
2220
- if (!shouldCalculateDuration(currentState)) return;
2221
- const duration = getDurationFromResolvedTracks(currentState);
2222
- if (duration === void 0 || !Number.isFinite(duration)) return;
2223
- const { presentation } = currentState;
2224
- state.patch({ presentation: {
2225
- ...presentation,
2226
- duration
2227
- } });
2228
- });
2229
- }
2230
-
2231
- //#endregion
2232
- //#region src/core/task.ts
2233
- /**
2234
- * Generic reusable task that wraps an async run function.
2235
- *
2236
- * Owns its own AbortController so it can always be aborted independently.
2237
- * Optionally composes an external AbortSignal so that a parent's cancellation
2238
- * propagates into the task's work without requiring the caller to track the
2239
- * task separately.
2240
- *
2241
- * Ordering guarantee: `value` is written before `status` transitions to `'done'`;
2242
- * `error` is written before `status` transitions to `'error'`. Any reader
2243
- * observing `status === 'done'` is guaranteed `value` is already present.
2244
- */
2245
- var Task = class {
2246
- id;
2247
- #runFn;
2248
- #abortController = new AbortController();
2249
- #signal;
2250
- #status = "pending";
2251
- #value = void 0;
2252
- #error = void 0;
2253
- constructor(runFn, config) {
2254
- this.#runFn = runFn;
2255
- const rawId = config?.id;
2256
- this.id = typeof rawId === "function" ? rawId() : rawId ?? generateId();
2257
- this.#signal = config?.signal ? AbortSignal.any([this.#abortController.signal, config.signal]) : this.#abortController.signal;
2258
- }
2259
- get status() {
2260
- return this.#status;
2261
- }
2262
- get value() {
2263
- return this.#value;
2264
- }
2265
- get error() {
2266
- return this.#error;
2267
- }
2268
- async run() {
2269
- this.#status = "running";
2270
- try {
2271
- const result = await this.#runFn(this.#signal);
2272
- this.#value = result;
2273
- this.#status = "done";
2274
- return result;
2275
- } catch (e) {
2276
- this.#error = e;
2277
- this.#status = "error";
2278
- throw e;
2279
- }
2280
- }
2281
- abort() {
2282
- this.#abortController.abort();
2283
- }
2284
- };
2285
- /**
2286
- * Runs tasks concurrently, deduplicated by task id.
2287
- *
2288
- * If a task with a given id is already in flight, subsequent schedule() calls
2289
- * for that id are silently ignored until the first completes. Tasks are stored
2290
- * so abortAll() can cancel any in-flight work (e.g. on engine cleanup).
2291
- */
2292
- var ConcurrentRunner = class {
2293
- #pending = /* @__PURE__ */ new Map();
2294
- schedule(task) {
2295
- if (this.#pending.has(task.id)) return;
2296
- this.#pending.set(task.id, task);
2297
- task.run().catch((error) => {
2298
- if (!(error instanceof Error && error.name === "AbortError")) throw error;
2299
- }).finally(() => {
2300
- this.#pending.delete(task.id);
2301
- });
2302
- }
2303
- abortAll() {
2304
- for (const task of this.#pending.values()) task.abort();
2305
- this.#pending.clear();
2306
- }
2307
- };
2308
- /**
2309
- * Runs tasks one at a time in submission order.
2310
- *
2311
- * Each schedule() call returns a Promise that resolves or rejects with the
2312
- * task's result when it is eventually executed. Tasks wait in queue until the
2313
- * prior task completes.
2314
- *
2315
- * Serialization is achieved by chaining each task's run() onto the tail of a
2316
- * shared promise chain — no explicit queue or drain loop needed.
2317
- *
2318
- * abortAll() aborts all pending (not yet started) tasks and the currently
2319
- * in-flight task. Pending tasks still run briefly but receive an aborted
2320
- * signal and are expected to exit early.
2321
- */
2322
- var SerialRunner = class {
2323
- #chain = Promise.resolve();
2324
- #pending = /* @__PURE__ */ new Set();
2325
- #current = null;
2326
- schedule(task) {
2327
- const t = task;
2328
- this.#pending.add(t);
2329
- const result = this.#chain.then(() => {
2330
- this.#pending.delete(t);
2331
- this.#current = t;
2332
- return task.run();
2333
- }).finally(() => {
2334
- this.#current = null;
2335
- });
2336
- this.#chain = result.then(() => {}, () => {});
2337
- return result;
2338
- }
2339
- abortAll() {
2340
- for (const task of this.#pending) task.abort();
2341
- this.#pending.clear();
2342
- this.#current?.abort();
2343
- }
2344
- destroy() {
2345
- this.abortAll();
2346
- }
2347
- };
2348
-
2349
- //#endregion
2350
- //#region src/core/features/resolve-track.ts
2351
- function canResolve(state, config) {
2352
- const track = getSelectedTrack(state, config.type);
2353
- if (!track) return false;
2354
- return !isResolvedTrack(track);
2355
- }
2356
- /**
2357
- * Determines if track resolution conditions are met.
2358
- *
2359
- * Currently always returns true - conditions are checked by canResolveTrack()
2360
- * and resolving flag. Kept as placeholder for future conditional logic.
2361
- *
2362
- * @param state - Current track resolution state
2363
- * @param event - Current action/event
2364
- * @returns true (conditions checked elsewhere)
2365
- */
2366
- function shouldResolve(_state, _event) {
2367
- return true;
2368
- }
2369
- /**
2370
- * Updates a track within a presentation (immutably).
2371
- * Generic - works for video, audio, or text tracks.
2372
- */
2373
- function updateTrackInPresentation(presentation, resolvedTrack) {
2374
- const trackId = resolvedTrack.id;
2375
- return {
2376
- ...presentation,
2377
- selectionSets: presentation.selectionSets.map((selectionSet) => ({
2378
- ...selectionSet,
2379
- switchingSets: selectionSet.switchingSets.map((switchingSet) => ({
2380
- ...switchingSet,
2381
- tracks: switchingSet.tracks.map((track) => track.id === trackId ? resolvedTrack : track)
2382
- }))
2383
- }))
2384
- };
2385
- }
2386
- /**
2387
- * Resolves unresolved tracks using reactive composition.
2388
- *
2389
- * The subscribe closure is pure scheduling logic: it checks conditions and
2390
- * creates a Task for the selected track when appropriate. The ConcurrentRunner
2391
- * handles all concurrency concerns — deduplication, parallel execution, and
2392
- * cleanup.
2393
- *
2394
- * Generic version that works for video, audio, or text tracks based on config.
2395
- * Type parameter T is inferred from config.type (use 'as const' for inference).
2396
- */
2397
- function resolveTrack({ state, events }, config) {
2398
- const runner = new ConcurrentRunner();
2399
- const cleanup = combineLatest([state, events]).subscribe(([currentState, event]) => {
2400
- if (!canResolve(currentState, config) || !shouldResolve(currentState, event)) return;
2401
- const track = getSelectedTrack(currentState, config.type);
2402
- if (!track) return;
2403
- const resolvedTrack = track;
2404
- runner.schedule(new Task(async (signal) => {
2405
- const mediaTrack = parseMediaPlaylist(await getResponseText(await fetchResolvable(resolvedTrack, { signal })), resolvedTrack);
2406
- const latestPresentation = state.current.presentation;
2407
- const updatedPresentation = updateTrackInPresentation(latestPresentation, mediaTrack);
2408
- state.patch({ presentation: updatedPresentation });
2409
- }, { id: track.id }));
2410
- });
2411
- return () => {
2412
- runner.abortAll();
2413
- cleanup();
2414
- };
2415
- }
2416
-
2417
- //#endregion
2418
- //#region src/core/features/select-tracks.ts
2419
- /**
2420
- * Pick text track to activate.
2421
- *
2422
- * Selection priority (if enabled):
2423
- * 1. User preference (preferredSubtitleLanguage)
2424
- * 2. DEFAULT track (if enableDefaultTrack is true and track has DEFAULT=YES + AUTOSELECT=YES)
2425
- * 3. No auto-selection (user opt-in)
2426
- *
2427
- * By default, FORCED tracks are excluded per Apple's HLS spec.
2428
- *
2429
- * @param presentation - Presentation with text tracks
2430
- * @param config - Selection configuration
2431
- * @returns Track ID or undefined (no auto-selection)
2432
- */
2433
- function pickTextTrack(presentation, config) {
2434
- const textSet = presentation.selectionSets.find((set) => set.type === "text");
2435
- if (!textSet?.switchingSets?.[0]?.tracks.length) return void 0;
2436
- const tracks = textSet.switchingSets[0].tracks;
2437
- const availableTracks = config.includeForcedTracks ? tracks : tracks.filter((track) => !track.forced);
2438
- if (availableTracks.length === 0) return void 0;
2439
- const { preferredSubtitleLanguage, enableDefaultTrack = false } = config;
2440
- if (preferredSubtitleLanguage) {
2441
- const languageMatch = availableTracks.find((track) => track.language === preferredSubtitleLanguage);
2442
- if (languageMatch) return languageMatch.id;
2443
- }
2444
- if (enableDefaultTrack) {
2445
- const defaultTrack = availableTracks.find((track) => track.default === true);
2446
- if (defaultTrack) return defaultTrack.id;
2447
- }
2448
- }
2449
- /**
2450
- * Check if we can select a track of the given type.
2451
- *
2452
- * Returns true when:
2453
- * - Presentation exists
2454
- * - Has tracks of the specified type
2455
- *
2456
- * Generic over track type - works for video, audio, or text.
2457
- */
2458
- function canSelectTrack(state, config) {
2459
- return !!state?.presentation?.selectionSets?.find(({ type }) => type === config.type)?.switchingSets?.[0]?.tracks.length;
2460
- }
2461
- /**
2462
- * Check if we should select a track of the given type.
2463
- *
2464
- * Returns true when:
2465
- * - Track of this type is not already selected
2466
- *
2467
- * Generic over track type - works for video, audio, or text.
2468
- *
2469
- * @TODO figure out reactive model for ABR cases - right now we're only selecting
2470
- * if we have nothing selected (CJP)
2471
- */
2472
- function shouldSelectTrack(state, config) {
2473
- return !state[SelectedTrackIdKeyByType[config.type]];
2474
- }
2475
- /**
2476
- * Select video track orchestration.
2477
- *
2478
- * Selects video track when:
2479
- * - Presentation exists
2480
- * - No video track is selected yet
2481
- *
2482
- * Uses bandwidth-based quality selection algorithm.
2483
- *
2484
- * @example
2485
- * const cleanup = selectVideoTrack(
2486
- * { state, owners, events },
2487
- * { initialBandwidth: 2_000_000 }
2488
- * );
2489
- */
2490
- function selectVideoTrack({ state }, config = { type: "video" }) {
2491
- let selecting = false;
2492
- return state.subscribe(async (currentState) => {
2493
- if (!canSelectTrack(currentState, config) || !shouldSelectTrack(currentState, config) || selecting) return;
2494
- try {
2495
- selecting = true;
2496
- const selectedTrackId = currentState.presentation?.selectionSets.find(({ type }) => type === config.type)?.switchingSets[0]?.tracks[0]?.id;
2497
- if (selectedTrackId) {
2498
- const selectedTrackKey = SelectedTrackIdKeyByType[config.type];
2499
- state.patch({ [selectedTrackKey]: selectedTrackId });
2500
- }
2501
- } finally {
2502
- selecting = false;
2503
- }
2504
- });
2505
- }
2506
- /**
2507
- * Select audio track orchestration.
2508
- *
2509
- * Selects audio track when:
2510
- * - Presentation exists
2511
- * - No audio track is selected yet
2512
- *
2513
- * Uses language and preference-based selection.
2514
- *
2515
- * @example
2516
- * const cleanup = selectAudioTrack(
2517
- * { state, owners, events },
2518
- * { preferredAudioLanguage: 'en' }
2519
- * );
2520
- */
2521
- function selectAudioTrack({ state }, config = { type: "audio" }) {
2522
- let selecting = false;
2523
- return state.subscribe(async (currentState) => {
2524
- if (!canSelectTrack(currentState, config) || !shouldSelectTrack(currentState, config) || selecting) return;
2525
- try {
2526
- selecting = true;
2527
- const selectedTrackId = currentState.presentation?.selectionSets.find(({ type }) => type === "audio")?.switchingSets[0]?.tracks[0]?.id;
2528
- if (selectedTrackId) state.patch({ selectedAudioTrackId: selectedTrackId });
2529
- } finally {
2530
- selecting = false;
2531
- }
2532
- });
2533
- }
2534
- /**
2535
- * Select text track orchestration.
2536
- *
2537
- * Selects text track when:
2538
- * - Presentation exists
2539
- * - No text track is selected yet
2540
- *
2541
- * Note: Currently does not auto-select (user opt-in).
2542
- *
2543
- * @example
2544
- * const cleanup = selectTextTrack({ state, owners, events }, {});
2545
- */
2546
- function selectTextTrack({ state }, config = { type: "text" }) {
2547
- let selecting = false;
2548
- return state.subscribe(async (currentState) => {
2549
- if (!canSelectTrack(currentState, config) || !shouldSelectTrack(currentState, config) || selecting) return;
2550
- try {
2551
- selecting = true;
2552
- const selectedTextTrackId = pickTextTrack(currentState.presentation, config);
2553
- if (selectedTextTrackId) state.patch({ selectedTextTrackId });
2554
- } finally {
2555
- selecting = false;
2556
- }
2557
- });
2558
- }
2559
-
2560
- //#endregion
2561
- //#region src/dom/features/end-of-stream.ts
2562
- /**
2563
- * Check if the last segment of a track has been appended to a SourceBuffer.
2564
- *
2565
- * Checks by segment ID rather than a pipeline flag, so it is robust across
2566
- * quality switches (different tracks have different segment IDs) and
2567
- * back-buffer flushes (flushed segment IDs are removed from the model).
2568
- */
2569
- function isLastSegmentAppended(segments, actor) {
2570
- if (segments.length === 0) return true;
2571
- const lastSeg = segments[segments.length - 1];
2572
- if (!lastSeg) return false;
2573
- return actor?.snapshot.context.segments.some((s) => s.id === lastSeg.id) ?? false;
2574
- }
2575
- /**
2576
- * Check if the last segment has been appended for each selected track.
2577
- *
2578
- * Handles video-only, audio-only, and video+audio scenarios.
2579
- * A track with no segments (e.g. unresolved) is considered not ready.
2580
- */
2581
- function hasLastSegmentLoaded(state, owners) {
2582
- const videoTrack = state.selectedVideoTrackId ? getSelectedTrack(state, "video") : void 0;
2583
- const audioTrack = state.selectedAudioTrackId ? getSelectedTrack(state, "audio") : void 0;
2584
- if (videoTrack && !isResolvedTrack(videoTrack)) return false;
2585
- if (audioTrack && !isResolvedTrack(audioTrack)) return false;
2586
- if (videoTrack && isResolvedTrack(videoTrack)) {
2587
- if (!isLastSegmentAppended(videoTrack.segments, owners.videoBufferActor)) return false;
2588
- }
2589
- if (audioTrack && isResolvedTrack(audioTrack)) {
2590
- if (!isLastSegmentAppended(audioTrack.segments, owners.audioBufferActor)) return false;
2591
- }
2592
- return true;
2593
- }
2594
- /**
2595
- * Check if we can call endOfStream.
2596
- */
2597
- function canEndStream(state, owners) {
2598
- return !!(owners.mediaSource && state.presentation);
2599
- }
2600
- /**
2601
- * Check if we should call endOfStream.
2602
- */
2603
- function shouldEndStream(state, owners) {
2604
- if (!canEndStream(state, owners)) return false;
2605
- const { mediaSource, mediaElement } = owners;
2606
- if (mediaSource.readyState !== "open") return false;
2607
- if (mediaElement && mediaElement.readyState < HTMLMediaElement.HAVE_METADATA) return false;
2608
- const hasVideoTrack = !!state.selectedVideoTrackId;
2609
- const hasAudioTrack = !!state.selectedAudioTrackId;
2610
- if (hasVideoTrack && !owners.videoBuffer) return false;
2611
- if (hasAudioTrack && !owners.audioBuffer) return false;
2612
- if (owners.videoBufferActor?.snapshot.status === "updating") return false;
2613
- if (owners.audioBufferActor?.snapshot.status === "updating") return false;
2614
- if (!hasLastSegmentLoaded(state, owners)) return false;
2615
- if (mediaElement) {
2616
- const videoTrack = hasVideoTrack ? getSelectedTrack(state, "video") : void 0;
2617
- const audioTrack = hasAudioTrack ? getSelectedTrack(state, "audio") : void 0;
2618
- const refTrack = videoTrack && isResolvedTrack(videoTrack) ? videoTrack : audioTrack && isResolvedTrack(audioTrack) ? audioTrack : void 0;
2619
- if (refTrack && refTrack.segments.length > 0) {
2620
- const lastSeg = refTrack.segments[refTrack.segments.length - 1];
2621
- if (mediaElement.currentTime < lastSeg.startTime) return false;
2622
- }
2623
- }
2624
- return true;
2625
- }
2626
- /**
2627
- * Wait for all currently-updating SourceBufferActors to finish.
2628
- * Uses actor status rather than raw SourceBuffer.updating so the wait is
2629
- * aligned with the same abstraction that owns all buffer operations.
2630
- */
2631
- function waitForSourceBuffersReady$1(owners) {
2632
- const updatingActors = [owners.videoBufferActor, owners.audioBufferActor].filter((actor) => actor !== void 0 && actor.snapshot.status === "updating");
2633
- if (updatingActors.length === 0) return Promise.resolve();
2634
- return Promise.all(updatingActors.map((actor) => new Promise((resolve) => {
2635
- const unsub = actor.subscribe((snapshot) => {
2636
- if (snapshot.status !== "updating") {
2637
- unsub();
2638
- resolve();
2639
- }
2640
- });
2641
- }))).then(() => void 0);
2642
- }
2643
- /**
2644
- * Get the highest buffered end time across all active SourceBuffers.
2645
- * Used to set the final duration from actual container timestamps rather
2646
- * than playlist metadata, which handles both shorter and longer cases.
2647
- */
2648
- function getMaxBufferedEnd$1(owners) {
2649
- let max = 0;
2650
- for (const buf of [owners.videoBuffer, owners.audioBuffer]) if (buf && buf.buffered.length > 0) {
2651
- const end = buf.buffered.end(buf.buffered.length - 1);
2652
- if (end > max) max = end;
2653
- }
2654
- return max;
2655
- }
2656
- /**
2657
- * End of stream task (module-level, pure).
2658
- * Sets the final duration from actual buffered end time, then calls endOfStream().
2659
- */
2660
- const endOfStreamTask = async ({ currentOwners }, _context) => {
2661
- const { mediaSource } = currentOwners;
2662
- if (mediaSource.readyState === "ended") return;
2663
- await waitForSourceBuffersReady$1(currentOwners);
2664
- if (mediaSource.readyState !== "open") return;
2665
- const bufferedEnd = getMaxBufferedEnd$1(currentOwners);
2666
- if (bufferedEnd > 0) mediaSource.duration = bufferedEnd;
2667
- mediaSource.endOfStream();
2668
- await new Promise((resolve) => requestAnimationFrame(resolve));
2669
- };
2670
- /**
2671
- * Call endOfStream when the last segment has been appended.
2672
- * This signals to the browser that the stream is complete.
2673
- *
2674
- * Per the MSE spec, appendBuffer() remains valid after endOfStream() —
2675
- * seeks that require re-appending earlier segments will still work.
2676
- * What becomes blocked is calling endOfStream() again, addSourceBuffer(),
2677
- * and MediaSource.duration updates.
2678
- */
2679
- function endOfStream({ state, owners }) {
2680
- let hasEnded = false;
2681
- let destroyed = false;
2682
- const activeActorUnsubs = [];
2683
- const runEvaluate = async () => {
2684
- if (destroyed) return;
2685
- const currentState = state.current;
2686
- const currentOwners = owners.current;
2687
- if (hasEnded) {
2688
- if (currentOwners.mediaSource?.readyState !== "open") return;
2689
- hasEnded = false;
2690
- }
2691
- if (!shouldEndStream(currentState, currentOwners)) return;
2692
- hasEnded = true;
2693
- try {
2694
- await endOfStreamTask({ currentOwners }, {});
2695
- } catch (error) {
2696
- console.error("Failed to call endOfStream:", error);
2697
- }
2698
- };
2699
- const cleanupOwners = owners.subscribe((currentOwners) => {
2700
- activeActorUnsubs.forEach((u) => u());
2701
- activeActorUnsubs.length = 0;
2702
- for (const actor of [currentOwners.videoBufferActor, currentOwners.audioBufferActor]) {
2703
- if (!actor) continue;
2704
- let isFirst = true;
2705
- activeActorUnsubs.push(actor.subscribe(() => {
2706
- if (isFirst) {
2707
- isFirst = false;
2708
- return;
2709
- }
2710
- runEvaluate();
2711
- }));
2712
- }
2713
- });
2714
- const cleanupCombineLatest = combineLatest([state, owners]).subscribe(async () => runEvaluate());
2715
- return () => {
2716
- destroyed = true;
2717
- activeActorUnsubs.forEach((u) => u());
2718
- cleanupOwners();
2719
- cleanupCombineLatest();
2720
- };
2721
- }
2722
-
2723
- //#endregion
2724
- //#region src/dom/features/setup-mediasource.ts
2725
- /**
2726
- * Check if we have the minimum requirements to create MediaSource.
2727
- */
2728
- function canSetup(state, owners) {
2729
- return !isNil(owners.mediaElement) && !isNil(state.presentation?.url);
2730
- }
2731
- /**
2732
- * Check if we should proceed with MediaSource creation.
2733
- * Placeholder for future conditions (e.g., checking if already created).
2734
- */
2735
- function shouldSetup(_state, owners) {
2736
- return isNil(owners.mediaSource);
2737
- }
2738
- /**
2739
- * Setup MediaSource orchestration.
2740
- *
2741
- * Creates and attaches MediaSource when:
2742
- * - mediaElement exists in owners
2743
- * - presentation.url exists in state
2744
- *
2745
- * Updates owners.mediaSource after successful setup.
2746
- */
2747
- function setupMediaSource({ state, owners }) {
2748
- let settingUp = false;
2749
- let abortController = null;
2750
- const unsubscribe = combineLatest([state, owners]).subscribe(async ([currentState, currentOwners]) => {
2751
- if (!canSetup(currentState, currentOwners) || !shouldSetup(currentState, currentOwners) || settingUp) return;
2752
- try {
2753
- settingUp = true;
2754
- abortController = new AbortController();
2755
- const mediaSource = createMediaSource({ preferManaged: true });
2756
- attachMediaSource(mediaSource, currentOwners.mediaElement);
2757
- await waitForSourceOpen(mediaSource, abortController.signal);
2758
- owners.patch({ mediaSource });
2759
- } catch (error) {
2760
- if (error instanceof DOMException && error.name === "AbortError") return;
2761
- throw error;
2762
- } finally {
2763
- settingUp = false;
2764
- }
2765
- });
2766
- return () => {
2767
- abortController?.abort();
2768
- unsubscribe();
2769
- };
2770
- }
2771
-
2772
- //#endregion
2773
- //#region src/dom/media/source-buffer-actor.ts
2774
- /**
2775
- * Thrown when a message is sent to the actor in a state that does not
2776
- * accept messages (currently: 'updating').
2777
- */
2778
- var SourceBufferActorError = class extends Error {
2779
- constructor(message) {
2780
- super(message);
2781
- this.name = "SourceBufferActorError";
2782
- }
2783
- };
2784
- function snapshotBuffered(buffered) {
2785
- const ranges = [];
2786
- for (let i = 0; i < buffered.length; i++) ranges.push({
2787
- start: buffered.start(i),
2788
- end: buffered.end(i)
2789
- });
2790
- return ranges;
2791
- }
2792
- function appendInitTask(message, { signal, getCtx, sourceBuffer }) {
2793
- return new Task(async (taskSignal) => {
2794
- const ctx = getCtx();
2795
- if (taskSignal.aborted) return ctx;
2796
- await appendSegment(sourceBuffer, message.data);
2797
- return {
2798
- ...ctx,
2799
- initTrackId: message.meta.trackId
2800
- };
2801
- }, { signal });
2802
- }
2803
- function appendSegmentTask(message, { signal, getCtx, sourceBuffer }) {
2804
- return new Task(async (taskSignal) => {
2805
- const ctx = getCtx();
2806
- if (taskSignal.aborted) return ctx;
2807
- await appendSegment(sourceBuffer, message.data);
2808
- const { meta } = message;
2809
- const EPSILON = 1e-4;
2810
- const filtered = ctx.segments.filter((s) => Math.abs(s.startTime - meta.startTime) >= EPSILON);
2811
- return {
2812
- ...ctx,
2813
- segments: [...filtered, {
2814
- id: meta.id,
2815
- startTime: meta.startTime,
2816
- duration: meta.duration,
2817
- trackId: meta.trackId,
2818
- ...meta.trackBandwidth !== void 0 && { trackBandwidth: meta.trackBandwidth }
2819
- }],
2820
- bufferedRanges: snapshotBuffered(sourceBuffer.buffered)
2821
- };
2822
- }, { signal });
2823
- }
2824
- function removeTask(message, { signal, getCtx, sourceBuffer }) {
2825
- return new Task(async (taskSignal) => {
2826
- const ctx = getCtx();
2827
- if (taskSignal.aborted) return ctx;
2828
- await flushBuffer(sourceBuffer, message.start, message.end);
2829
- const bufferedRanges = snapshotBuffered(sourceBuffer.buffered);
2830
- const filtered = ctx.segments.filter((s) => {
2831
- const midpoint = s.startTime + s.duration / 2;
2832
- return bufferedRanges.some((r) => midpoint >= r.start && midpoint < r.end);
2833
- });
2834
- return {
2835
- ...ctx,
2836
- segments: filtered,
2837
- bufferedRanges
2838
- };
2839
- }, { signal });
2840
- }
2841
- const messageTaskFactories = {
2842
- "append-init": appendInitTask,
2843
- "append-segment": appendSegmentTask,
2844
- remove: removeTask
2845
- };
2846
- function messageToTask(message, options) {
2847
- const factory = messageTaskFactories[message.type];
2848
- return factory(message, options);
2849
- }
2850
- function createSourceBufferActor(sourceBuffer, initialContext) {
2851
- const state = createState({
2852
- status: "idle",
2853
- context: {
2854
- segments: [],
2855
- bufferedRanges: [],
2856
- initTrackId: void 0,
2857
- ...initialContext
2858
- }
2859
- });
2860
- const runner = new SerialRunner();
2861
- function applyResult(newContext) {
2862
- const status = state.current.status === "destroyed" ? "destroyed" : "idle";
2863
- state.patch({
2864
- status,
2865
- context: newContext
2866
- });
2867
- state.flush();
2868
- }
2869
- function handleError(e) {
2870
- const status = state.current.status === "destroyed" ? "destroyed" : "idle";
2871
- state.patch({ status });
2872
- state.flush();
2873
- throw e;
2874
- }
2875
- return {
2876
- get snapshot() {
2877
- return state.current;
2878
- },
2879
- subscribe(listener) {
2880
- return state.subscribe(listener);
2881
- },
2882
- send(message, signal) {
2883
- if (state.current.status !== "idle") return Promise.reject(new SourceBufferActorError(`send() called while actor is ${state.current.status}`));
2884
- state.patch({ status: "updating" });
2885
- const task = messageToTask(message, {
2886
- signal,
2887
- getCtx: () => state.current.context,
2888
- sourceBuffer
2889
- });
2890
- return runner.schedule(task).then(applyResult).catch(handleError);
2891
- },
2892
- batch(messages, signal) {
2893
- if (state.current.status !== "idle") return Promise.reject(new SourceBufferActorError(`batch() called while actor is ${state.current.status}`));
2894
- if (messages.length === 0) return Promise.resolve();
2895
- state.patch({ status: "updating" });
2896
- let workingCtx = state.current.context;
2897
- for (const message of messages.slice(0, -1)) {
2898
- const task = messageToTask(message, {
2899
- signal,
2900
- getCtx: () => workingCtx,
2901
- sourceBuffer
2902
- });
2903
- runner.schedule(task).then((newCtx) => {
2904
- workingCtx = newCtx;
2905
- });
2906
- }
2907
- const lastTask = messageToTask(messages[messages.length - 1], {
2908
- signal,
2909
- getCtx: () => workingCtx,
2910
- sourceBuffer
2911
- });
2912
- return runner.schedule(lastTask).then(applyResult).catch(handleError);
2913
- },
2914
- destroy() {
2915
- state.patch({ status: "destroyed" });
2916
- state.flush();
2917
- runner.destroy();
2918
- }
2919
- };
2920
- }
2921
-
2922
- //#endregion
2923
- //#region src/dom/features/setup-sourcebuffer.ts
2924
- /** Map track type to SourceBufferActor owner property key. */
2925
- const ActorKeyByType = {
2926
- video: "videoBufferActor",
2927
- audio: "audioBufferActor"
2928
- };
2929
- /**
2930
- * Setup SourceBuffer task (module-level, pure).
2931
- * Creates SourceBuffer for resolved track and waits a frame before completing.
2932
- */
2933
- const setupSourceBufferTask = async ({ currentState, currentOwners }, context) => {
2934
- const track = getSelectedTrack(currentState, context.config.type);
2935
- if (!track || !isResolvedTrack(track)) return;
2936
- if (!track.codecs || track.codecs.length === 0) return;
2937
- const mimeCodec = buildMimeCodec(track);
2938
- const buffer = createSourceBuffer(currentOwners.mediaSource, mimeCodec);
2939
- const actor = createSourceBufferActor(buffer);
2940
- const bufferKey = BufferKeyByType[context.config.type];
2941
- const actorKey = ActorKeyByType[context.config.type];
2942
- context.owners.patch({
2943
- [bufferKey]: buffer,
2944
- [actorKey]: actor
2945
- });
2946
- await new Promise((resolve) => requestAnimationFrame(resolve));
2947
- };
2948
- /**
2949
- * Build MIME codec string from track metadata.
2950
- *
2951
- * @param track - Resolved track with mimeType and codecs
2952
- * @returns MIME codec string (e.g., 'video/mp4; codecs="avc1.42E01E,mp4a.40.2"')
2953
- *
2954
- * @example
2955
- * buildMimeCodec({ mimeType: 'video/mp4', codecs: ['avc1.42E01E'] })
2956
- * // => 'video/mp4; codecs="avc1.42E01E"'
2957
- */
2958
- function buildMimeCodec(track) {
2959
- const codecString = track.codecs?.join(",") ?? "";
2960
- return `${track.mimeType}; codecs="${codecString}"`;
2961
- }
2962
- /**
2963
- * Check if we can setup SourceBuffer for track type.
2964
- *
2965
- * Requires:
2966
- * - MediaSource exists in owners
2967
- * - Track is selected
2968
- *
2969
- * Note: We don't check mediaSource.readyState because owners holds references
2970
- * to mutable objects. Changes to properties on those objects won't trigger
2971
- * observations. Instead, setupMediaSource only patches owners.mediaSource after
2972
- * it's already open, so if it exists in owners, it's ready to use.
2973
- *
2974
- * Note: Track does not need to be resolved yet. The orchestration will wait
2975
- * for the track to be resolved (via resolveTrack) before creating the SourceBuffer.
2976
- */
2977
- function canSetupBuffer(state, owners, type) {
2978
- if (!owners.mediaSource) return false;
2979
- if (!getSelectedTrack(state, type)) return false;
2980
- return true;
2981
- }
2982
- /**
2983
- * Check if we should create SourceBuffer (not already created).
2984
- */
2985
- function shouldSetupBuffer(owners, type) {
2986
- const bufferKey = BufferKeyByType[type];
2987
- return isUndefined(owners[bufferKey]);
2988
- }
2989
- /**
2990
- * Setup SourceBuffer orchestration.
2991
- *
2992
- * Triggers when:
2993
- * - MediaSource exists and is in 'open' state
2994
- * - Track is selected (same condition as resolveTrack)
2995
- *
2996
- * Creates SourceBuffer when track becomes resolved with codecs.
2997
- * This allows setupSourceBuffer to run in parallel with resolveTrack.
2998
- *
2999
- * Note: Text tracks don't use SourceBuffers and should be handled separately.
3000
- *
3001
- * Generic over track type - create one orchestration per track type:
3002
- * @example
3003
- * const videoCleanup = setupSourceBuffer({ state, owners }, { type: 'video' });
3004
- * const audioCleanup = setupSourceBuffer({ state, owners }, { type: 'audio' });
3005
- */
3006
- function setupSourceBuffer({ state, owners }, config) {
3007
- let currentTask = null;
3008
- return combineLatest([state, owners]).subscribe(async ([currentState, currentOwners]) => {
3009
- if (currentTask) return;
3010
- if (!canSetupBuffer(currentState, currentOwners, config.type) || !shouldSetupBuffer(currentOwners, config.type)) return;
3011
- currentTask = setupSourceBufferTask({
3012
- currentState,
3013
- currentOwners
3014
- }, {
3015
- owners,
3016
- config
3017
- });
3018
- try {
3019
- await currentTask;
3020
- } finally {
3021
- currentTask = null;
3022
- }
3023
- });
3024
- }
3025
-
3026
- //#endregion
3027
- //#region src/dom/features/setup-text-tracks.ts
3028
- /**
3029
- * Get all text tracks from presentation.
3030
- */
3031
- function getTextTracks(presentation) {
3032
- if (!presentation?.selectionSets) return [];
3033
- const textSet = presentation.selectionSets.find((set) => set.type === "text");
3034
- if (!textSet?.switchingSets?.[0]?.tracks) return [];
3035
- return textSet.switchingSets[0].tracks;
3036
- }
3037
- /**
3038
- * Check if we can setup text tracks.
3039
- *
3040
- * Requires:
3041
- * - mediaElement exists
3042
- * - presentation has text tracks to setup
3043
- */
3044
- function canSetupTextTracks(state, owners) {
3045
- return !!owners.mediaElement && !!getTextTracks(state.presentation).length;
3046
- }
3047
- /**
3048
- * Check if we should setup text tracks (not already set up).
3049
- */
3050
- function shouldSetupTextTracks(owners) {
3051
- return !owners.textTracks;
3052
- }
3053
- /**
3054
- * Create a track element for a text track.
3055
- *
3056
- * Note: We use DOM <track> elements instead of the TextTrack JS API
3057
- * because there's no way to remove TextTracks added via addTextTrack().
3058
- */
3059
- function createTrackElement(track) {
3060
- const trackElement = document.createElement("track");
3061
- trackElement.id = track.id;
3062
- trackElement.kind = track.kind;
3063
- trackElement.label = track.label;
3064
- if (track.language) trackElement.srclang = track.language;
3065
- if (track.default) trackElement.default = true;
3066
- trackElement.src = track.url;
3067
- return trackElement;
3068
- }
3069
- /**
3070
- * Setup text tracks orchestration.
3071
- *
3072
- * Triggers when:
3073
- * - mediaElement exists
3074
- * - presentation is resolved (has text tracks)
3075
- *
3076
- * Creates <track> elements for all text tracks and adds them as children
3077
- * to the media element. This allows the browser's native text track rendering.
3078
- *
3079
- * Note: Uses DOM track elements instead of TextTrack API because tracks
3080
- * added via addTextTrack() cannot be removed.
3081
- *
3082
- * @example
3083
- * const cleanup = setupTextTracks({ state, owners });
3084
- */
3085
- function setupTextTracks({ state, owners }) {
3086
- let hasSetup = false;
3087
- let createdTracks = [];
3088
- const unsubscribe = combineLatest([state, owners]).subscribe(([s, o]) => {
3089
- if (hasSetup) return;
3090
- if (!canSetupTextTracks(s, o) || !shouldSetupTextTracks(o)) return;
3091
- hasSetup = true;
3092
- const textTracks = getTextTracks(s.presentation);
3093
- if (textTracks.length === 0) return;
3094
- const trackMap = /* @__PURE__ */ new Map();
3095
- for (const track of textTracks) {
3096
- const trackElement = createTrackElement(track);
3097
- o.mediaElement.appendChild(trackElement);
3098
- trackMap.set(track.id, trackElement);
3099
- createdTracks.push(trackElement);
3100
- }
3101
- owners.patch({ textTracks: trackMap });
3102
- });
3103
- return () => {
3104
- for (const trackElement of createdTracks) trackElement.remove();
3105
- createdTracks = [];
3106
- unsubscribe();
3107
- };
3108
- }
3109
-
3110
- //#endregion
3111
- //#region src/dom/features/sync-selected-text-track-from-dom.ts
3112
- /**
3113
- * Sync selectedTextTrackId from DOM text track mode changes.
3114
- *
3115
- * Listens to the `change` event on `media.textTracks` and updates
3116
- * `selectedTextTrackId` when external code (e.g. the captions button via
3117
- * `toggleSubtitles()`) changes a subtitle/caption track mode to 'showing'.
3118
- *
3119
- * This bridges the core store's `toggleSubtitles()` with SPF's reactive text
3120
- * track pipeline (`syncTextTrackModes`, `loadTextTrackCues`). Without this
3121
- * bridge, direct DOM mode changes would be immediately overridden by
3122
- * `syncTextTrackModes` on the next SPF state update.
3123
- *
3124
- * When a subtitle/caption track's mode is 'showing', its DOM `id` — which
3125
- * matches the SPF track ID set by `setupTextTracks` — is written to
3126
- * `selectedTextTrackId`. When no subtitle/caption track is 'showing',
3127
- * `selectedTextTrackId` is cleared along with the deselected track's
3128
- * `textBufferState` entry — setting mode to 'disabled' clears native cues from
3129
- * the track element, so the buffer must be reset to re-fetch cues on re-enable.
3130
- *
3131
- * @example
3132
- * const cleanup = syncSelectedTextTrackFromDom({ state, owners });
3133
- */
3134
- function syncSelectedTextTrackFromDom({ state, owners }) {
3135
- let lastMediaElement;
3136
- let removeListener = null;
3137
- const unsubscribe = owners.subscribe((currentOwners) => {
3138
- const { mediaElement } = currentOwners;
3139
- if (mediaElement === lastMediaElement) return;
3140
- removeListener?.();
3141
- removeListener = null;
3142
- lastMediaElement = mediaElement;
3143
- if (!mediaElement) return;
3144
- const sync = () => {
3145
- const newId = Array.from(mediaElement.textTracks).find((t) => t.mode === "showing" && (t.kind === "subtitles" || t.kind === "captions"))?.id || void 0;
3146
- const current = state.current;
3147
- if (current.selectedTextTrackId === newId) return;
3148
- if (newId) state.patch({ selectedTextTrackId: newId });
3149
- else {
3150
- const prevId = current.selectedTextTrackId;
3151
- if (prevId && current.textBufferState?.[prevId]) {
3152
- const next = { ...current.textBufferState };
3153
- delete next[prevId];
3154
- state.patch({
3155
- selectedTextTrackId: void 0,
3156
- textBufferState: next
3157
- });
3158
- } else state.patch({ selectedTextTrackId: void 0 });
3159
- }
3160
- };
3161
- removeListener = listen(mediaElement.textTracks, "change", sync);
3162
- });
3163
- return () => {
3164
- removeListener?.();
3165
- unsubscribe();
3166
- };
3167
- }
3168
-
3169
- //#endregion
3170
- //#region src/dom/features/sync-text-track-modes.ts
3171
- /**
3172
- * Check if we can sync text track modes.
3173
- *
3174
- * Requires:
3175
- * - textTracks map exists (track elements created)
3176
- */
3177
- function canSyncTextTrackModes(owners) {
3178
- return !!owners.textTracks && owners.textTracks.size > 0;
3179
- }
3180
- /**
3181
- * Sync text track modes orchestration.
3182
- *
3183
- * Manages track element modes based on selectedTextTrackId:
3184
- * - Selected track: mode = "showing"
3185
- * - Other tracks: mode = "hidden"
3186
- * - No selection: all tracks mode = "hidden"
3187
- *
3188
- * Note: Uses "hidden" instead of "disabled" for non-selected tracks
3189
- * so they remain available in the browser's track menu.
3190
- *
3191
- * @example
3192
- * const cleanup = syncTextTrackModes({ state, owners });
3193
- */
3194
- function syncTextTrackModes({ state, owners }) {
3195
- return combineLatest([state, owners]).subscribe(([s, o]) => {
3196
- if (!canSyncTextTrackModes(o)) return;
3197
- const selectedId = s.selectedTextTrackId;
3198
- for (const [trackId, trackElement] of o.textTracks) if (trackId === selectedId) trackElement.track.mode = "showing";
3199
- else trackElement.track.mode = "hidden";
3200
- });
3201
- }
3202
-
3203
- //#endregion
3204
- //#region src/dom/features/update-duration.ts
3205
- /**
3206
- * Check if we can update MediaSource duration (have required data).
3207
- */
3208
- function canUpdateDuration(state, owners) {
3209
- return !!(owners.mediaSource && state.presentation && hasPresentationDuration(state.presentation));
3210
- }
3211
- /**
3212
- * Get the maximum buffered end time across all SourceBuffers.
3213
- */
3214
- function getMaxBufferedEnd(owners) {
3215
- let maxEnd = 0;
3216
- const buffers = [owners.videoSourceBuffer, owners.audioSourceBuffer].filter((buf) => buf !== void 0);
3217
- for (const buffer of buffers) {
3218
- const { buffered } = buffer;
3219
- if (buffered.length > 0) {
3220
- const end = buffered.end(buffered.length - 1);
3221
- if (end > maxEnd) maxEnd = end;
3222
- }
3223
- }
3224
- return maxEnd;
3225
- }
3226
- /**
3227
- * Check if we should update MediaSource duration (conditions met).
3228
- */
3229
- function shouldUpdateDuration(state, owners) {
3230
- if (!canUpdateDuration(state, owners)) return false;
3231
- const { mediaSource } = owners;
3232
- const { presentation } = state;
3233
- if (mediaSource.readyState !== "open") return false;
3234
- const duration = presentation.duration;
3235
- if (!Number.isFinite(duration) || Number.isNaN(duration) || duration <= 0) return false;
3236
- return Number.isNaN(mediaSource.duration);
3237
- }
3238
- /**
3239
- * Wait for all currently-updating SourceBuffers to finish.
3240
- *
3241
- * The MSE spec forbids setting MediaSource.duration while any attached
3242
- * SourceBuffer has updating === true. This defers until all are idle.
3243
- */
3244
- function waitForSourceBuffersReady(owners) {
3245
- const updating = [owners.videoSourceBuffer, owners.audioSourceBuffer].filter((buf) => buf?.updating === true);
3246
- if (updating.length === 0) return Promise.resolve();
3247
- return Promise.all(updating.map((buf) => new Promise((resolve) => buf.addEventListener("updateend", () => resolve(), { once: true })))).then(() => void 0);
3248
- }
3249
- /**
3250
- * Update MediaSource duration when presentation duration becomes available.
3251
- */
3252
- function updateDuration({ state, owners }) {
3253
- let destroyed = false;
3254
- const unsubscribe = combineLatest([state, owners]).subscribe(async ([currentState, currentOwners]) => {
3255
- if (!shouldUpdateDuration(currentState, currentOwners)) return;
3256
- const { mediaSource } = currentOwners;
3257
- await waitForSourceBuffersReady(currentOwners);
3258
- if (destroyed || mediaSource.readyState !== "open") return;
3259
- let duration = currentState.presentation.duration;
3260
- const maxBufferedEnd = getMaxBufferedEnd(currentOwners);
3261
- if (maxBufferedEnd > duration) duration = maxBufferedEnd;
3262
- mediaSource.duration = duration;
3263
- });
3264
- return () => {
3265
- destroyed = true;
3266
- unsubscribe();
3267
- };
3268
- }
3269
-
3270
- //#endregion
3271
- //#region src/dom/playback-engine/engine.ts
3272
- /**
3273
- * Create a POC playback engine.
3274
- *
3275
- * Wires together all orchestrations to create a reactive playback pipeline:
3276
- * 1. Resolve presentation (multivariant playlist)
3277
- * 2. Select initial video and audio tracks
3278
- * 3. Resolve selected tracks (media playlists)
3279
- * 4. Setup MediaSource
3280
- * 5. Setup SourceBuffers for video and audio
3281
- *
3282
- * Note: This is a POC - does not yet load/append segments.
3283
- *
3284
- * @param config - Playback engine configuration
3285
- * @returns Playback engine instance with state, owners, and destroy function
3286
- *
3287
- * @example
3288
- * const engine = createPlaybackEngine({
3289
- * initialBandwidth: 2_000_000,
3290
- * preferredAudioLanguage: 'en',
3291
- * });
3292
- *
3293
- * // Initialize by patching state and owners
3294
- * engine.owners.patch({ mediaElement: document.querySelector('video') });
3295
- * engine.state.patch({
3296
- * presentation: { url: 'https://example.com/playlist.m3u8' },
3297
- * preload: 'auto',
3298
- * });
3299
- *
3300
- * // Inspect state
3301
- * console.log(engine.state.current);
3302
- *
3303
- * // Cleanup
3304
- * engine.destroy();
3305
- */
3306
- function createPlaybackEngine(config = {}) {
3307
- const state = createState({ bandwidthState: {
3308
- fastEstimate: 0,
3309
- fastTotalWeight: 0,
3310
- slowEstimate: 0,
3311
- slowTotalWeight: 0,
3312
- bytesSampled: 0
3313
- } });
3314
- const owners = createState({});
3315
- const events = createEventStream();
3316
- const cleanups = [
3317
- syncPreloadAttribute(state, owners),
3318
- trackPlaybackInitiated({
3319
- state,
3320
- owners,
3321
- events
3322
- }),
3323
- resolvePresentation({
3324
- state,
3325
- events
3326
- }),
3327
- selectVideoTrack({
3328
- state,
3329
- owners,
3330
- events
3331
- }, {
3332
- type: "video",
3333
- ...config.initialBandwidth !== void 0 && { initialBandwidth: config.initialBandwidth }
3334
- }),
3335
- selectAudioTrack({
3336
- state,
3337
- owners,
3338
- events
3339
- }, {
3340
- type: "audio",
3341
- ...config.preferredAudioLanguage !== void 0 && { preferredAudioLanguage: config.preferredAudioLanguage }
3342
- }),
3343
- selectTextTrack({
3344
- state,
3345
- owners,
3346
- events
3347
- }, {
3348
- type: "text",
3349
- ...config.preferredSubtitleLanguage !== void 0 && { preferredSubtitleLanguage: config.preferredSubtitleLanguage },
3350
- ...config.includeForcedTracks !== void 0 && { includeForcedTracks: config.includeForcedTracks },
3351
- ...config.enableDefaultTrack !== void 0 && { enableDefaultTrack: config.enableDefaultTrack }
3352
- }),
3353
- resolveTrack({
3354
- state,
3355
- events
3356
- }, { type: "video" }),
3357
- resolveTrack({
3358
- state,
3359
- events
3360
- }, { type: "audio" }),
3361
- resolveTrack({
3362
- state,
3363
- events
3364
- }, { type: "text" }),
3365
- calculatePresentationDuration({ state }),
3366
- setupMediaSource({
3367
- state,
3368
- owners
3369
- }),
3370
- updateDuration({
3371
- state,
3372
- owners
3373
- }),
3374
- setupSourceBuffer({
3375
- state,
3376
- owners
3377
- }, { type: "video" }),
3378
- setupSourceBuffer({
3379
- state,
3380
- owners
3381
- }, { type: "audio" }),
3382
- trackCurrentTime({
3383
- state,
3384
- owners
3385
- }),
3386
- switchQuality({ state }),
3387
- loadSegments({
3388
- state,
3389
- owners
3390
- }, { type: "video" }),
3391
- loadSegments({
3392
- state,
3393
- owners
3394
- }, { type: "audio" }),
3395
- endOfStream({
3396
- state,
3397
- owners
3398
- }),
3399
- setupTextTracks({
3400
- state,
3401
- owners
3402
- }),
3403
- syncTextTrackModes({
3404
- state,
3405
- owners
3406
- }),
3407
- syncSelectedTextTrackFromDom({
3408
- state,
3409
- owners
3410
- }),
3411
- loadTextTrackCues({
3412
- state,
3413
- owners
3414
- })
3415
- ];
3416
- events.dispatch({ type: "@@INITIALIZE@@" });
3417
- return {
3418
- state,
3419
- owners,
3420
- events,
3421
- destroy: () => {
3422
- cleanups.forEach((cleanup) => cleanup());
3423
- destroyVttParser();
3424
- }
3425
- };
3426
- }
3427
-
3428
- //#endregion
3429
- //#region src/dom/playback-engine/adapter.ts
3430
- /**
3431
- * HTMLMediaElement-compatible adapter for the SPF playback engine.
3432
- *
3433
- * Implements the src/play() contract per the WHATWG HTML spec so that SPF can
3434
- * be used anywhere a media element API is expected.
3435
- *
3436
- * A new engine is created on every src assignment — this fully tears down all
3437
- * state, SourceBuffers, and in-flight requests from the previous source before
3438
- * the next one begins. The media element reference is preserved across src
3439
- * changes and re-applied to the new engine automatically.
3440
- *
3441
- * @example
3442
- * const media = new SpfMedia({ preferredAudioLanguage: 'en' });
3443
- * media.attach(document.querySelector('video'));
3444
- * media.src = 'https://stream.mux.com/abc123.m3u8';
3445
- *
3446
- * // Change source — old engine is destroyed, new one starts clean:
3447
- * media.src = 'https://stream.mux.com/xyz456.m3u8';
3448
- *
3449
- * // Explicit teardown:
3450
- * media.destroy();
3451
- */
3452
- var SpfMedia = class {
3453
- #engine;
3454
- #config;
3455
- /** Pending loadstart listener from a deferred play() retry, if any. */
3456
- #loadstartListener = null;
3457
- constructor(config = {}) {
3458
- this.#config = config;
3459
- this.#engine = createPlaybackEngine(config);
3460
- }
3461
- get engine() {
3462
- return this.#engine;
3463
- }
3464
- attach(mediaElement) {
3465
- this.#engine.owners.patch({ mediaElement });
3466
- }
3467
- detach() {
3468
- this.#cancelPendingPlay();
3469
- this.#engine.owners.patch({ mediaElement: void 0 });
3470
- }
3471
- destroy() {
3472
- this.#cancelPendingPlay();
3473
- this.#engine.destroy();
3474
- }
3475
- get src() {
3476
- return this.#engine.state.current.presentation?.url ?? "";
3477
- }
3478
- set src(value) {
3479
- const prevMediaElement = this.#engine.owners.current.mediaElement;
3480
- this.#cancelPendingPlay();
3481
- this.#engine.destroy();
3482
- this.#engine = createPlaybackEngine(this.#config);
3483
- if (prevMediaElement) this.#engine.owners.patch({ mediaElement: prevMediaElement });
3484
- if (value) this.#engine.state.patch({ presentation: { url: value } });
3485
- }
3486
- play() {
3487
- const { mediaElement } = this.#engine.owners.current;
3488
- if (!mediaElement) return Promise.reject(/* @__PURE__ */ new Error("SpfMedia: no media element attached"));
3489
- this.#engine.state.patch({ playbackInitiated: true });
3490
- return mediaElement.play().catch((err) => {
3491
- if (this.src) return new Promise((resolve, reject) => {
3492
- const listener = () => {
3493
- this.#loadstartListener = null;
3494
- mediaElement.play().then(resolve, reject);
3495
- };
3496
- this.#loadstartListener = listener;
3497
- mediaElement.addEventListener("loadstart", listener, { once: true });
3498
- });
3499
- throw err;
3500
- });
3501
- }
3502
- #cancelPendingPlay() {
3503
- if (!this.#loadstartListener) return;
3504
- const { mediaElement } = this.#engine.owners.current;
3505
- mediaElement?.removeEventListener("loadstart", this.#loadstartListener);
3506
- this.#loadstartListener = null;
3507
- }
3508
- };
3509
-
3510
- //#endregion
3511
- export { trackPlaybackInitiated as a, destroyVttParser as c, appendSegment as i, parseVttSegment as l, createPlaybackEngine as n, trackCurrentTime as o, flushBuffer as r, loadTextTrackCues as s, SpfMedia as t, loadSegments as u };
3512
- //# sourceMappingURL=adapter-CMw-rvbk.js.map