eyevinn-channel-engine 5.1.2 → 5.2.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 (97) hide show
  1. package/.github/workflows/nodejs.yml +1 -1
  2. package/.github/workflows/publish.yml +1 -1
  3. package/.github/workflows/rc.yml +1 -1
  4. package/CONTRIBUTING.md +40 -0
  5. package/Dockerfile +1 -1
  6. package/README.md +70 -8
  7. package/dist/engine/chaos_monkey.d.ts +1 -1
  8. package/dist/engine/chaos_monkey.js +1 -0
  9. package/dist/engine/event_stream.d.ts +1 -6
  10. package/dist/engine/event_stream.js +2 -0
  11. package/dist/engine/memcached_state_store.d.ts +1 -13
  12. package/dist/engine/memcached_state_store.js +4 -0
  13. package/dist/engine/memory_state_store.d.ts +1 -13
  14. package/dist/engine/memory_state_store.js +5 -0
  15. package/dist/engine/playhead_state.d.ts +0 -26
  16. package/dist/engine/playhead_state.js +9 -0
  17. package/dist/engine/preflight.d.ts +1 -1
  18. package/dist/engine/preflight.js +1 -0
  19. package/dist/engine/redis_state_store.d.ts +1 -19
  20. package/dist/engine/redis_state_store.js +5 -0
  21. package/dist/engine/server.d.ts +27 -0
  22. package/dist/engine/server.js +140 -6
  23. package/dist/engine/session.d.ts +1 -148
  24. package/dist/engine/session.js +398 -11
  25. package/dist/engine/session_live.d.ts +1 -181
  26. package/dist/engine/session_live.js +19 -4
  27. package/dist/engine/session_live_state.d.ts +0 -23
  28. package/dist/engine/session_live_state.js +5 -0
  29. package/dist/engine/session_state.d.ts +0 -45
  30. package/dist/engine/session_state.js +10 -0
  31. package/dist/engine/shared_state_store.d.ts +1 -25
  32. package/dist/engine/shared_state_store.js +10 -0
  33. package/dist/engine/state_store_types.d.ts +32 -0
  34. package/dist/engine/state_store_types.js +5 -0
  35. package/dist/engine/stream_switcher.d.ts +1 -40
  36. package/dist/engine/stream_switcher.js +108 -20
  37. package/dist/engine/subtitle_slicer.d.ts +1 -8
  38. package/dist/engine/subtitle_slicer.js +1 -0
  39. package/dist/engine/util.d.ts +1 -29
  40. package/dist/engine/util.js +2 -1
  41. package/dist/examples/adbreak.d.ts +1 -0
  42. package/dist/examples/adbreak.js +104 -0
  43. package/dist/index.d.ts +1 -1
  44. package/dist/package.json +20 -4
  45. package/docs/design/mixing-muxed-demuxed-audio.md +153 -0
  46. package/docs/design/subtitles-live-mix-demux.md +135 -0
  47. package/docs/reference.md +67 -0
  48. package/engine/chaos_monkey.ts +17 -0
  49. package/engine/{event_stream.js → event_stream.ts} +5 -3
  50. package/engine/{memcached_state_store.js → memcached_state_store.ts} +19 -12
  51. package/engine/memory_state_store.ts +71 -0
  52. package/engine/{playhead_state.js → playhead_state.ts} +92 -82
  53. package/engine/{preflight.js → preflight.ts} +1 -1
  54. package/engine/{redis_state_store.js → redis_state_store.ts} +216 -208
  55. package/engine/server.ts +210 -8
  56. package/engine/{session.js → session.ts} +421 -22
  57. package/engine/{session_live.js → session_live.ts} +54 -31
  58. package/engine/{session_live_state.js → session_live_state.ts} +129 -120
  59. package/engine/{session_state.js → session_state.ts} +269 -248
  60. package/engine/{shared_state_store.js → shared_state_store.ts} +31 -19
  61. package/engine/state_store_types.ts +35 -0
  62. package/engine/{stream_switcher.js → stream_switcher.ts} +133 -34
  63. package/engine/{subtitle_slicer.js → subtitle_slicer.ts} +10 -8
  64. package/engine/{util.js → util.ts} +28 -24
  65. package/examples/adbreak.ts +115 -0
  66. package/index.ts +2 -0
  67. package/package.json +20 -4
  68. package/spec/engine/custom_vod_request_params_spec.ts +99 -0
  69. package/spec/engine/drm_spec.ts +128 -0
  70. package/spec/engine/{engine_spec.js → engine_spec.ts} +44 -1
  71. package/spec/engine/{ha_spec.js → ha_spec.ts} +7 -4
  72. package/spec/engine/{init_switching_spec.js → init_switching_spec.ts} +10 -6
  73. package/spec/engine/{interface_spec.js → interface_spec.ts} +16 -4
  74. package/spec/engine/{playhead_live_spec.js → playhead_live_spec.ts} +2 -1
  75. package/spec/engine/{playhead_spec.js → playhead_spec.ts} +15 -8
  76. package/spec/engine/session_spec.ts +800 -0
  77. package/spec/engine/stream_switcher_audio_reconcile_spec.ts +158 -0
  78. package/spec/engine/{stream_switcher_spec.js → stream_switcher_spec.ts} +111 -13
  79. package/spec/engine/subtitle_missing_language_spec.ts +196 -0
  80. package/spec/engine/{subtitle_spec.js → subtitle_spec.ts} +28 -27
  81. package/spec/helpers/ts-resolve.js +65 -0
  82. package/spec/support/jasmine.json +1 -1
  83. package/spec/testvectors/hls_subs_no_language/config.subtitleTracks.json +12 -0
  84. package/spec/testvectors/hls_subs_no_language/evidence_dummy_segments_name_mismatch.m3u8 +24 -0
  85. package/spec/testvectors/hls_subs_no_language/evidence_real_cues_name_match.m3u8 +24 -0
  86. package/spec/testvectors/hls_subs_no_language/french.m3u8 +9 -0
  87. package/spec/testvectors/hls_subs_no_language/master.m3u8 +11 -0
  88. package/spec/testvectors/hls_subs_no_language/video.m3u8 +25 -0
  89. package/spec/testvectors/slate/master.m3u8 +3 -0
  90. package/spec/testvectors/slate/media.m3u8 +9 -0
  91. package/tsconfig.json +21 -4
  92. package/tsconfig.spec.json +16 -0
  93. package/engine/chaos_monkey.js +0 -17
  94. package/engine/memory_state_store.js +0 -63
  95. package/spec/engine/session_spec.js +0 -116
  96. /package/spec/engine/{session_live_spec.js → session_live_spec.ts} +0 -0
  97. /package/spec/engine/{util_spec.js → util_spec.ts} +0 -0
