prismcast 1.6.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. package/dist/browser/cdp.js +1 -1
  2. package/dist/browser/cdp.js.map +1 -1
  3. package/dist/browser/channelSelection.d.ts +10 -34
  4. package/dist/browser/channelSelection.js +19 -96
  5. package/dist/browser/channelSelection.js.map +1 -1
  6. package/dist/browser/display.d.ts +19 -0
  7. package/dist/browser/display.js +16 -11
  8. package/dist/browser/display.js.map +1 -1
  9. package/dist/browser/index.d.ts +9 -46
  10. package/dist/browser/index.js +136 -191
  11. package/dist/browser/index.js.map +1 -1
  12. package/dist/browser/login.d.ts +65 -0
  13. package/dist/browser/login.js +193 -0
  14. package/dist/browser/login.js.map +1 -0
  15. package/dist/browser/precaching.js +12 -0
  16. package/dist/browser/precaching.js.map +1 -1
  17. package/dist/browser/tuning/comcastPolymer.d.ts +23 -0
  18. package/dist/browser/tuning/comcastPolymer.js +655 -0
  19. package/dist/browser/tuning/comcastPolymer.js.map +1 -0
  20. package/dist/browser/tuning/cox.d.ts +2 -0
  21. package/dist/browser/tuning/cox.js +14 -0
  22. package/dist/browser/tuning/cox.js.map +1 -0
  23. package/dist/browser/tuning/directv.js +1 -1
  24. package/dist/browser/tuning/directv.js.map +1 -1
  25. package/dist/browser/tuning/fox.js +2 -2
  26. package/dist/browser/tuning/fox.js.map +1 -1
  27. package/dist/browser/tuning/hbo.js +1 -1
  28. package/dist/browser/tuning/hbo.js.map +1 -1
  29. package/dist/browser/tuning/hulu.js +1 -1
  30. package/dist/browser/tuning/hulu.js.map +1 -1
  31. package/dist/browser/tuning/shared.d.ts +46 -0
  32. package/dist/browser/tuning/shared.js +100 -0
  33. package/dist/browser/tuning/shared.js.map +1 -0
  34. package/dist/browser/tuning/sling.js +1 -1
  35. package/dist/browser/tuning/sling.js.map +1 -1
  36. package/dist/browser/tuning/spectrum.js +1 -1
  37. package/dist/browser/tuning/spectrum.js.map +1 -1
  38. package/dist/browser/tuning/thumbnailRow.js +1 -1
  39. package/dist/browser/tuning/thumbnailRow.js.map +1 -1
  40. package/dist/browser/tuning/tileClick.js +1 -1
  41. package/dist/browser/tuning/tileClick.js.map +1 -1
  42. package/dist/browser/tuning/xfinity.js +10 -603
  43. package/dist/browser/tuning/xfinity.js.map +1 -1
  44. package/dist/browser/tuning/youtubeTv.js +1 -1
  45. package/dist/browser/tuning/youtubeTv.js.map +1 -1
  46. package/dist/browser/video.d.ts +18 -0
  47. package/dist/browser/video.js +69 -107
  48. package/dist/browser/video.js.map +1 -1
  49. package/dist/channels/index.d.ts +2 -2
  50. package/dist/channels/index.js +2075 -800
  51. package/dist/channels/index.js.map +1 -1
  52. package/dist/config/health.js +20 -2
  53. package/dist/config/health.js.map +1 -1
  54. package/dist/config/index.js +29 -64
  55. package/dist/config/index.js.map +1 -1
  56. package/dist/config/providerPacks.js +4 -1
  57. package/dist/config/providerPacks.js.map +1 -1
  58. package/dist/config/providers.d.ts +12 -5
  59. package/dist/config/providers.js +110 -94
  60. package/dist/config/providers.js.map +1 -1
  61. package/dist/config/sites.js +15 -9
  62. package/dist/config/sites.js.map +1 -1
  63. package/dist/config/userChannels.d.ts +50 -2
  64. package/dist/config/userChannels.js +212 -10
  65. package/dist/config/userChannels.js.map +1 -1
  66. package/dist/config/userConfig.d.ts +1 -1
  67. package/dist/config/userConfig.js +2 -15
  68. package/dist/config/userConfig.js.map +1 -1
  69. package/dist/hdhr/channelMap.d.ts +1 -1
  70. package/dist/hdhr/channelMap.js +4 -4
  71. package/dist/hdhr/channelMap.js.map +1 -1
  72. package/dist/index.js +9 -15
  73. package/dist/index.js.map +1 -1
  74. package/dist/native/index.d.ts +3 -0
  75. package/dist/native/index.js +2 -1
  76. package/dist/native/index.js.map +1 -1
  77. package/dist/native/probe.d.ts +4 -3
  78. package/dist/native/probe.js +36 -12
  79. package/dist/native/probe.js.map +1 -1
  80. package/dist/native/proxy.d.ts +2 -0
  81. package/dist/native/proxy.js +369 -326
  82. package/dist/native/proxy.js.map +1 -1
  83. package/dist/routes/components.d.ts +43 -0
  84. package/dist/routes/components.js +122 -0
  85. package/dist/routes/components.js.map +1 -1
  86. package/dist/routes/config/channels/index.d.ts +2 -2
  87. package/dist/routes/config/channels/index.js +1 -1
  88. package/dist/routes/config/channels/index.js.map +1 -1
  89. package/dist/routes/config/channels/routes.js +443 -65
  90. package/dist/routes/config/channels/routes.js.map +1 -1
  91. package/dist/routes/config/channels/table.d.ts +76 -0
  92. package/dist/routes/config/channels/table.js +352 -66
  93. package/dist/routes/config/channels/table.js.map +1 -1
  94. package/dist/routes/config/index.d.ts +1 -1
  95. package/dist/routes/config/index.js +1 -1
  96. package/dist/routes/config/index.js.map +1 -1
  97. package/dist/routes/config/providers.d.ts +6 -6
  98. package/dist/routes/config/providers.js +69 -95
  99. package/dist/routes/config/providers.js.map +1 -1
  100. package/dist/routes/index.d.ts +0 -16
  101. package/dist/routes/index.js +0 -17
  102. package/dist/routes/index.js.map +1 -1
  103. package/dist/routes/providers.js +106 -3
  104. package/dist/routes/providers.js.map +1 -1
  105. package/dist/routes/root/content.js +55 -38
  106. package/dist/routes/root/content.js.map +1 -1
  107. package/dist/routes/root/index.js +2 -1
  108. package/dist/routes/root/index.js.map +1 -1
  109. package/dist/routes/root/scripts/channels.js +772 -312
  110. package/dist/routes/root/scripts/channels.js.map +1 -1
  111. package/dist/routes/root/scripts/config.js +596 -544
  112. package/dist/routes/root/scripts/config.js.map +1 -1
  113. package/dist/routes/root/scripts/index.d.ts +1 -0
  114. package/dist/routes/root/scripts/index.js +1 -0
  115. package/dist/routes/root/scripts/index.js.map +1 -1
  116. package/dist/routes/root/scripts/shared.d.ts +6 -0
  117. package/dist/routes/root/scripts/shared.js +391 -0
  118. package/dist/routes/root/scripts/shared.js.map +1 -0
  119. package/dist/routes/root/scripts/status.js +36 -21
  120. package/dist/routes/root/scripts/status.js.map +1 -1
  121. package/dist/routes/root/styles.js +113 -8
  122. package/dist/routes/root/styles.js.map +1 -1
  123. package/dist/service/commands.js +2 -1
  124. package/dist/service/commands.js.map +1 -1
  125. package/dist/streaming/fmp4Segmenter.d.ts +2 -0
  126. package/dist/streaming/fmp4Segmenter.js +7 -4
  127. package/dist/streaming/fmp4Segmenter.js.map +1 -1
  128. package/dist/streaming/hls.js +269 -188
  129. package/dist/streaming/hls.js.map +1 -1
  130. package/dist/streaming/hlsResume.d.ts +9 -3
  131. package/dist/streaming/hlsResume.js +13 -6
  132. package/dist/streaming/hlsResume.js.map +1 -1
  133. package/dist/streaming/hlsSegments.d.ts +1 -2
  134. package/dist/streaming/hlsSegments.js +48 -46
  135. package/dist/streaming/hlsSegments.js.map +1 -1
  136. package/dist/streaming/lifecycle.js +8 -12
  137. package/dist/streaming/lifecycle.js.map +1 -1
  138. package/dist/streaming/monitor.js +625 -585
  139. package/dist/streaming/monitor.js.map +1 -1
  140. package/dist/streaming/mpegts.js +1 -1
  141. package/dist/streaming/mpegts.js.map +1 -1
  142. package/dist/streaming/preroll.d.ts +40 -20
  143. package/dist/streaming/preroll.js +147 -86
  144. package/dist/streaming/preroll.js.map +1 -1
  145. package/dist/streaming/recovery.d.ts +0 -6
  146. package/dist/streaming/recovery.js +0 -8
  147. package/dist/streaming/recovery.js.map +1 -1
  148. package/dist/streaming/registry.d.ts +36 -9
  149. package/dist/streaming/registry.js +6 -9
  150. package/dist/streaming/registry.js.map +1 -1
  151. package/dist/streaming/setup.d.ts +1 -1
  152. package/dist/streaming/setup.js +44 -21
  153. package/dist/streaming/setup.js.map +1 -1
  154. package/dist/streaming/showInfo.d.ts +7 -6
  155. package/dist/streaming/showInfo.js +156 -36
  156. package/dist/streaming/showInfo.js.map +1 -1
  157. package/dist/streaming/statusEmitter.d.ts +14 -2
  158. package/dist/streaming/statusEmitter.js +22 -4
  159. package/dist/streaming/statusEmitter.js.map +1 -1
  160. package/dist/types/channels.d.ts +31 -0
  161. package/dist/types/config.d.ts +2 -2
  162. package/dist/types/index.d.ts +1 -1
  163. package/dist/types/index.js.map +1 -1
  164. package/dist/types/profiles.d.ts +8 -3
  165. package/dist/types/selection.d.ts +1 -0
  166. package/dist/types/shared.d.ts +1 -1
  167. package/dist/utils/debugFilter.d.ts +0 -5
  168. package/dist/utils/debugFilter.js +5 -11
  169. package/dist/utils/debugFilter.js.map +1 -1
  170. package/dist/utils/delay.d.ts +12 -0
  171. package/dist/utils/delay.js +20 -0
  172. package/dist/utils/delay.js.map +1 -1
  173. package/dist/utils/evaluate.js +6 -11
  174. package/dist/utils/evaluate.js.map +1 -1
  175. package/dist/utils/ffmpeg.d.ts +13 -5
  176. package/dist/utils/ffmpeg.js +32 -11
  177. package/dist/utils/ffmpeg.js.map +1 -1
  178. package/dist/utils/format.d.ts +6 -0
  179. package/dist/utils/format.js +8 -0
  180. package/dist/utils/format.js.map +1 -1
  181. package/dist/utils/index.d.ts +1 -0
  182. package/dist/utils/index.js +1 -0
  183. package/dist/utils/index.js.map +1 -1
  184. package/dist/utils/logEmitter.js +1 -1
  185. package/dist/utils/logEmitter.js.map +1 -1
  186. package/dist/utils/retry.d.ts +15 -9
  187. package/dist/utils/retry.js +7 -23
  188. package/dist/utils/retry.js.map +1 -1
  189. package/dist/utils/timing.d.ts +5 -0
  190. package/dist/utils/timing.js +13 -0
  191. package/dist/utils/timing.js.map +1 -0
  192. package/dist/utils/version.js +2 -2
  193. package/dist/utils/version.js.map +1 -1
  194. package/package.json +5 -5
