@videojs/spf 10.0.0-beta.9 → 10.0.0-rc.2

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 (556) hide show
  1. package/README.md +19 -38
  2. package/dist/default/core/actors/create-machine-actor.js +89 -0
  3. package/dist/default/core/actors/create-machine-actor.js.map +1 -0
  4. package/dist/default/core/actors/create-transition-actor.js +44 -0
  5. package/dist/default/core/actors/create-transition-actor.js.map +1 -0
  6. package/dist/default/core/composition/create-composition.js +82 -0
  7. package/dist/default/core/composition/create-composition.js.map +1 -0
  8. package/dist/default/core/composition/share-signals.js +34 -0
  9. package/dist/default/core/composition/share-signals.js.map +1 -0
  10. package/dist/default/core/machine.js +25 -0
  11. package/dist/default/core/machine.js.map +1 -0
  12. package/dist/default/core/reactors/create-machine-reactor.js +84 -0
  13. package/dist/default/core/reactors/create-machine-reactor.js.map +1 -0
  14. package/dist/default/core/signals/effect.js +61 -0
  15. package/dist/default/core/signals/effect.js.map +1 -0
  16. package/dist/default/core/signals/primitives.js +50 -0
  17. package/dist/default/core/signals/primitives.js.map +1 -0
  18. package/dist/default/core/signals/when.js +36 -0
  19. package/dist/default/core/signals/when.js.map +1 -0
  20. package/dist/default/core/tasks/delayed-reschedule.js +27 -0
  21. package/dist/default/core/tasks/delayed-reschedule.js.map +1 -0
  22. package/dist/default/core/tasks/task.js +298 -0
  23. package/dist/default/core/tasks/task.js.map +1 -0
  24. package/dist/default/dom.js +9 -0
  25. package/dist/default/hls-audio.js +3 -0
  26. package/dist/default/hls-background-video.js +3 -0
  27. package/dist/default/hls-video.js +4 -0
  28. package/dist/default/hls.js +10 -0
  29. package/dist/default/index.js +22 -0
  30. package/dist/default/index.js.map +1 -0
  31. package/dist/default/media/abr/quality-selection.js +17 -0
  32. package/dist/default/media/abr/quality-selection.js.map +1 -0
  33. package/dist/default/media/buffer/back-buffer.js +42 -0
  34. package/dist/default/media/buffer/back-buffer.js.map +1 -0
  35. package/dist/default/media/buffer/forward-buffer.js +110 -0
  36. package/dist/default/media/buffer/forward-buffer.js.map +1 -0
  37. package/dist/default/media/dom/capabilities.js +61 -0
  38. package/dist/default/media/dom/capabilities.js.map +1 -0
  39. package/dist/default/media/dom/mse/append-segment.js +58 -0
  40. package/dist/default/media/dom/mse/append-segment.js.map +1 -0
  41. package/dist/default/media/dom/mse/buffer-flusher.js +55 -0
  42. package/dist/default/media/dom/mse/buffer-flusher.js.map +1 -0
  43. package/dist/default/media/dom/mse/duration.js +87 -0
  44. package/dist/default/media/dom/mse/duration.js.map +1 -0
  45. package/dist/default/media/dom/mse/end-of-stream.js +17 -0
  46. package/dist/default/media/dom/mse/end-of-stream.js.map +1 -0
  47. package/dist/default/media/dom/mse/mediasource-setup.js +227 -0
  48. package/dist/default/media/dom/mse/mediasource-setup.js.map +1 -0
  49. package/dist/default/media/dom/screen.js +95 -0
  50. package/dist/default/media/dom/screen.js.map +1 -0
  51. package/dist/default/media/dom/text/resolve-vtt-segment.js +50 -0
  52. package/dist/default/media/dom/text/resolve-vtt-segment.js.map +1 -0
  53. package/dist/default/media/dom/text/text-track-slots.js +61 -0
  54. package/dist/default/media/dom/text/text-track-slots.js.map +1 -0
  55. package/dist/default/media/errors.js +60 -0
  56. package/dist/default/media/errors.js.map +1 -0
  57. package/dist/default/media/hls/parse-attributes.js +131 -0
  58. package/dist/default/media/hls/parse-attributes.js.map +1 -0
  59. package/dist/default/media/hls/parse-media-playlist.js +253 -0
  60. package/dist/default/media/hls/parse-media-playlist.js.map +1 -0
  61. package/dist/default/media/hls/parse-multivariant.js +234 -0
  62. package/dist/default/media/hls/parse-multivariant.js.map +1 -0
  63. package/dist/default/media/hls/reload-policy.js +63 -0
  64. package/dist/default/media/hls/reload-policy.js.map +1 -0
  65. package/dist/default/media/hls/resolve-url.js +9 -0
  66. package/dist/default/media/hls/resolve-url.js.map +1 -0
  67. package/dist/default/media/live-window.js +32 -0
  68. package/dist/default/media/live-window.js.map +1 -0
  69. package/dist/default/media/media-tracks/media-tracks.js +96 -0
  70. package/dist/default/media/media-tracks/media-tracks.js.map +1 -0
  71. package/dist/default/media/mp4/box.js +57 -0
  72. package/dist/default/media/mp4/box.js.map +1 -0
  73. package/dist/default/media/mp4/timestamp-origin.js +95 -0
  74. package/dist/default/media/mp4/timestamp-origin.js.map +1 -0
  75. package/dist/default/media/primitives/resolution.js +26 -0
  76. package/dist/default/media/primitives/resolution.js.map +1 -0
  77. package/dist/default/media/primitives/select-tracks.js +97 -0
  78. package/dist/default/media/primitives/select-tracks.js.map +1 -0
  79. package/dist/default/media/text/parse-vtt-timestamp-map.js +40 -0
  80. package/dist/default/media/text/parse-vtt-timestamp-map.js.map +1 -0
  81. package/dist/default/media/text/resolve-vtt-metadata.js +22 -0
  82. package/dist/default/media/text/resolve-vtt-metadata.js.map +1 -0
  83. package/dist/default/media/types/index.js +42 -0
  84. package/dist/default/media/types/index.js.map +1 -0
  85. package/dist/default/media/utils/cdn.js +50 -0
  86. package/dist/default/media/utils/cdn.js.map +1 -0
  87. package/dist/default/media/utils/preload.js +21 -0
  88. package/dist/default/media/utils/preload.js.map +1 -0
  89. package/dist/default/media/utils/track-selection.js +43 -0
  90. package/dist/default/media/utils/track-selection.js.map +1 -0
  91. package/dist/default/media/utils/tracks.js +146 -0
  92. package/dist/default/media/utils/tracks.js.map +1 -0
  93. package/dist/default/media-tracks.js +2 -0
  94. package/dist/default/network/bandwidth-estimator.js +95 -0
  95. package/dist/default/network/bandwidth-estimator.js.map +1 -0
  96. package/dist/default/network/chunked-stream-iterable.js +47 -0
  97. package/dist/default/network/chunked-stream-iterable.js.map +1 -0
  98. package/dist/default/network/ewma.js +68 -0
  99. package/dist/default/network/ewma.js.map +1 -0
  100. package/dist/default/network/fetch.js +108 -0
  101. package/dist/default/network/fetch.js.map +1 -0
  102. package/dist/default/playback/actors/dom/segment-loader.js +233 -0
  103. package/dist/default/playback/actors/dom/segment-loader.js.map +1 -0
  104. package/dist/default/playback/actors/dom/source-buffer.js +139 -0
  105. package/dist/default/playback/actors/dom/source-buffer.js.map +1 -0
  106. package/dist/default/playback/actors/dom/text-tracks.js +46 -0
  107. package/dist/default/playback/actors/dom/text-tracks.js.map +1 -0
  108. package/dist/default/playback/actors/text-track-segment-loader.js +138 -0
  109. package/dist/default/playback/actors/text-track-segment-loader.js.map +1 -0
  110. package/dist/default/playback/adapters/hls-audio/adapter.js +8 -0
  111. package/dist/default/playback/adapters/hls-audio/adapter.js.map +1 -0
  112. package/dist/default/playback/adapters/hls-audio/mixin.js +178 -0
  113. package/dist/default/playback/adapters/hls-audio/mixin.js.map +1 -0
  114. package/dist/default/playback/adapters/hls-background-video/adapter.js +17 -0
  115. package/dist/default/playback/adapters/hls-background-video/adapter.js.map +1 -0
  116. package/dist/default/playback/adapters/hls-background-video/host.js +56 -0
  117. package/dist/default/playback/adapters/hls-background-video/host.js.map +1 -0
  118. package/dist/default/playback/adapters/hls-background-video/mixin.js +191 -0
  119. package/dist/default/playback/adapters/hls-background-video/mixin.js.map +1 -0
  120. package/dist/default/playback/adapters/hls-video/adapter.js +11 -0
  121. package/dist/default/playback/adapters/hls-video/adapter.js.map +1 -0
  122. package/dist/default/playback/adapters/hls-video/error-surface.js +46 -0
  123. package/dist/default/playback/adapters/hls-video/error-surface.js.map +1 -0
  124. package/dist/default/playback/adapters/hls-video/media-tracks.js +125 -0
  125. package/dist/default/playback/adapters/hls-video/media-tracks.js.map +1 -0
  126. package/dist/default/playback/adapters/hls-video/mixin.js +299 -0
  127. package/dist/default/playback/adapters/hls-video/mixin.js.map +1 -0
  128. package/dist/default/playback/behaviors/calculate-presentation-duration.js +33 -0
  129. package/dist/default/playback/behaviors/calculate-presentation-duration.js.map +1 -0
  130. package/dist/default/playback/behaviors/collect-errors.js +98 -0
  131. package/dist/default/playback/behaviors/collect-errors.js.map +1 -0
  132. package/dist/default/playback/behaviors/derive-cdn-priority.js +61 -0
  133. package/dist/default/playback/behaviors/derive-cdn-priority.js.map +1 -0
  134. package/dist/default/playback/behaviors/dom/airplay.js +188 -0
  135. package/dist/default/playback/behaviors/dom/airplay.js.map +1 -0
  136. package/dist/default/playback/behaviors/dom/apply-start-position.js +81 -0
  137. package/dist/default/playback/behaviors/dom/apply-start-position.js.map +1 -0
  138. package/dist/default/playback/behaviors/dom/end-of-stream.js +97 -0
  139. package/dist/default/playback/behaviors/dom/end-of-stream.js.map +1 -0
  140. package/dist/default/playback/behaviors/dom/load-segments.js +169 -0
  141. package/dist/default/playback/behaviors/dom/load-segments.js.map +1 -0
  142. package/dist/default/playback/behaviors/dom/recover-end-stall.js +72 -0
  143. package/dist/default/playback/behaviors/dom/recover-end-stall.js.map +1 -0
  144. package/dist/default/playback/behaviors/dom/seek-to-live-edge.js +113 -0
  145. package/dist/default/playback/behaviors/dom/seek-to-live-edge.js.map +1 -0
  146. package/dist/default/playback/behaviors/dom/setup-buffer-actors.js +181 -0
  147. package/dist/default/playback/behaviors/dom/setup-buffer-actors.js.map +1 -0
  148. package/dist/default/playback/behaviors/dom/setup-mediasource.js +100 -0
  149. package/dist/default/playback/behaviors/dom/setup-mediasource.js.map +1 -0
  150. package/dist/default/playback/behaviors/dom/setup-text-track-actors.js +40 -0
  151. package/dist/default/playback/behaviors/dom/setup-text-track-actors.js.map +1 -0
  152. package/dist/default/playback/behaviors/dom/sync-live-seekable-range.js +25 -0
  153. package/dist/default/playback/behaviors/dom/sync-live-seekable-range.js.map +1 -0
  154. package/dist/default/playback/behaviors/dom/sync-text-tracks.js +109 -0
  155. package/dist/default/playback/behaviors/dom/sync-text-tracks.js.map +1 -0
  156. package/dist/default/playback/behaviors/dom/track-current-time.js +50 -0
  157. package/dist/default/playback/behaviors/dom/track-current-time.js.map +1 -0
  158. package/dist/default/playback/behaviors/dom/track-load-triggers.js +86 -0
  159. package/dist/default/playback/behaviors/dom/track-load-triggers.js.map +1 -0
  160. package/dist/default/playback/behaviors/dom/track-playback-rate.js +35 -0
  161. package/dist/default/playback/behaviors/dom/track-playback-rate.js.map +1 -0
  162. package/dist/default/playback/behaviors/dom/track-player-resolution.js +53 -0
  163. package/dist/default/playback/behaviors/dom/track-player-resolution.js.map +1 -0
  164. package/dist/default/playback/behaviors/dom/track-screen-resolution.js +28 -0
  165. package/dist/default/playback/behaviors/dom/track-screen-resolution.js.map +1 -0
  166. package/dist/default/playback/behaviors/dom/update-mediasource-duration.js +98 -0
  167. package/dist/default/playback/behaviors/dom/update-mediasource-duration.js.map +1 -0
  168. package/dist/default/playback/behaviors/establish-start-media-time.js +187 -0
  169. package/dist/default/playback/behaviors/establish-start-media-time.js.map +1 -0
  170. package/dist/default/playback/behaviors/resolve-presentation.js +76 -0
  171. package/dist/default/playback/behaviors/resolve-presentation.js.map +1 -0
  172. package/dist/default/playback/behaviors/resolve-track.js +134 -0
  173. package/dist/default/playback/behaviors/resolve-track.js.map +1 -0
  174. package/dist/default/playback/behaviors/select-tracks.js +189 -0
  175. package/dist/default/playback/behaviors/select-tracks.js.map +1 -0
  176. package/dist/default/playback/behaviors/setup-failover-monitor.js +61 -0
  177. package/dist/default/playback/behaviors/setup-failover-monitor.js.map +1 -0
  178. package/dist/default/playback/behaviors/sync-preload.js +59 -0
  179. package/dist/default/playback/behaviors/sync-preload.js.map +1 -0
  180. package/dist/default/playback/behaviors/track-switching.js +407 -0
  181. package/dist/default/playback/behaviors/track-switching.js.map +1 -0
  182. package/dist/default/playback/engines/hls/engine-audio-only.js +94 -0
  183. package/dist/default/playback/engines/hls/engine-audio-only.js.map +1 -0
  184. package/dist/default/playback/engines/hls/engine-background-video.js +87 -0
  185. package/dist/default/playback/engines/hls/engine-background-video.js.map +1 -0
  186. package/dist/default/playback/engines/hls/engine.js +144 -0
  187. package/dist/default/playback/engines/hls/engine.js.map +1 -0
  188. package/dist/default/playback/primitives/error-messages.js +42 -0
  189. package/dist/default/playback/primitives/error-messages.js.map +1 -0
  190. package/dist/default/playback/primitives/failover-fetch.js +37 -0
  191. package/dist/default/playback/primitives/failover-fetch.js.map +1 -0
  192. package/dist/default/playback/primitives/head-peek.js +41 -0
  193. package/dist/default/playback/primitives/head-peek.js.map +1 -0
  194. package/dist/default/playback/primitives/live-window.js +63 -0
  195. package/dist/default/playback/primitives/live-window.js.map +1 -0
  196. package/dist/default/playback/primitives/relocation-pipelines.js +191 -0
  197. package/dist/default/playback/primitives/relocation-pipelines.js.map +1 -0
  198. package/dist/default/playback/primitives/report-track-conditions.js +74 -0
  199. package/dist/default/playback/primitives/report-track-conditions.js.map +1 -0
  200. package/dist/default/playback/primitives/segment-load-pipeline.js +96 -0
  201. package/dist/default/playback/primitives/segment-load-pipeline.js.map +1 -0
  202. package/dist/default/playback/primitives/selection-rules.js +115 -0
  203. package/dist/default/playback/primitives/selection-rules.js.map +1 -0
  204. package/dist/default/playback/primitives/text-segment-load-pipeline.js +36 -0
  205. package/dist/default/playback/primitives/text-segment-load-pipeline.js.map +1 -0
  206. package/dist/default/playback/primitives/track-types.js +53 -0
  207. package/dist/default/playback/primitives/track-types.js.map +1 -0
  208. package/dist/dev/core/actors/actor.d.ts +26 -0
  209. package/dist/dev/core/actors/actor.d.ts.map +1 -0
  210. package/dist/dev/core/actors/create-machine-actor.d.ts +119 -0
  211. package/dist/dev/core/actors/create-machine-actor.d.ts.map +1 -0
  212. package/dist/dev/core/actors/create-machine-actor.js +89 -0
  213. package/dist/dev/core/actors/create-machine-actor.js.map +1 -0
  214. package/dist/dev/core/actors/create-transition-actor.d.ts +37 -0
  215. package/dist/dev/core/actors/create-transition-actor.d.ts.map +1 -0
  216. package/dist/dev/core/actors/create-transition-actor.js +44 -0
  217. package/dist/dev/core/actors/create-transition-actor.js.map +1 -0
  218. package/dist/dev/core/composition/create-composition.d.ts +241 -0
  219. package/dist/dev/core/composition/create-composition.d.ts.map +1 -0
  220. package/dist/dev/core/composition/create-composition.js +82 -0
  221. package/dist/dev/core/composition/create-composition.js.map +1 -0
  222. package/dist/dev/core/composition/share-signals.d.ts +39 -0
  223. package/dist/dev/core/composition/share-signals.d.ts.map +1 -0
  224. package/dist/dev/core/composition/share-signals.js +34 -0
  225. package/dist/dev/core/composition/share-signals.js.map +1 -0
  226. package/dist/dev/core/machine.d.ts +21 -0
  227. package/dist/dev/core/machine.d.ts.map +1 -0
  228. package/dist/dev/core/machine.js +25 -0
  229. package/dist/dev/core/machine.js.map +1 -0
  230. package/dist/dev/core/reactors/create-machine-reactor.d.ts +87 -0
  231. package/dist/dev/core/reactors/create-machine-reactor.d.ts.map +1 -0
  232. package/dist/dev/core/reactors/create-machine-reactor.js +84 -0
  233. package/dist/dev/core/reactors/create-machine-reactor.js.map +1 -0
  234. package/dist/dev/core/signals/effect.d.ts +14 -0
  235. package/dist/dev/core/signals/effect.d.ts.map +1 -0
  236. package/dist/dev/core/signals/effect.js +61 -0
  237. package/dist/dev/core/signals/effect.js.map +1 -0
  238. package/dist/dev/core/signals/primitives.d.ts +44 -0
  239. package/dist/dev/core/signals/primitives.d.ts.map +1 -0
  240. package/dist/dev/core/signals/primitives.js +50 -0
  241. package/dist/dev/core/signals/primitives.js.map +1 -0
  242. package/dist/dev/core/signals/when.js +36 -0
  243. package/dist/dev/core/signals/when.js.map +1 -0
  244. package/dist/dev/core/tasks/delayed-reschedule.js +27 -0
  245. package/dist/dev/core/tasks/delayed-reschedule.js.map +1 -0
  246. package/dist/dev/core/tasks/task.d.ts +144 -0
  247. package/dist/dev/core/tasks/task.d.ts.map +1 -0
  248. package/dist/dev/core/tasks/task.js +298 -0
  249. package/dist/dev/core/tasks/task.js.map +1 -0
  250. package/dist/dev/dom.d.ts +9 -0
  251. package/dist/dev/dom.js +9 -0
  252. package/dist/dev/hls-audio.d.ts +3 -0
  253. package/dist/dev/hls-audio.js +3 -0
  254. package/dist/dev/hls-background-video.d.ts +4 -0
  255. package/dist/dev/hls-background-video.js +3 -0
  256. package/dist/dev/hls-video.d.ts +5 -0
  257. package/dist/dev/hls-video.js +4 -0
  258. package/dist/dev/hls.d.ts +11 -0
  259. package/dist/dev/hls.js +10 -0
  260. package/dist/dev/index.d.ts +23 -0
  261. package/dist/dev/index.d.ts.map +1 -0
  262. package/dist/dev/index.js +22 -0
  263. package/dist/dev/index.js.map +1 -0
  264. package/dist/dev/media/abr/quality-selection.d.ts +19 -0
  265. package/dist/dev/media/abr/quality-selection.d.ts.map +1 -0
  266. package/dist/dev/media/abr/quality-selection.js +17 -0
  267. package/dist/dev/media/abr/quality-selection.js.map +1 -0
  268. package/dist/dev/media/buffer/back-buffer.d.ts +9 -0
  269. package/dist/dev/media/buffer/back-buffer.d.ts.map +1 -0
  270. package/dist/dev/media/buffer/back-buffer.js +42 -0
  271. package/dist/dev/media/buffer/back-buffer.js.map +1 -0
  272. package/dist/dev/media/buffer/forward-buffer.d.ts +9 -0
  273. package/dist/dev/media/buffer/forward-buffer.d.ts.map +1 -0
  274. package/dist/dev/media/buffer/forward-buffer.js +110 -0
  275. package/dist/dev/media/buffer/forward-buffer.js.map +1 -0
  276. package/dist/dev/media/dom/capabilities.js +61 -0
  277. package/dist/dev/media/dom/capabilities.js.map +1 -0
  278. package/dist/dev/media/dom/mse/append-segment.d.ts +16 -0
  279. package/dist/dev/media/dom/mse/append-segment.d.ts.map +1 -0
  280. package/dist/dev/media/dom/mse/append-segment.js +58 -0
  281. package/dist/dev/media/dom/mse/append-segment.js.map +1 -0
  282. package/dist/dev/media/dom/mse/buffer-flusher.d.ts +24 -0
  283. package/dist/dev/media/dom/mse/buffer-flusher.d.ts.map +1 -0
  284. package/dist/dev/media/dom/mse/buffer-flusher.js +55 -0
  285. package/dist/dev/media/dom/mse/buffer-flusher.js.map +1 -0
  286. package/dist/dev/media/dom/mse/duration.js +87 -0
  287. package/dist/dev/media/dom/mse/duration.js.map +1 -0
  288. package/dist/dev/media/dom/mse/end-of-stream.js +17 -0
  289. package/dist/dev/media/dom/mse/end-of-stream.js.map +1 -0
  290. package/dist/dev/media/dom/mse/mediasource-setup.js +227 -0
  291. package/dist/dev/media/dom/mse/mediasource-setup.js.map +1 -0
  292. package/dist/dev/media/dom/screen.d.ts +7 -0
  293. package/dist/dev/media/dom/screen.d.ts.map +1 -0
  294. package/dist/dev/media/dom/screen.js +95 -0
  295. package/dist/dev/media/dom/screen.js.map +1 -0
  296. package/dist/dev/media/dom/text/resolve-vtt-segment.d.ts +6 -0
  297. package/dist/dev/media/dom/text/resolve-vtt-segment.d.ts.map +1 -0
  298. package/dist/dev/media/dom/text/resolve-vtt-segment.js +50 -0
  299. package/dist/dev/media/dom/text/resolve-vtt-segment.js.map +1 -0
  300. package/dist/dev/media/dom/text/text-track-slots.d.ts +24 -0
  301. package/dist/dev/media/dom/text/text-track-slots.d.ts.map +1 -0
  302. package/dist/dev/media/dom/text/text-track-slots.js +61 -0
  303. package/dist/dev/media/dom/text/text-track-slots.js.map +1 -0
  304. package/dist/dev/media/errors.d.ts +68 -0
  305. package/dist/dev/media/errors.d.ts.map +1 -0
  306. package/dist/dev/media/errors.js +60 -0
  307. package/dist/dev/media/errors.js.map +1 -0
  308. package/dist/dev/media/hls/parse-attributes.js +131 -0
  309. package/dist/dev/media/hls/parse-attributes.js.map +1 -0
  310. package/dist/dev/media/hls/parse-media-playlist.js +253 -0
  311. package/dist/dev/media/hls/parse-media-playlist.js.map +1 -0
  312. package/dist/dev/media/hls/parse-multivariant.js +234 -0
  313. package/dist/dev/media/hls/parse-multivariant.js.map +1 -0
  314. package/dist/dev/media/hls/reload-policy.js +63 -0
  315. package/dist/dev/media/hls/reload-policy.js.map +1 -0
  316. package/dist/dev/media/hls/resolve-url.js +9 -0
  317. package/dist/dev/media/hls/resolve-url.js.map +1 -0
  318. package/dist/dev/media/live-window.js +32 -0
  319. package/dist/dev/media/live-window.js.map +1 -0
  320. package/dist/dev/media/media-tracks/media-tracks.d.ts +46 -0
  321. package/dist/dev/media/media-tracks/media-tracks.d.ts.map +1 -0
  322. package/dist/dev/media/media-tracks/media-tracks.js +96 -0
  323. package/dist/dev/media/media-tracks/media-tracks.js.map +1 -0
  324. package/dist/dev/media/mp4/box.js +57 -0
  325. package/dist/dev/media/mp4/box.js.map +1 -0
  326. package/dist/dev/media/mp4/timestamp-origin.js +95 -0
  327. package/dist/dev/media/mp4/timestamp-origin.js.map +1 -0
  328. package/dist/dev/media/primitives/resolution.d.ts +22 -0
  329. package/dist/dev/media/primitives/resolution.d.ts.map +1 -0
  330. package/dist/dev/media/primitives/resolution.js +26 -0
  331. package/dist/dev/media/primitives/resolution.js.map +1 -0
  332. package/dist/dev/media/primitives/select-tracks.js +97 -0
  333. package/dist/dev/media/primitives/select-tracks.js.map +1 -0
  334. package/dist/dev/media/text/parse-vtt-timestamp-map.js +40 -0
  335. package/dist/dev/media/text/parse-vtt-timestamp-map.js.map +1 -0
  336. package/dist/dev/media/text/resolve-vtt-metadata.js +22 -0
  337. package/dist/dev/media/text/resolve-vtt-metadata.js.map +1 -0
  338. package/dist/dev/media/types/index.d.ts +306 -0
  339. package/dist/dev/media/types/index.d.ts.map +1 -0
  340. package/dist/dev/media/types/index.js +42 -0
  341. package/dist/dev/media/types/index.js.map +1 -0
  342. package/dist/dev/media/utils/cdn.d.ts +11 -0
  343. package/dist/dev/media/utils/cdn.d.ts.map +1 -0
  344. package/dist/dev/media/utils/cdn.js +50 -0
  345. package/dist/dev/media/utils/cdn.js.map +1 -0
  346. package/dist/dev/media/utils/preload.js +21 -0
  347. package/dist/dev/media/utils/preload.js.map +1 -0
  348. package/dist/dev/media/utils/track-selection.js +43 -0
  349. package/dist/dev/media/utils/track-selection.js.map +1 -0
  350. package/dist/dev/media/utils/tracks.js +146 -0
  351. package/dist/dev/media/utils/tracks.js.map +1 -0
  352. package/dist/dev/media-tracks.d.ts +3 -0
  353. package/dist/dev/media-tracks.js +2 -0
  354. package/dist/dev/network/bandwidth-estimator.d.ts +48 -0
  355. package/dist/dev/network/bandwidth-estimator.d.ts.map +1 -0
  356. package/dist/dev/network/bandwidth-estimator.js +95 -0
  357. package/dist/dev/network/bandwidth-estimator.js.map +1 -0
  358. package/dist/dev/network/chunked-stream-iterable.js +47 -0
  359. package/dist/dev/network/chunked-stream-iterable.js.map +1 -0
  360. package/dist/dev/network/ewma.js +68 -0
  361. package/dist/dev/network/ewma.js.map +1 -0
  362. package/dist/dev/network/fetch.js +108 -0
  363. package/dist/dev/network/fetch.js.map +1 -0
  364. package/dist/dev/playback/actors/dom/segment-loader.d.ts +44 -0
  365. package/dist/dev/playback/actors/dom/segment-loader.d.ts.map +1 -0
  366. package/dist/dev/playback/actors/dom/segment-loader.js +233 -0
  367. package/dist/dev/playback/actors/dom/segment-loader.js.map +1 -0
  368. package/dist/dev/playback/actors/dom/source-buffer.d.ts +45 -0
  369. package/dist/dev/playback/actors/dom/source-buffer.d.ts.map +1 -0
  370. package/dist/dev/playback/actors/dom/source-buffer.js +139 -0
  371. package/dist/dev/playback/actors/dom/source-buffer.js.map +1 -0
  372. package/dist/dev/playback/actors/dom/text-tracks.d.ts +3 -0
  373. package/dist/dev/playback/actors/dom/text-tracks.js +46 -0
  374. package/dist/dev/playback/actors/dom/text-tracks.js.map +1 -0
  375. package/dist/dev/playback/actors/text-track-segment-loader.d.ts +48 -0
  376. package/dist/dev/playback/actors/text-track-segment-loader.d.ts.map +1 -0
  377. package/dist/dev/playback/actors/text-track-segment-loader.js +138 -0
  378. package/dist/dev/playback/actors/text-track-segment-loader.js.map +1 -0
  379. package/dist/dev/playback/actors/text-tracks.d.ts +30 -0
  380. package/dist/dev/playback/actors/text-tracks.d.ts.map +1 -0
  381. package/dist/dev/playback/adapters/hls-audio/adapter.d.ts +11 -0
  382. package/dist/dev/playback/adapters/hls-audio/adapter.d.ts.map +1 -0
  383. package/dist/dev/playback/adapters/hls-audio/adapter.js +8 -0
  384. package/dist/dev/playback/adapters/hls-audio/adapter.js.map +1 -0
  385. package/dist/dev/playback/adapters/hls-audio/mixin.d.ts +52 -0
  386. package/dist/dev/playback/adapters/hls-audio/mixin.d.ts.map +1 -0
  387. package/dist/dev/playback/adapters/hls-audio/mixin.js +178 -0
  388. package/dist/dev/playback/adapters/hls-audio/mixin.js.map +1 -0
  389. package/dist/dev/playback/adapters/hls-background-video/adapter.d.ts +19 -0
  390. package/dist/dev/playback/adapters/hls-background-video/adapter.d.ts.map +1 -0
  391. package/dist/dev/playback/adapters/hls-background-video/adapter.js +17 -0
  392. package/dist/dev/playback/adapters/hls-background-video/adapter.js.map +1 -0
  393. package/dist/dev/playback/adapters/hls-background-video/host.d.ts +34 -0
  394. package/dist/dev/playback/adapters/hls-background-video/host.d.ts.map +1 -0
  395. package/dist/dev/playback/adapters/hls-background-video/host.js +56 -0
  396. package/dist/dev/playback/adapters/hls-background-video/host.js.map +1 -0
  397. package/dist/dev/playback/adapters/hls-background-video/mixin.d.ts +69 -0
  398. package/dist/dev/playback/adapters/hls-background-video/mixin.d.ts.map +1 -0
  399. package/dist/dev/playback/adapters/hls-background-video/mixin.js +191 -0
  400. package/dist/dev/playback/adapters/hls-background-video/mixin.js.map +1 -0
  401. package/dist/dev/playback/adapters/hls-video/adapter.d.ts +11 -0
  402. package/dist/dev/playback/adapters/hls-video/adapter.d.ts.map +1 -0
  403. package/dist/dev/playback/adapters/hls-video/adapter.js +11 -0
  404. package/dist/dev/playback/adapters/hls-video/adapter.js.map +1 -0
  405. package/dist/dev/playback/adapters/hls-video/error-surface.d.ts +17 -0
  406. package/dist/dev/playback/adapters/hls-video/error-surface.d.ts.map +1 -0
  407. package/dist/dev/playback/adapters/hls-video/error-surface.js +46 -0
  408. package/dist/dev/playback/adapters/hls-video/error-surface.js.map +1 -0
  409. package/dist/dev/playback/adapters/hls-video/media-tracks.d.ts +21 -0
  410. package/dist/dev/playback/adapters/hls-video/media-tracks.d.ts.map +1 -0
  411. package/dist/dev/playback/adapters/hls-video/media-tracks.js +125 -0
  412. package/dist/dev/playback/adapters/hls-video/media-tracks.js.map +1 -0
  413. package/dist/dev/playback/adapters/hls-video/mixin.d.ts +62 -0
  414. package/dist/dev/playback/adapters/hls-video/mixin.d.ts.map +1 -0
  415. package/dist/dev/playback/adapters/hls-video/mixin.js +299 -0
  416. package/dist/dev/playback/adapters/hls-video/mixin.js.map +1 -0
  417. package/dist/dev/playback/behaviors/calculate-presentation-duration.d.ts +23 -0
  418. package/dist/dev/playback/behaviors/calculate-presentation-duration.d.ts.map +1 -0
  419. package/dist/dev/playback/behaviors/calculate-presentation-duration.js +33 -0
  420. package/dist/dev/playback/behaviors/calculate-presentation-duration.js.map +1 -0
  421. package/dist/dev/playback/behaviors/collect-errors.d.ts +2 -0
  422. package/dist/dev/playback/behaviors/collect-errors.js +98 -0
  423. package/dist/dev/playback/behaviors/collect-errors.js.map +1 -0
  424. package/dist/dev/playback/behaviors/derive-cdn-priority.js +61 -0
  425. package/dist/dev/playback/behaviors/derive-cdn-priority.js.map +1 -0
  426. package/dist/dev/playback/behaviors/dom/airplay.js +188 -0
  427. package/dist/dev/playback/behaviors/dom/airplay.js.map +1 -0
  428. package/dist/dev/playback/behaviors/dom/apply-start-position.js +81 -0
  429. package/dist/dev/playback/behaviors/dom/apply-start-position.js.map +1 -0
  430. package/dist/dev/playback/behaviors/dom/end-of-stream.js +97 -0
  431. package/dist/dev/playback/behaviors/dom/end-of-stream.js.map +1 -0
  432. package/dist/dev/playback/behaviors/dom/load-segments.d.ts +69 -0
  433. package/dist/dev/playback/behaviors/dom/load-segments.d.ts.map +1 -0
  434. package/dist/dev/playback/behaviors/dom/load-segments.js +169 -0
  435. package/dist/dev/playback/behaviors/dom/load-segments.js.map +1 -0
  436. package/dist/dev/playback/behaviors/dom/recover-end-stall.js +72 -0
  437. package/dist/dev/playback/behaviors/dom/recover-end-stall.js.map +1 -0
  438. package/dist/dev/playback/behaviors/dom/seek-to-live-edge.js +113 -0
  439. package/dist/dev/playback/behaviors/dom/seek-to-live-edge.js.map +1 -0
  440. package/dist/dev/playback/behaviors/dom/setup-buffer-actors.js +181 -0
  441. package/dist/dev/playback/behaviors/dom/setup-buffer-actors.js.map +1 -0
  442. package/dist/dev/playback/behaviors/dom/setup-mediasource.js +100 -0
  443. package/dist/dev/playback/behaviors/dom/setup-mediasource.js.map +1 -0
  444. package/dist/dev/playback/behaviors/dom/setup-text-track-actors.d.ts +28 -0
  445. package/dist/dev/playback/behaviors/dom/setup-text-track-actors.d.ts.map +1 -0
  446. package/dist/dev/playback/behaviors/dom/setup-text-track-actors.js +40 -0
  447. package/dist/dev/playback/behaviors/dom/setup-text-track-actors.js.map +1 -0
  448. package/dist/dev/playback/behaviors/dom/sync-live-seekable-range.js +25 -0
  449. package/dist/dev/playback/behaviors/dom/sync-live-seekable-range.js.map +1 -0
  450. package/dist/dev/playback/behaviors/dom/sync-text-tracks.js +109 -0
  451. package/dist/dev/playback/behaviors/dom/sync-text-tracks.js.map +1 -0
  452. package/dist/dev/playback/behaviors/dom/track-current-time.d.ts +33 -0
  453. package/dist/dev/playback/behaviors/dom/track-current-time.d.ts.map +1 -0
  454. package/dist/dev/playback/behaviors/dom/track-current-time.js +50 -0
  455. package/dist/dev/playback/behaviors/dom/track-current-time.js.map +1 -0
  456. package/dist/dev/playback/behaviors/dom/track-load-triggers.d.ts +41 -0
  457. package/dist/dev/playback/behaviors/dom/track-load-triggers.d.ts.map +1 -0
  458. package/dist/dev/playback/behaviors/dom/track-load-triggers.js +86 -0
  459. package/dist/dev/playback/behaviors/dom/track-load-triggers.js.map +1 -0
  460. package/dist/dev/playback/behaviors/dom/track-playback-rate.d.ts +33 -0
  461. package/dist/dev/playback/behaviors/dom/track-playback-rate.d.ts.map +1 -0
  462. package/dist/dev/playback/behaviors/dom/track-playback-rate.js +35 -0
  463. package/dist/dev/playback/behaviors/dom/track-playback-rate.js.map +1 -0
  464. package/dist/dev/playback/behaviors/dom/track-player-resolution.d.ts +8 -0
  465. package/dist/dev/playback/behaviors/dom/track-player-resolution.d.ts.map +1 -0
  466. package/dist/dev/playback/behaviors/dom/track-player-resolution.js +53 -0
  467. package/dist/dev/playback/behaviors/dom/track-player-resolution.js.map +1 -0
  468. package/dist/dev/playback/behaviors/dom/track-screen-resolution.js +28 -0
  469. package/dist/dev/playback/behaviors/dom/track-screen-resolution.js.map +1 -0
  470. package/dist/dev/playback/behaviors/dom/update-mediasource-duration.js +98 -0
  471. package/dist/dev/playback/behaviors/dom/update-mediasource-duration.js.map +1 -0
  472. package/dist/dev/playback/behaviors/establish-start-media-time.d.ts +32 -0
  473. package/dist/dev/playback/behaviors/establish-start-media-time.d.ts.map +1 -0
  474. package/dist/dev/playback/behaviors/establish-start-media-time.js +187 -0
  475. package/dist/dev/playback/behaviors/establish-start-media-time.js.map +1 -0
  476. package/dist/dev/playback/behaviors/resolve-presentation.d.ts +8 -0
  477. package/dist/dev/playback/behaviors/resolve-presentation.d.ts.map +1 -0
  478. package/dist/dev/playback/behaviors/resolve-presentation.js +76 -0
  479. package/dist/dev/playback/behaviors/resolve-presentation.js.map +1 -0
  480. package/dist/dev/playback/behaviors/resolve-track.js +134 -0
  481. package/dist/dev/playback/behaviors/resolve-track.js.map +1 -0
  482. package/dist/dev/playback/behaviors/select-tracks.d.ts +61 -0
  483. package/dist/dev/playback/behaviors/select-tracks.d.ts.map +1 -0
  484. package/dist/dev/playback/behaviors/select-tracks.js +189 -0
  485. package/dist/dev/playback/behaviors/select-tracks.js.map +1 -0
  486. package/dist/dev/playback/behaviors/setup-failover-monitor.d.ts +11 -0
  487. package/dist/dev/playback/behaviors/setup-failover-monitor.d.ts.map +1 -0
  488. package/dist/dev/playback/behaviors/setup-failover-monitor.js +61 -0
  489. package/dist/dev/playback/behaviors/setup-failover-monitor.js.map +1 -0
  490. package/dist/dev/playback/behaviors/sync-preload.js +59 -0
  491. package/dist/dev/playback/behaviors/sync-preload.js.map +1 -0
  492. package/dist/dev/playback/behaviors/track-switching.d.ts +110 -0
  493. package/dist/dev/playback/behaviors/track-switching.d.ts.map +1 -0
  494. package/dist/dev/playback/behaviors/track-switching.js +407 -0
  495. package/dist/dev/playback/behaviors/track-switching.js.map +1 -0
  496. package/dist/dev/playback/engines/hls/engine-audio-only.d.ts +160 -0
  497. package/dist/dev/playback/engines/hls/engine-audio-only.d.ts.map +1 -0
  498. package/dist/dev/playback/engines/hls/engine-audio-only.js +94 -0
  499. package/dist/dev/playback/engines/hls/engine-audio-only.js.map +1 -0
  500. package/dist/dev/playback/engines/hls/engine-background-video.d.ts +131 -0
  501. package/dist/dev/playback/engines/hls/engine-background-video.d.ts.map +1 -0
  502. package/dist/dev/playback/engines/hls/engine-background-video.js +87 -0
  503. package/dist/dev/playback/engines/hls/engine-background-video.js.map +1 -0
  504. package/dist/dev/playback/engines/hls/engine.d.ts +289 -0
  505. package/dist/dev/playback/engines/hls/engine.d.ts.map +1 -0
  506. package/dist/dev/playback/engines/hls/engine.js +144 -0
  507. package/dist/dev/playback/engines/hls/engine.js.map +1 -0
  508. package/dist/dev/playback/primitives/derive-start-media-time.d.ts +16 -0
  509. package/dist/dev/playback/primitives/derive-start-media-time.d.ts.map +1 -0
  510. package/dist/dev/playback/primitives/error-messages.js +42 -0
  511. package/dist/dev/playback/primitives/error-messages.js.map +1 -0
  512. package/dist/dev/playback/primitives/failover-fetch.js +37 -0
  513. package/dist/dev/playback/primitives/failover-fetch.js.map +1 -0
  514. package/dist/dev/playback/primitives/head-peek.js +41 -0
  515. package/dist/dev/playback/primitives/head-peek.js.map +1 -0
  516. package/dist/dev/playback/primitives/live-window.js +63 -0
  517. package/dist/dev/playback/primitives/live-window.js.map +1 -0
  518. package/dist/dev/playback/primitives/relocation-pipelines.js +191 -0
  519. package/dist/dev/playback/primitives/relocation-pipelines.js.map +1 -0
  520. package/dist/dev/playback/primitives/report-track-conditions.d.ts +8 -0
  521. package/dist/dev/playback/primitives/report-track-conditions.d.ts.map +1 -0
  522. package/dist/dev/playback/primitives/report-track-conditions.js +74 -0
  523. package/dist/dev/playback/primitives/report-track-conditions.js.map +1 -0
  524. package/dist/dev/playback/primitives/segment-load-pipeline.d.ts +2 -0
  525. package/dist/dev/playback/primitives/segment-load-pipeline.js +96 -0
  526. package/dist/dev/playback/primitives/segment-load-pipeline.js.map +1 -0
  527. package/dist/dev/playback/primitives/selection-rules.d.ts +66 -0
  528. package/dist/dev/playback/primitives/selection-rules.d.ts.map +1 -0
  529. package/dist/dev/playback/primitives/selection-rules.js +115 -0
  530. package/dist/dev/playback/primitives/selection-rules.js.map +1 -0
  531. package/dist/dev/playback/primitives/source-buffer-messages.d.ts +40 -0
  532. package/dist/dev/playback/primitives/source-buffer-messages.d.ts.map +1 -0
  533. package/dist/dev/playback/primitives/text-segment-load-pipeline.d.ts +56 -0
  534. package/dist/dev/playback/primitives/text-segment-load-pipeline.d.ts.map +1 -0
  535. package/dist/dev/playback/primitives/text-segment-load-pipeline.js +36 -0
  536. package/dist/dev/playback/primitives/text-segment-load-pipeline.js.map +1 -0
  537. package/dist/dev/playback/primitives/text-track-messages.d.ts +14 -0
  538. package/dist/dev/playback/primitives/text-track-messages.d.ts.map +1 -0
  539. package/dist/dev/playback/primitives/track-types.js +53 -0
  540. package/dist/dev/playback/primitives/track-types.js.map +1 -0
  541. package/package.json +60 -41
  542. package/dist/adapter-25AtMN8s.d.ts +0 -719
  543. package/dist/adapter-25AtMN8s.d.ts.map +0 -1
  544. package/dist/adapter-CflgYzjF.js +0 -3556
  545. package/dist/adapter-CflgYzjF.js.map +0 -1
  546. package/dist/dom/index.d.ts +0 -221
  547. package/dist/dom/index.d.ts.map +0 -1
  548. package/dist/dom/index.js +0 -38
  549. package/dist/dom/index.js.map +0 -1
  550. package/dist/dom/playback-engine/index.d.ts +0 -2
  551. package/dist/dom/playback-engine/index.js +0 -4
  552. package/dist/index.d.ts +0 -13
  553. package/dist/index.d.ts.map +0 -1
  554. package/dist/index.js +0 -3
  555. package/dist/src-DRsS_H80.js +0 -14
  556. package/dist/src-DRsS_H80.js.map +0 -1