@@ -0,0 +1,35 @@
1
+ // Shared type definitions for the engine state-store layer (#373).
2
+ // Type-only declarations — no runtime code is emitted for this module beyond
3
+ // an empty object, and nothing here changes runtime behavior.
4
+
5
+ /**
6
+ * The low-level key/value store contract implemented by the memory, memcached
7
+ * and redis backends and driven by `SharedStateStore`.
8
+ */
9
+ export interface IStateStore {
10
+ initAsync(id: string, initData: Record<string, any>): Promise<any>;
11
+ resetAsync(id: string, initData: Record<string, any>): Promise<void>;
12
+ resetAllAsync(): Promise<void>;
13
+ getAsync(id: string, key: string): Promise<any>;
14
+ setAsync(id: string, key: string, value: any): Promise<any>;
15
+ setVolatileAsync(id: string, key: string, value: any): Promise<any>;
16
+ removeAsync(id: string, key: string): Promise<any>;
17
+ getValues?(id: string, keys: string[]): Promise<Record<string, any>>;
18
+ setValues?(id: string, data: Record<string, any>): Promise<Record<string, any>>;
19
+ }
20
+
21
+ export type SharedStates = { [id: string]: { [key: string]: any } | null };
22
+
23
+ export interface ISharedStateStoreOpts {
24
+ cacheTTL?: number;
25
+ redisUrl?: string;
26
+ memcachedUrl?: string;
27
+ version?: string;
28
+ volatileKeyTTL?: number;
29
+ [key: string]: any;
30
+ }
31
+
32
+ export interface ILeaderCache {
33
+ ts: number;
34
+ value: string | null;
35
+ }
@@ -22,8 +22,16 @@ const StreamType = Object.freeze({
22
22
  const FAIL_TIMEOUT = 3000;
23
23
  const MAX_FAILS = 3;
24
24
 
25
+ // Implicit global assigned to (without a var/let/const declaration) inside
26
+ // _createCustomSimpleSegmentList; declared ambiently here so the type-checker
27
+ // knows the name. `declare` emits no JavaScript, preserving the original
28
+ // (undeclared-assignment) runtime behavior exactly.
29
+ declare let byteRangeOffset: any;
30
+
25
31
  class StreamSwitcher {
26
- constructor(config) {
32
+ [key: string]: any;
33
+
34
+ constructor(config?: any) {
27
35
  this.sessionId = crypto.randomBytes(20).toString("hex");
28
36
  this.useDemuxedAudio = false;
29
37
  this.cloudWatchLogging = false;
@@ -54,6 +62,39 @@ class StreamSwitcher {
54
62
  return this.eventId;
55
63
  }
56
64
 
65
+ /**
66
+ * Report this channel's event-polling state, used by the global StreamSwitchLoop
67
+ * to pick an adaptive poll cadence without leaking switcher internals.
68
+ *
69
+ * "Mid-event"/ongoing (per #365): the switcher is on a live stream
70
+ * (this.streamTypeLive === true) and the current scheduleObj is within its
71
+ * window, i.e. now >= start_time && now < end_time.
72
+ *
73
+ * "Near end": an ongoing event whose remaining time is within the switcher's
74
+ * existing end-of-event guard window (end_time - now <= 10000; see the 10000ms
75
+ * guard in streamSwitcher()). Derived from that guard rather than a new constant.
76
+ *
77
+ * @returns {{ midEvent: boolean, nearEnd: boolean, msUntilEnd: (number|null) }}
78
+ * msUntilEnd is null when there is no ongoing event.
79
+ */
80
+ getEventPollingState() {
81
+ const NEAR_END_GUARD_MS = 10000;
82
+ const scheduleObj = this.timeDiff;
83
+ if (!this.streamTypeLive || !scheduleObj || scheduleObj.end_time == null || scheduleObj.start_time == null) {
84
+ return { midEvent: false, nearEnd: false, msUntilEnd: null };
85
+ }
86
+ const now = Date.now();
87
+ if (now < scheduleObj.start_time || now >= scheduleObj.end_time) {
88
+ return { midEvent: false, nearEnd: false, msUntilEnd: null };
89
+ }
90
+ const msUntilEnd = scheduleObj.end_time - now;
91
+ return {
92
+ midEvent: true,
93
+ nearEnd: msUntilEnd <= NEAR_END_GUARD_MS,
94
+ msUntilEnd,
95
+ };
96
+ }
97
+
57
98
  async abortLiveFeed(session, sessionLive, message) {
58
99
  if (this.streamTypeLive) {
59
100
  let status = null;
@@ -64,7 +105,7 @@ class StreamSwitcher {
64
105
  return status;
65
106
  } catch (err) {
66
107
  debug(`Failed to force a switch off live feed: ${err}`);
67
- throw new Error(err);
108
+ throw err instanceof Error ? err : new Error(String(err));
68
109
  }
69
110
  }
70
111
  }
@@ -220,23 +261,23 @@ class StreamSwitcher {
220
261
  } catch (err) {
221
262
  debug(`[${this.sessionId}]: Unexpected failure in Stream Switcher...`);
222
263
  console.error(err);
223
- throw new Error(err);
264
+ throw err instanceof Error ? err : new Error(String(err));
224
265
  }
225
266
  }
226
267
 
227
268
  async _initSwitching(state, session, sessionLive, scheduleObj) {
228
269
  this.working = true;
229
270
  const RESET_DELAY = 5000;
230
- let liveCounts = 0;
231
- let liveSegments = null;
232
- let currVodCounts = 0;
233
- let currLiveCounts = 0;
234
- let currVodSegments = null;
235
- let eventSegments = null;
271
+ let liveCounts: any = 0;
272
+ let liveSegments: any = null;
273
+ let currVodCounts: any = 0;
274
+ let currLiveCounts: any = 0;
275
+ let currVodSegments: any = null;
276
+ let eventSegments: any = null;
236
277
 
237
- let liveAudioSegments = null;
238
- let currVodAudioSegments = null;
239
- let eventAudioSegments = null;
278
+ let liveAudioSegments: any = null;
279
+ let currVodAudioSegments: any = null;
280
+ let eventAudioSegments: any = null;
240
281
 
241
282
 
242
283
  let liveUri = null;
@@ -289,7 +330,7 @@ class StreamSwitcher {
289
330
  this.eventId = null;
290
331
  debug(`[${this.sessionId}]: [ ERROR Switching from V2L->LIVE ]`);
291
332
  console.error(err);
292
- throw new Error(err);
333
+ throw err instanceof Error ? err : new Error(String(err));
293
334
  }
294
335
 
295
336
  case SwitcherState.V2L_TO_VOD:
@@ -300,8 +341,11 @@ class StreamSwitcher {
300
341
  eventSegments = await session.getTruncatedVodSegments(scheduleObj.uri, scheduleObj.duration / 1000);
301
342
  eventAudioSegments = await session.getTruncatedVodAudioSegments(scheduleObj.uri, scheduleObj.duration / 1000);
302
343
 
344
+ // #382: derive per-source whether THIS VOD actually provided demuxed
345
+ // audio, instead of assuming it from the channel-level output flag.
346
+ const vodHasDemuxedAudio = this._sourceHasDemuxedAudio(eventAudioSegments);
303
347
 
304
- if (!eventSegments || (this.useDemuxedAudio && !eventAudioSegments)) {
348
+ if (!eventSegments) {
305
349
  debug(`[${this.sessionId}]: [ ERROR Switching from V2L->VOD ]`);
306
350
  this.working = false;
307
351
  this.eventId = null;
@@ -312,14 +356,22 @@ class StreamSwitcher {
312
356
  if (this.prerollsCache[this.sessionId] && this.prerollsCache[this.sessionId].isValid) {
313
357
  const prerollSegments = this.prerollsCache[this.sessionId].segments;
314
358
  eventSegments = this._mergeSegments(prerollSegments, eventSegments, true);
315
- if (this.useDemuxedAudio) {
359
+ if (this.useDemuxedAudio && vodHasDemuxedAudio) {
316
360
  const prerollAudioSegments = this.prerollsCache[this.sessionId].audioSegments;
317
361
  eventAudioSegments = this._mergeAudioSegments(prerollAudioSegments, eventAudioSegments, true);
318
362
  }
319
363
  }
320
364
 
321
365
  await session.setCurrentMediaAndDiscSequenceCount(currVodCounts.mediaSeq, currVodCounts.discSeq, currVodCounts.audioSeq, currVodCounts.audioDiscSeq);
322
- await session.setCurrentMediaSequenceSegments(eventSegments, 0, true, eventAudioSegments, 0);
366
+ // #382: only carry audio segments into the write when THIS VOD actually
367
+ // provided demuxed audio. A muxed VOD returns {} from
368
+ // getTruncatedVodAudioSegments; passing that through would crash inside
369
+ // setCurrentMediaSequenceSegments (Object.keys on an undefined group).
370
+ if (this.useDemuxedAudio && vodHasDemuxedAudio) {
371
+ await session.setCurrentMediaSequenceSegments(eventSegments, 0, true, eventAudioSegments, 0);
372
+ } else {
373
+ await session.setCurrentMediaSequenceSegments(eventSegments, 0, true);
374
+ }
323
375
 
324
376
  this.working = false;
325
377
  debug(`[${this.sessionId}]: [ Switched from V2L->VOD ]`);
@@ -329,7 +381,7 @@ class StreamSwitcher {
329
381
  this.working = false;
330
382
  this.eventId = null;
331
383
  debug(`[${this.sessionId}]: [ ERROR Switching from V2L->VOD ]`);
332
- throw new Error(err);
384
+ throw err instanceof Error ? err : new Error(String(err));
333
385
  }
334
386
  case SwitcherState.LIVE_TO_V2L:
335
387
  try {
@@ -340,10 +392,14 @@ class StreamSwitcher {
340
392
  liveAudioSegments = await sessionLive.getCurrentAudioSequenceSegments();
341
393
  }
342
394
  liveCounts = await sessionLive.getCurrentMediaAndDiscSequenceCount();
395
+ // #382: derive per-source whether THIS live source actually produced
396
+ // demuxed audio, instead of asserting it purely from the channel flag.
397
+ const liveHasDemuxedAudio =
398
+ this.useDemuxedAudio && liveAudioSegments && !this._isEmpty(liveAudioSegments.currMseqSegs);
343
399
  if (scheduleObj && !scheduleObj.duration) {
344
400
  debug(`[${this.sessionId}]: Cannot switch VOD. No duration specified for schedule item: [${scheduleObj.assetId}]`);
345
401
  }
346
- if (this._isEmpty(liveSegments.currMseqSegs) || (this.useDemuxedAudio && this._isEmpty(liveAudioSegments.currMseqSegs))) {
402
+ if (this._isEmpty(liveSegments.currMseqSegs)) {
347
403
  this.working = false;
348
404
  this.streamTypeLive = false;
349
405
  debug(`[${this.sessionId}]: [ Switched from LIVE->V2L ]`);
@@ -354,7 +410,7 @@ class StreamSwitcher {
354
410
  const prerollSegments = this.prerollsCache[this.sessionId].segments;
355
411
  liveSegments.currMseqSegs = this._mergeSegments(prerollSegments, liveSegments.currMseqSegs, false);
356
412
  liveSegments.segCount += prerollSegments.length;
357
- if (this.useDemuxedAudio) {
413
+ if (liveHasDemuxedAudio) {
358
414
  const prerollAudioSegments = this.prerollsCache[this.sessionId].audioSegments;
359
415
  liveAudioSegments.currMseqSegs = this._mergeAudioSegments(prerollAudioSegments, liveAudioSegments.currMseqSegs, false);
360
416
  liveAudioSegments.segCount += prerollAudioSegments.length;
@@ -362,7 +418,7 @@ class StreamSwitcher {
362
418
  }
363
419
 
364
420
  await session.setCurrentMediaAndDiscSequenceCount(liveCounts.mediaSeq, liveCounts.discSeq, liveCounts.audioSeq, liveCounts.audioDiscSeq);
365
- if (this.useDemuxedAudio) {
421
+ if (liveHasDemuxedAudio) {
366
422
  await session.setCurrentMediaSequenceSegments(liveSegments.currMseqSegs, liveSegments.segCount, false, liveAudioSegments.currMseqSegs, liveAudioSegments.segCount);
367
423
  } else {
368
424
  await session.setCurrentMediaSequenceSegments(liveSegments.currMseqSegs, liveSegments.segCount, false);
@@ -379,7 +435,7 @@ class StreamSwitcher {
379
435
  this.working = false;
380
436
  this.eventId = null;
381
437
  debug(`[${this.sessionId}]: [ ERROR Switching from LIVE->V2L ] ${err}`);
382
- throw new Error(err);
438
+ throw err instanceof Error ? err : new Error(String(err));
383
439
  }
384
440
  case SwitcherState.LIVE_TO_VOD:
385
441
  try {
@@ -392,6 +448,16 @@ class StreamSwitcher {
392
448
  eventSegments = await session.getTruncatedVodSegments(scheduleObj.uri, scheduleObj.duration / 1000);
393
449
  eventAudioSegments = await session.getTruncatedVodAudioSegments(scheduleObj.uri, scheduleObj.duration / 1000);
394
450
 
451
+ // #383: reconcile across a possible muxed<->demuxed boundary at this
452
+ // LIVE->VOD switch point. The channel OUTPUT mode is `useDemuxedAudio`;
453
+ // each side of the transition may or may not actually carry demuxed
454
+ // audio. We only ever write audio into the (demuxed-output) channel when
455
+ // the SPECIFIC source being written actually provided demuxed audio, so a
456
+ // muxed source crossing into a demuxed channel does not corrupt the audio
457
+ // group / audio discontinuity-sequence with empty or mismatched data.
458
+ const liveHasDemuxedAudioLTV =
459
+ this.useDemuxedAudio && liveAudioSegments && !this._isEmpty(liveAudioSegments.currMseqSegs);
460
+ const vodHasDemuxedAudioLTV = this.useDemuxedAudio && this._sourceHasDemuxedAudio(eventAudioSegments);
395
461
 
396
462
  if (!eventSegments) {
397
463
  debug(`[${this.sessionId}]: [ ERROR Switching from LIVE->VOD ]`);
@@ -402,7 +468,7 @@ class StreamSwitcher {
402
468
  }
403
469
 
404
470
  await session.setCurrentMediaAndDiscSequenceCount(liveCounts.mediaSeq - 1, liveCounts.discSeq - 1, liveCounts.audioSeq - 1, liveCounts.audioDiscSeq - 1);
405
- if (this.useDemuxedAudio) {
471
+ if (liveHasDemuxedAudioLTV) {
406
472
  await session.setCurrentMediaSequenceSegments(liveSegments.currMseqSegs, liveSegments.segCount, false, liveAudioSegments.currMseqSegs, liveAudioSegments.segCount);
407
473
  } else {
408
474
  await session.setCurrentMediaSequenceSegments(liveSegments.currMseqSegs, liveSegments.segCount);
@@ -413,12 +479,16 @@ class StreamSwitcher {
413
479
  const prerollSegments = this.prerollsCache[this.sessionId].segments;
414
480
  eventSegments = this._mergeSegments(prerollSegments, eventSegments, true);
415
481
 
416
- if (this.useDemuxedAudio) {
482
+ if (vodHasDemuxedAudioLTV) {
417
483
  const prerollAudioSegments = this.prerollsCache[this.sessionId].audioSegments;
418
484
  eventAudioSegments = this._mergeAudioSegments(prerollAudioSegments, eventAudioSegments, true);
419
485
  }
420
486
  }
421
- await session.setCurrentMediaSequenceSegments(eventSegments, 0, true);
487
+ if (vodHasDemuxedAudioLTV) {
488
+ await session.setCurrentMediaSequenceSegments(eventSegments, 0, true, eventAudioSegments, 0);
489
+ } else {
490
+ await session.setCurrentMediaSequenceSegments(eventSegments, 0, true);
491
+ }
422
492
 
423
493
  await sessionLive.resetSession();
424
494
  sessionLive.resetLiveStoreAsync(RESET_DELAY); // In parallel
@@ -432,7 +502,7 @@ class StreamSwitcher {
432
502
  this.working = false;
433
503
  this.eventId = null;
434
504
  debug(`[${this.sessionId}]: [ ERROR Switching from LIVE->VOD ]`);
435
- throw new Error(err);
505
+ throw err instanceof Error ? err : new Error(String(err));
436
506
  }
437
507
  case SwitcherState.LIVE_TO_LIVE:
438
508
  try {
@@ -443,6 +513,14 @@ class StreamSwitcher {
443
513
  eventAudioSegments = await sessionLive.getCurrentAudioSequenceSegments();
444
514
  currLiveCounts = await sessionLive.getCurrentMediaAndDiscSequenceCount();
445
515
 
516
+ // #383: reconcile a possible muxed<->demuxed boundary across a LIVE->LIVE
517
+ // switch. Only carry the demuxed audio rendition when the outgoing live
518
+ // source actually produced one; if it didn't (a muxed source on a demuxed
519
+ // channel), skip the audio write so we don't push an empty audio group /
520
+ // desync the audio discontinuity-sequence into the next live source.
521
+ const liveHasDemuxedAudioLTL =
522
+ this.useDemuxedAudio && eventAudioSegments && !this._isEmpty(eventAudioSegments.currMseqSegs);
523
+
446
524
  await sessionLive.resetSession();
447
525
  await sessionLive.resetLiveStoreAsync(0);
448
526
 
@@ -452,10 +530,10 @@ class StreamSwitcher {
452
530
  this._insertTimedMetadata(prerollSegments, scheduleObj.timedMetadata || {});
453
531
  eventSegments.currMseqSegs = this._mergeSegments(prerollSegments, eventSegments.currMseqSegs, false);
454
532
 
455
- if (this.useDemuxedAudio) {
533
+ if (liveHasDemuxedAudioLTL) {
456
534
  const prerollSegmentsAudio = this.prerollsCache[this.sessionId].audioSegments;
457
535
  this._insertTimedMetadataAudio(prerollSegmentsAudio, scheduleObj.timedMetadata || {});
458
- eventSegments.currMseqSegs = this._mergeAudioSegments(prerollSegmentsAudio, eventAudioSegments.currMseqSegs, false);
536
+ eventAudioSegments.currMseqSegs = this._mergeAudioSegments(prerollSegmentsAudio, eventAudioSegments.currMseqSegs, false);
459
537
  }
460
538
  }
461
539
 
@@ -464,7 +542,9 @@ class StreamSwitcher {
464
542
  console.error("cound not set switch live-> live", currVodCounts.mediaSeq, currVodCounts.discSeq, currVodCounts.audioSeq, currVodCounts.audioDiscSeq)
465
543
  }
466
544
  await sessionLive.setCurrentMediaSequenceSegments(eventSegments.currMseqSegs);
467
- await sessionLive.setCurrentAudioSequenceSegments(eventAudioSegments.currMseqSegs);
545
+ if (liveHasDemuxedAudioLTL) {
546
+ await sessionLive.setCurrentAudioSequenceSegments(eventAudioSegments.currMseqSegs);
547
+ }
468
548
  liveUri = await sessionLive.setLiveUri(scheduleObj.uri);
469
549
 
470
550
  if (!liveUri) {
@@ -483,7 +563,7 @@ class StreamSwitcher {
483
563
  this.working = false;
484
564
  this.eventId = null;
485
565
  debug(`[${this.sessionId}]: [ ERROR Switching from LIVE->LIVE ]`);
486
- throw new Error(err);
566
+ throw err instanceof Error ? err : new Error(String(err));
487
567
  }
488
568
  default:
489
569
  debug(`[${this.sessionId}]: SwitcherState [${state}] not implemented`);
@@ -506,6 +586,20 @@ class StreamSwitcher {
506
586
  return true;
507
587
  }
508
588
 
589
+ /**
590
+ * Per-source (#382): does THIS loaded VOD/live source actually provide demuxed
591
+ * audio? Derived from the presence of a non-empty audioSegments structure at
592
+ * load time, rather than assumed from the channel-level `useDemuxedAudio` flag.
593
+ *
594
+ * `useDemuxedAudio` stays the channel-level OUTPUT mode; this signal is the
595
+ * per-source INPUT fact used for validity/transition checks so a demuxed-output
596
+ * channel can still ingest a source that lacks demuxed audio (e.g. a muxed VOD)
597
+ * without flagging it invalid.
598
+ */
599
+ _sourceHasDemuxedAudio(audioSegments) {
600
+ return !ItemIsEmpty(audioSegments);
601
+ }
602
+
509
603
  async _validURI(uri) {
510
604
  if (!uri) {
511
605
  return false;
@@ -539,7 +633,7 @@ class StreamSwitcher {
539
633
  const audioURIs = {};
540
634
  const audioM3UPlaylists = {};
541
635
  try {
542
- const m3u = await this._fetchParseM3u8(uri);
636
+ const m3u: any = await this._fetchParseM3u8(uri);
543
637
  debug(`[${this.sessionId}]: ...Fetched a New Preroll Slate Master Manifest from:\n${uri}`);
544
638
  // Is the first URI an actual Multivariant manifest
545
639
  if (m3u.items.StreamItem.length > 0) {
@@ -611,7 +705,7 @@ class StreamSwitcher {
611
705
  const results = await Promise.allSettled(loadMediaPromises);
612
706
  const resultsAudio = await Promise.allSettled(loadAudioPromises);
613
707
  // Process...
614
- results.forEach((item, idx) => {
708
+ results.forEach((item: any, idx) => {
615
709
  if (item.status === "fulfilled" && item.value) {
616
710
  const resultM3U = item.value;
617
711
  const bw = bandwidths[idx];
@@ -620,7 +714,7 @@ class StreamSwitcher {
620
714
  });
621
715
 
622
716
  if (resultsAudio) {
623
- resultsAudio.forEach((item, idx) => {
717
+ resultsAudio.forEach((item: any, idx) => {
624
718
  const resultM3U = item.value;
625
719
  const indexes = this._getGroupAndLangIdxFromIdx(idx, audioURIs)
626
720
  if (!audioM3UPlaylists[indexes.groupId]) {
@@ -668,7 +762,7 @@ class StreamSwitcher {
668
762
  debug(`[${this.sessionId}]: Loaded all Variants of the Preroll Slate!`);
669
763
  return { mediaSegments: prerollSegments, audioSegments: prerollSegmentsAudio };
670
764
  } catch (err) {
671
- throw new Error(err);
765
+ throw err instanceof Error ? err : new Error(String(err));
672
766
  }
673
767
  }
674
768
 
@@ -676,7 +770,7 @@ class StreamSwitcher {
676
770
  let segments = [];
677
771
  for (let k = 0; k < segmentList.length; k++) {
678
772
  try {
679
- let seg = {};
773
+ let seg: any = {};
680
774
  const playlistItem = segmentList[k];
681
775
  let segmentUri;
682
776
  let byteRange = undefined;
@@ -799,9 +893,14 @@ class StreamSwitcher {
799
893
  answerFound = true
800
894
  } else {
801
895
  storedLength = langs.length;
896
+ // @ts-ignore -- pre-existing behavior: `startIdx` is `const`; this path
897
+ // throws at runtime if ever reached. Preserved byte-for-byte in the TS
898
+ // port (type-only migration, #374) rather than "fixed" here.
802
899
  startIdx++;
803
900
  }
804
901
  }
902
+ // @ts-ignore -- pre-existing behavior: `groupIds`/`langs` are block-scoped to
903
+ // the while body above and are not in scope here. Preserved as-is.
805
904
  return { groupId: groupIds[startIdx], lang: langs[idx - storedLength] }
806
905
  }
807
906
 
@@ -1,11 +1,13 @@
1
1
  const fetch = require("node-fetch");
2
2
  const fs = require("fs");
3
3
  class SubtitleSlicer {
4
+ declare vttFiles: any;
5
+ declare vttFile: any;
4
6
  constructor() {
5
7
  this.vttFiles = {};
6
8
  }
7
9
 
8
- async getVttFile(url) {
10
+ async getVttFile(url: string): Promise<string> {
9
11
  let resp = await fetch(url)
10
12
  if (resp.status === 200) { // TODO add error handeling
11
13
  let text = await resp.text();
@@ -17,7 +19,7 @@ class SubtitleSlicer {
17
19
 
18
20
  }
19
21
 
20
- checkTimeStamp(line, startTime, endTime, elapsedtime) {
22
+ checkTimeStamp(line: string, startTime: any, endTime: any, elapsedtime: any): boolean {
21
23
  const times = line.split("-->");
22
24
  let startTimeTimestamp = times[0].split(":");
23
25
  let endTimeTimestamp = times[1].split(":");
@@ -50,22 +52,22 @@ class SubtitleSlicer {
50
52
 
51
53
  }
52
54
 
53
- streamToString(stream) {
54
- const chunks = [];
55
+ streamToString(stream: any): Promise<string> {
56
+ const chunks: Buffer[] = [];
55
57
  return new Promise((resolve, reject) => {
56
- stream.on('data', (chunk) => chunks.push(Buffer.from(chunk)));
57
- stream.on('error', (err) => reject(err));
58
+ stream.on('data', (chunk: any) => chunks.push(Buffer.from(chunk)));
59
+ stream.on('error', (err: any) => reject(err));
58
60
  stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
59
61
  })
60
62
  }
61
63
 
62
- async generateVtt(params, _injectedVttFile, _injectedPreviousVttFile) {
64
+ async generateVtt(params: any, _injectedVttFile?: any, _injectedPreviousVttFile?: any): Promise<string> {
63
65
  const paramEncode = new URLSearchParams(params)
64
66
  const uri = paramEncode.get("vtturi");
65
67
  const startTime = paramEncode.get("starttime");
66
68
  const endTime = paramEncode.get("endtime");
67
69
  const elapsedTime = paramEncode.get("elapsedtime");
68
- const previousParams = new URLSearchParams(paramEncode.get("previousvtturi"))
70
+ const previousParams = new URLSearchParams(paramEncode.get("previousvtturi") as any)
69
71
  const previousUri = previousParams.get("vtturi");
70
72
  const previousStartTime = previousParams.get("starttime");
71
73
  const previousEndTime = previousParams.get("endtime");
@@ -8,15 +8,15 @@ const COMMON_HEADERS = {
8
8
  "Cache-Control": "no-cache"
9
9
  }
10
10
 
11
- const filterQueryParser = (filterQuery) => {
11
+ const filterQueryParser = (filterQuery: string): any => {
12
12
  const conditions = filterQuery.match(/\(([^\(\)]*?)\)/g);
13
13
 
14
- let filter = {};
14
+ let filter: any = {};
15
15
 
16
16
  if (!conditions) {
17
17
  return filter;
18
18
  }
19
- conditions.map((c) => {
19
+ conditions.map((c: string) => {
20
20
  const m = c.match(/\(type=="(.*?)"(AND|\|\|)(.*?)(<|>)(.*)\)/);
21
21
  if (m) {
22
22
  const type = m[1];
@@ -43,8 +43,8 @@ const filterQueryParser = (filterQuery) => {
43
43
  return filter;
44
44
  };
45
45
 
46
- const applyFilter = (profiles, filter) => {
47
- let filteredProfiles = {};
46
+ const applyFilter = (profiles: any, filter: any): any => {
47
+ let filteredProfiles: any = {};
48
48
  const supportedFilterKeys = ["systemBitrate", "height"];
49
49
 
50
50
  if (!filter.video) {
@@ -89,7 +89,7 @@ const applyFilter = (profiles, filter) => {
89
89
  return filteredProfiles;
90
90
  };
91
91
 
92
- const ItemIsEmpty = (obj) => {
92
+ const ItemIsEmpty = (obj: any): boolean => {
93
93
  if (!obj) {
94
94
  return true;
95
95
  }
@@ -101,7 +101,7 @@ const ItemIsEmpty = (obj) => {
101
101
  return true;
102
102
  };
103
103
 
104
- const cloudWatchLog = (silent, type, logEntry) => {
104
+ const cloudWatchLog = (silent: boolean, type: string, logEntry: any): void => {
105
105
  if (!silent) {
106
106
  logEntry.type = type;
107
107
  logEntry.time = new Date().toISOString();
@@ -109,14 +109,14 @@ const cloudWatchLog = (silent, type, logEntry) => {
109
109
  }
110
110
  };
111
111
 
112
- const m3u8Header = (instanceId) => {
112
+ const m3u8Header = (instanceId?: string): string => {
113
113
  let m3u8 = "";
114
114
  m3u8 += `## Created with Eyevinn Channel Engine library (version=${version}${instanceId ? "<" + instanceId + ">" : ""})\n`;
115
115
  m3u8 += "## https://www.npmjs.com/package/eyevinn-channel-engine\n";
116
116
  return m3u8;
117
117
  };
118
118
 
119
- const toHHMMSS = (secs) => {
119
+ const toHHMMSS = (secs: any): string => {
120
120
  var sec_num = parseInt(secs, 10);
121
121
  var hours = Math.floor(sec_num / 3600);
122
122
  var minutes = Math.floor(sec_num / 60) % 60;
@@ -125,28 +125,32 @@ const toHHMMSS = (secs) => {
125
125
  return [hours, minutes, seconds].map((v) => (v < 10 ? "0" + v : v)).join(":");
126
126
  };
127
127
 
128
- const logerror = (sessionId, err) => {
128
+ const logerror = (sessionId: any, err: any): void => {
129
129
  console.error(`ERROR [${sessionId}]:`);
130
130
  console.error(err);
131
131
  };
132
132
 
133
- const timer = (ms) => new Promise((res) => setTimeout(res, ms));
133
+ const timer = (ms: number): Promise<void> => new Promise((res) => setTimeout(res, ms));
134
134
 
135
135
  class WaitTimeGenerator {
136
- constructor(defaultIntervalMs, minValue) {
136
+ declare timestamp: Date | null;
137
+ declare prevWaitTime: number | null;
138
+ declare defaultIntervalMs: number;
139
+ declare minValue: any;
140
+ constructor(defaultIntervalMs: number, minValue: any) {
137
141
  (this.timestamp = null), (this.prevWaitTime = null), (this.defaultIntervalMs = defaultIntervalMs || 3000), (this.minValue = minValue);
138
142
  }
139
- _getWaitTimeFromTimestamp() {
143
+ _getWaitTimeFromTimestamp(): number {
140
144
  if (!this.timestamp) {
141
145
  this.timestamp = new Date();
142
146
  }
143
147
  const sec = this.timestamp.getSeconds();
144
148
  const defaultSec = this.defaultIntervalMs / 1000;
145
- const d = parseInt(sec / defaultSec);
149
+ const d = parseInt((sec / defaultSec) as any);
146
150
  const waitSec = defaultSec * (d + 1) - sec;
147
151
  return waitSec * 1000;
148
152
  }
149
- async getWaitTime(plannedTime) {
153
+ async getWaitTime(plannedTime: any): Promise<any> {
150
154
  if (!this.timestamp || (this.prevWaitTime === this.minValue && plannedTime !== this.minValue)) {
151
155
  this.timestamp = new Date();
152
156
  const waitMs = this._getWaitTimeFromTimestamp();
@@ -158,13 +162,13 @@ class WaitTimeGenerator {
158
162
  }
159
163
  }
160
164
 
161
- const findNearestValue = (val, array) => {
165
+ const findNearestValue = (val: number, array: number[]): number => {
162
166
  const sorted = array.sort((a, b) => b - a);
163
167
  return sorted.reduce((a, b) => {
164
168
  return Math.abs(b - val) < Math.abs(a - val) ? b : a;
165
169
  });
166
170
  };
167
- const findAudioGroupOrLang = (val, array) => {
171
+ const findAudioGroupOrLang = (val: any, array: any[]): any => {
168
172
  for(let i = 0; i < array.length; i++) {
169
173
  if (array[i] === val) {
170
174
  return val
@@ -173,7 +177,7 @@ const findAudioGroupOrLang = (val, array) => {
173
177
  return array[0];
174
178
  };
175
179
 
176
- const isValidUrl = (url) => {
180
+ const isValidUrl = (url: string): boolean => {
177
181
  try {
178
182
  const _url = new URL(url);
179
183
  return true;
@@ -182,10 +186,10 @@ const isValidUrl = (url) => {
182
186
  }
183
187
  };
184
188
 
185
- const fetchWithRetry = async (uri, opts, maxRetries, retryDelayMs, timeoutMs, debug) => {
189
+ const fetchWithRetry = async (uri: any, opts: any, maxRetries?: number, retryDelayMs?: number, timeoutMs?: number, debug?: any): Promise<any> => {
186
190
  if (!debug) {
187
- var debug = (msg) => { console.log(msg); };
188
- }
191
+ var debug: any = (msg: any) => { console.log(msg); };
192
+ }
189
193
  let tryFetchCount = 0;
190
194
  const RETRY_LIMIT = maxRetries || 5;
191
195
  const TIMEOUT_LIMIT = timeoutMs || 10 * 1000;
@@ -227,7 +231,7 @@ const fetchWithRetry = async (uri, opts, maxRetries, retryDelayMs, timeoutMs, de
227
231
  }
228
232
  };
229
233
 
230
- const codecsFromString = (codecs) => {
234
+ const codecsFromString = (codecs: string): (string | undefined)[] => {
231
235
  const audioCodecs = codecs.split(",").find(c => {
232
236
  return c.match(/^mp4a/) || c.match(/^ac-3/) || c.match(/^ec-3/);
233
237
  });
@@ -237,7 +241,7 @@ const codecsFromString = (codecs) => {
237
241
  return [videoCodecs, audioCodecs];
238
242
  };
239
243
 
240
- const timeLeft = (endTimestamp, currentTimestamp) => {
244
+ const timeLeft = (endTimestamp: number, currentTimestamp: number): string => {
241
245
  const secondsLeft = Math.floor((endTimestamp - currentTimestamp) / 1000);
242
246
  if (secondsLeft < 0) {
243
247
  return "Time has already passed.";
@@ -256,7 +260,7 @@ const timeLeft = (endTimestamp, currentTimestamp) => {
256
260
  return msg;
257
261
  };
258
262
 
259
- const roundToThreeDecimals = (number) => {
263
+ const roundToThreeDecimals = (number: any): any => {
260
264
  if (typeof number !== "number") {
261
265
  try {
262
266
  number = parseFloat(number);