@@ -1,10 +1,10 @@
1
1
  import { LOG, formatError, runWithStreamContext, startTimer } from "../utils/index.js";
2
+ import { generatePrerollPlaylist, getPrerollCodec, getPrerollSegmentCount, isPrerollReady } from "./preroll.js";
2
3
  import { StreamSetupError, createPageWithCapture, generateStreamId, setupStream } from "./setup.js";
3
- import { consumeResumeData, getResumeSegmentIndex } from "./hlsResume.js";
4
4
  import { createHLSState, getAllStreams, getNextStreamId, getStream, getStreamCount, registerStream, updateLastAccess } from "./registry.js";
5
5
  import { createInitialStreamStatus, emitStreamAdded } from "./statusEmitter.js";
6
+ import { deleteResumeData, getResumeSegmentIndex, peekResumeData } from "./hlsResume.js";
6
7
  import { emitCurrentSystemStatus, isLoginModeActive, unregisterManagedPage } from "../browser/index.js";
7
- import { generatePrerollPlaylist, getPrerollSegmentCount, isPrerollReady } from "./preroll.js";
8
8
  import { getAllChannels, isPredefinedChannelDisabled } from "../config/userChannels.js";
9
9
  import { getAudioPlaylist, getAudioSegment, getInitSegment, getPlaylist, getSegment, getVideoPlaylist, waitForPlaylist } from "./hlsSegments.js";
10
10
  import { getAuthDomainForChannel, getProviderTagForChannel, getResolvedChannel, resolveProviderKey } from "../config/providers.js";