@@ -0,0 +1,407 @@
1
+ import { computed, peek } from "../../core/signals/primitives.js";
2
+ import { defineBehavior } from "../../core/composition/create-composition.js";
3
+ import { createMachineReactor } from "../../core/reactors/create-machine-reactor.js";
4
+ import { isResolvedPresentation } from "../../media/types/index.js";
5
+ import { getCodecFamilies, getTracksByType } from "../../media/utils/tracks.js";
6
+ import { SVTA_NO_SUPPORTED_AUDIO_TRACK, SVTA_NO_SUPPORTED_VIDEO_TRACK } from "../../media/errors.js";
7
+ import { matchesPartialTrack, pickTextTrackFromTracks, smallestCoveringPixelArea, tracksUnderPixelArea } from "../../media/primitives/select-tracks.js";
8
+ import { applyConstraints, applyRules, excludeUnplayableTracks, preferCodecFamilies, sameCandidateSet } from "../primitives/selection-rules.js";
9
+ import { DEFAULT_QUALITY_CONFIG, resolutionArea } from "../../media/abr/quality-selection.js";
10
+ import { getCdnId } from "../../media/utils/cdn.js";
11
+ import { DEFAULT_BANDWIDTH_CONFIG, getBandwidthEstimate } from "../../network/bandwidth-estimator.js";
12
+ import { emitError } from "./collect-errors.js";
13
+ //#region src/playback/behaviors/track-switching.ts
14
+ /**
15
+ * **Per-type track selection as a rule chain.** While a presentation is resolved, owns that type's
16
+ * `selected{Video,Audio,Text}TrackId` signal: pick a default, react to user intent and algorithmic ranking, and clear
17
+ * it on src unload.
18
+ *
19
+ * Selection runs in two stages. First a **hard-constraints pre-pass** (`applyConstraints`) prunes the unplayable from
20
+ * the candidate set — the failed-CDN constraint (`excludeFailedCdns`, failover cooldown), the capability constraint
21
+ * (`excludeUnplayableTracks`, codec support), and the codec-family sticky constraint (`stickToSelectedCodecs`, no
22
+ * `SourceBuffer.changeType()` — see its note). Then a small ordered chain of rules (`applyRules`) picks among the
23
+ * survivors. Each constraint/rule reads the signals it needs at apply time, so the effect subscribes to exactly what
24
+ * was consulted. The chain runs most authoritative first:
25
+ *
26
+ * 1. **user intent** — a soft filter on `user*TrackSelection`: narrow to the partial-track match; an empty match falls
27
+ * through to the full set.
28
+ * 2. **codec-family preference** — a soft filter on `preferredCodecs` (`preferCodecFamilies`, default AVC/AAC): on a
29
+ * mixed-codec source, narrow which family the _initial_ pick — the one the sticky constraint then holds — lands in.
30
+ * Behind user intent so an explicit initial pick may land anywhere; inert once the constraint narrows to a
31
+ * non-preferred family.
32
+ * 3. **active CDN** — a soft filter on `cdnPriority` (`preferActiveCdn`): narrow to the highest-priority CDN that still
33
+ * has tracks; an empty match falls through. Shared by video and audio, so every type stays on one CDN
34
+ * (`deriveCdnPriority` owns the list). No-op for non-redundant sources.
35
+ * 4. **player resolution** — a soft filter on `playerResolution` (`playerResolutionCap`, video only): narrow to the
36
+ * smallest rendition tier covering the player element, plus everything below it. No-op without a measurement. Ahead
37
+ * of the ranker but behind the CDN scope, so the cap chooses _within_ a host rather than between hosts.
38
+ * 5. **ranking** — the terminal sort: `rankByBandwidth`, shared by video and audio. Fitting tracks (within the throughput
39
+ * threshold) first, highest bitrate first; over-throughput tracks after, least-over first. Hysteresis via boosting
40
+ * the current track's sort weight by `upgradeMargin`.
41
+ *
42
+ * The composer's early-bail (one survivor → stop) is load-bearing: a user selection that narrows to a single track is
43
+ * the pick without the ranker running, so the bandwidth estimate is never read and the effect doesn't re-fire on
44
+ * bandwidth while that choice holds.
45
+ *
46
+ * Lifecycle: `'presentation-unresolved'` ↔ `'presentation-resolved'`. The resolved state owns the signal; its
47
+ * entry-returned cleanup clears it on exit (canonical cleanup-binds-to-setup per `reactors.md`).
48
+ *
49
+ * The pick is the chain's result mapped to a slot value by `resolveSelection` (default: the head,
50
+ * `applyRules(...)[0]`). Each variant supplies its **constraints + rule chain (+ optional resolveSelection)** via
51
+ * config; `setupTrackSwitching` owns only the lifecycle and runs what it's given. Video and audio run constraints
52
+ * `[excludeFailedCdns, excludeUnplayableTracks, stickToSelectedCodecs]` then rules `[filterByUserSelection,
53
+ * preferCodecFamilies, preferActiveCdn, rankByBandwidth]` and take the head; video inserts `playerResolutionCap` after
54
+ * the active-CDN scope, and `switchVideoTrack` also accepts ABR tuning config, `switchAudioTrack` takes none.
55
+ * `switchTextTrack` differs — selection is _optional_ (captions are opt-in / off-able), so it runs
56
+ * `[excludeFailedCdns]` + `[preferActiveCdn]` and supplies a text terminal (`pickResolvedTextTrack`) that resolves
57
+ * standing user intent (`userTextTrackSelection`, incl. `'off'`) and may yield no selection. (The active-CDN _scope_ is
58
+ * the sticky-pick half of multi-CDN; the failed-CDN _constraint_ is the failover half — prune the cooled-down CDN, the
59
+ * scope falls to the next.)
60
+ *
61
+ * When the pre-pass prunes a type that _has_ tracks to empty, the behavior clears the selection (so a now-unplayable
62
+ * pick can't linger and stall) and reports the type's `noSupportedTrackCode`. Which constraint emptied the set is
63
+ * deliberately not consulted — the behavior reads no constraint's state, so the chain stays composable. A type with no
64
+ * tracks at all is left alone; that's a legitimate source shape, not a failure. The late `createSourceBuffer` check
65
+ * stays as the structural backstop.
66
+ *
67
+ * Deferred: audio's preferred-language / default-track selection as standing soft-filter rules (previously the
68
+ * empty-slot picker, dropped in the move to the rule chain).
69
+ */
70
+ /** Default initial-bandwidth value before bandwidth measurements arrive. */
71
+ const DEFAULT_INITIAL_BANDWIDTH = 5e6;
72
+ /**
73
+ * User intent — a soft filter. Narrows to tracks matching the partial-track selection in `user*TrackSelection`; an
74
+ * empty match falls through (the composer skips it) to the unfiltered set — e.g. a stale id from a previous source.
75
+ */
76
+ function filterByUserSelection(tracks, { state, config }) {
77
+ const key = config.userSelectionKey;
78
+ if (!key) return tracks;
79
+ const filter = state[key]?.get();
80
+ return filter ? tracks.filter((track) => matchesPartialTrack(track, filter)) : tracks;
81
+ }
82
+ /**
83
+ * Player-resolution cap — a soft filter, video only. Narrows to the renditions worth delivering at the player element's
84
+ * rendered size, so a small embed doesn't pull segments nobody can perceive. The tighter sibling of
85
+ * `screenResolutionCap`: the element's box, not the screen behind it.
86
+ *
87
+ * The cap is the _smallest tier that still covers the player_, and everything at or below it survives — not "everything
88
+ * at or below the player's area," which under-serves a player falling between two tiers. Take an 800×450 player against
89
+ * a 360p/720p/1080p ladder: only 360p is below it, so capping at the player's area would hold an 800-px-wide box to a
90
+ * 640-px-wide picture. The honest answer is the tier above, 720p, with 360p left in for the ranker.
91
+ * `smallestCoveringPixelArea` picks that cap; `tracksUnderPixelArea` — the same filter `screenResolutionCap` narrows
92
+ * with — applies it.
93
+ *
94
+ * Renditions declaring no width or height compare as area `0` and are never capped out — they can't be judged against
95
+ * the player, and dropping them could strand a source whose renditions all omit it.
96
+ *
97
+ * Runs _after_ `preferActiveCdn`, so it narrows within the host already chosen. Ahead of it, a cap that pruned every
98
+ * rendition of the preferred CDN would leave the scope to fall to the next one with survivors — a size preference
99
+ * silently moving playback to another host. Redundant streams normally mirror the same ladder, which makes that a
100
+ * nonstandard-but-legal mismatch across CDNs rather than an everyday case; the ordering costs nothing either way.
101
+ *
102
+ * Reading `state.playerResolution` through its signal is what subscribes the chain to resizes; `undefined` — no signal
103
+ * composed, or nothing to measure — means "don't cap" rather than a cap of zero, so the chain proceeds unnarrowed.
104
+ */
105
+ function playerResolutionCap(tracks, { state }) {
106
+ const playerResolution = state.playerResolution?.get();
107
+ if (!playerResolution) return tracks;
108
+ const cap = smallestCoveringPixelArea(tracks, playerResolution.width * playerResolution.height);
109
+ return tracksUnderPixelArea(tracks, cap);
110
+ }
111
+ /**
112
+ * Failed-CDN constraint — a _hard_ filter (constraints pre-pass), shared by video and audio. Removes tracks served from
113
+ * a CDN currently in failover cooldown (`failedCdns`, written by the failover monitor). Removed tracks are never
114
+ * attempted; the scope then narrows to the next surviving CDN in `cdnPriority`, and snaps back to the primary once it
115
+ * leaves cooldown.
116
+ *
117
+ * Passes everything through when there's no `failedCdns` signal/value. When it prunes _every_ track (all CDNs cooled
118
+ * down), the empty result is preserved (per `applyConstraints`) — "nothing playable," which clears the selection (no
119
+ * pick); a later CDN recovery refills the candidate set and re-picks.
120
+ */
121
+ function excludeFailedCdns(tracks, { state, config }) {
122
+ const failed = state.failedCdns?.get();
123
+ if (!failed?.length) return tracks;
124
+ const getCdnId$1 = config.getCdnId ?? getCdnId;
125
+ const failedSet = new Set(failed);
126
+ return tracks.filter((track) => !failedSet.has(getCdnId$1(track.url)));
127
+ }
128
+ /**
129
+ * Active-CDN scope — a soft filter, shared by video and audio. Narrows to the highest-priority CDN in `cdnPriority`
130
+ * (owned by `deriveCdnPriority`) that still has tracks, so every track type stays on one CDN. A redundant-streams
131
+ * source lists the same renditions on multiple hosts; this keeps the pick on one host rather than letting the ranker
132
+ * drift across them.
133
+ *
134
+ * "Active" is derived, not stored: constraints run before the rule chain, so a failed CDN's tracks are already pruned
135
+ * by the time this runs — "first CDN with survivors" _is_ the active CDN, and it falls through to the next on failover
136
+ * (and snaps back to the primary when it recovers). Content steering reorders `cdnPriority`; this rule just honors the
137
+ * order.
138
+ *
139
+ * Soft-filter semantics: passes through when there's no `cdnPriority` signal/value (no preference) or when nothing
140
+ * matches (`applyRules` skips an empty result). Non-redundant sources have one CDN, so the narrow is a no-op.
141
+ *
142
+ * The CDN-id derivation defaults to origin-based `getCdnId`, overridable via the `getCdnId` config — it must match the
143
+ * one `deriveCdnPriority` used to build `cdnPriority`, or no track's CDN would ever equal an entry.
144
+ */
145
+ function preferActiveCdn(tracks, { state, config }) {
146
+ const cdnPriority = state.cdnPriority?.get();
147
+ if (!cdnPriority?.length) return tracks;
148
+ const getCdnId$2 = config.getCdnId ?? getCdnId;
149
+ for (const cdn of cdnPriority) {
150
+ const tracksUsingCdn = tracks.filter((track) => getCdnId$2(track.url) === cdn);
151
+ if (tracksUsingCdn.length) return tracksUsingCdn;
152
+ }
153
+ return tracks;
154
+ }
155
+ /**
156
+ * Codec-family sticky constraint — a _hard_ filter for the constraints pre-pass, shared by video and audio, and the
157
+ * reason the re-evaluating variants can run ABR over a mixed-codec source at all: SPF implements no
158
+ * `SourceBuffer.changeType()`, so once segments of the selected track's codec families are what a buffer was created
159
+ * for, a pick outside them could never play — constraint semantics ("can't play here"), not preference. Removes the
160
+ * candidates whose codec-family set doesn't _equal_ the selected track's (set-equality so a muxed `hvc1,mp4a` rendition
161
+ * can't pass as a match for `avc1,mp4a` on its audio half). Purely relational: the lock _is_ the current selection's
162
+ * families, no state of its own. Pruned pre-pass, a cross-family user selection mid-stream never reaches the user
163
+ * filter, which falls through unhonored instead of killing playback. Before any selection exists (the initial pick) it
164
+ * removes nothing, which is what leaves the initial family choice to the rule chain (user intent, then
165
+ * `preferCodecFamilies`).
166
+ *
167
+ * The selected track's families come from the _presentation's_ track list, not the already-pruned candidates: a CDN
168
+ * entering cooldown may prune the current track itself while same-family renditions survive on another host, and the
169
+ * lock must carry over to them. Removes nothing when: no selection yet, a selection the presentation no longer carries,
170
+ * or a selected track without codecs (then no candidate's compatibility is decidable — same inertness as
171
+ * `preferCodecFamilies` on a codec-less ladder).
172
+ *
173
+ * When the selected family genuinely vanishes from the playable set, the pre-pass empties: the behavior reports the
174
+ * type's no-supported-track code and clears the selection — an explicable stop instead of a cross-family append
175
+ * surfacing as an opaque decode error. Clearing also releases the lock (it keys on the live selection), so a following
176
+ * pick may land in the surviving family on freshly-created buffer actors; whether the append layer survives that
177
+ * rebuild is the changeType gap, out of this constraint's hands. If `changeType` support ever lands, this constraint is
178
+ * what relaxes.
179
+ *
180
+ * Reading the selection here — a slot the picking effect itself writes, from inside the candidate-set computed — is
181
+ * safe only because the effect scheduler revalidates an effect's sources after each run; see `core/signals/effect.ts`
182
+ * (`revalidateSources`) for the lost-wakeup it prevents.
183
+ *
184
+ * Composed only into the re-evaluating `switch*` variants: the pinned `selectVideoTrack` (background compositions)
185
+ * evaluates once and never re-picks, so it's immune by construction.
186
+ */
187
+ function stickToSelectedCodecs(tracks, { state, config }) {
188
+ const currentId = state[config.selectionKey].get();
189
+ if (!currentId) return tracks;
190
+ const presentation = state.presentation.get();
191
+ if (!isResolvedPresentation(presentation)) return tracks;
192
+ const current = config.getTracks(presentation).find((track) => track.id === currentId);
193
+ const families = current && getCodecFamilies(current);
194
+ if (!families) return tracks;
195
+ return tracks.filter((track) => {
196
+ const candidateFamilies = getCodecFamilies(track);
197
+ return !!candidateFamilies && candidateFamilies.length === families.length && candidateFamilies.every((family) => families.includes(family));
198
+ });
199
+ }
200
+ /**
201
+ * Bandwidth ranking — the terminal sort, shared by video and audio. Orders by the throughput estimate: tracks within
202
+ * the bandwidth threshold first (fitting), highest bitrate first; then over-threshold tracks, least-over first. The
203
+ * head is the best-quality track that fits, falling back to the smallest over-throughput track when nothing fits.
204
+ *
205
+ * Hysteresis without temporal state: the current track's effective bitrate is boosted by `upgradeMargin` in the fitting
206
+ * sort, so a higher track only outranks it once it clears `current.bitrate * upgradeMargin` (no flapping on marginal
207
+ * bandwidth gains). Downgrades fall out for free — a current track over the threshold isn't in the fitting set to be
208
+ * boosted, so the best fit (a downgrade) wins immediately. Equal-bitrate tracks break by resolution (higher `width ×
209
+ * height` first), so an equal-bitrate ladder never picks a lower- quality rendition by manifest order; audio tracks
210
+ * carry no dimensions, so they area-compare equal and a stable sort keeps their candidate order (e.g. same-bitrate
211
+ * language variants). Early-bail skips this rule when a prior one narrowed to a single track, so the estimate is
212
+ * neither read nor subscribed while that holds.
213
+ */
214
+ function rankByBandwidth(tracks, { state, config }) {
215
+ const safetyMargin = config.quality?.safetyMargin ?? DEFAULT_QUALITY_CONFIG.safetyMargin;
216
+ const upgradeMargin = config.quality?.upgradeMargin ?? DEFAULT_QUALITY_CONFIG.upgradeMargin;
217
+ const initialBandwidth = config.initialBandwidth ?? 5e6;
218
+ const bandwidthConfig = {
219
+ ...DEFAULT_BANDWIDTH_CONFIG,
220
+ ...config.bandwidth
221
+ };
222
+ if (!state.bandwidthState) console.debug("[track-switching] rankByBandwidth: no bandwidthState signal in composition; ranking on initialBandwidth");
223
+ const threshold = getBandwidthEstimate(state.bandwidthState?.get(), initialBandwidth, bandwidthConfig) * safetyMargin;
224
+ const currentId = state[config.selectionKey].get();
225
+ const bitrate = (track) => track.bandwidth ?? 0;
226
+ const rank = (track) => track.id === currentId ? bitrate(track) * upgradeMargin : bitrate(track);
227
+ const fitting = tracks.filter((track) => bitrate(track) <= threshold).sort((a, b) => rank(b) - rank(a) || resolutionArea(b) - resolutionArea(a));
228
+ const over = tracks.filter((track) => bitrate(track) > threshold).sort((a, b) => bitrate(a) - bitrate(b) || resolutionArea(b) - resolutionArea(a));
229
+ return [...fitting, ...over];
230
+ }
231
+ /**
232
+ * Default final pick: the chain head. `applyRules` never narrows to nothing and early-bails to a single survivor, so
233
+ * video and audio always converge to a track and the head is the pick.
234
+ */
235
+ function selectChainHead(candidates) {
236
+ return candidates[0].id;
237
+ }
238
+ /**
239
+ * Terminal pick for text — the `resolveSelection` the text variant supplies. Resolves the standing
240
+ * `userTextTrackSelection` intent against the chain's survivors (already CDN-failover-pruned and active-CDN-scoped):
241
+ *
242
+ * - `'off'` → no selection (clear the slot). Sticky through re-evaluation, so a live refresh or failover re-run can't
243
+ * re-assert a default.
244
+ * - Explicit `Partial<TextTrack>` → narrow to the match (language-based). A stale pick whose match is gone (e.g. the
245
+ * language dropped on a source change) falls through to the default policy.
246
+ * - Auto (`undefined`) → the opt-in default policy (`preferredSubtitleLanguage` → `DEFAULT=YES + AUTOSELECT=YES` → none),
247
+ * via `pickTextTrackFromTracks`.
248
+ *
249
+ * Returning `undefined` is a real outcome (captions are opt-in), which is why the text variant relies on
250
+ * `setupTrackSwitching`'s no-selection seam.
251
+ */
252
+ function pickResolvedTextTrack(candidates, { state, config }) {
253
+ const intent = state.userTextTrackSelection?.get();
254
+ if (intent === "off") return void 0;
255
+ if (intent) {
256
+ const matched = candidates.filter((track) => matchesPartialTrack(track, intent));
257
+ if (matched.length) return matched[0].id;
258
+ }
259
+ return pickTextTrackFromTracks(candidates, config);
260
+ }
261
+ function setupTrackSwitching(deps) {
262
+ const { state, config } = deps;
263
+ const { selectionKey, getTracks, rules, resolveSelection = selectChainHead, noSupportedTrackCode } = config;
264
+ const derivedStateSignal = computed(() => isResolvedPresentation(state.presentation.get()) ? "presentation-resolved" : "presentation-unresolved");
265
+ const candidateSet = computed(() => {
266
+ const presentation = state.presentation.get();
267
+ if (!isResolvedPresentation(presentation)) return [];
268
+ return applyConstraints(config.constraints ?? [], getTracks(presentation), deps);
269
+ }, { equals: sameCandidateSet });
270
+ return createMachineReactor({
271
+ initial: "presentation-unresolved",
272
+ monitor: () => derivedStateSignal.get(),
273
+ states: {
274
+ "presentation-unresolved": {},
275
+ "presentation-resolved": {
276
+ entry: () => () => state[selectionKey].set(void 0),
277
+ effects: [() => {
278
+ const tracks = candidateSet.get();
279
+ if (!tracks.length) {
280
+ const presentation = peek(state.presentation);
281
+ if (isResolvedPresentation(presentation) && getTracks(presentation).length > 0) {
282
+ if (noSupportedTrackCode !== void 0) emitError(state, {
283
+ code: noSupportedTrackCode,
284
+ data: { selectionKey }
285
+ });
286
+ state[selectionKey].set(void 0);
287
+ }
288
+ return;
289
+ }
290
+ const candidates = applyRules(rules, tracks, deps);
291
+ if (!candidates.length) {
292
+ console.error("[track-switching] applyRules returned no candidates");
293
+ return;
294
+ }
295
+ state[selectionKey].set(resolveSelection(candidates, deps));
296
+ }]
297
+ }
298
+ }
299
+ });
300
+ }
301
+ /**
302
+ * Manage `selectedVideoTrackId`: pick a default on src load, dynamically adjust based on bandwidth, clear on src
303
+ * unload. Honors `userVideoTrackSelection` as a partial-track constraint on candidates; short-circuits ABR when the
304
+ * constraint narrows to a single track.
305
+ *
306
+ * @example
307
+ * const reactor = switchVideoTrack.setup({ state });
308
+ */
309
+ const switchVideoTrack = defineBehavior({
310
+ stateKeys: ["presentation", "selectedVideoTrackId"],
311
+ contextKeys: [],
312
+ setup: ({ state, config, ...otherProps }) => setupTrackSwitching({
313
+ ...otherProps,
314
+ state,
315
+ config: {
316
+ ...config,
317
+ selectionKey: "selectedVideoTrackId",
318
+ userSelectionKey: "userVideoTrackSelection",
319
+ getTracks: (presentation) => getTracksByType(presentation, "video"),
320
+ constraints: [
321
+ excludeFailedCdns,
322
+ excludeUnplayableTracks,
323
+ stickToSelectedCodecs
324
+ ],
325
+ rules: [
326
+ filterByUserSelection,
327
+ preferCodecFamilies,
328
+ preferActiveCdn,
329
+ playerResolutionCap,
330
+ rankByBandwidth
331
+ ],
332
+ noSupportedTrackCode: SVTA_NO_SUPPORTED_VIDEO_TRACK
333
+ }
334
+ })
335
+ });
336
+ /**
337
+ * Manage `selectedAudioTrackId`: pick a default on src load, narrow by `userAudioTrackSelection` filter, re-pick on
338
+ * filter change, clear on src unload.
339
+ *
340
+ * Mid-stream flush on language switch is handled by the segment-loader's `planTasks` (see
341
+ * `playback/actors/dom/segment-loader.ts`) — not this behavior. Same split as the video pipeline: slot owner writes;
342
+ * loader orchestrates segment + flush plans.
343
+ *
344
+ * @example
345
+ * const reactor = switchAudioTrack.setup({ state });
346
+ */
347
+ const switchAudioTrack = defineBehavior({
348
+ stateKeys: ["presentation", "selectedAudioTrackId"],
349
+ contextKeys: [],
350
+ setup: ({ state, config, ...otherProps }) => setupTrackSwitching({
351
+ ...otherProps,
352
+ state,
353
+ config: {
354
+ ...config,
355
+ selectionKey: "selectedAudioTrackId",
356
+ userSelectionKey: "userAudioTrackSelection",
357
+ getTracks: (presentation) => getTracksByType(presentation, "audio"),
358
+ constraints: [
359
+ excludeFailedCdns,
360
+ excludeUnplayableTracks,
361
+ stickToSelectedCodecs
362
+ ],
363
+ rules: [
364
+ filterByUserSelection,
365
+ preferCodecFamilies,
366
+ preferActiveCdn,
367
+ rankByBandwidth
368
+ ],
369
+ noSupportedTrackCode: SVTA_NO_SUPPORTED_AUDIO_TRACK
370
+ }
371
+ })
372
+ });
373
+ /**
374
+ * Manage `selectedTextTrackId` as the single-writer **output** of standing user intent (`userTextTrackSelection`)
375
+ * resolved against the playable, CDN-scoped text renditions: clear on src unload; re-resolve when a CDN fails or
376
+ * recovers.
377
+ *
378
+ * Unlike video/audio, the selection is _optional_ — captions are opt-in and the user can turn them off — so the chain
379
+ * skips the bandwidth ranker and the shared user-selection filter, and supplies a text-specific terminal
380
+ * (`pickResolvedTextTrack`) that may resolve to no-selection via `setupTrackSwitching`'s `resolveSelection` seam.
381
+ * Constraints are failed-CDN only (`excludeUnplayableTracks`/`canPlayTrack` is MSE-based — the wrong probe for text,
382
+ * whose playability is SPF-parser support); the active-CDN scope co-locates captions with the surviving CDN on
383
+ * failover.
384
+ *
385
+ * @example
386
+ * const reactor = switchTextTrack.setup({ state, config: { preferredSubtitleLanguage: 'en' } });
387
+ */
388
+ const switchTextTrack = defineBehavior({
389
+ stateKeys: ["presentation", "selectedTextTrackId"],
390
+ contextKeys: [],
391
+ setup: ({ state, config, ...otherProps }) => setupTrackSwitching({
392
+ ...otherProps,
393
+ state,
394
+ config: {
395
+ ...config,
396
+ selectionKey: "selectedTextTrackId",
397
+ getTracks: (presentation) => getTracksByType(presentation, "text"),
398
+ constraints: [excludeFailedCdns],
399
+ rules: [preferActiveCdn],
400
+ resolveSelection: pickResolvedTextTrack
401
+ }
402
+ })
403
+ });
404
+ //#endregion
405
+ export { DEFAULT_INITIAL_BANDWIDTH, setupTrackSwitching, stickToSelectedCodecs, switchAudioTrack, switchTextTrack, switchVideoTrack };
406
+
407
+ //# sourceMappingURL=track-switching.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"track-switching.js","names":["getCdnId","defaultGetCdnId"],"sources":["../../../../src/playback/behaviors/track-switching.ts"],"sourcesContent":["/**\n * **Per-type track selection as a rule chain.** While a presentation is resolved, owns that type's\n * `selected{Video,Audio,Text}TrackId` signal: pick a default, react to user intent and algorithmic ranking, and clear\n * it on src unload.\n *\n * Selection runs in two stages. First a **hard-constraints pre-pass** (`applyConstraints`) prunes the unplayable from\n * the candidate set — the failed-CDN constraint (`excludeFailedCdns`, failover cooldown), the capability constraint\n * (`excludeUnplayableTracks`, codec support), and the codec-family sticky constraint (`stickToSelectedCodecs`, no\n * `SourceBuffer.changeType()` — see its note). Then a small ordered chain of rules (`applyRules`) picks among the\n * survivors. Each constraint/rule reads the signals it needs at apply time, so the effect subscribes to exactly what\n * was consulted. The chain runs most authoritative first:\n *\n * 1. **user intent** — a soft filter on `user*TrackSelection`: narrow to the partial-track match; an empty match falls\n * through to the full set.\n * 2. **codec-family preference** — a soft filter on `preferredCodecs` (`preferCodecFamilies`, default AVC/AAC): on a\n * mixed-codec source, narrow which family the _initial_ pick — the one the sticky constraint then holds — lands in.\n * Behind user intent so an explicit initial pick may land anywhere; inert once the constraint narrows to a\n * non-preferred family.\n * 3. **active CDN** — a soft filter on `cdnPriority` (`preferActiveCdn`): narrow to the highest-priority CDN that still\n * has tracks; an empty match falls through. Shared by video and audio, so every type stays on one CDN\n * (`deriveCdnPriority` owns the list). No-op for non-redundant sources.\n * 4. **player resolution** — a soft filter on `playerResolution` (`playerResolutionCap`, video only): narrow to the\n * smallest rendition tier covering the player element, plus everything below it. No-op without a measurement. Ahead\n * of the ranker but behind the CDN scope, so the cap chooses _within_ a host rather than between hosts.\n * 5. **ranking** — the terminal sort: `rankByBandwidth`, shared by video and audio. Fitting tracks (within the throughput\n * threshold) first, highest bitrate first; over-throughput tracks after, least-over first. Hysteresis via boosting\n * the current track's sort weight by `upgradeMargin`.\n *\n * The composer's early-bail (one survivor → stop) is load-bearing: a user selection that narrows to a single track is\n * the pick without the ranker running, so the bandwidth estimate is never read and the effect doesn't re-fire on\n * bandwidth while that choice holds.\n *\n * Lifecycle: `'presentation-unresolved'` ↔ `'presentation-resolved'`. The resolved state owns the signal; its\n * entry-returned cleanup clears it on exit (canonical cleanup-binds-to-setup per `reactors.md`).\n *\n * The pick is the chain's result mapped to a slot value by `resolveSelection` (default: the head,\n * `applyRules(...)[0]`). Each variant supplies its **constraints + rule chain (+ optional resolveSelection)** via\n * config; `setupTrackSwitching` owns only the lifecycle and runs what it's given. Video and audio run constraints\n * `[excludeFailedCdns, excludeUnplayableTracks, stickToSelectedCodecs]` then rules `[filterByUserSelection,\n * preferCodecFamilies, preferActiveCdn, rankByBandwidth]` and take the head; video inserts `playerResolutionCap` after\n * the active-CDN scope, and `switchVideoTrack` also accepts ABR tuning config, `switchAudioTrack` takes none.\n * `switchTextTrack` differs — selection is _optional_ (captions are opt-in / off-able), so it runs\n * `[excludeFailedCdns]` + `[preferActiveCdn]` and supplies a text terminal (`pickResolvedTextTrack`) that resolves\n * standing user intent (`userTextTrackSelection`, incl. `'off'`) and may yield no selection. (The active-CDN _scope_ is\n * the sticky-pick half of multi-CDN; the failed-CDN _constraint_ is the failover half — prune the cooled-down CDN, the\n * scope falls to the next.)\n *\n * When the pre-pass prunes a type that _has_ tracks to empty, the behavior clears the selection (so a now-unplayable\n * pick can't linger and stall) and reports the type's `noSupportedTrackCode`. Which constraint emptied the set is\n * deliberately not consulted — the behavior reads no constraint's state, so the chain stays composable. A type with no\n * tracks at all is left alone; that's a legitimate source shape, not a failure. The late `createSourceBuffer` check\n * stays as the structural backstop.\n *\n * Deferred: audio's preferred-language / default-track selection as standing soft-filter rules (previously the\n * empty-slot picker, dropped in the move to the rule chain).\n */\n\nimport { type AnySlotMap, defineBehavior } from '../../core/composition/create-composition';\nimport { createMachineReactor } from '../../core/reactors/create-machine-reactor';\nimport { computed, peek, type ReadonlySignal, type Signal } from '../../core/signals/primitives';\nimport { DEFAULT_QUALITY_CONFIG, type QualityConfig, resolutionArea } from '../../media/abr/quality-selection';\nimport { SVTA_NO_SUPPORTED_AUDIO_TRACK, SVTA_NO_SUPPORTED_VIDEO_TRACK } from '../../media/errors';\nimport type { Resolution } from '../../media/primitives/resolution';\nimport {\n matchesPartialTrack,\n pickTextTrackFromTracks,\n smallestCoveringPixelArea,\n type TextSelectionConfig,\n tracksUnderPixelArea,\n} from '../../media/primitives/select-tracks';\nimport {\n type AudioTrack,\n type CanPlayTrack,\n isResolvedPresentation,\n type MaybeResolvedPresentation,\n type PartiallyResolvedAudioTrack,\n type PartiallyResolvedTextTrack,\n type PartiallyResolvedVideoTrack,\n type TextTrack,\n type VideoTrack,\n} from '../../media/types';\nimport { getCdnId as defaultGetCdnId, type GetCdnId } from '../../media/utils/cdn';\nimport { getCodecFamilies, getTracksByType } from '../../media/utils/tracks';\nimport type { BandwidthConfig, BandwidthState } from '../../network/bandwidth-estimator';\nimport { DEFAULT_BANDWIDTH_CONFIG, getBandwidthEstimate } from '../../network/bandwidth-estimator';\nimport type { SelectionRule, SelectionRuleDeps } from '../primitives/selection-rules';\nimport {\n applyConstraints,\n applyRules,\n excludeUnplayableTracks,\n preferCodecFamilies,\n sameCandidateSet,\n} from '../primitives/selection-rules';\nimport { type ErrorEmitterState, emitError } from './collect-errors';\n\n// ============================================================================\n// State + Config\n// ============================================================================\n\n/**\n * The slots `setupTrackSwitching` itself owns: the `presentation` gate it reads and the per-type `selected*TrackId` it\n * writes. Rule-only inputs are deliberately absent — `user*TrackSelection` and `bandwidthState` belong to whoever\n * materializes them (the embedder via `shareSignals`, the buffer-actor sampler), and each rule declares the signal it\n * consults as an optional slot on its own deps map, so the behavior never assumes a rule's signal exists.\n */\nexport interface TrackSwitchingState {\n presentation?: MaybeResolvedPresentation;\n selectedVideoTrackId?: string;\n selectedAudioTrackId?: string;\n selectedTextTrackId?: string;\n}\n\n/**\n * Config for `switchVideoTrack` — the ABR tuning read by its ranker rule (`rankByBandwidth`). `quality.safetyMargin` is\n * the bandwidth-headroom multiplier; `quality.upgradeMargin` the hysteresis ratio gating upgrades; `bandwidth` tunes\n * the estimator; `initialBandwidth` is the pre-sample fallback. Defaults: `DEFAULT_QUALITY_CONFIG` (0.85 / 1.15),\n * `DEFAULT_BANDWIDTH_CONFIG`, `DEFAULT_INITIAL_BANDWIDTH` (5 Mbps).\n */\nexport interface SwitchVideoTrackConfig {\n quality?: Partial<QualityConfig>;\n bandwidth?: Partial<BandwidthConfig>;\n initialBandwidth?: number;\n /** Override CDN-id derivation (shared by the CDN scope + failover constraint). */\n getCdnId?: GetCdnId;\n /**\n * Codec capability probe read by the `excludeUnplayableTracks` hard constraint — drops renditions this environment\n * can't decode before selection runs. Injected (rather than imported) so the DOM-free behavior never reaches a DOM\n * API directly; the engine defaults it to the `MediaSource.isTypeSupported`-backed `canPlayTrack`. Absent → no codec\n * filtering (the constraint passes everything through).\n */\n canPlayTrack?: CanPlayTrack;\n /**\n * Codec families (RFC 6381 4CCs, e.g. `'avc1'` / `'hvc1'` / `'mp4a'`) the initial pick prefers on a mixed-codec\n * source, read by the `preferCodecFamilies` scope. With no `SourceBuffer.changeType()`, the initial family is the one\n * `stickToSelectedCodecs` holds for the source's lifetime, so this decides which family that is. Cross-cutting like\n * `getCdnId` — one list serves video and audio (each type's rule matches only the families its tracks carry).\n * Defaults to `DEFAULT_PREFERRED_CODECS` (AVC + AAC); pass `[]` to disable.\n */\n preferredCodecs?: string[];\n}\n\n/** Default initial-bandwidth value before bandwidth measurements arrive. */\nexport const DEFAULT_INITIAL_BANDWIDTH = 5_000_000;\n\n// ============================================================================\n// Rule chain\n// ============================================================================\n\n// Re-exported so a consumer typing against this module's rules doesn't need a\n// second import; the definitions live in `../primitives/selection-rules` so the\n// simple `selectVideoTrack` variant can share them without pulling the ABR path\n// in with them. See that module's note.\nexport type { CodecPreferenceConfig, SelectionRule, SelectionRuleDeps } from '../primitives/selection-rules';\nexport {\n applyConstraints,\n applyRules,\n DEFAULT_PREFERRED_CODECS,\n excludeUnplayableTracks,\n preferCodecFamilies,\n} from '../primitives/selection-rules';\n\n// ============================================================================\n// Specialization helper\n//\n// `setupTrackSwitching` has the same shape as a Behavior `setup` function:\n// `({ state, config }) => Reactor`. Each `switchXTrack` export below calls\n// it from inside its own `defineBehavior` setup. Its generics — `S` (selection\n// slot key), `T` (candidate track type), `C` (the concrete config the variant\n// builds) — all infer from the passed `state` + `config`, so the variants need\n// no explicit type arguments. `C extends TrackSwitchingConfig<S, T>` lets the\n// variant's richer config (rule-specific fields included) flow through the\n// helper untouched; the rules read those fields off their own config views.\n//\n// -- Design note: why narrow `SelectionKey` / `UserSelectionKey` unions ----\n// Goal we did not reach: have callers \"fully pass in\" the slot keys, with\n// the helper enforcing zero internal knowledge of which literals are valid.\n// What blocks it: indexing a mapped-type intersection by a generic key.\n// When `S extends keyof TrackSwitchingState` (or `string`), TS conservatively\n// treats `state[selectionKey]` as the union of every possible match across\n// the intersected mapped portions — including the fixed-key signal\n// (`presentation`) — and widens to their value-type union.\n// The sibling pattern hits the same constraint and answers it the same way:\n// `SelectedTrackKey` in `select-tracks.ts` is a hardcoded narrow union for\n// the same reason.\n//\n// Current pick is the narrow-union route because it matches siblings and\n// the unions read as documentation (\"these are the slots this helper\n// manages\") rather than restriction. Extending to a new track-switching\n// axis is one literal per union.\n// --------------------------------------------------------------------------\n// ============================================================================\n\n/**\n * Minimum candidate-track shape consumed by the helper and its rules: an `id` (the pick), a `url` (the active-CDN scope\n * derives the CDN from it), an optional `bandwidth` (the ranker's throughput sort), and optional `width`/`height` (the\n * ranker's equal-bitrate tie-break — absent on audio, so audio candidates area-compare equal). Every\n * resolved/partially-resolved video track carries them all; audio tracks omit the dimensions.\n */\ntype SwitchableTrack = {\n id: string;\n url: string;\n bandwidth?: number;\n width?: number;\n height?: number;\n // Read by the capability constraint to probe codec support. Optional on the\n // minimal shape; every resolved/partially-resolved video & audio candidate\n // carries them, and an absent `mimeType` makes a track unprobeable (kept).\n mimeType?: string;\n codecs?: string[];\n};\n\n/**\n * Map the rule chain's surviving candidates to the final selection id, or `undefined` for a deliberate no-selection.\n * Defaults to the chain head (`selectChainHead`) — the always-pick contract video and audio rely on (`applyRules`\n * guarantees a non-empty result, so the head is always there). A variant whose selection is legitimately optional\n * (text: opt-in captions, explicit off) supplies its own picker that may return `undefined`; the helper writes that\n * straight through to the slot, clearing it.\n */\nexport type ResolveSelection<T extends SwitchableTrack, State = unknown, Context = unknown, Config = unknown> = (\n candidates: readonly T[],\n deps: SelectionRuleDeps<State, Context, Config>\n) => string | undefined;\n\ntype SelectionKey = 'selectedVideoTrackId' | 'selectedAudioTrackId' | 'selectedTextTrackId';\ntype UserSelectionKey = 'userVideoTrackSelection' | 'userAudioTrackSelection';\n\n// Each mapped value references `P` so TS keeps the per-key dependency and\n// resolves `state[selectionKey]` to the right arm. `T` (track type) stays out\n// of the state map (it flows through `TrackSwitchingConfig` instead).\n//\n// Only the behavior's own lifecycle signals are required here: the presentation\n// gate and the selection slot it writes. Signals a *rule* reads but the\n// behavior doesn't — `user*TrackSelection` (the user-selection filter) and\n// `bandwidthState` (the bandwidth ranker) — are NOT here; each rule declares\n// the signal it needs as *optional* on its own deps and reads it defensively,\n// so the behavior never assumes a rule-only signal exists. Those slots are\n// materialized by whoever owns them: `shareSignals` for the consumer-input\n// `user*TrackSelection`, the buffer-actor sampler for `bandwidthState`.\nexport type TrackSwitchingStateMap<S extends SelectionKey> = {\n presentation: ReadonlySignal<TrackSwitchingState['presentation']>;\n} & { [P in S]: Signal<TrackSwitchingState[P]> };\n\n/**\n * The lifecycle map plus the _optional_ `errors` slot reporters append to. Owned by `collectErrors`; optional so a\n * composition without it still type-checks and emission no-ops. The behavior reads no constraint's state — see\n * `noSupportedTrackCode`.\n */\ntype TrackSwitchingReporterStateMap<S extends SelectionKey> = TrackSwitchingStateMap<S> & ErrorEmitterState;\n\n/**\n * Config `setupTrackSwitching` itself reads — its own wiring: which selection slot to write and clear (`selectionKey`),\n * how to enumerate candidate tracks (`getTracks`), the optional **hard-constraints pre-pass** (`constraints`, applied\n * before the chain to prune the unplayable), and the **rule chain** to run (`rules`), and how to map the chain's\n * survivors to the final pick (`resolveSelection`, defaulting to the chain head). Rule-/constraint-specific config is\n * deliberately absent — each declares the fields it reads as _optional_ on its own config view (`UserSelectionConfig`,\n * `BandwidthRankerConfig`), so the behavior never enumerates them. The variant builds the concrete config as this base\n * plus whatever its chain consults; it flows through untouched as the `C` type param on `setupTrackSwitching`.\n */\ninterface TrackSwitchingConfig<S extends SelectionKey, T extends SwitchableTrack> {\n selectionKey: S;\n getTracks: (presentation: MaybeResolvedPresentation) => readonly T[];\n constraints?: readonly SelectionRule<T, TrackSwitchingStateMap<S>, AnySlotMap, TrackSwitchingConfig<S, T>>[];\n rules: readonly SelectionRule<T, TrackSwitchingStateMap<S>, AnySlotMap, TrackSwitchingConfig<S, T>>[];\n /**\n * Map the chain's surviving candidates to the final selection id. Optional — absent means the chain head\n * (`selectChainHead`), the always-pick path video and audio use. A variant with optional selection (text) supplies\n * one that may return `undefined`.\n */\n resolveSelection?: ResolveSelection<T, TrackSwitchingStateMap<S>, AnySlotMap, TrackSwitchingConfig<S, T>>;\n /**\n * SVTA code to report when this type _has_ tracks but the constraints pruned every one. Per-variant because the\n * condition isn't universally an error: video and audio supply {@link SVTA_NO_SUPPORTED_VIDEO_TRACK} /\n * {@link SVTA_NO_SUPPORTED_AUDIO_TRACK}, while text supplies none — an unavailable subtitle track is a legitimate\n * outcome, not a playback failure. Absent → the selection still clears, nothing is reported.\n */\n noSupportedTrackCode?: number;\n}\n\n/**\n * State the user-selection filter reads: the lifecycle map plus an _optional_ user-selection slot (keyed by `U`),\n * holding a partial-track description to match against the candidates (`Partial<T>` — `{ id }`, `{ language }`, `{\n * height }`, …). The slot exists only when the composition provides it (materialized by `shareSignals`); the filter\n * reads it defensively and no-ops when it's absent (no user override).\n */\ntype UserSelectionStateMap<\n S extends SelectionKey,\n U extends UserSelectionKey,\n T extends SwitchableTrack,\n> = TrackSwitchingStateMap<S> & {\n [P in U]?: ReadonlySignal<Partial<T> | undefined>;\n};\n\n/**\n * Config the user-selection filter reads: `userSelectionKey` names the state slot holding the user's selection.\n * _Optional_ on the rule's view — the base config doesn't carry it, so an unwired key means \"no user selection\" and the\n * filter passes through. The variants always supply it.\n */\ntype UserSelectionConfig<\n S extends SelectionKey,\n U extends UserSelectionKey,\n T extends SwitchableTrack,\n> = TrackSwitchingConfig<S, T> & { userSelectionKey?: U };\n\n/**\n * State the bandwidth ranker reads: the lifecycle map plus an _optional_ `bandwidthState`. The signal exists only when\n * the composition includes a bandwidth sampler; the ranker reads it defensively and falls back to `initialBandwidth`\n * (with a debug note) when it's absent.\n */\ntype BandwidthRankerStateMap<S extends SelectionKey> = TrackSwitchingStateMap<S> & {\n bandwidthState?: ReadonlySignal<BandwidthState | undefined>;\n};\n\n/**\n * Config the bandwidth ranker reads: the ABR tuning in `SwitchVideoTrackConfig` (`quality` / `bandwidth` /\n * `initialBandwidth`), all optional with defaults.\n */\ntype BandwidthRankerConfig<S extends SelectionKey, T extends SwitchableTrack> = TrackSwitchingConfig<S, T> &\n SwitchVideoTrackConfig;\n\n/**\n * State the player-resolution cap reads: TrackSwitchingStateMap plus the _optional_ player measurement, manifested by\n * `trackPlayerResolution`.\n */\ntype PlayerResolutionCapStateMap<S extends SelectionKey> = TrackSwitchingStateMap<S> & {\n playerResolution?: ReadonlySignal<Resolution | undefined>;\n};\n\n/**\n * State the active-CDN scope reads: the lifecycle map plus an _optional_ `cdnPriority` — the manifest-ordered CDN list\n * (most-preferred first). The signal exists only when the composition includes `deriveCdnPriority` (which materializes\n * + owns it); the scope reads it defensively and passes through when it's absent (no CDN preference).\n */\ntype CdnScopeStateMap<S extends SelectionKey> = TrackSwitchingStateMap<S> & {\n cdnPriority?: ReadonlySignal<string[] | undefined>;\n};\n\n/**\n * State the failed-CDN constraint reads: the lifecycle map plus an _optional_ `failedCdns` — the CDN ids currently in\n * failover cooldown. The signal exists only when the composition includes a failover monitor (or an external driver);\n * the constraint reads it defensively and excludes nothing when it's absent.\n */\ntype CdnConstraintStateMap<S extends SelectionKey> = TrackSwitchingStateMap<S> & {\n failedCdns?: ReadonlySignal<string[] | undefined>;\n};\n\n/**\n * Config the CDN rules read: the base config plus an _optional_ `getCdnId` override. Both `excludeFailedCdns` and\n * `preferActiveCdn` derive a track's CDN from its URL; the override must be the _same_ one `deriveCdnPriority` and the\n * failover trip use, or the keys stop matching. Optional → defaults to the origin-based `getCdnId`, so the base config\n * (without it) stays assignable.\n */\ntype CdnRuleConfig<S extends SelectionKey, T extends SwitchableTrack> = TrackSwitchingConfig<S, T> & {\n getCdnId?: GetCdnId;\n};\n\ntype VideoTrackCandidate = PartiallyResolvedVideoTrack | VideoTrack;\ntype AudioTrackCandidate = PartiallyResolvedAudioTrack | AudioTrack;\ntype TextTrackCandidate = PartiallyResolvedTextTrack | TextTrack;\n\n// ----------------------------------------------------------------------------\n// Rules — defined outside the behavior closure, parameterized only by their\n// deps. Each is generic over the slot keys + track type; the variant's\n// concrete keys instantiate it where the chain is assembled.\n// ----------------------------------------------------------------------------\n\n/**\n * User intent — a soft filter. Narrows to tracks matching the partial-track selection in `user*TrackSelection`; an\n * empty match falls through (the composer skips it) to the unfiltered set — e.g. a stale id from a previous source.\n */\nfunction filterByUserSelection<S extends SelectionKey, U extends UserSelectionKey, T extends SwitchableTrack>(\n tracks: readonly T[],\n { state, config }: SelectionRuleDeps<UserSelectionStateMap<S, U, T>, AnySlotMap, UserSelectionConfig<S, U, T>>\n): readonly T[] {\n const key = config.userSelectionKey;\n if (!key) return tracks;\n\n const filter = state[key]?.get();\n\n return filter ? tracks.filter((track) => matchesPartialTrack(track, filter)) : tracks;\n}\n\n/**\n * Player-resolution cap — a soft filter, video only. Narrows to the renditions worth delivering at the player element's\n * rendered size, so a small embed doesn't pull segments nobody can perceive. The tighter sibling of\n * `screenResolutionCap`: the element's box, not the screen behind it.\n *\n * The cap is the _smallest tier that still covers the player_, and everything at or below it survives — not \"everything\n * at or below the player's area,\" which under-serves a player falling between two tiers. Take an 800×450 player against\n * a 360p/720p/1080p ladder: only 360p is below it, so capping at the player's area would hold an 800-px-wide box to a\n * 640-px-wide picture. The honest answer is the tier above, 720p, with 360p left in for the ranker.\n * `smallestCoveringPixelArea` picks that cap; `tracksUnderPixelArea` — the same filter `screenResolutionCap` narrows\n * with — applies it.\n *\n * Renditions declaring no width or height compare as area `0` and are never capped out — they can't be judged against\n * the player, and dropping them could strand a source whose renditions all omit it.\n *\n * Runs _after_ `preferActiveCdn`, so it narrows within the host already chosen. Ahead of it, a cap that pruned every\n * rendition of the preferred CDN would leave the scope to fall to the next one with survivors — a size preference\n * silently moving playback to another host. Redundant streams normally mirror the same ladder, which makes that a\n * nonstandard-but-legal mismatch across CDNs rather than an everyday case; the ordering costs nothing either way.\n *\n * Reading `state.playerResolution` through its signal is what subscribes the chain to resizes; `undefined` — no signal\n * composed, or nothing to measure — means \"don't cap\" rather than a cap of zero, so the chain proceeds unnarrowed.\n */\nfunction playerResolutionCap<S extends SelectionKey, T extends SwitchableTrack>(\n tracks: readonly T[],\n { state }: SelectionRuleDeps<PlayerResolutionCapStateMap<S>, AnySlotMap, TrackSwitchingConfig<S, T>>\n): readonly T[] {\n const playerResolution = state.playerResolution?.get();\n if (!playerResolution) return tracks;\n\n // A player larger than every rendition has no covering tier, so the cap is\n // `undefined` and the filter's unbounded default narrows nothing.\n const cap = smallestCoveringPixelArea(tracks, playerResolution.width * playerResolution.height);\n\n return tracksUnderPixelArea(tracks, cap);\n}\n\n/**\n * Failed-CDN constraint — a _hard_ filter (constraints pre-pass), shared by video and audio. Removes tracks served from\n * a CDN currently in failover cooldown (`failedCdns`, written by the failover monitor). Removed tracks are never\n * attempted; the scope then narrows to the next surviving CDN in `cdnPriority`, and snaps back to the primary once it\n * leaves cooldown.\n *\n * Passes everything through when there's no `failedCdns` signal/value. When it prunes _every_ track (all CDNs cooled\n * down), the empty result is preserved (per `applyConstraints`) — \"nothing playable,\" which clears the selection (no\n * pick); a later CDN recovery refills the candidate set and re-picks.\n */\nfunction excludeFailedCdns<S extends SelectionKey, T extends SwitchableTrack>(\n tracks: readonly T[],\n { state, config }: SelectionRuleDeps<CdnConstraintStateMap<S>, AnySlotMap, CdnRuleConfig<S, T>>\n): readonly T[] {\n const failed = state.failedCdns?.get();\n if (!failed?.length) return tracks;\n\n const getCdnId = config.getCdnId ?? defaultGetCdnId;\n const failedSet = new Set(failed);\n\n return tracks.filter((track) => !failedSet.has(getCdnId(track.url)));\n}\n\n/**\n * Active-CDN scope — a soft filter, shared by video and audio. Narrows to the highest-priority CDN in `cdnPriority`\n * (owned by `deriveCdnPriority`) that still has tracks, so every track type stays on one CDN. A redundant-streams\n * source lists the same renditions on multiple hosts; this keeps the pick on one host rather than letting the ranker\n * drift across them.\n *\n * \"Active\" is derived, not stored: constraints run before the rule chain, so a failed CDN's tracks are already pruned\n * by the time this runs — \"first CDN with survivors\" _is_ the active CDN, and it falls through to the next on failover\n * (and snaps back to the primary when it recovers). Content steering reorders `cdnPriority`; this rule just honors the\n * order.\n *\n * Soft-filter semantics: passes through when there's no `cdnPriority` signal/value (no preference) or when nothing\n * matches (`applyRules` skips an empty result). Non-redundant sources have one CDN, so the narrow is a no-op.\n *\n * The CDN-id derivation defaults to origin-based `getCdnId`, overridable via the `getCdnId` config — it must match the\n * one `deriveCdnPriority` used to build `cdnPriority`, or no track's CDN would ever equal an entry.\n */\nfunction preferActiveCdn<S extends SelectionKey, T extends SwitchableTrack>(\n tracks: readonly T[],\n { state, config }: SelectionRuleDeps<CdnScopeStateMap<S>, AnySlotMap, CdnRuleConfig<S, T>>\n): readonly T[] {\n const cdnPriority = state.cdnPriority?.get();\n if (!cdnPriority?.length) return tracks;\n\n const getCdnId = config.getCdnId ?? defaultGetCdnId;\n\n for (const cdn of cdnPriority) {\n const tracksUsingCdn = tracks.filter((track) => getCdnId(track.url) === cdn);\n if (tracksUsingCdn.length) return tracksUsingCdn;\n }\n\n return tracks;\n}\n\n/**\n * Codec-family sticky constraint — a _hard_ filter for the constraints pre-pass, shared by video and audio, and the\n * reason the re-evaluating variants can run ABR over a mixed-codec source at all: SPF implements no\n * `SourceBuffer.changeType()`, so once segments of the selected track's codec families are what a buffer was created\n * for, a pick outside them could never play — constraint semantics (\"can't play here\"), not preference. Removes the\n * candidates whose codec-family set doesn't _equal_ the selected track's (set-equality so a muxed `hvc1,mp4a` rendition\n * can't pass as a match for `avc1,mp4a` on its audio half). Purely relational: the lock _is_ the current selection's\n * families, no state of its own. Pruned pre-pass, a cross-family user selection mid-stream never reaches the user\n * filter, which falls through unhonored instead of killing playback. Before any selection exists (the initial pick) it\n * removes nothing, which is what leaves the initial family choice to the rule chain (user intent, then\n * `preferCodecFamilies`).\n *\n * The selected track's families come from the _presentation's_ track list, not the already-pruned candidates: a CDN\n * entering cooldown may prune the current track itself while same-family renditions survive on another host, and the\n * lock must carry over to them. Removes nothing when: no selection yet, a selection the presentation no longer carries,\n * or a selected track without codecs (then no candidate's compatibility is decidable — same inertness as\n * `preferCodecFamilies` on a codec-less ladder).\n *\n * When the selected family genuinely vanishes from the playable set, the pre-pass empties: the behavior reports the\n * type's no-supported-track code and clears the selection — an explicable stop instead of a cross-family append\n * surfacing as an opaque decode error. Clearing also releases the lock (it keys on the live selection), so a following\n * pick may land in the surviving family on freshly-created buffer actors; whether the append layer survives that\n * rebuild is the changeType gap, out of this constraint's hands. If `changeType` support ever lands, this constraint is\n * what relaxes.\n *\n * Reading the selection here — a slot the picking effect itself writes, from inside the candidate-set computed — is\n * safe only because the effect scheduler revalidates an effect's sources after each run; see `core/signals/effect.ts`\n * (`revalidateSources`) for the lost-wakeup it prevents.\n *\n * Composed only into the re-evaluating `switch*` variants: the pinned `selectVideoTrack` (background compositions)\n * evaluates once and never re-picks, so it's immune by construction.\n */\nexport function stickToSelectedCodecs<S extends SelectionKey, T extends SwitchableTrack>(\n tracks: readonly T[],\n { state, config }: SelectionRuleDeps<TrackSwitchingStateMap<S>, AnySlotMap, TrackSwitchingConfig<S, T>>\n): readonly T[] {\n const currentId = state[config.selectionKey].get();\n if (!currentId) return tracks;\n\n const presentation = state.presentation.get();\n if (!isResolvedPresentation(presentation)) return tracks;\n\n const current = config.getTracks(presentation).find((track) => track.id === currentId);\n const families = current && getCodecFamilies(current);\n if (!families) return tracks;\n\n return tracks.filter((track) => {\n const candidateFamilies = getCodecFamilies(track);\n\n return (\n !!candidateFamilies &&\n candidateFamilies.length === families.length &&\n candidateFamilies.every((family) => families.includes(family))\n );\n });\n}\n\n/**\n * Bandwidth ranking — the terminal sort, shared by video and audio. Orders by the throughput estimate: tracks within\n * the bandwidth threshold first (fitting), highest bitrate first; then over-threshold tracks, least-over first. The\n * head is the best-quality track that fits, falling back to the smallest over-throughput track when nothing fits.\n *\n * Hysteresis without temporal state: the current track's effective bitrate is boosted by `upgradeMargin` in the fitting\n * sort, so a higher track only outranks it once it clears `current.bitrate * upgradeMargin` (no flapping on marginal\n * bandwidth gains). Downgrades fall out for free — a current track over the threshold isn't in the fitting set to be\n * boosted, so the best fit (a downgrade) wins immediately. Equal-bitrate tracks break by resolution (higher `width ×\n * height` first), so an equal-bitrate ladder never picks a lower- quality rendition by manifest order; audio tracks\n * carry no dimensions, so they area-compare equal and a stable sort keeps their candidate order (e.g. same-bitrate\n * language variants). Early-bail skips this rule when a prior one narrowed to a single track, so the estimate is\n * neither read nor subscribed while that holds.\n */\nfunction rankByBandwidth<S extends SelectionKey, T extends SwitchableTrack>(\n tracks: readonly T[],\n { state, config }: SelectionRuleDeps<BandwidthRankerStateMap<S>, AnySlotMap, BandwidthRankerConfig<S, T>>\n): readonly T[] {\n const safetyMargin = config.quality?.safetyMargin ?? DEFAULT_QUALITY_CONFIG.safetyMargin;\n const upgradeMargin = config.quality?.upgradeMargin ?? DEFAULT_QUALITY_CONFIG.upgradeMargin;\n const initialBandwidth = config.initialBandwidth ?? DEFAULT_INITIAL_BANDWIDTH;\n const bandwidthConfig: BandwidthConfig = { ...DEFAULT_BANDWIDTH_CONFIG, ...config.bandwidth };\n\n if (!state.bandwidthState) {\n console.debug(\n '[track-switching] rankByBandwidth: no bandwidthState signal in composition; ranking on initialBandwidth'\n );\n }\n\n const threshold = getBandwidthEstimate(state.bandwidthState?.get(), initialBandwidth, bandwidthConfig) * safetyMargin;\n const currentId = state[config.selectionKey].get();\n const bitrate = (track: T) => track.bandwidth ?? 0;\n // Boost the current track's sort weight by upgradeMargin (fitting set only) so\n // an upgrade must clear current.bitrate * upgradeMargin to outrank it.\n const rank = (track: T) => (track.id === currentId ? bitrate(track) * upgradeMargin : bitrate(track));\n // Equal bitrate → prefer higher resolution (width × height), so an\n // equal-bitrate ladder doesn't pick a lower-quality rendition by manifest\n // order. Audio tracks carry no dimensions, so they area-compare equal and\n // keep candidate order (stable sort).\n const fitting = tracks\n .filter((track) => bitrate(track) <= threshold)\n .sort((a, b) => rank(b) - rank(a) || resolutionArea(b) - resolutionArea(a));\n const over = tracks\n .filter((track) => bitrate(track) > threshold)\n .sort((a, b) => bitrate(a) - bitrate(b) || resolutionArea(b) - resolutionArea(a));\n\n return [...fitting, ...over];\n}\n\n/**\n * Default final pick: the chain head. `applyRules` never narrows to nothing and early-bails to a single survivor, so\n * video and audio always converge to a track and the head is the pick.\n */\nfunction selectChainHead<T extends SwitchableTrack>(candidates: readonly T[]): string {\n return candidates[0]!.id;\n}\n\n/**\n * State the text terminal reads: the lifecycle map plus an _optional_ `userTextTrackSelection` — the standing user\n * intent. `Partial<TextTrack>` is an explicit pick (language-based), `'off'` is explicit no-captions, `undefined` is\n * auto (no preference). The slot exists only when the composition materializes it (`shareSignals`); the terminal reads\n * it defensively and treats absence as auto.\n *\n * Unlike `user*TrackSelection` for video/audio, this carries the `'off'` sentinel and feeds the terminal pick (not the\n * shared `filterByUserSelection`) — text is the only type whose selection is legitimately optional, so the off/auto\n * logic lives in one text-specific place rather than widening the shared filter.\n */\ntype TextSelectionStateMap = TrackSwitchingStateMap<'selectedTextTrackId'> & {\n userTextTrackSelection?: ReadonlySignal<Partial<TextTrack> | 'off' | undefined>;\n};\n\n/** Config the text terminal reads: the base config plus the opt-in default policy. */\ntype TextTerminalConfig = TrackSwitchingConfig<'selectedTextTrackId', TextTrackCandidate> & TextSelectionConfig;\n\n/**\n * Terminal pick for text — the `resolveSelection` the text variant supplies. Resolves the standing\n * `userTextTrackSelection` intent against the chain's survivors (already CDN-failover-pruned and active-CDN-scoped):\n *\n * - `'off'` → no selection (clear the slot). Sticky through re-evaluation, so a live refresh or failover re-run can't\n * re-assert a default.\n * - Explicit `Partial<TextTrack>` → narrow to the match (language-based). A stale pick whose match is gone (e.g. the\n * language dropped on a source change) falls through to the default policy.\n * - Auto (`undefined`) → the opt-in default policy (`preferredSubtitleLanguage` → `DEFAULT=YES + AUTOSELECT=YES` → none),\n * via `pickTextTrackFromTracks`.\n *\n * Returning `undefined` is a real outcome (captions are opt-in), which is why the text variant relies on\n * `setupTrackSwitching`'s no-selection seam.\n */\nfunction pickResolvedTextTrack<T extends TextTrackCandidate>(\n candidates: readonly T[],\n { state, config }: SelectionRuleDeps<TextSelectionStateMap, AnySlotMap, TextTerminalConfig>\n): string | undefined {\n const intent = state.userTextTrackSelection?.get();\n if (intent === 'off') return undefined;\n\n if (intent) {\n // The stored intent is a `Partial<TextTrack>`; cast to the candidate's own\n // partial shape so the generic `matchesPartialTrack` accepts it (every field\n // it carries — language, forced — exists on the candidate too).\n const matched = candidates.filter((track) => matchesPartialTrack(track, intent as Partial<T>));\n if (matched.length) return matched[0]!.id;\n }\n\n return pickTextTrackFromTracks(candidates, config);\n}\n\n// `context` is the composition's context map, threaded in by each variant's\n// rest-spread and typed as the generic slot-map shape (`AnySlotMap`). It can't\n// be a typed param on the `defineBehavior` setup without widening `ContextMap`\n// to its constraint and forcing the slot required, so the variants forward it\n// untyped via the rest and it lands here — absent on direct setup calls, and\n// passed straight through to the rules (which don't read it yet).\nexport function setupTrackSwitching<\n S extends SelectionKey,\n T extends SwitchableTrack,\n C extends TrackSwitchingConfig<S, T>,\n>(deps: { state: TrackSwitchingReporterStateMap<S>; context?: AnySlotMap; config: C }) {\n const { state, config } = deps;\n const { selectionKey, getTracks, rules, resolveSelection = selectChainHead, noSupportedTrackCode } = config;\n\n const derivedStateSignal = computed(() =>\n isResolvedPresentation(state.presentation.get())\n ? ('presentation-resolved' as const)\n : ('presentation-unresolved' as const)\n );\n\n // The playable candidate set — the tracks the rule chain gets to pick from,\n // derived *outside* the reaction. The hard-constraints pre-pass (capability\n // probing, CDN-failover cooldown) narrows the type's tracks before the chain\n // runs. Because this is a `computed`, a constraint's own signal reads (e.g.\n // `cdnHealth`) are tracked here, so when the playable set changes — a new\n // source, or a *dynamic* constraint like a CDN entering cooldown — the effect\n // re-picks. With no constraints configured this is just the type's tracks\n // while a presentation is resolved.\n //\n // The `equals` gates notification on the *set of track ids*, not array\n // identity: a live playlist refresh swaps in a new presentation object with\n // the same variant tracks, and a constraint's inputs can churn without\n // changing which tracks survive. In both cases the playable set is unchanged,\n // so the reaction must not re-fire (the rule chain still re-runs on its own\n // inputs — bandwidth, user selection). Same intent as `equalsById`, for the\n // track list.\n const candidateSet = computed<readonly T[]>(\n () => {\n const presentation = state.presentation.get();\n if (!isResolvedPresentation(presentation)) return [];\n\n return applyConstraints(config.constraints ?? [], getTracks(presentation), deps);\n },\n { equals: sameCandidateSet }\n );\n\n return createMachineReactor({\n initial: 'presentation-unresolved',\n monitor: () => derivedStateSignal.get(),\n states: {\n 'presentation-unresolved': {},\n 'presentation-resolved': {\n // Canonical cleanup-binds-to-setup: the selection signal's valid\n // lifespan is exactly 'presentation-resolved'. Clear fires on exit,\n // covering both src unload and behavior destroy.\n entry: () => () => state[selectionKey].set(undefined),\n effects: [\n () => {\n // Reactive read: subscribes the reaction to the candidate set, so a\n // new presentation — or a constraint pruning it — re-fires this and\n // re-picks.\n const tracks = candidateSet.get();\n\n // Empty candidate set — two shapes, told apart by whether the type\n // has any tracks at all:\n // - The type has no tracks (e.g. a video-only source's absent\n // audio): legitimate, nothing to pick or clear.\n // - The type HAS tracks but the hard-constraints pre-pass pruned\n // every one (every rendition undecodable, or every CDN in\n // failover cooldown): no playable rendition. Clear the selection\n // so a pick made earlier — e.g. under the initial mp4 label,\n // before resolve-track relabeled the type to a non-fMP4\n // container — can't linger as a now-unplayable selection and\n // silently stall the pipeline.\n if (!tracks.length) {\n const presentation = peek(state.presentation);\n const hasTracksOfType = isResolvedPresentation(presentation) && getTracks(presentation).length > 0;\n\n if (hasTracksOfType) {\n // Reported generically: *why* the set emptied is the constraints'\n // business, not this behavior's, so no constraint's state is read\n // here and no cause is distinguished. Whatever the reason, a type\n // that has renditions but none selectable can't play — a codec\n // this environment can't decode, or every CDN failed, which is\n // itself fatal-or-nearly so. Finer causes (container vs codec)\n // would need `CanPlayTrack` to report a reason; see\n // `internal/design/spf/features/errors.md`.\n if (noSupportedTrackCode !== undefined) {\n emitError(state, { code: noSupportedTrackCode, data: { selectionKey } });\n }\n\n state[selectionKey].set(undefined);\n }\n\n return;\n }\n\n // The whole deps object passes straight through to every rule in the\n // variant-supplied chain (state + config from the behavior; context\n // threaded in by the variant's rest-spread). Typed against the base\n // config — each rule re-declares the extra fields it reads as\n // optional, and the concrete `C` is assignable to the base.\n const candidates = applyRules<T, TrackSwitchingStateMap<S>, AnySlotMap, TrackSwitchingConfig<S, T>>(\n rules,\n tracks,\n deps\n );\n\n // applyRules early-bails to a single survivor and never narrows to\n // nothing (a soft filter that would empty the set falls through), so\n // the pick is just the head. An empty result means a rule misbehaved\n // — applyRules is supposed to account for those cases, so surface it.\n if (!candidates.length) {\n console.error('[track-switching] applyRules returned no candidates');\n return;\n }\n\n // Map survivors to the final id. Defaults to the chain head; a\n // variant with optional selection (text) may resolve to `undefined`,\n // which clears the slot (e.g. explicit off, opt-in decline).\n // No change-guard needed: the slot uses default (Object.is) equality,\n // so re-setting the same value is a no-op (no notify, no re-fire).\n state[selectionKey].set(resolveSelection(candidates, deps));\n },\n ],\n },\n },\n });\n}\n\n// ============================================================================\n// Variant: switchVideoTrack — bandwidth-driven ABR\n// ============================================================================\n\n/**\n * Manage `selectedVideoTrackId`: pick a default on src load, dynamically adjust based on bandwidth, clear on src\n * unload. Honors `userVideoTrackSelection` as a partial-track constraint on candidates; short-circuits ABR when the\n * constraint narrows to a single track.\n *\n * @example\n * const reactor = switchVideoTrack.setup({ state });\n */\nexport const switchVideoTrack = defineBehavior({\n stateKeys: ['presentation', 'selectedVideoTrackId'],\n contextKeys: [],\n setup: ({\n state,\n config,\n ...otherProps\n }: {\n state: TrackSwitchingStateMap<'selectedVideoTrackId'>;\n config?: SwitchVideoTrackConfig;\n }) =>\n setupTrackSwitching({\n ...otherProps,\n state,\n config: {\n ...config,\n selectionKey: 'selectedVideoTrackId',\n userSelectionKey: 'userVideoTrackSelection',\n getTracks: (presentation) => getTracksByType(presentation, 'video') as readonly VideoTrackCandidate[],\n constraints: [excludeFailedCdns, excludeUnplayableTracks, stickToSelectedCodecs],\n rules: [filterByUserSelection, preferCodecFamilies, preferActiveCdn, playerResolutionCap, rankByBandwidth],\n noSupportedTrackCode: SVTA_NO_SUPPORTED_VIDEO_TRACK,\n },\n }),\n});\n\n// ============================================================================\n// Variant: switchAudioTrack — bandwidth-ranked (shared ranker)\n// ============================================================================\n\n/**\n * Manage `selectedAudioTrackId`: pick a default on src load, narrow by `userAudioTrackSelection` filter, re-pick on\n * filter change, clear on src unload.\n *\n * Mid-stream flush on language switch is handled by the segment-loader's `planTasks` (see\n * `playback/actors/dom/segment-loader.ts`) — not this behavior. Same split as the video pipeline: slot owner writes;\n * loader orchestrates segment + flush plans.\n *\n * @example\n * const reactor = switchAudioTrack.setup({ state });\n */\nexport const switchAudioTrack = defineBehavior({\n stateKeys: ['presentation', 'selectedAudioTrackId'],\n contextKeys: [],\n setup: ({\n state,\n config,\n ...otherProps\n }: {\n state: TrackSwitchingStateMap<'selectedAudioTrackId'>;\n // Shares the video config shape so the engine config spreads through (CDN\n // derivation + any future cross-cutting fields).\n config?: SwitchVideoTrackConfig;\n }) =>\n setupTrackSwitching({\n ...otherProps,\n state,\n config: {\n // Spread engine config so cross-cutting fields (`getCdnId`, future shared\n // tuning) flow through like they do for video, then override the per-type\n // wiring. Video-only ABR tuning (`quality`/`bandwidth`/`initialBandwidth`)\n // rides along into the shared `rankByBandwidth` too; harmless since audio\n // has no `bandwidthState` to act on it and the ranker always yields a pick.\n // FOLLOW-UP: a shared config type for the genuinely cross-cutting fields\n // would keep video-only tuning out of audio entirely (CJP).\n ...config,\n selectionKey: 'selectedAudioTrackId',\n userSelectionKey: 'userAudioTrackSelection',\n getTracks: (presentation) => getTracksByType(presentation, 'audio') as readonly AudioTrackCandidate[],\n constraints: [excludeFailedCdns, excludeUnplayableTracks, stickToSelectedCodecs],\n rules: [filterByUserSelection, preferCodecFamilies, preferActiveCdn, rankByBandwidth],\n noSupportedTrackCode: SVTA_NO_SUPPORTED_AUDIO_TRACK,\n },\n }),\n});\n\n// ============================================================================\n// Variant: switchTextTrack — intent-resolved, optional selection\n// ============================================================================\n\n/**\n * Config for `switchTextTrack` — the opt-in default policy (`preferredSubtitleLanguage` / `includeForcedTracks` /\n * `enableDefaultTrack`, via `TextSelectionConfig`) read by the terminal when the user has no standing intent, plus the\n * `getCdnId` override shared with the CDN constraint + scope.\n */\nexport interface SwitchTextTrackConfig extends TextSelectionConfig {\n /** Override CDN-id derivation (shared by the failed-CDN constraint + active-CDN scope). */\n getCdnId?: GetCdnId;\n}\n\n/**\n * Manage `selectedTextTrackId` as the single-writer **output** of standing user intent (`userTextTrackSelection`)\n * resolved against the playable, CDN-scoped text renditions: clear on src unload; re-resolve when a CDN fails or\n * recovers.\n *\n * Unlike video/audio, the selection is _optional_ — captions are opt-in and the user can turn them off — so the chain\n * skips the bandwidth ranker and the shared user-selection filter, and supplies a text-specific terminal\n * (`pickResolvedTextTrack`) that may resolve to no-selection via `setupTrackSwitching`'s `resolveSelection` seam.\n * Constraints are failed-CDN only (`excludeUnplayableTracks`/`canPlayTrack` is MSE-based — the wrong probe for text,\n * whose playability is SPF-parser support); the active-CDN scope co-locates captions with the surviving CDN on\n * failover.\n *\n * @example\n * const reactor = switchTextTrack.setup({ state, config: { preferredSubtitleLanguage: 'en' } });\n */\nexport const switchTextTrack = defineBehavior({\n stateKeys: ['presentation', 'selectedTextTrackId'],\n contextKeys: [],\n setup: ({\n state,\n config,\n ...otherProps\n }: {\n state: TrackSwitchingStateMap<'selectedTextTrackId'>;\n config?: SwitchTextTrackConfig;\n }) =>\n // Explicit type args pin the candidate type to `TextTrackCandidate`. Video and\n // audio let it infer to the `SwitchableTrack` constraint (harmless — every\n // rule is assignable up to it), but the text terminal needs the narrower type\n // (it reads text-only fields), so it's named here rather than inferred.\n setupTrackSwitching<'selectedTextTrackId', TextTrackCandidate, TextTerminalConfig & SwitchTextTrackConfig>({\n ...otherProps,\n state,\n config: {\n ...config,\n selectionKey: 'selectedTextTrackId',\n getTracks: (presentation) => getTracksByType(presentation, 'text') as readonly TextTrackCandidate[],\n constraints: [excludeFailedCdns],\n rules: [preferActiveCdn],\n resolveSelection: pickResolvedTextTrack,\n },\n }),\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8IA,MAAa,4BAA4B;;;;;AAmOzC,SAAS,sBACP,QACA,EAAE,OAAO,UACK;CACd,MAAM,MAAM,OAAO;CACnB,IAAI,CAAC,KAAK,OAAO;CAEjB,MAAM,SAAS,MAAM,IAAI,EAAE,IAAI;CAE/B,OAAO,SAAS,OAAO,QAAQ,UAAU,oBAAoB,OAAO,MAAM,CAAC,IAAI;AACjF;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAS,oBACP,QACA,EAAE,SACY;CACd,MAAM,mBAAmB,MAAM,kBAAkB,IAAI;CACrD,IAAI,CAAC,kBAAkB,OAAO;CAI9B,MAAM,MAAM,0BAA0B,QAAQ,iBAAiB,QAAQ,iBAAiB,MAAM;CAE9F,OAAO,qBAAqB,QAAQ,GAAG;AACzC;;;;;;;;;;;AAYA,SAAS,kBACP,QACA,EAAE,OAAO,UACK;CACd,MAAM,SAAS,MAAM,YAAY,IAAI;CACrC,IAAI,CAAC,QAAQ,QAAQ,OAAO;CAE5B,MAAMA,aAAW,OAAO,YAAYC;CACpC,MAAM,YAAY,IAAI,IAAI,MAAM;CAEhC,OAAO,OAAO,QAAQ,UAAU,CAAC,UAAU,IAAID,WAAS,MAAM,GAAG,CAAC,CAAC;AACrE;;;;;;;;;;;;;;;;;;AAmBA,SAAS,gBACP,QACA,EAAE,OAAO,UACK;CACd,MAAM,cAAc,MAAM,aAAa,IAAI;CAC3C,IAAI,CAAC,aAAa,QAAQ,OAAO;CAEjC,MAAMA,aAAW,OAAO,YAAYC;CAEpC,KAAK,MAAM,OAAO,aAAa;EAC7B,MAAM,iBAAiB,OAAO,QAAQ,UAAUD,WAAS,MAAM,GAAG,MAAM,GAAG;EAC3E,IAAI,eAAe,QAAQ,OAAO;CACpC;CAEA,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,SAAgB,sBACd,QACA,EAAE,OAAO,UACK;CACd,MAAM,YAAY,MAAM,OAAO,aAAa,CAAC,IAAI;CACjD,IAAI,CAAC,WAAW,OAAO;CAEvB,MAAM,eAAe,MAAM,aAAa,IAAI;CAC5C,IAAI,CAAC,uBAAuB,YAAY,GAAG,OAAO;CAElD,MAAM,UAAU,OAAO,UAAU,YAAY,CAAC,CAAC,MAAM,UAAU,MAAM,OAAO,SAAS;CACrF,MAAM,WAAW,WAAW,iBAAiB,OAAO;CACpD,IAAI,CAAC,UAAU,OAAO;CAEtB,OAAO,OAAO,QAAQ,UAAU;EAC9B,MAAM,oBAAoB,iBAAiB,KAAK;EAEhD,OACE,CAAC,CAAC,qBACF,kBAAkB,WAAW,SAAS,UACtC,kBAAkB,OAAO,WAAW,SAAS,SAAS,MAAM,CAAC;CAEjE,CAAC;AACH;;;;;;;;;;;;;;;AAgBA,SAAS,gBACP,QACA,EAAE,OAAO,UACK;CACd,MAAM,eAAe,OAAO,SAAS,gBAAgB,uBAAuB;CAC5E,MAAM,gBAAgB,OAAO,SAAS,iBAAiB,uBAAuB;CAC9E,MAAM,mBAAmB,OAAO,oBAAA;CAChC,MAAM,kBAAmC;EAAE,GAAG;EAA0B,GAAG,OAAO;CAAU;CAE5F,IAAI,CAAC,MAAM,gBACT,QAAQ,MACN,yGACF;CAGF,MAAM,YAAY,qBAAqB,MAAM,gBAAgB,IAAI,GAAG,kBAAkB,eAAe,IAAI;CACzG,MAAM,YAAY,MAAM,OAAO,aAAa,CAAC,IAAI;CACjD,MAAM,WAAW,UAAa,MAAM,aAAa;CAGjD,MAAM,QAAQ,UAAc,MAAM,OAAO,YAAY,QAAQ,KAAK,IAAI,gBAAgB,QAAQ,KAAK;CAKnG,MAAM,UAAU,OACb,QAAQ,UAAU,QAAQ,KAAK,KAAK,SAAS,CAAC,CAC9C,MAAM,GAAG,MAAM,KAAK,CAAC,IAAI,KAAK,CAAC,KAAK,eAAe,CAAC,IAAI,eAAe,CAAC,CAAC;CAC5E,MAAM,OAAO,OACV,QAAQ,UAAU,QAAQ,KAAK,IAAI,SAAS,CAAC,CAC7C,MAAM,GAAG,MAAM,QAAQ,CAAC,IAAI,QAAQ,CAAC,KAAK,eAAe,CAAC,IAAI,eAAe,CAAC,CAAC;CAElF,OAAO,CAAC,GAAG,SAAS,GAAG,IAAI;AAC7B;;;;;AAMA,SAAS,gBAA2C,YAAkC;CACpF,OAAO,WAAW,EAAE,CAAE;AACxB;;;;;;;;;;;;;;;AAiCA,SAAS,sBACP,YACA,EAAE,OAAO,UACW;CACpB,MAAM,SAAS,MAAM,wBAAwB,IAAI;CACjD,IAAI,WAAW,OAAO,OAAO,KAAA;CAE7B,IAAI,QAAQ;EAIV,MAAM,UAAU,WAAW,QAAQ,UAAU,oBAAoB,OAAO,MAAoB,CAAC;EAC7F,IAAI,QAAQ,QAAQ,OAAO,QAAQ,EAAE,CAAE;CACzC;CAEA,OAAO,wBAAwB,YAAY,MAAM;AACnD;AAQA,SAAgB,oBAId,MAAqF;CACrF,MAAM,EAAE,OAAO,WAAW;CAC1B,MAAM,EAAE,cAAc,WAAW,OAAO,mBAAmB,iBAAiB,yBAAyB;CAErG,MAAM,qBAAqB,eACzB,uBAAuB,MAAM,aAAa,IAAI,CAAC,IAC1C,0BACA,yBACP;CAkBA,MAAM,eAAe,eACb;EACJ,MAAM,eAAe,MAAM,aAAa,IAAI;EAC5C,IAAI,CAAC,uBAAuB,YAAY,GAAG,OAAO,CAAC;EAEnD,OAAO,iBAAiB,OAAO,eAAe,CAAC,GAAG,UAAU,YAAY,GAAG,IAAI;CACjF,GACA,EAAE,QAAQ,iBAAiB,CAC7B;CAEA,OAAO,qBAAqB;EAC1B,SAAS;EACT,eAAe,mBAAmB,IAAI;EACtC,QAAQ;GACN,2BAA2B,CAAC;GAC5B,yBAAyB;IAIvB,mBAAmB,MAAM,aAAa,CAAC,IAAI,KAAA,CAAS;IACpD,SAAS,OACD;KAIJ,MAAM,SAAS,aAAa,IAAI;KAahC,IAAI,CAAC,OAAO,QAAQ;MAClB,MAAM,eAAe,KAAK,MAAM,YAAY;MAG5C,IAFwB,uBAAuB,YAAY,KAAK,UAAU,YAAY,CAAC,CAAC,SAAS,GAE5E;OASnB,IAAI,yBAAyB,KAAA,GAC3B,UAAU,OAAO;QAAE,MAAM;QAAsB,MAAM,EAAE,aAAa;OAAE,CAAC;OAGzE,MAAM,aAAa,CAAC,IAAI,KAAA,CAAS;MACnC;MAEA;KACF;KAOA,MAAM,aAAa,WACjB,OACA,QACA,IACF;KAMA,IAAI,CAAC,WAAW,QAAQ;MACtB,QAAQ,MAAM,qDAAqD;MACnE;KACF;KAOA,MAAM,aAAa,CAAC,IAAI,iBAAiB,YAAY,IAAI,CAAC;IAC5D,CACF;GACF;EACF;CACF,CAAC;AACH;;;;;;;;;AAcA,MAAa,mBAAmB,eAAe;CAC7C,WAAW,CAAC,gBAAgB,sBAAsB;CAClD,aAAa,CAAC;CACd,QAAQ,EACN,OACA,QACA,GAAG,iBAKH,oBAAoB;EAClB,GAAG;EACH;EACA,QAAQ;GACN,GAAG;GACH,cAAc;GACd,kBAAkB;GAClB,YAAY,iBAAiB,gBAAgB,cAAc,OAAO;GAClE,aAAa;IAAC;IAAmB;IAAyB;GAAqB;GAC/E,OAAO;IAAC;IAAuB;IAAqB;IAAiB;IAAqB;GAAe;GACzG,sBAAsB;EACxB;CACF,CAAC;AACL,CAAC;;;;;;;;;;;;AAiBD,MAAa,mBAAmB,eAAe;CAC7C,WAAW,CAAC,gBAAgB,sBAAsB;CAClD,aAAa,CAAC;CACd,QAAQ,EACN,OACA,QACA,GAAG,iBAOH,oBAAoB;EAClB,GAAG;EACH;EACA,QAAQ;GAQN,GAAG;GACH,cAAc;GACd,kBAAkB;GAClB,YAAY,iBAAiB,gBAAgB,cAAc,OAAO;GAClE,aAAa;IAAC;IAAmB;IAAyB;GAAqB;GAC/E,OAAO;IAAC;IAAuB;IAAqB;IAAiB;GAAe;GACpF,sBAAsB;EACxB;CACF,CAAC;AACL,CAAC;;;;;;;;;;;;;;;;AA+BD,MAAa,kBAAkB,eAAe;CAC5C,WAAW,CAAC,gBAAgB,qBAAqB;CACjD,aAAa,CAAC;CACd,QAAQ,EACN,OACA,QACA,GAAG,iBASH,oBAA2G;EACzG,GAAG;EACH;EACA,QAAQ;GACN,GAAG;GACH,cAAc;GACd,YAAY,iBAAiB,gBAAgB,cAAc,MAAM;GACjE,aAAa,CAAC,iBAAiB;GAC/B,OAAO,CAAC,eAAe;GACvB,kBAAkB;EACpB;CACF,CAAC;AACL,CAAC"}
@@ -0,0 +1,94 @@
1
+ import { createComposition } from "../../../core/composition/create-composition.js";
2
+ import { makeShareSignals } from "../../../core/composition/share-signals.js";
3
+ import { loadAudioSegments } from "../../behaviors/dom/load-segments.js";
4
+ import { trackCurrentTime } from "../../behaviors/dom/track-current-time.js";
5
+ import { trackLoadTriggers } from "../../behaviors/dom/track-load-triggers.js";
6
+ import { deriveSharedMinStartMediaTime, establishStartMediaTime } from "../../behaviors/establish-start-media-time.js";
7
+ import { collectErrors } from "../../behaviors/collect-errors.js";
8
+ import { switchAudioTrack } from "../../behaviors/track-switching.js";
9
+ import { attachMediaSourceAsSourceElement } from "../../../media/dom/mse/mediasource-setup.js";
10
+ import { canPlayTrack } from "../../../media/dom/capabilities.js";
11
+ import { parseMultivariantPlaylist } from "../../../media/hls/parse-multivariant.js";
12
+ import { getResolvedSelectedTrackDuration } from "../../../media/utils/track-selection.js";
13
+ import { calculatePresentationDuration } from "../../behaviors/calculate-presentation-duration.js";
14
+ import { deriveCdnPriority } from "../../behaviors/derive-cdn-priority.js";
15
+ import { setupAirPlay } from "../../behaviors/dom/airplay.js";
16
+ import { applyStartPosition } from "../../behaviors/dom/apply-start-position.js";
17
+ import { endOfStream } from "../../behaviors/dom/end-of-stream.js";
18
+ import { recoverEndStall } from "../../behaviors/dom/recover-end-stall.js";
19
+ import { setupAudioBufferActors } from "../../behaviors/dom/setup-buffer-actors.js";
20
+ import { setupMediaSource } from "../../behaviors/dom/setup-mediasource.js";
21
+ import { updateMediaSourceDuration } from "../../behaviors/dom/update-mediasource-duration.js";
22
+ import { resolvePresentation } from "../../behaviors/resolve-presentation.js";
23
+ import { resolveAudioTrack } from "../../behaviors/resolve-track.js";
24
+ import { setupFailoverMonitor } from "../../behaviors/setup-failover-monitor.js";
25
+ import { syncPreload } from "../../behaviors/sync-preload.js";
26
+ import { relocationPipelinesFor } from "../../primitives/relocation-pipelines.js";
27
+ import { reportUnsupportedTrackConditions } from "../../primitives/report-track-conditions.js";
28
+ //#region src/playback/engines/hls/engine-audio-only.ts
29
+ const shareSignals = makeShareSignals(["userAudioTrackSelection", "disableRemotePlayback"]);
30
+ /**
31
+ * Create an audio-only HLS playback engine.
32
+ *
33
+ * Subtractive composition variant of `createHlsVideoEngine`: omits video-side behaviors (`resolveVideoTrack`,
34
+ * `switchVideoTrack`, `setupVideoBufferActors`, `loadVideoSegments`) and text-track behaviors (`switchTextTrack`,
35
+ * `resolveTextTrack`, `syncTextTracks`, `setupTextTrackActors`, `loadTextTrackSegments`). The remaining audio pipeline
36
+ * composes unchanged.
37
+ *
38
+ * Handles both truly audio-only HLS sources (no video stream-inf) and mixed-AV HLS sources where the audio rendition is
39
+ * selected and video / subtitle renditions are ignored at composition time. The variant decision is encoded by adapter
40
+ * choice; this engine does not branch on source shape.
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * let signals: HlsAudioEngineSignals;
45
+ * const engine = createHlsAudioEngine({
46
+ * preferredAudioLanguage: 'en',
47
+ * onSignalsReady: (refs) => {
48
+ * signals = refs;
49
+ * },
50
+ * });
51
+ *
52
+ * signals.context.mediaElement.set(audioEl);
53
+ * signals.state.presentation.set({ url: 'https://example.com/stream.m3u8' });
54
+ * ```;
55
+ */
56
+ function createHlsAudioEngine(config = {}) {
57
+ const deriveStartMediaTime = config.deriveStartMediaTime ?? deriveSharedMinStartMediaTime;
58
+ const finalConfig = {
59
+ ...config,
60
+ deriveStartMediaTime,
61
+ attachMediaSource: attachMediaSourceAsSourceElement,
62
+ canPlayTrack: config.canPlayTrack ?? canPlayTrack,
63
+ reportUnsupportedTrackConditions: config.reportUnsupportedTrackConditions ?? reportUnsupportedTrackConditions,
64
+ resolveDuration: config.resolveDuration ?? getResolvedSelectedTrackDuration,
65
+ parsePresentation: config.parsePresentation ?? parseMultivariantPlaylist,
66
+ audioMessagePipelines: relocationPipelinesFor("audio", deriveStartMediaTime)
67
+ };
68
+ return createComposition([
69
+ syncPreload,
70
+ trackLoadTriggers,
71
+ resolvePresentation,
72
+ deriveCdnPriority,
73
+ setupFailoverMonitor,
74
+ collectErrors,
75
+ switchAudioTrack,
76
+ resolveAudioTrack,
77
+ calculatePresentationDuration,
78
+ setupMediaSource,
79
+ updateMediaSourceDuration,
80
+ establishStartMediaTime,
81
+ setupAudioBufferActors,
82
+ setupAirPlay,
83
+ trackCurrentTime,
84
+ applyStartPosition,
85
+ loadAudioSegments,
86
+ endOfStream,
87
+ recoverEndStall,
88
+ shareSignals
89
+ ], { config: finalConfig });
90
+ }
91
+ //#endregion
92
+ export { createHlsAudioEngine };
93
+
94
+ //# sourceMappingURL=engine-audio-only.js.map