@codenkay/video-nsgplayer-core 5.0.0 → 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.
package/dist/index.js CHANGED
@@ -146,7 +146,8 @@ var AuthManager = class {
146
146
 
147
147
  // src/config/defaults.ts
148
148
  var PLAYBACK_RATES = [0.5, 0.75, 1, 1.25, 1.5, 2];
149
- var PACKAGE_VERSION = "3.0.3";
149
+ var DEFAULT_PLAYBACK_REFRESH_INTERVAL_MS = 45e3;
150
+ var PACKAGE_VERSION = "5.2.0";
150
151
  var DEFAULT_PLAYER_BEHAVIOR = {
151
152
  autoplay: true,
152
153
  startMuted: true,
@@ -218,7 +219,12 @@ var DEFAULT_PLAYER_CONFIG = {
218
219
  enableWorker: true,
219
220
  // VOD + AES-128: LL mode causes ABR thrash → bufferAppendError on MSE.
220
221
  lowLatencyMode: false,
221
- backBufferLength: 90,
222
+ // Match a smooth encrypted VOD: 30s forward target, 60s ceiling,
223
+ // 20MB cap, and a short back buffer so MSE does not stall when full.
224
+ backBufferLength: 30,
225
+ maxBufferLength: 30,
226
+ maxMaxBufferLength: 60,
227
+ maxBufferSize: 20 * 1024 * 1024,
222
228
  fatalRecoveryLimit: 3
223
229
  }
224
230
  },
@@ -242,6 +248,7 @@ var SKIP_DEEP_SCAN_KEYS = /* @__PURE__ */ new Set([
242
248
  "getsource",
243
249
  "refreshsource",
244
250
  "keyproxyurlbuilder",
251
+ "mediaproxyurlbuilder",
245
252
  "getkeyaccesstoken"
246
253
  ]);
247
254
  var SECRET_SCAN_MAX_DEPTH = 32;
@@ -326,6 +333,7 @@ function mergePlayerConfig(partial) {
326
333
  ...DEFAULT_PLAYER_CONFIG.streaming.hls,
327
334
  ...partial?.streaming?.hls
328
335
  },
336
+ mediaProxyUrlBuilder: partial?.streaming?.mediaProxyUrlBuilder,
329
337
  keyProxyUrlBuilder: partial?.streaming?.keyProxyUrlBuilder,
330
338
  getKeyAccessToken: partial?.streaming?.getKeyAccessToken,
331
339
  keyProxyMaxFailures: partial?.streaming?.keyProxyMaxFailures
@@ -634,6 +642,7 @@ var RefreshManager = class {
634
642
  constructor(options) {
635
643
  this.options = options;
636
644
  this.timer = null;
645
+ this.intervalTimer = null;
637
646
  this.coalesceTimer = null;
638
647
  this.inFlight = false;
639
648
  this.consecutiveFailures = 0;
@@ -642,6 +651,7 @@ var RefreshManager = class {
642
651
  }
643
652
  start(initialExpiresAt) {
644
653
  this.schedule(initialExpiresAt);
654
+ this.armInterval();
645
655
  }
646
656
  requestRenew(reason = "frag_error") {
647
657
  if (this.stopped || this.options.isDestroyed()) return;
@@ -657,8 +667,10 @@ var RefreshManager = class {
657
667
  stop() {
658
668
  this.stopped = true;
659
669
  if (this.timer) clearTimeout(this.timer);
670
+ if (this.intervalTimer) clearTimeout(this.intervalTimer);
660
671
  if (this.coalesceTimer) clearTimeout(this.coalesceTimer);
661
672
  this.timer = null;
673
+ this.intervalTimer = null;
662
674
  this.coalesceTimer = null;
663
675
  }
664
676
  schedule(expiresAt) {
@@ -672,13 +684,25 @@ var RefreshManager = class {
672
684
  void this.renew("proactive");
673
685
  }, delay);
674
686
  }
687
+ /** Rotate the token on a fixed cadence. The loader reads the store live. */
688
+ armInterval() {
689
+ const interval = this.options.refreshIntervalMs;
690
+ if (!interval || interval < 5e3 || this.stopped) return;
691
+ if (this.intervalTimer) clearTimeout(this.intervalTimer);
692
+ this.intervalTimer = setTimeout(() => {
693
+ this.intervalTimer = null;
694
+ if (this.stopped) return;
695
+ void this.renew("proactive");
696
+ this.armInterval();
697
+ }, interval);
698
+ }
675
699
  async renew(reason) {
676
700
  if (this.stopped || this.options.isDestroyed() || this.inFlight) {
677
701
  if (this.inFlight) this.pendingReason = reason;
678
702
  return;
679
703
  }
680
704
  this.inFlight = true;
681
- this.options.onRenewing?.();
705
+ this.options.onRenewing?.(reason);
682
706
  try {
683
707
  await this.options.authManager.ensureToken({
684
708
  reason: reason === "proactive" ? "expiring" : "unauthorized",
@@ -689,7 +713,7 @@ var RefreshManager = class {
689
713
  reason: reason === "proactive" ? "expiring" : reason === "manual" ? "manual" : "auth_error"
690
714
  });
691
715
  this.consecutiveFailures = 0;
692
- this.options.onRenewed?.(source.expiresAt);
716
+ this.options.onRenewed?.(source.expiresAt, reason);
693
717
  this.schedule(source.expiresAt);
694
718
  this.options.logger.debug("Playback source renewed", { reason });
695
719
  } catch (error) {
@@ -767,6 +791,26 @@ function seekToLiveEdge(media, options) {
767
791
  return { moved: true, edge };
768
792
  }
769
793
 
794
+ // src/streaming/mediaUrl.ts
795
+ var LIVE_PLAYLIST_PATH = /\/(?:hls-web-live|live)\//i;
796
+ function isLivePlaylistUrl(value) {
797
+ if (LIVE_PLAYLIST_PATH.test(value)) return true;
798
+ try {
799
+ const parsed = new URL(value, "http://localhost");
800
+ const inner = parsed.searchParams.get("url");
801
+ return Boolean(inner && LIVE_PLAYLIST_PATH.test(inner));
802
+ } catch {
803
+ return false;
804
+ }
805
+ }
806
+ function isSameOriginHttpUrl(value, baseOrigin) {
807
+ try {
808
+ return new URL(value, baseOrigin).origin === new URL(baseOrigin).origin;
809
+ } catch {
810
+ return false;
811
+ }
812
+ }
813
+
770
814
  // src/streaming/authParamsLoader.ts
771
815
  var ENC_KEY_PATH_RE = /enc\.key$/i;
772
816
  var BUILTIN_LOADER_NAMES = /* @__PURE__ */ new Set(["XhrLoader", "FetchLoader"]);
@@ -836,8 +880,16 @@ function rewriteHlsRequestUrl(rawUrl, store, options = {}, baseOrigin = typeof l
836
880
  mobile: snapshot.mobile
837
881
  });
838
882
  }
839
- if (!store.hasParams()) return parsed.toString();
840
- return store.applyToUrl(rawUrl, baseOrigin);
883
+ const withAuth = store.hasParams() ? store.applyToUrl(rawUrl, baseOrigin) : parsed.toString();
884
+ return applyMediaProxy(withAuth, options, baseOrigin);
885
+ }
886
+ function applyMediaProxy(url, options, baseOrigin) {
887
+ if (!options.mediaProxyUrlBuilder) return url;
888
+ if (isSameOriginHttpUrl(url, baseOrigin)) return url;
889
+ return options.mediaProxyUrlBuilder({
890
+ url,
891
+ videoId: options.videoId
892
+ });
841
893
  }
842
894
  function createLoaderStats() {
843
895
  const now = performance.now();
@@ -868,12 +920,14 @@ function isProxyUpstreamBlocked(status, contentType, bodyHead, errorText) {
868
920
  return false;
869
921
  }
870
922
  async function fetchEncryptionKeyBytes(url, accessToken, signal) {
871
- const headers = accessToken ? { Authorization: `Bearer ${accessToken}`, Accept: "*/*" } : void 0;
923
+ const pageOrigin = typeof location !== "undefined" ? location.origin : "http://localhost";
924
+ const sameOrigin = isSameOriginHttpUrl(url, pageOrigin);
925
+ const headers = !sameOrigin && accessToken ? { Authorization: `Bearer ${accessToken}`, Accept: "*/*" } : void 0;
872
926
  try {
873
927
  const response = await fetch(url, {
874
928
  method: "GET",
875
929
  ...headers ? { headers } : {},
876
- credentials: "omit",
930
+ credentials: sameOrigin ? "same-origin" : "omit",
877
931
  cache: "no-store",
878
932
  signal
879
933
  });
@@ -1164,7 +1218,7 @@ function createAuthParamsLoader(HlsModule, store, options = {}) {
1164
1218
  const originalUrl = context.url;
1165
1219
  const isKey = isEncryptionKeyUrl(originalUrl);
1166
1220
  if (!isKey) {
1167
- if (store.hasParams()) {
1221
+ if (store.hasParams() || options.mediaProxyUrlBuilder) {
1168
1222
  context.url = rewriteHlsRequestUrl(originalUrl, store, {
1169
1223
  ...options,
1170
1224
  keyProxyUrlBuilder: void 0
@@ -1289,7 +1343,7 @@ var HlsEngine = class {
1289
1343
  if (videoEl.canPlayType("application/vnd.apple.mpegurl")) {
1290
1344
  this.supportMode = "native";
1291
1345
  this.options.callbacks.onSupportMode?.("native");
1292
- videoEl.src = this.options.authParams.applyToUrl(playbackUrl);
1346
+ videoEl.src = this.playbackRequestUrl(playbackUrl);
1293
1347
  this.bindMediaEvents();
1294
1348
  this.bindNativeTextTracks();
1295
1349
  this.options.callbacks.onStateChange?.("ready");
@@ -1314,6 +1368,7 @@ var HlsEngine = class {
1314
1368
  } = this.options;
1315
1369
  const loader = createAuthParamsLoader(Hls, authParams, {
1316
1370
  videoId,
1371
+ mediaProxyUrlBuilder: this.options.mediaProxyUrlBuilder,
1317
1372
  keyProxyUrlBuilder,
1318
1373
  getKeyAccessToken,
1319
1374
  keyProxyMaxFailures: this.options.keyProxyMaxFailures
@@ -1324,25 +1379,25 @@ var HlsEngine = class {
1324
1379
  "Disabling hls.js worker on Firefox to avoid MSE bufferAppendError"
1325
1380
  );
1326
1381
  }
1382
+ const startPosition = this.options.startPosition;
1327
1383
  this.hls = new Hls({
1328
1384
  enableWorker,
1329
1385
  // LL mode on short encrypted VOD drives aggressive ABR thrash → MSE errors.
1330
1386
  lowLatencyMode: hlsConfig.lowLatencyMode,
1331
1387
  backBufferLength: hlsConfig.backBufferLength,
1332
- // Stabilize ABR: avoid first-frag-only bandwidth test that immediately
1333
- // hops levels on single-segment Appextech VODs (HAR showed truncated
1334
- // 720p body vs Content-Length during level switches).
1388
+ maxBufferLength: hlsConfig.maxBufferLength,
1389
+ maxMaxBufferLength: hlsConfig.maxMaxBufferLength,
1390
+ maxBufferSize: hlsConfig.maxBufferSize,
1391
+ startPosition: typeof startPosition === "number" && startPosition > 0 ? startPosition : -1,
1392
+ // A first-fragment bandwidth probe on short encrypted VODs truncates
1393
+ // the body and immediately hops levels. ABR itself stays on hls.js
1394
+ // defaults so a long VOD is not held on the lowest rung.
1335
1395
  testBandwidth: false,
1336
- abrEwmaDefaultEstimate: 5e5,
1337
- abrBandWidthFactor: 0.8,
1338
- abrBandWidthUpFactor: 0.5,
1339
- maxStarvationDelay: 4,
1340
- capLevelToPlayerSize: true,
1341
1396
  startLevel: -1,
1342
1397
  loader
1343
1398
  });
1344
1399
  this.hls.attachMedia(videoEl);
1345
- this.hls.loadSource(authParams.applyToUrl(playbackUrl));
1400
+ this.hls.loadSource(this.playbackRequestUrl(playbackUrl));
1346
1401
  this.hls.on(Hls.Events.MANIFEST_PARSED, (_event, data) => {
1347
1402
  if (this.destroyed) return;
1348
1403
  this.qualities = (data.levels ?? []).map((level, index) => ({
@@ -1445,35 +1500,35 @@ var HlsEngine = class {
1445
1500
  }
1446
1501
  }
1447
1502
  clampStartPosition(raw, videoEl) {
1448
- let t = Math.max(0, raw);
1503
+ const t = Math.max(0, raw);
1449
1504
  const duration = videoEl.duration;
1450
1505
  if (Number.isFinite(duration) && duration > 0) {
1451
- t = Math.min(t, Math.max(0, duration - 0.35));
1452
- }
1453
- if (videoEl.seekable.length > 0) {
1454
- const end = videoEl.seekable.end(videoEl.seekable.length - 1);
1455
- if (Number.isFinite(end)) {
1456
- t = Math.min(t, end);
1457
- }
1506
+ return Math.min(t, Math.max(0, duration - 0.35));
1458
1507
  }
1459
1508
  return t;
1460
1509
  }
1461
1510
  async applyStartPositionOnly() {
1462
1511
  if (this.destroyed || this.startPositionApplied) return;
1463
1512
  const { videoEl, startPosition } = this.options;
1513
+ if (typeof startPosition !== "number" || startPosition <= 0) {
1514
+ this.startPositionApplied = true;
1515
+ return;
1516
+ }
1517
+ const durationKnown = Number.isFinite(videoEl.duration) && videoEl.duration > 0;
1518
+ if (!durationKnown) {
1519
+ videoEl.addEventListener(
1520
+ "loadedmetadata",
1521
+ () => {
1522
+ void this.applyStartPositionOnly();
1523
+ },
1524
+ { once: true }
1525
+ );
1526
+ return;
1527
+ }
1464
1528
  this.startPositionApplied = true;
1465
- if (typeof startPosition !== "number" || startPosition <= 0) return;
1466
- const seek = () => {
1467
- if (this.destroyed) return;
1468
- try {
1469
- videoEl.currentTime = this.clampStartPosition(startPosition, videoEl);
1470
- } catch {
1471
- }
1472
- };
1473
- if (videoEl.seekable.length > 0 || Number.isFinite(videoEl.duration)) {
1474
- seek();
1475
- } else {
1476
- videoEl.addEventListener("loadedmetadata", seek, { once: true });
1529
+ try {
1530
+ videoEl.currentTime = this.clampStartPosition(startPosition, videoEl);
1531
+ } catch {
1477
1532
  }
1478
1533
  }
1479
1534
  async applyAutoplayOnly() {
@@ -1520,16 +1575,28 @@ var HlsEngine = class {
1520
1575
  if (this.supportMode === "native" && this.options.videoEl) {
1521
1576
  const time = this.options.videoEl.currentTime;
1522
1577
  const wasPaused = this.options.videoEl.paused;
1523
- this.options.videoEl.src = this.options.authParams.applyToUrl(
1524
- this.options.playbackUrl
1525
- );
1578
+ this.options.videoEl.src = this.playbackRequestUrl(this.options.playbackUrl);
1526
1579
  this.options.videoEl.currentTime = time;
1527
1580
  if (!wasPaused) void this.options.videoEl.play();
1528
1581
  }
1529
1582
  }
1530
- resumeAfterAuthRenew() {
1583
+ playbackRequestUrl(playbackUrl) {
1584
+ return rewriteHlsRequestUrl(playbackUrl, this.options.authParams, {
1585
+ videoId: this.options.videoId,
1586
+ mediaProxyUrlBuilder: this.options.mediaProxyUrlBuilder,
1587
+ keyProxyUrlBuilder: this.options.keyProxyUrlBuilder,
1588
+ getKeyAccessToken: this.options.getKeyAccessToken,
1589
+ keyProxyMaxFailures: this.options.keyProxyMaxFailures
1590
+ });
1591
+ }
1592
+ /**
1593
+ * Auth params are already on the shared store, so the next request uses
1594
+ * the new token. Restart the loader only after a real auth failure.
1595
+ * A proactive refresh must not abort the buffered segments.
1596
+ */
1597
+ resumeAfterAuthRenew(restart = true) {
1531
1598
  this.networkRecoveryCount = 0;
1532
- this.hls?.startLoad();
1599
+ if (restart) this.hls?.startLoad();
1533
1600
  this.updateAuthParams();
1534
1601
  }
1535
1602
  setQuality(selection) {
@@ -1791,7 +1858,7 @@ function createVideoPlayer(options) {
1791
1858
  const source = {
1792
1859
  url: options.sourceUrl,
1793
1860
  expiresAt: Date.now() + 24 * 60 * 60 * 1e3,
1794
- live: /\/hls-web-live\//i.test(options.sourceUrl)
1861
+ live: isLivePlaylistUrl(options.sourceUrl)
1795
1862
  };
1796
1863
  sourceManager.applyDirectSource(source);
1797
1864
  playbackUrl = source.url;
@@ -1821,6 +1888,7 @@ function createVideoPlayer(options) {
1821
1888
  startPosition: config.player.startPosition,
1822
1889
  volume: config.player.volume,
1823
1890
  videoId: options.videoId,
1891
+ mediaProxyUrlBuilder: config.streaming.mediaProxyUrlBuilder,
1824
1892
  keyProxyUrlBuilder: config.streaming.keyProxyUrlBuilder,
1825
1893
  // Enterprise AES key auth (see authParamsLoader):
1826
1894
  // 1) keyProxyUrlBuilder BFF — max 2 failures then circuit
@@ -1914,12 +1982,15 @@ function createVideoPlayer(options) {
1914
1982
  renewMaxRetries: options.playback.renewMaxRetries ?? 3,
1915
1983
  renewBackoffMs: options.playback.renewBackoffMs ?? 2e3,
1916
1984
  coalesceMs: options.playback.authRecoveryCoalesceMs ?? 1e3,
1985
+ refreshIntervalMs: options.playback.refreshIntervalMs ?? DEFAULT_PLAYBACK_REFRESH_INTERVAL_MS,
1917
1986
  logger,
1918
1987
  isDestroyed: () => destroyed,
1919
- onRenewing: () => setState("renewing"),
1920
- onRenewed: (nextExpiresAt) => {
1921
- engine?.resumeAfterAuthRenew();
1922
- if (!destroyed) {
1988
+ onRenewing: (reason) => {
1989
+ if (reason !== "proactive") setState("renewing");
1990
+ },
1991
+ onRenewed: (nextExpiresAt, reason) => {
1992
+ engine?.resumeAfterAuthRenew(reason !== "proactive");
1993
+ if (reason !== "proactive" && !destroyed) {
1923
1994
  const el2 = videoEl;
1924
1995
  if (el2 && !el2.paused && !el2.ended) {
1925
1996
  setState("playing");
@@ -1979,8 +2050,13 @@ function createVideoPlayer(options) {
1979
2050
  },
1980
2051
  seek(time) {
1981
2052
  const el = ensureVideoElement();
1982
- const duration = Number.isFinite(el.duration) ? el.duration : time;
1983
- el.currentTime = Math.min(Math.max(0, time), duration);
2053
+ const requested = Math.max(0, time);
2054
+ const duration = el.duration;
2055
+ if (Number.isFinite(duration) && duration > 0) {
2056
+ el.currentTime = Math.min(requested, Math.max(0, duration - 0.05));
2057
+ } else {
2058
+ el.currentTime = requested;
2059
+ }
1984
2060
  },
1985
2061
  goToLive() {
1986
2062
  const el = ensureVideoElement();
@@ -2152,6 +2228,7 @@ function createVideoPlayer(options) {
2152
2228
  streaming: {
2153
2229
  engine: "hls",
2154
2230
  hls: { ...config.streaming.hls, ...partial?.streaming?.hls },
2231
+ mediaProxyUrlBuilder: partial?.streaming?.mediaProxyUrlBuilder ?? config.streaming.mediaProxyUrlBuilder,
2155
2232
  keyProxyUrlBuilder: partial?.streaming?.keyProxyUrlBuilder ?? config.streaming.keyProxyUrlBuilder,
2156
2233
  getKeyAccessToken: partial?.streaming?.getKeyAccessToken ?? config.streaming.getKeyAccessToken ?? (() => authManager.getAccessToken()),
2157
2234
  keyProxyMaxFailures: partial?.streaming?.keyProxyMaxFailures ?? config.streaming.keyProxyMaxFailures
@@ -2180,6 +2257,7 @@ export {
2180
2257
  AuthParamsStore,
2181
2258
  DEFAULT_CONTROLS,
2182
2259
  DEFAULT_LIVE_EDGE_TOLERANCE_SECONDS,
2260
+ DEFAULT_PLAYBACK_REFRESH_INTERVAL_MS,
2183
2261
  DEFAULT_PLAYER_BEHAVIOR,
2184
2262
  DEFAULT_PLAYER_CONFIG,
2185
2263
  DEFAULT_THEME,
@@ -2199,7 +2277,9 @@ export {
2199
2277
  getLiveEdgeTime,
2200
2278
  isAtLiveEdge,
2201
2279
  isEncryptionKeyUrl,
2280
+ isLivePlaylistUrl,
2202
2281
  isPlainObject,
2282
+ isSameOriginHttpUrl,
2203
2283
  mergePlayerConfig,
2204
2284
  redactObject,
2205
2285
  redactSensitive,