@@ -15,27 +15,34 @@ import { attemptNativeStreaming } from "../native/index.js";
15
15
  import { clearProbeCache } from "../native/probe.js";
16
16
  import { createFMP4Segmenter } from "./fmp4Segmenter.js";
17
17
  import { createHash } from "node:crypto";
18
+ import { getGpuCapabilities } from "../browser/display.js";
18
19
  import { getProviderBySlug } from "../browser/channelSelection.js";
19
20
  import { registerClient } from "./clients.js";
21
+ import { suppressPageAudio } from "../browser/video.js";
20
22
  import { triggerShowNameUpdate } from "./showInfo.js";
21
23
  /* This module handles HLS (HTTP Live Streaming) output using fMP4 (fragmented MP4) segments. HLS mode uses MP4/AAC capture from puppeteer-stream, which is then
22
- * segmented natively without any external dependencies. The overall flow uses a two-phase "preroll-first" architecture:
24
+ * segmented natively without any external dependencies. The stream initialization flow has three phases:
23
25
  *
24
- * 1. Client requests playlist at /hls/:name/stream.m3u8 (predefined channel) or /play?url=...&profile=... (ad-hoc URL)
25
- * 2. If no stream exists, a pending stream entry is registered immediately with a preroll playlist (black frame + silence). The client receives a valid, playable
26
- * playlist on the first request — no blocking wait for the real stream.
27
- * 3. Asynchronously, setupStream() creates the browser page, navigates, captures, and creates the fMP4 segmenter. The segmenter starts at segment index 10
28
- * (after the preroll range) with a pending discontinuity tag.
29
- * 4. When the segmenter produces its first real playlist, it overwrites the preroll playlist. The next client poll receives real content.
30
- * 5. Client fetches init.mp4 once, then media segments at /hls/:name/segmentN.m4s
31
- * 6. Idle timeout terminates streams with no recent segment requests
26
+ * Phase 1 — Registration (synchronous, in the request handler):
27
+ * The client requests a playlist. If no stream exists and preroll is available, a pending registry entry is registered immediately with a deferred preroll timer.
28
+ * The client receives a valid, playable playlist on the first request — no blocking wait for the real stream. If preroll is unavailable, the request blocks until
29
+ * stream setup completes (fallback path).
32
30
  *
33
- * Shared streams: If multiple clients request the same channel (or the same ad-hoc URL with the same profile), they share one segmenter. The first client triggers
31
+ * Phase 2 — Browser setup (async, fire-and-forget from the request handler):
32
+ * setupStream() creates the browser page, navigates to the URL, initializes playback, and starts capture. This produces the StreamSetupResult with the capture
33
+ * stream, page, profile, and monitor. The pending registry entry is filled in with these references.
34
+ *
35
+ * Phase 3 — Streaming pipeline (async, after browser setup):
36
+ * If the provider's manifest is interceptable, native HLS streaming is attempted via startNativeProxy(). If native is viable, the capture pipeline is stopped and
37
+ * the proxy takes over. Otherwise, createCaptureSegmenter() creates the fMP4 segmenter and pipes the capture stream. When the first real playlist arrives
38
+ * (from either the segmenter or native proxy), the preroll timer is cancelled and the client receives live content on the next poll.
39
+ *
40
+ * Shared streams: If multiple clients request the same channel (or the same ad-hoc URL with the same profile), they share one stream. The first client triggers
34
41
  * stream creation, and subsequent clients get the existing playlist and segments. Ad-hoc streams are identified by a synthetic key ("play-<hash>") derived from the
35
42
  * URL and profile, allowing them to use the same channelToStreamId deduplication mechanism as predefined channels.
36
43
  */
37
44
  // Delay before seeding the preroll playlist in milliseconds. If stream setup completes before this timer fires, the preroll is skipped and the client receives real
38
- // content directly. This ensures fast-tuning providers (native HLS at 2-3s, most capture providers at 4-7s) never see preroll, while slow providers (Xfinity at
45
+ // content directly. This ensures fast-tuning providers (native HLS at 2-3s, most capture providers at 4-7s) never see preroll, while slow providers (Xfinity/Cox at
39
46
  // 13-15s) get preroll content after the delay to prevent HTTP timeouts.
40
47
  const PREROLL_DELAY_MS = 9_000;
41
48
  // Login mode error body used by both validateChannel() and handlePlayStream() to ensure consistent response format.
@@ -122,7 +129,8 @@ export async function ensureChannelStream(channelName, req, res) {
122
129
  }
123
130
  // When the preroll is available, register a pending stream immediately with a preroll playlist so the client gets a valid playlist on the first request. The full
124
131
  // stream setup runs asynchronously. When the preroll is not available (FFmpeg missing or failed), fall back to blocking initialization.
125
- if (isPrerollReady()) {
132
+ const prerollCodec = getPrerollCodec();
133
+ if (isPrerollReady(prerollCodec)) {
126
134
  // Check capacity before registering the pending entry. The pending entry occupies a registry slot, so registering it at max capacity would cause setupStream's
127
135
  // capacity check to reject — after we've already returned a preroll playlist to the client. By gating here, we can still send a proper 503 error response.
128
136
  if (getStreamCount() >= CONFIG.streaming.maxConcurrentStreams) {
@@ -134,7 +142,7 @@ export async function ensureChannelStream(channelName, req, res) {
134
142
  }
135
143
  }
136
144
  const clientAddress = req.ip ?? req.socket.remoteAddress ?? null;
137
- const pending = registerPendingStream(channelName, validation.channel, clientAddress, req);
145
+ const pending = registerPendingStream(channelName, validation.channel, clientAddress, req, prerollCodec);
138
146
  // Launch async setup. Errors are caught here to clean up the pending entry and prevent unhandled rejections.
139
147
  void completeStreamSetup({
140
148
  channel: validation.channel,
@@ -346,8 +354,8 @@ async function sendPlaylistResponse(streamId, clientAddress, res) {
346
354
  // the segmenter's playlist takes over.
347
355
  const stream = getStream(streamId);
348
356
  if (stream && !stream.hls.hasRealPlaylist) {
349
- if (stream.hls.prerollBaseUrl && stream.hls.prerollStartTime) {
350
- playlist = generatePrerollPlaylist(stream.hls.prerollBaseUrl, stream.hls.resumeSegmentIndex, stream.hls.prerollStartTime);
357
+ if (stream.hls.prerollBaseUrl && stream.hls.prerollCodec && stream.hls.prerollStartTime) {
358
+ playlist = generatePrerollPlaylist(stream.hls.prerollBaseUrl, stream.hls.prerollCodec, stream.hls.resumeSegmentIndex, stream.hls.prerollStartTime);
351
359
  }
352
360
  LOG.debug("streaming:preroll", "Serving preroll playlist for stream %d.", streamId);
353
361
  }
@@ -392,6 +400,34 @@ function cleanupOrphanedSetup(segmenter) {
392
400
  LOG.debug("streaming:setup", "Stream was terminated during setup. Stopping orphaned segmenter.");
393
401
  segmenter.stop();
394
402
  }
403
+ // Maps vertical resolution heights to standard display labels. Used by formatNativeQuality() to convert "1920x1080" → "1080p".
404
+ const RESOLUTION_LABELS = { "1080": "1080p", "2160": "4K", "360": "360p", "480": "480p", "720": "720p" };
405
+ /**
406
+ * Formats the native HLS quality string for the "Streaming..." log line. Combines codec, bandwidth (as Mbps), and resolution (as standard label like "1080p")
407
+ * into a compact suffix. Returns an empty string when no values are available, or a comma-prefixed string like ", H264 12.1Mbps 1080p" for inclusion in the log.
408
+ * @param bandwidth - Declared bandwidth in bits per second from the manifest. Zero when absent.
409
+ * @param codec - Video codec label (e.g., "H264", "HEVC"), or null when absent.
410
+ * @param resolution - Resolution string from the manifest (e.g., "1920x1080"), or null when absent.
411
+ * @returns Formatted quality string for log output.
412
+ */
413
+ function formatNativeQuality(bandwidth, codec, resolution) {
414
+ const parts = [];
415
+ if (codec) {
416
+ parts.push(codec);
417
+ }
418
+ if (bandwidth > 0) {
419
+ parts.push((bandwidth / 1000000).toFixed(1) + "Mbps");
420
+ }
421
+ if (resolution) {
422
+ // Map the vertical resolution to a standard label. Parse the height from "WIDTHxHEIGHT" format.
423
+ const height = resolution.split("x")[1];
424
+ parts.push(RESOLUTION_LABELS[height] ?? resolution);
425
+ }
426
+ if (parts.length === 0) {
427
+ return "";
428
+ }
429
+ return ", " + parts.join(" ");
430
+ }
395
431
  /**
396
432
  * Creates a tab replacement handler for recovery from unresponsive browser tabs. When the monitor detects 3+ consecutive evaluate timeouts, it calls this handler to:
397
433
  * 1. Stop the current segmenter and FFmpeg process
@@ -553,14 +589,15 @@ export async function initializeStream(options) {
553
589
  * Registers a pending stream entry in the registry with deferred preroll. This is the synchronous Phase 1 of the two-phase stream initialization used by the HLS
554
590
  * playlist handler. The pending entry has a real stream ID but no playlist yet — the response is held until either the preroll timer fires (after PREROLL_DELAY_MS)
555
591
  * or real content arrives from the segmenter/native proxy. This ensures that fast-tuning streams (native, most capture providers) skip preroll entirely, while slow
556
- * streams (Xfinity at 13-15s) get preroll content after the delay.
592
+ * streams (Xfinity/Cox at 13-15s) get preroll content after the delay.
557
593
  * @param channelName - The channel key for registration and deduplication.
558
594
  * @param channel - The resolved channel definition.
559
595
  * @param clientAddress - Client IP address for Channels DVR API integration.
560
596
  * @param req - Express request object for deriving the base URL.
597
+ * @param codec - The preroll codec variant to use for this stream.
561
598
  * @returns The allocated stream IDs.
562
599
  */
563
- function registerPendingStream(channelName, channel, clientAddress, req) {
600
+ function registerPendingStream(channelName, channel, clientAddress, req, codec) {
564
601
  const numericStreamId = getNextStreamId();
565
602
  const streamIdStr = generateStreamId(channelName, channel.url);
566
603
  // Derive the base URL from the request for absolute preroll segment URLs.
@@ -578,18 +615,19 @@ function registerPendingStream(channelName, channel, clientAddress, req) {
578
615
  hls.resumeSegmentIndex = getResumeSegmentIndex(channelName) ?? 0;
579
616
  // Capture the stream start time at registration. This timestamp is used for the registry's startTime field (stream age display, etc.).
580
617
  const streamStartTime = new Date();
581
- if (isPrerollReady()) {
618
+ if (isPrerollReady(codec)) {
582
619
  // Set preroll metadata immediately at registration so the segmenter and native proxy can read it regardless of whether the deferred timer has fired. The segment
583
- // count and base URL are structural properties of the preroll system — they determine segment index offsets and composite playlist behavior. The timer controls
584
- // only the client-facing timing (when the standalone preroll playlist begins serving). Decoupling these ensures correct behavior for fast-tune/slow-proxy
585
- // scenarios (e.g., Fox native at 5s tune but 15s proxy first poll) where setup completes before the timer fires.
620
+ // count, codec, and base URL are structural properties of the preroll system — they determine segment index offsets, codec-aware URL paths, and composite playlist
621
+ // behavior. The timer controls only the client-facing timing (when the standalone preroll playlist begins serving). Decoupling these ensures correct behavior for
622
+ // fast-tune/slow-proxy scenarios (e.g., Fox native at 5s tune but 15s proxy first poll) where setup completes before the timer fires.
586
623
  hls.prerollBaseUrl = baseUrl;
587
- hls.prerollSegmentCount = getPrerollSegmentCount();
624
+ hls.prerollCodec = codec;
625
+ hls.prerollSegmentCount = getPrerollSegmentCount(codec);
588
626
  hls.prerollTimer = setTimeout(() => {
589
627
  // Record the preroll start time and seed the initial progressive playlist. On subsequent polls, sendPlaylistResponse() regenerates the playlist with an
590
628
  // advancing window based on elapsed time from this start time, simulating a live stream.
591
629
  hls.prerollStartTime = new Date();
592
- hls.playlist = generatePrerollPlaylist(baseUrl, hls.resumeSegmentIndex, hls.prerollStartTime);
630
+ hls.playlist = generatePrerollPlaylist(baseUrl, codec, hls.resumeSegmentIndex, hls.prerollStartTime);
593
631
  hls.signalPlaylistReady();
594
632
  }, PREROLL_DELAY_MS);
595
633
  }
@@ -606,9 +644,11 @@ function registerPendingStream(channelName, channel, clientAddress, req) {
606
644
  function createPendingEntry(options) {
607
645
  const { channel, channelName, hls, numericStreamId, streamIdStr, url } = options;
608
646
  registerStream({
647
+ captureCodec: null,
609
648
  channelName: channel?.name ?? null,
610
649
  clientAddress: options.clientAddress ?? null,
611
650
  ffmpegProcess: null,
651
+ hardwareAccelerated: false,
612
652
  hls,
613
653
  id: numericStreamId,
614
654
  info: {
@@ -616,7 +656,9 @@ function createPendingEntry(options) {
616
656
  storeKey: channelName
617
657
  },
618
658
  mpegTsClientCount: 0,
659
+ nativeBandwidth: 0,
619
660
  nativeProxy: null,
661
+ nativeResolution: null,
620
662
  page: null,
621
663
  preTuned: options.preTuned ?? false,
622
664
  profile: null,
@@ -652,13 +694,168 @@ function handleSetupFailure(numericStreamId, channelName, channel, error, logErr
652
694
  // Only log when the error won't be caught and logged by an outer handler (non-blocking fire-and-forget path).
653
695
  if (logError) {
654
696
  if (error instanceof StreamSetupError) {
655
- LOG.warn("Stream setup failed for %s: %s.", channelName, error.userMessage);
697
+ LOG.warn("Stream setup failed for %s: %s", channelName, error.userMessage);
656
698
  }
657
699
  else {
658
700
  LOG.error("Unexpected error during stream setup for %s: %s.", channelName, formatError(error));
659
701
  }
660
702
  }
661
703
  }
704
+ /**
705
+ * Attempts to upgrade the stream from capture to native HLS. Finalizes the manifest interception, probes the manifest, creates a native proxy, stops the capture
706
+ * pipeline, suppresses page audio, and updates the registry entry. Returns the codec and formatted quality string on success, or null if native is not viable.
707
+ * @param setup - The stream setup result from setupStream().
708
+ * @param numericStreamId - The stream's numeric ID.
709
+ * @param channelName - The channel key for logging and cache operations.
710
+ * @param url - The stream URL for the native proxy.
711
+ * @param mpegTsClient - Whether the client is an MPEG-TS consumer.
712
+ * @returns The native codec and quality info, or null if native streaming was not viable.
713
+ */
714
+ async function startNativeProxy(setup, numericStreamId, channelName, url, mpegTsClient) {
715
+ if (!setup.manifestInterception) {
716
+ return null;
717
+ }
718
+ setup.manifestInterception.finalize(setup.directTune);
719
+ // Read the preroll segment count from the pending entry to pass to the native coordinator. This value is set at registration time (not in the timer callback),
720
+ // so it's available regardless of whether the deferred preroll timer has fired. The proxy uses it for segment index offset. The base URL for composite playlists
721
+ // is read dynamically from the stream's HLS state at playlist generation time.
722
+ const pendingForNative = getStream(numericStreamId);
723
+ const nativePrerollSegmentCount = pendingForNative?.hls.prerollSegmentCount ?? 0;
724
+ const nativeResult = await attemptNativeStreaming({
725
+ channelName,
726
+ interceptionPromise: setup.manifestInterception.promise,
727
+ mpegTsClient,
728
+ onError: (error) => {
729
+ if (isTerminationInitiated(numericStreamId)) {
730
+ return;
731
+ }
732
+ // Log the error and clear the probe cache. The proxy has already stopped itself (set errorThresholdReached + stopped). The monitor detects
733
+ // hasErrored() on the next 2-second tick and triggers L3 fallback to capture mode, preserving the stream for the DVR client.
734
+ LOG.warn("Native proxy error for %s: %s. Falling back to capture.", channelName, error);
735
+ clearProbeCache(channelName);
736
+ },
737
+ page: setup.page,
738
+ prerollCodec: pendingForNative?.hls.prerollCodec ?? "h264",
739
+ prerollSegmentCount: nativePrerollSegmentCount,
740
+ streamId: numericStreamId,
741
+ streamIdStr: setup.streamId,
742
+ url
743
+ });
744
+ if (!nativeResult) {
745
+ return null;
746
+ }
747
+ const currentStream = getStream(numericStreamId);
748
+ if (!currentStream) {
749
+ nativeResult.proxy.stop();
750
+ return null;
751
+ }
752
+ // Stop the capture pipeline — native streaming replaces it entirely.
753
+ if (!setup.rawCaptureStream.destroyed) {
754
+ setup.rawCaptureStream.destroy();
755
+ }
756
+ if (setup.ffmpegProcess) {
757
+ setup.ffmpegProcess.kill();
758
+ }
759
+ // Update the registry entry to reflect native mode. For streams with separate audio, clear preroll state — preroll is muxed video+audio and can't be
760
+ // split into separate renditions. For muxed-audio streams, preserve preroll state so the proxy can build composite playlists with preroll entries.
761
+ currentStream.ffmpegProcess = null;
762
+ currentStream.hls.hasAudio = nativeResult.hasAudio;
763
+ if (nativeResult.hasAudio) {
764
+ currentStream.hls.prerollBaseUrl = null;
765
+ currentStream.hls.prerollCodec = null;
766
+ currentStream.hls.prerollSegmentCount = 0;
767
+ }
768
+ currentStream.captureCodec = nativeResult.codec;
769
+ currentStream.hardwareAccelerated = false;
770
+ currentStream.nativeBandwidth = nativeResult.bandwidth;
771
+ currentStream.nativeProxy = nativeResult.proxy;
772
+ currentStream.nativeResolution = nativeResult.resolution;
773
+ currentStream.rawCaptureStream = null;
774
+ currentStream.streamingMode = "native";
775
+ // Start the native proxy. Signal init segment readiness immediately — native MPEG-TS segments carry their own PAT/PMT codec configuration in every
776
+ // segment, so there is no separate init segment to wait for. Without this, MPEG-TS clients block on waitForInitSegment() and time out before the proxy's
777
+ // first poll cycle completes.
778
+ nativeResult.proxy.start();
779
+ currentStream.hls.signalInitSegmentReady();
780
+ // Suppress audio on the browser page. The page stays alive for token refresh but the video element's audio is not part of the native stream — without
781
+ // suppression, it plays audibly on the local machine.
782
+ await suppressPageAudio(setup.page);
783
+ LOG.debug("native:coordinator", "Capture pipeline stopped for %s. Native proxy active.", channelName);
784
+ return { codec: nativeResult.codec, quality: formatNativeQuality(nativeResult.bandwidth, nativeResult.codec, nativeResult.resolution) };
785
+ }
786
+ /**
787
+ * Creates the fMP4 segmenter for capture mode streams. Reads resume data, creates the segmenter with preroll and resume configuration, pipes the capture stream,
788
+ * and stores the segmenter in the registry. Resume data is consumed only after the segmenter is successfully stored, ensuring it survives if creation fails.
789
+ * @param setup - The stream setup result from setupStream().
790
+ * @param numericStreamId - The stream's numeric ID.
791
+ * @param channelName - The channel key for resume data and logging.
792
+ * @returns True if the segmenter was created and stored, false if the stream was terminated during setup.
793
+ */
794
+ function createCaptureSegmenter(setup, numericStreamId, channelName) {
795
+ // Peek at resume data from a previous shutdown without consuming it. The data is consumed (deleted) only after the segmenter is successfully created and
796
+ // stored in the registry. This ensures resume data survives if segmenter creation fails — the next stream start retries with the same resume state instead
797
+ // of losing it and causing an HLS sequence reset.
798
+ const resumeData = peekResumeData(channelName);
799
+ const currentStream = getStream(numericStreamId);
800
+ const prerollSegmentCount = currentStream?.hls.prerollSegmentCount ?? 0;
801
+ // When preroll is active, use the snapshotted resume index (stored on HLS state at registration) so the segmenter's starting index is guaranteed to match
802
+ // the preroll playlist's MEDIA-SEQUENCE offset. When preroll is inactive, use the resume data directly — no preroll playlist to be consistent with.
803
+ const baseSegmentIndex = (prerollSegmentCount > 0) ? (currentStream?.hls.resumeSegmentIndex ?? 0) : (resumeData?.segmentIndex ?? 0);
804
+ // Create the fMP4 segmenter. The starting segment index accounts for both the resume offset and the preroll segment range. When preroll is active, the
805
+ // segmenter includes preroll entries in its sliding window via the compositor. The pending discontinuity at the preroll-to-real boundary is always needed —
806
+ // previousInitSegment is only passed without preroll, because the preroll init segment differs from the real init and the discontinuity must not be
807
+ // suppressed by an init-match comparison against the prior session.
808
+ const segmenter = createFMP4Segmenter({
809
+ ...(resumeData ? {
810
+ initialTrackTimestamps: resumeData.trackTimestamps,
811
+ ...((prerollSegmentCount === 0) ? { previousInitSegment: resumeData.initSegment } : {}),
812
+ startingInitVersion: resumeData.initVersion
813
+ } : {}),
814
+ ...((prerollSegmentCount > 0) ? {
815
+ prerollBaseUrl: currentStream?.hls.prerollBaseUrl ?? null,
816
+ prerollCodec: currentStream?.hls.prerollCodec ?? "h264",
817
+ prerollSegmentCount
818
+ } : {}),
819
+ ...((resumeData || (prerollSegmentCount > 0)) ? {
820
+ pendingDiscontinuity: true,
821
+ startingSegmentIndex: baseSegmentIndex + prerollSegmentCount
822
+ } : {}),
823
+ onError: (error) => {
824
+ // Skip error handling if termination was already initiated.
825
+ if (isTerminationInitiated(numericStreamId)) {
826
+ return;
827
+ }
828
+ LOG.error("Segmenter error for %s: %s.", channelName, formatError(error));
829
+ terminateStream(numericStreamId, channelName, "stream processing error");
830
+ void emitCurrentSystemStatus();
831
+ },
832
+ onStop: () => {
833
+ // Skip handling if termination was already initiated.
834
+ if (isTerminationInitiated(numericStreamId)) {
835
+ return;
836
+ }
837
+ LOG.error("Segmenter stopped unexpectedly for %s.", channelName);
838
+ terminateStream(numericStreamId, channelName, "stream ended unexpectedly");
839
+ void emitCurrentSystemStatus();
840
+ },
841
+ streamId: numericStreamId
842
+ });
843
+ // Pipe the capture stream to the segmenter.
844
+ segmenter.pipe(setup.captureStream);
845
+ // Store the segmenter reference in the registry.
846
+ const captureStream = getStream(numericStreamId);
847
+ if (captureStream) {
848
+ captureStream.segmenter = segmenter;
849
+ // Now that the segmenter is created, piped, and stored, consume the resume data so it's not used again on a subsequent stream start for the same channel.
850
+ if (resumeData) {
851
+ deleteResumeData(channelName);
852
+ }
853
+ return true;
854
+ }
855
+ // Stream was terminated during setup (rare race condition). Clean up the orphaned segmenter.
856
+ cleanupOrphanedSetup(segmenter);
857
+ return false;
858
+ }
662
859
  /**
663
860
  * Completes the async portion of stream initialization. Creates the browser page, navigates to the URL, sets up capture, creates the segmenter, and fills in the
664
861
  * pending registry entry. On failure, cleans up the pending entry via terminateStream().
@@ -726,135 +923,29 @@ async function completeStreamSetup(options) {
726
923
  // seconds. If we cancelled the timer at setup completion, the client would have no playlist during the proxy's first poll — the preroll timer fires after
727
924
  // PREROLL_DELAY_MS and provides content during that gap. For the capture path, the segmenter produces its first playlist within ~2 seconds of creation, so
728
925
  // the timer is cancelled almost immediately after setup anyway.
729
- // Attempt native streaming if a manifest interception handle is available. Signal finalize() to tell the interceptor that channel selection is complete and it
730
- // should resolve with the most recently captured manifest URL. For direct-navigation sites, the manifest was captured during page load and finalize resolves
731
- // immediately. For guide-based sites (Fox, Hulu, etc.), the manifest from the correct channel was captured after the strategy clicked the right entry.
926
+ // Attempt native streaming if a manifest interception handle is available. If native is viable, the capture pipeline is stopped and the proxy takes over.
927
+ let nativeCodec = null;
928
+ let nativeQuality = "";
732
929
  let streamingMode = "capture";
733
- if (setup.manifestInterception) {
734
- setup.manifestInterception.finalize(setup.directTune);
735
- // Read the preroll segment count from the pending entry to pass to the native coordinator. This value is set at registration time (not in the timer callback),
736
- // so it's available regardless of whether the deferred preroll timer has fired. The proxy uses it for segment index offset. The base URL for composite playlists
737
- // is read dynamically from the stream's HLS state at playlist generation time.
738
- const pendingForNative = getStream(numericStreamId);
739
- const nativePrerollSegmentCount = pendingForNative?.hls.prerollSegmentCount ?? 0;
740
- const nativeResult = await attemptNativeStreaming({
741
- channelName,
742
- interceptionPromise: setup.manifestInterception.promise,
743
- mpegTsClient,
744
- onError: (error) => {
745
- if (isTerminationInitiated(numericStreamId)) {
746
- return;
747
- }
748
- // Log the error and clear the probe cache. The proxy has already stopped itself (set errorThresholdReached + stopped). The monitor detects
749
- // hasErrored() on the next 2-second tick and triggers L3 fallback to capture mode, preserving the stream for the DVR client.
750
- LOG.warn("Native proxy error for %s: %s. Falling back to capture.", channelName, error);
751
- clearProbeCache(channelName);
752
- },
753
- page: setup.page,
754
- prerollSegmentCount: nativePrerollSegmentCount,
755
- streamId: numericStreamId,
756
- streamIdStr: setup.streamId,
757
- url
758
- });
759
- if (nativeResult) {
760
- const currentStream = getStream(numericStreamId);
761
- if (!currentStream) {
762
- nativeResult.proxy.stop();
763
- return null;
764
- }
765
- // Stop the capture pipeline — native streaming replaces it entirely.
766
- if (!setup.rawCaptureStream.destroyed) {
767
- setup.rawCaptureStream.destroy();
768
- }
769
- if (setup.ffmpegProcess) {
770
- setup.ffmpegProcess.kill();
771
- }
772
- // Update the registry entry to reflect native mode. For streams with separate audio, clear preroll state — preroll is muxed video+audio and can't be
773
- // split into separate renditions. For muxed-audio streams, preserve preroll state so the proxy can build composite playlists with preroll entries.
774
- currentStream.ffmpegProcess = null;
775
- currentStream.hls.hasAudio = nativeResult.hasAudio;
776
- if (nativeResult.hasAudio) {
777
- currentStream.hls.prerollBaseUrl = null;
778
- currentStream.hls.prerollSegmentCount = 0;
779
- }
780
- currentStream.nativeProxy = nativeResult.proxy;
781
- currentStream.rawCaptureStream = null;
782
- currentStream.streamingMode = "native";
783
- streamingMode = "native";
784
- // Start the native proxy. Signal init segment readiness immediately — native MPEG-TS segments carry their own PAT/PMT codec configuration in every
785
- // segment, so there is no separate init segment to wait for. Without this, MPEG-TS clients block on waitForInitSegment() and time out before the proxy's
786
- // first poll cycle completes.
787
- nativeResult.proxy.start();
788
- currentStream.hls.signalInitSegmentReady();
789
- LOG.debug("native:coordinator", "Capture pipeline stopped for %s. Native proxy active.", channelName);
790
- }
930
+ const nativeStreamResult = await startNativeProxy(setup, numericStreamId, channelName, url, mpegTsClient);
931
+ if (nativeStreamResult) {
932
+ streamingMode = "native";
933
+ nativeCodec = nativeStreamResult.codec;
934
+ nativeQuality = nativeStreamResult.quality;
791
935
  }
792
936
  // If native streaming was not viable or not attempted, create the fMP4 segmenter for capture mode.
793
937
  if (streamingMode === "capture") {
794
- // Check for resume data from a previous shutdown. If available, the segmenter continues from the saved sequence numbers instead of starting at 0,
795
- // preventing HLS sequence resets that cause Channels DVR to produce broken recording timelines. Preroll and resume work together — the preroll playlist
796
- // is already offset by the resume segment index (set in registerPendingStream), and the segmenter starts after the preroll range.
797
- const resumeData = consumeResumeData(channelName);
798
- const currentStream = getStream(numericStreamId);
799
- const prerollSegmentCount = currentStream?.hls.prerollSegmentCount ?? 0;
800
- // When preroll is active, use the snapshotted resume index (stored on HLS state at registration) so the segmenter's starting index is guaranteed to match
801
- // the preroll playlist's MEDIA-SEQUENCE offset. When preroll is inactive, use the resume data directly — no preroll playlist to be consistent with.
802
- const baseSegmentIndex = (prerollSegmentCount > 0) ? (currentStream?.hls.resumeSegmentIndex ?? 0) : (resumeData?.segmentIndex ?? 0);
803
- // Create the fMP4 segmenter. The starting segment index accounts for both the resume offset and the preroll segment range. When preroll is active, the
804
- // segmenter includes preroll entries in its sliding window via the compositor. The pending discontinuity at the preroll→real boundary is always needed —
805
- // previousInitSegment is only passed without preroll, because the preroll init segment differs from the real init and the discontinuity must not be
806
- // suppressed by an init-match comparison against the prior session.
807
- const segmenter = createFMP4Segmenter({
808
- ...(resumeData ? {
809
- initialTrackTimestamps: resumeData.trackTimestamps,
810
- ...((prerollSegmentCount === 0) ? { previousInitSegment: resumeData.initSegment } : {}),
811
- startingInitVersion: resumeData.initVersion
812
- } : {}),
813
- ...((prerollSegmentCount > 0) ? {
814
- prerollBaseUrl: currentStream?.hls.prerollBaseUrl ?? null,
815
- prerollSegmentCount
816
- } : {}),
817
- ...((resumeData || (prerollSegmentCount > 0)) ? {
818
- pendingDiscontinuity: true,
819
- startingSegmentIndex: baseSegmentIndex + prerollSegmentCount
820
- } : {}),
821
- onError: (error) => {
822
- // Skip error handling if termination was already initiated.
823
- if (isTerminationInitiated(numericStreamId)) {
824
- return;
825
- }
826
- LOG.error("Segmenter error for %s: %s.", channelName, formatError(error));
827
- terminateStream(numericStreamId, channelName, "stream processing error");
828
- void emitCurrentSystemStatus();
829
- },
830
- onStop: () => {
831
- // Skip handling if termination was already initiated.
832
- if (isTerminationInitiated(numericStreamId)) {
833
- return;
834
- }
835
- LOG.error("Segmenter stopped unexpectedly for %s.", channelName);
836
- terminateStream(numericStreamId, channelName, "stream ended unexpectedly");
837
- void emitCurrentSystemStatus();
838
- },
839
- streamId: numericStreamId
840
- });
841
- // Pipe the capture stream to the segmenter.
842
- segmenter.pipe(setup.captureStream);
843
- // Store the segmenter reference in the registry.
844
- const captureStream = getStream(numericStreamId);
845
- if (captureStream) {
846
- captureStream.segmenter = segmenter;
847
- }
848
- else {
849
- // Stream was terminated during setup (rare race condition). Clean up the orphaned segmenter.
850
- cleanupOrphanedSetup(segmenter);
938
+ if (!createCaptureSegmenter(setup, numericStreamId, channelName)) {
851
939
  return null;
852
940
  }
853
941
  }
854
- const captureMode = streamingMode === "native" ? "native HLS" : (CONFIG.streaming.captureMode === "ffmpeg" ? "FFmpeg" : "Native fMP4");
942
+ const gpu = getGpuCapabilities();
943
+ const ffmpegCodec = gpu?.hevcHardwareEncoding ? "\u26A1 HEVC" : (gpu?.h264HardwareEncoding ? "\u26A1 H264" : "H264");
944
+ const captureMode = (streamingMode === "native") ? ("native HLS" + nativeQuality) :
945
+ (CONFIG.streaming.captureMode === "ffmpeg" ? "FFmpeg [" + ffmpegCodec + "]" : "Native fMP4");
855
946
  const displayName = channel?.name ?? url;
856
947
  const tuneTime = ((Date.now() - setup.startTime.getTime()) / 1000).toFixed(1);
857
- LOG.info("Streaming %s (%s, %s). Tuned in %ss%s.", displayName, setup.profileName, captureMode, tuneTime, setup.directTune ? " (direct)" : "");
948
+ LOG.info("Streaming %s: %s, %s, %s. Tuned in %ss%s.", displayName, setup.providerName, setup.profileName, captureMode, tuneTime, setup.directTune ? " (direct)" : "");
858
949
  // Mark channel health as successful. Only for predefined channels (channel is defined). Ad-hoc URL streams have no persistent channel identity. Domain auth
859
950
  // is conditionally skipped when the provider defines validateTune and the tuned channel does not prove paid access (e.g., Sling Freestream channels).
860
951
  if (channel) {
@@ -865,9 +956,19 @@ async function completeStreamSetup(options) {
865
956
  const markAuth = !provider?.validateTune || provider.validateTune(channel.channelSelector ?? channelName);
866
957
  markChannelSuccess(channelName, successAuthDomain, markAuth);
867
958
  }
868
- // Emit stream added event.
959
+ // Update the registry entry with codec and hardware acceleration state, then emit the stream added event for the dashboard. Native streams set their codec
960
+ // and quality fields earlier (when the native proxy is created), so only capture mode needs updating here.
961
+ const streamCodec = (streamingMode === "native") ? nativeCodec : (gpu?.hevcHardwareEncoding ? "HEVC" : "H264");
962
+ const hwAccelerated = (streamingMode !== "native") && (gpu?.h264HardwareEncoding === true);
963
+ const currentEntry = getStream(numericStreamId);
964
+ if (currentEntry) {
965
+ currentEntry.captureCodec = streamCodec;
966
+ currentEntry.hardwareAccelerated = hwAccelerated;
967
+ }
869
968
  emitStreamAdded(createInitialStreamStatus({
969
+ captureCodec: streamCodec,
870
970
  channelName: channel?.name ?? null,
971
+ hardwareAccelerated: hwAccelerated,
871
972
  numericStreamId,
872
973
  providerName: setup.providerName,
873
974
  startTime: setup.startTime,
@@ -913,62 +1014,42 @@ async function startHLSStream(channelName, url, req, res, channel) {
913
1014
  }
914
1015
  }
915
1016
  // Idle Detection.
1017
+ /**
1018
+ * Returns all streams that have exceeded the idle timeout and have no active MPEG-TS clients. Pretuned streams are excluded — they have no clients by design and
1019
+ * the pretune module manages their lifecycle via a safety timeout. The result is sorted by last access time (oldest first) so callers can efficiently pick the
1020
+ * longest-idle stream for reclamation.
1021
+ * @returns Idle streams sorted by last access time ascending (oldest first).
1022
+ */
1023
+ function getIdleStreams() {
1024
+ const now = Date.now();
1025
+ return getAllStreams()
1026
+ .filter((stream) => !stream.preTuned && (stream.mpegTsClientCount === 0) && ((now - stream.info.lastPlaylistRequest) >= CONFIG.hls.idleTimeout))
1027
+ .sort((a, b) => a.info.lastPlaylistRequest - b.info.lastPlaylistRequest);
1028
+ }
916
1029
  /**
917
1030
  * Checks for idle streams and terminates them. Called periodically by the idle detection interval.
918
1031
  */
919
1032
  export function cleanupIdleStreams() {
920
- const streams = getAllStreams();
921
- const now = Date.now();
922
- let terminatedCount = 0;
923
- for (const stream of streams) {
924
- // Skip pretuned streams. These have no clients by design and must not be terminated by the idle timer. The pretune module manages their lifecycle via a
925
- // safety timeout.
926
- if (stream.preTuned) {
927
- continue;
928
- }
929
- // Skip streams with active MPEG-TS clients. These streams are still being consumed even if no HLS playlist requests have been made recently.
930
- if (stream.mpegTsClientCount > 0) {
931
- continue;
932
- }
933
- const idleTime = now - stream.info.lastPlaylistRequest;
934
- if (idleTime >= CONFIG.hls.idleTimeout) {
935
- terminateStream(stream.id, stream.info.storeKey, "no active clients");
936
- terminatedCount++;
937
- }
1033
+ const idle = getIdleStreams();
1034
+ for (const stream of idle) {
1035
+ terminateStream(stream.id, stream.info.storeKey, "no active clients");
938
1036
  }
939
1037
  // Emit system status once after all idle streams are terminated.
940
- if (terminatedCount > 0) {
1038
+ if (idle.length > 0) {
941
1039
  void emitCurrentSystemStatus();
942
1040
  }
943
1041
  }
944
1042
  /**
945
- * Attempts to reclaim a single idle stream to free capacity for a new request. Finds the stream that has been idle the longest and terminates it. A stream is
946
- * considered idle when it has no MPEG-TS clients and its last access exceeds the idle timeout. This is called when the concurrent stream limit is reached, allowing
947
- * channel-surfing users to get new streams without being rejected while abandoned streams linger.
1043
+ * Attempts to reclaim a single idle stream to free capacity for a new request. Terminates the stream that has been idle the longest. This is called when the
1044
+ * concurrent stream limit is reached, allowing channel-surfing users to get new streams without being rejected while abandoned streams linger.
948
1045
  * @returns True if a stream was reclaimed, false if no idle streams exist.
949
1046
  */
950
1047
  function reclaimIdleStream() {
951
- const streams = getAllStreams();
952
- const now = Date.now();
953
- let oldest = null;
954
- for (const stream of streams) {
955
- // Skip pretuned streams — they should not be reclaimed for new stream capacity.
956
- if (stream.preTuned) {
957
- continue;
958
- }
959
- // Skip streams with active MPEG-TS clients.
960
- if (stream.mpegTsClientCount > 0) {
961
- continue;
962
- }
963
- const idleTime = now - stream.info.lastPlaylistRequest;
964
- // Only consider streams that have exceeded the idle timeout, and pick the one that has been idle the longest.
965
- if ((idleTime >= CONFIG.hls.idleTimeout) && (!oldest || (stream.info.lastPlaylistRequest < oldest.info.lastPlaylistRequest))) {
966
- oldest = stream;
967
- }
968
- }
969
- if (!oldest) {
1048
+ const idle = getIdleStreams();
1049
+ if (idle.length === 0) {
970
1050
  return false;
971
1051
  }
1052
+ const oldest = idle[0];
972
1053
  LOG.info("Reclaiming idle stream %s (%s) to free capacity.", oldest.id, oldest.info.storeKey);
973
1054
  terminateStream(oldest.id, oldest.info.storeKey, "reclaimed for new stream");
974
1055
  void emitCurrentSystemStatus();