@nomercy-entertainment/nomercy-video-player 2.5.0 → 2.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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,28 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [2.7.0] — 2026-11-01
6
+
7
+ ### Changed
8
+
9
+ - A failed load carries the HTTP status of the failed request, so `next()` can skip a missing item (404, 410), refresh once on 401 and raise `fatal` on 5xx.
10
+ - The fixed 10 s `waitForLoadedMetadata` limit is gone for every load; the media pipeline's own retry and error events decide.
11
+ - Needs `@nomercy-entertainment/nomercy-player-core` 2.6.0.
12
+
13
+ ## [2.6.0] — 2026-11-01
14
+
15
+ ### Added
16
+
17
+ - The next item's master playlist, nearest level playlist, default audio rendition and first segments load in the background before the hand-off, so the next episode starts from memory and falls back to the network on a miss. It skips when offline, on data saver or when the current buffer is low, and cancels on seek back, item change and dispose. `preloadSegments` sets the segment count.
18
+
19
+ ### Changed
20
+
21
+ - `preloadLeadSeconds` defaults to 60 for video (was 10). The subtitle and font prefetch starts earlier with it.
22
+
23
+ ### Fixed
24
+
25
+ - The ASS renderer redraws the carried selection from the `item` event, so a late media load no longer leaves the selection without a renderer.
26
+
5
27
  ## [2.5.0] — 2026-11-01
6
28
 
7
29
  ### Fixed
@@ -66,6 +66,7 @@ export interface BackendEventPayload extends MinimalBackendEventPayload {
66
66
  fatal: boolean;
67
67
  message?: string;
68
68
  rawCodec?: string;
69
+ status?: number;
69
70
  };
70
71
  /**
71
72
  * The backend is about to retry after a fatal HLS error. Consumers can
@@ -157,6 +158,12 @@ export interface IVideoBackend {
157
158
  * here once, at backend construction; unset means the backend's own default.
158
159
  */
159
160
  setHdrOnSdrFallback?(fallback: HdrOnSdrFallback): void;
161
+ /** Fetch the manifests and first `segments` segments of `url` into memory for the next `load(url)`. Optional; a repeat call for the same URL is a no-op. */
162
+ warm?(url: string, opts?: {
163
+ segments?: number;
164
+ }): Promise<void>;
165
+ /** Abort an in-flight `warm()` and drop what it held. Idempotent. */
166
+ cancelWarm?(): void;
160
167
  play(): Promise<void>;
161
168
  pause(): void;
162
169
  stop(): void;
@@ -0,0 +1,48 @@
1
+ import type { HlsConfig, Loader, LoaderContext } from 'hls.js';
2
+ export type HlsLoaderConstructor = new (config: HlsConfig) => Loader<LoaderContext>;
3
+ export interface WarmEntry {
4
+ data: ArrayBuffer;
5
+ /** Wall time the original fetch took; replayed into hls.js's bandwidth estimate. */
6
+ fetchMs: number;
7
+ }
8
+ export type WarmEntries = Map<string, Promise<WarmEntry | undefined>>;
9
+ export interface WarmOptions {
10
+ /** Media segments to fetch per stream after its playlist. */
11
+ segments: number;
12
+ /** Height of the level the viewer is on now; the warmed level is the nearest one. */
13
+ preferredHeight?: number;
14
+ /** Stop starting new segment fetches once this many bytes are held. */
15
+ maxBytes: number;
16
+ authHeader?: (url: string) => string | undefined;
17
+ fetch?: typeof fetch;
18
+ }
19
+ export interface WarmedSource {
20
+ entries: WarmEntries;
21
+ /** Absolute URL of the level playlist that was warmed, for the start-level pick. */
22
+ levelUrl: string | undefined;
23
+ }
24
+ export declare function warmKey(url: string, rangeStart?: number, rangeEnd?: number): string;
25
+ /**
26
+ * Fetches the opening of an HLS stream ahead of the `load()` that will need it
27
+ * and holds the bodies in memory, keyed by URL. hls.js is pointed at them
28
+ * through `createWarmLoader`, so the swap needs no HTTP cache headers.
29
+ */
30
+ export declare class HlsWarmCache {
31
+ private _url;
32
+ private _source;
33
+ private _abort;
34
+ private _bytes;
35
+ /** The master URL warmed or being warmed; `undefined` when idle. */
36
+ get url(): string | undefined;
37
+ /** Start warming `masterUrl`. A second call for the same URL is a no-op. */
38
+ warm(masterUrl: string, opts: WarmOptions): Promise<void>;
39
+ /** Hand the warmed bodies to the `load()` that needs them and forget them here. */
40
+ take(masterUrl: string): WarmedSource | undefined;
41
+ /** Abort in-flight fetches and drop everything held. Idempotent. */
42
+ cancel(): void;
43
+ }
44
+ /**
45
+ * Wraps hls.js's own loader: a URL held in `entries` is answered from memory,
46
+ * anything else goes to the network exactly as before.
47
+ */
48
+ export declare function createWarmLoader(Base: HlsLoaderConstructor, entries: WarmEntries): HlsLoaderConstructor;
@@ -0,0 +1,218 @@
1
+ // -----------------------------------------------------------------------------
2
+ // Copyright (c) NoMercy Entertainment
3
+ //
4
+ // Licensed under the Apache License, Version 2.0. See LICENSE for details.
5
+ //
6
+ // SPDX-License-Identifier: Apache-2.0
7
+ // -----------------------------------------------------------------------------
8
+ export function warmKey(url, rangeStart, rangeEnd) {
9
+ // hls.js sends 0..0 for a request without a byte range.
10
+ const ranged = (rangeStart ?? 0) !== 0 || (rangeEnd ?? 0) !== 0;
11
+ return ranged ? `${url}#${rangeStart}-${rangeEnd}` : url;
12
+ }
13
+ /** Resolve like hls.js: an absolute master gives absolute children, a root-relative master gives root-relative ones. */
14
+ function resolveChild(child, masterUrl) {
15
+ const resolved = new URL(child, new URL(masterUrl, 'http://warm.invalid'));
16
+ return /^[a-z][a-z0-9+.-]*:/i.test(masterUrl) ? resolved.href : `${resolved.pathname}${resolved.search}`;
17
+ }
18
+ function parseAttributes(line) {
19
+ const attrs = {};
20
+ const body = line.slice(line.indexOf(':') + 1);
21
+ for (const match of body.matchAll(/([A-Z0-9-]+)=("[^"]*"|[^,]*)/g)) {
22
+ attrs[match[1]] = match[2].replace(/^"|"$/g, '');
23
+ }
24
+ return attrs;
25
+ }
26
+ function pickVariant(master, preferredHeight) {
27
+ const lines = master.split(/\r?\n/);
28
+ const variants = [];
29
+ for (let index = 0; index < lines.length; index++) {
30
+ const line = lines[index];
31
+ if (!line.startsWith('#EXT-X-STREAM-INF'))
32
+ continue;
33
+ const uri = lines.slice(index + 1).find(next => next.trim() !== '' && !next.startsWith('#'));
34
+ if (!uri)
35
+ continue;
36
+ const attrs = parseAttributes(line);
37
+ const height = Number(attrs.RESOLUTION?.split('x')[1] ?? 0);
38
+ variants.push({ uri: uri.trim(), height, bandwidth: Number(attrs.BANDWIDTH ?? 0), audioGroup: attrs.AUDIO });
39
+ }
40
+ if (variants.length === 0)
41
+ return undefined;
42
+ if (preferredHeight === undefined || preferredHeight <= 0)
43
+ return variants.reduce((low, next) => (next.bandwidth < low.bandwidth ? next : low));
44
+ return variants.reduce((best, next) => (Math.abs(next.height - preferredHeight) < Math.abs(best.height - preferredHeight) ? next : best));
45
+ }
46
+ function pickAudioUri(master, group) {
47
+ if (group === undefined)
48
+ return undefined;
49
+ const candidates = master.split(/\r?\n/)
50
+ .filter(line => line.startsWith('#EXT-X-MEDIA') && line.includes('TYPE=AUDIO'))
51
+ .map(parseAttributes)
52
+ .filter(attrs => attrs['GROUP-ID'] === group && attrs.URI);
53
+ const chosen = candidates.find(attrs => attrs.DEFAULT === 'YES') ?? candidates[0];
54
+ return chosen?.URI;
55
+ }
56
+ /** Init segment first, then the first `count` media segments. Empty when byte ranges make the keys unpredictable. */
57
+ function leadingResources(playlist, count) {
58
+ if (playlist.includes('#EXT-X-BYTERANGE'))
59
+ return [];
60
+ const resources = [];
61
+ const lines = playlist.split(/\r?\n/);
62
+ const mapLine = lines.find(line => line.startsWith('#EXT-X-MAP'));
63
+ const mapUri = mapLine ? parseAttributes(mapLine).URI : undefined;
64
+ if (mapUri)
65
+ resources.push(mapUri);
66
+ for (const line of lines) {
67
+ if (resources.length >= count + (mapUri ? 1 : 0))
68
+ break;
69
+ if (line.trim() !== '' && !line.startsWith('#'))
70
+ resources.push(line.trim());
71
+ }
72
+ return resources;
73
+ }
74
+ /**
75
+ * Fetches the opening of an HLS stream ahead of the `load()` that will need it
76
+ * and holds the bodies in memory, keyed by URL. hls.js is pointed at them
77
+ * through `createWarmLoader`, so the swap needs no HTTP cache headers.
78
+ */
79
+ export class HlsWarmCache {
80
+ _url;
81
+ _source;
82
+ _abort;
83
+ _bytes = 0;
84
+ /** The master URL warmed or being warmed; `undefined` when idle. */
85
+ get url() {
86
+ return this._url;
87
+ }
88
+ /** Start warming `masterUrl`. A second call for the same URL is a no-op. */
89
+ async warm(masterUrl, opts) {
90
+ if (this._url === masterUrl)
91
+ return;
92
+ this.cancel();
93
+ const abort = new AbortController();
94
+ this._abort = abort;
95
+ this._url = masterUrl;
96
+ this._bytes = 0;
97
+ const entries = new Map();
98
+ const source = { entries, levelUrl: undefined };
99
+ this._source = source;
100
+ const doFetch = opts.fetch ?? globalThis.fetch.bind(globalThis);
101
+ const grab = (url) => {
102
+ const startedAt = performance.now();
103
+ const authorization = opts.authHeader?.(url);
104
+ return doFetch(url, {
105
+ signal: abort.signal,
106
+ headers: authorization ? { Authorization: authorization } : undefined,
107
+ priority: 'low',
108
+ }).then(async (response) => {
109
+ if (!response.ok)
110
+ return undefined;
111
+ const data = await response.arrayBuffer();
112
+ this._bytes += data.byteLength;
113
+ return { data, fetchMs: performance.now() - startedAt };
114
+ }).catch(() => undefined);
115
+ };
116
+ const register = (url) => {
117
+ const pending = grab(url);
118
+ entries.set(warmKey(url), pending);
119
+ return pending;
120
+ };
121
+ const text = async (entry) => {
122
+ const resolved = await entry;
123
+ return resolved ? new TextDecoder().decode(resolved.data) : undefined;
124
+ };
125
+ const master = await text(register(masterUrl));
126
+ if (master === undefined || abort.signal.aborted)
127
+ return;
128
+ const variant = pickVariant(master, opts.preferredHeight);
129
+ if (variant === undefined)
130
+ return;
131
+ const levelUrl = resolveChild(variant.uri, masterUrl);
132
+ source.levelUrl = levelUrl;
133
+ const audioUri = pickAudioUri(master, variant.audioGroup);
134
+ const streams = [levelUrl, ...(audioUri ? [resolveChild(audioUri, masterUrl)] : [])];
135
+ await Promise.all(streams.map(async (playlistUrl) => {
136
+ const playlist = await text(register(playlistUrl));
137
+ if (playlist === undefined)
138
+ return;
139
+ for (const resource of leadingResources(playlist, opts.segments)) {
140
+ if (abort.signal.aborted || this._bytes >= opts.maxBytes)
141
+ return;
142
+ await register(resolveChild(resource, playlistUrl));
143
+ }
144
+ }));
145
+ }
146
+ /** Hand the warmed bodies to the `load()` that needs them and forget them here. */
147
+ take(masterUrl) {
148
+ if (this._url !== masterUrl || this._source === undefined)
149
+ return undefined;
150
+ const source = this._source;
151
+ this._url = undefined;
152
+ this._source = undefined;
153
+ this._abort = undefined;
154
+ return source;
155
+ }
156
+ /** Abort in-flight fetches and drop everything held. Idempotent. */
157
+ cancel() {
158
+ this._abort?.abort();
159
+ this._abort = undefined;
160
+ this._source = undefined;
161
+ this._url = undefined;
162
+ this._bytes = 0;
163
+ }
164
+ }
165
+ /**
166
+ * Wraps hls.js's own loader: a URL held in `entries` is answered from memory,
167
+ * anything else goes to the network exactly as before.
168
+ */
169
+ export function createWarmLoader(Base, entries) {
170
+ return class WarmLoader {
171
+ _inner;
172
+ _aborted = false;
173
+ constructor(config) {
174
+ this._inner = new Base(config);
175
+ }
176
+ get stats() {
177
+ return this._inner.stats;
178
+ }
179
+ get context() {
180
+ return this._inner.context;
181
+ }
182
+ load(context, config, callbacks) {
183
+ const key = warmKey(context.url, context.rangeStart, context.rangeEnd);
184
+ const held = entries.get(key);
185
+ if (held === undefined) {
186
+ this._inner.load(context, config, callbacks);
187
+ return;
188
+ }
189
+ entries.delete(key);
190
+ this._aborted = false;
191
+ void held.then((entry) => {
192
+ if (this._aborted)
193
+ return;
194
+ if (entry === undefined) {
195
+ this._inner.load(context, config, callbacks);
196
+ return;
197
+ }
198
+ const stats = this._inner.stats;
199
+ const now = performance.now();
200
+ stats.loaded = entry.data.byteLength;
201
+ stats.total = entry.data.byteLength;
202
+ stats.loading.start = now - entry.fetchMs;
203
+ stats.loading.first = now - entry.fetchMs;
204
+ stats.loading.end = now;
205
+ const data = context.responseType === 'arraybuffer' ? entry.data : new TextDecoder().decode(entry.data);
206
+ callbacks.onSuccess({ url: context.url, data }, stats, context, null);
207
+ });
208
+ }
209
+ abort() {
210
+ this._aborted = true;
211
+ this._inner.abort();
212
+ }
213
+ destroy() {
214
+ this._aborted = true;
215
+ this._inner.destroy();
216
+ }
217
+ };
218
+ }
@@ -137,6 +137,11 @@ export declare class Html5VideoBackend extends MediaElementBackend<HTMLVideoElem
137
137
  preload?: HtmlPreloadMode;
138
138
  startTime?: number;
139
139
  }): Promise<void>;
140
+ private readonly _warmCache;
141
+ warm(url: string, opts?: {
142
+ segments?: number;
143
+ }): Promise<void>;
144
+ cancelWarm(): void;
140
145
  unload(): void;
141
146
  dispose(): void;
142
147
  private _teardownAudioGraph;
@@ -5,8 +5,11 @@
5
5
  //
6
6
  // SPDX-License-Identifier: Apache-2.0
7
7
  // -----------------------------------------------------------------------------
8
- import { abrCeiling, appendAuthTokenParam, createAuthorizationXhrSetup, destroyHlsInstance, detectDisplayHdr, hdrDecision, isHls, MediaElementBackend, MediaFormatError, mediaFormatError, panePixels, resetMediaElement, sizeAbrCeiling, supportsNativeHls, } from '@nomercy-entertainment/nomercy-player-core';
9
- import { isMediaAbsentStatus, MEDIA_ABSENT, SOURCE_OUTAGE_BACKOFF_MS, sourceOutageRetryLimit } from './source-outage.js';
8
+ import { abrCeiling, appendAuthTokenParam, createAuthorizationXhrSetup, destroyHlsInstance, detectDisplayHdr, hdrDecision, isHls, MediaElementBackend, MediaFormatError, mediaFormatError, panePixels, resetMediaElement, sizeAbrCeiling, StreamError, supportsNativeHls, } from '@nomercy-entertainment/nomercy-player-core';
9
+ import { createWarmLoader, HlsWarmCache } from './hls-warm-cache.js';
10
+ import { definiteFailureCode, SOURCE_OUTAGE_BACKOFF_MS, sourceOutageRetryLimit } from './source-outage.js';
11
+ /** Cap on bytes the next-item warmup may hold in memory. */
12
+ const WARM_MAX_BYTES = 24 * 1024 * 1024;
10
13
  const CODEC_LABELS = [
11
14
  [/avc1|h264/i, 'H.264'],
12
15
  [/hvc1|hev1|h265/i, 'H.265 (HEVC)'],
@@ -193,6 +196,7 @@ export class Html5VideoBackend extends MediaElementBackend {
193
196
  if (opts?.preload)
194
197
  this.element.preload = opts.preload;
195
198
  const hlsUrl = isHls(url);
199
+ const warmed = this._warmCache.take(url);
196
200
  const nativeHls = supportsNativeHls(this.element);
197
201
  // Tear down any previous Hls instance BEFORE wiring a new source.
198
202
  // Without this, every load() leaks an Hls that keeps polling segment 0
@@ -266,7 +270,10 @@ export class Html5VideoBackend extends MediaElementBackend {
266
270
  suggestion: 'Use a Chromium-based browser, Safari, or Firefox 119+ for HLS support.',
267
271
  });
268
272
  }
273
+ const BaseLoader = Hls.DefaultConfig?.loader;
274
+ const warmLoader = warmed && BaseLoader ? createWarmLoader(BaseLoader, warmed.entries) : undefined;
269
275
  const hlsInstance = new Hls({
276
+ ...(warmLoader ? { loader: warmLoader } : {}),
270
277
  autoStartLoad: true,
271
278
  enableWorker: true,
272
279
  lowLatencyMode: false,
@@ -280,6 +287,10 @@ export class Html5VideoBackend extends MediaElementBackend {
280
287
  hlsInstance.on(Hls.Events.MANIFEST_PARSED, () => {
281
288
  performance.mark('nm:backend:manifest-parsed');
282
289
  this._emitHlsTrackLists();
290
+ // Start on the level that was warmed so its playlist and segments are the ones served from memory.
291
+ const warmedLevel = warmed?.levelUrl ? hlsInstance.levels.findIndex(level => level.uri === warmed.levelUrl) : -1;
292
+ if (warmedLevel >= 0)
293
+ hlsInstance.startLevel = warmedLevel;
283
294
  });
284
295
  // hls.js fills its audio list after the manifest parse, then fires this.
285
296
  hlsInstance.on(Hls.Events.AUDIO_TRACKS_UPDATED, () => {
@@ -314,6 +325,21 @@ export class Html5VideoBackend extends MediaElementBackend {
314
325
  this._state = 'ready';
315
326
  this.emit('loadedmetadata', { url, kind: this.kind, duration: this.element.duration });
316
327
  }
328
+ _warmCache = new HlsWarmCache();
329
+ async warm(url, opts) {
330
+ if (!isHls(url) || supportsNativeHls(this.element))
331
+ return;
332
+ const playingHeight = this.hls?.levels[this.currentLevel()]?.height;
333
+ await this._warmCache.warm(url, {
334
+ segments: opts?.segments ?? 3,
335
+ preferredHeight: playingHeight,
336
+ maxBytes: WARM_MAX_BYTES,
337
+ authHeader: this._authHeaderProvider,
338
+ });
339
+ }
340
+ cancelWarm() {
341
+ this._warmCache.cancel();
342
+ }
317
343
  unload() {
318
344
  this._state = 'idle';
319
345
  this._ended = false;
@@ -334,6 +360,7 @@ export class Html5VideoBackend extends MediaElementBackend {
334
360
  this.emit('waiting');
335
361
  }
336
362
  dispose() {
363
+ this._warmCache.cancel();
337
364
  if (this._retryTimer !== undefined) {
338
365
  clearTimeout(this._retryTimer);
339
366
  this._retryTimer = undefined;
@@ -902,9 +929,12 @@ export class Html5VideoBackend extends MediaElementBackend {
902
929
  // that, and a consumer can act on it — offer the next item — but only if
903
930
  // it is told which failure this was, so it gets its own code rather than
904
931
  // the generic network one every outage ends with.
905
- if (isMediaAbsentStatus(httpStatus) && !this._sawConnectionFailure) {
932
+ const definiteCode = this._sawConnectionFailure
933
+ ? undefined
934
+ : definiteFailureCode(httpStatus, this._state === 'loading');
935
+ if (definiteCode) {
906
936
  this._recoveringFromOutage = false;
907
- this._escalateHlsError(MEDIA_ABSENT, `media absent (HTTP ${httpStatus}): ${data.details}`);
937
+ this._escalateHlsError(definiteCode, `HTTP ${httpStatus}: ${data.details}`, httpStatus);
908
938
  return;
909
939
  }
910
940
  if (this._netRetryCount >= limit) {
@@ -970,10 +1000,10 @@ export class Html5VideoBackend extends MediaElementBackend {
970
1000
  * @param details - `HlsErrorData.details` string from hls.js
971
1001
  * @param message - Human-readable summary for the error payload
972
1002
  */
973
- _escalateHlsError(details, message) {
1003
+ _escalateHlsError(details, message, status) {
974
1004
  this._hadError = true;
975
1005
  this._state = 'error';
976
- this.emit('stream:error', { details, fatal: true });
1006
+ this.emit('stream:error', status === undefined ? { details, fatal: true } : { details, fatal: true, status });
977
1007
  // Construct a synthetic error event so the `error` channel stays
978
1008
  // typed as `Event` (BackendEventPayload contract). Consumers that
979
1009
  // want the typed PlayerError should listen on `stream:error`.
@@ -1308,14 +1338,11 @@ export class Html5VideoBackend extends MediaElementBackend {
1308
1338
  waitForLoadedMetadata() {
1309
1339
  if (this.element.readyState >= 1 /* HAVE_METADATA */)
1310
1340
  return Promise.resolve();
1311
- const METADATA_TIMEOUT_MS = 10_000;
1312
1341
  return new Promise((resolve, reject) => {
1313
- let timer;
1314
1342
  let onLoad;
1315
1343
  let onElementError;
1316
1344
  let onStreamError;
1317
1345
  const cleanup = () => {
1318
- clearTimeout(timer);
1319
1346
  this.element.removeEventListener('loadedmetadata', onLoad);
1320
1347
  this.element.removeEventListener('error', onElementError);
1321
1348
  this.off('stream:error', onStreamError);
@@ -1334,18 +1361,15 @@ export class Html5VideoBackend extends MediaElementBackend {
1334
1361
  onStreamError = (data) => {
1335
1362
  if (data?.fatal) {
1336
1363
  cleanup();
1337
- reject(new Error(`HLS fatal: ${data.details}`));
1364
+ reject(new StreamError({
1365
+ code: data.details,
1366
+ severity: 'error',
1367
+ scope: { kind: 'stream', id: 'hls' },
1368
+ message: `HLS fatal: ${data.details}`,
1369
+ context: data.status === undefined ? undefined : { httpStatus: data.status },
1370
+ }));
1338
1371
  }
1339
1372
  };
1340
- // Hard backstop: if neither loadedmetadata nor a fatal error arrives
1341
- // within METADATA_TIMEOUT_MS, reject so load() never parks indefinitely.
1342
- // This catches the case where HLS.js retries exhaust slowly (the default
1343
- // three-retry back-off takes 7 s on manifest 404s) or where a non-fatal
1344
- // error loop never escalates to fatal at all.
1345
- timer = setTimeout(() => {
1346
- cleanup();
1347
- reject(new Error(`waitForLoadedMetadata timed out after ${METADATA_TIMEOUT_MS} ms`));
1348
- }, METADATA_TIMEOUT_MS);
1349
1373
  this.element.addEventListener('loadedmetadata', onLoad, { once: true });
1350
1374
  this.element.addEventListener('error', onElementError, { once: true });
1351
1375
  this.on('stream:error', onStreamError);
@@ -57,6 +57,8 @@ export declare const NO_RETRIES = 0;
57
57
  * 410 is the same answer said more firmly.
58
58
  */
59
59
  export declare function isMediaAbsentStatus(httpStatus: number): boolean;
60
+ /** True for a 5xx from a server that is up (500, 501, 505...), as opposed to an origin-down status. */
61
+ export declare function isServerErrorStatus(httpStatus: number): boolean;
60
62
  /**
61
63
  * How many rungs this failure is allowed.
62
64
  *
@@ -80,3 +82,9 @@ export declare function sourceOutageRetryLimit(httpStatus: number, sawConnection
80
82
  * other.
81
83
  */
82
84
  export declare const MEDIA_ABSENT = "core:stream/media-absent";
85
+ /** The server answered 5xx while up; the player raises a fatal error. */
86
+ export declare const SERVER_ERROR = "core:stream/server-error";
87
+ /** The media request was refused with 401; the player refreshes the token once. */
88
+ export declare const UNAUTHENTICATED = "core:auth/unauthenticated";
89
+ /** The code for a failure no retry changes, else `undefined`. */
90
+ export declare function definiteFailureCode(httpStatus: number, loading: boolean): string | undefined;
@@ -77,6 +77,10 @@ export const NO_RETRIES = 0;
77
77
  export function isMediaAbsentStatus(httpStatus) {
78
78
  return httpStatus === 404 || httpStatus === 410;
79
79
  }
80
+ /** True for a 5xx from a server that is up (500, 501, 505...), as opposed to an origin-down status. */
81
+ export function isServerErrorStatus(httpStatus) {
82
+ return httpStatus >= 500 && httpStatus <= 599 && !isOriginDownStatus(httpStatus);
83
+ }
80
84
  /**
81
85
  * How many rungs this failure is allowed.
82
86
  *
@@ -99,7 +103,7 @@ export function sourceOutageRetryLimit(httpStatus, sawConnectionFailure) {
99
103
  return SOURCE_OUTAGE_BACKOFF_MS.length;
100
104
  if (isOriginDownStatus(httpStatus))
101
105
  return SOURCE_OUTAGE_BACKOFF_MS.length;
102
- if (isMediaAbsentStatus(httpStatus))
106
+ if (isMediaAbsentStatus(httpStatus) || isServerErrorStatus(httpStatus))
103
107
  return NO_RETRIES;
104
108
  if (httpStatus > 0)
105
109
  return HTTP_STATUS_RETRY_LIMIT;
@@ -112,3 +116,18 @@ export function sourceOutageRetryLimit(httpStatus, sawConnectionFailure) {
112
116
  * other.
113
117
  */
114
118
  export const MEDIA_ABSENT = 'core:stream/media-absent';
119
+ /** The server answered 5xx while up; the player raises a fatal error. */
120
+ export const SERVER_ERROR = 'core:stream/server-error';
121
+ /** The media request was refused with 401; the player refreshes the token once. */
122
+ export const UNAUTHENTICATED = 'core:auth/unauthenticated';
123
+ /** The code for a failure no retry changes, else `undefined`. */
124
+ export function definiteFailureCode(httpStatus, loading) {
125
+ if (isMediaAbsentStatus(httpStatus))
126
+ return MEDIA_ABSENT;
127
+ if (isServerErrorStatus(httpStatus))
128
+ return SERVER_ERROR;
129
+ // A 401 counts only while loading: mid-playback the ladder picks up a refreshed token.
130
+ if (httpStatus === 401 && loading)
131
+ return UNAUTHENTICATED;
132
+ return undefined;
133
+ }
package/dist/index.d.ts CHANGED
@@ -2,6 +2,7 @@ import type { ActionOptions, AriaLiveLevel, AudioTrack, AuthConfig, BasePlaylist
2
2
  import type { IVideoBackend, VideoBackendKind } from './adapters/video-backend/IVideoBackend.js';
3
3
  import type { AudioTrackState, IVideoPlayer, PlayState, QualityState, RepeatState, SegmentOptions, ShuffleState, Stretching, VideoEventMap, VideoPlayerConfig, VideoPlaylistItem, VideoRect, VolumeState } from './types.js';
4
4
  import { EventEmitter } from '@nomercy-entertainment/nomercy-player-core';
5
+ import { NextItemWarmup } from './player/next-item-warmup.js';
5
6
  import { FullscreenState, PipState, SubtitleState, TheaterState } from './types.js';
6
7
  export type { IChapterSource } from './adapters/chapter-source/IChapterSource.js';
7
8
  export { VttChapterSource } from './adapters/chapter-source/vtt-chapters.js';
@@ -172,6 +173,7 @@ export declare class NMVideoPlayer<T extends VideoPlaylistItem = VideoPlaylistIt
172
173
  plugins: () => ReadonlyArray<Plugin>;
173
174
  enabledPlugins: () => ReadonlyArray<Plugin>;
174
175
  constructor(id?: string | number);
176
+ readonly _nextItemWarmup: NextItemWarmup;
175
177
  private _languageMemoryInstance;
176
178
  /**
177
179
  * Carries the viewer's chosen audio / subtitle language across items. Built
package/dist/index.js CHANGED
@@ -8,6 +8,7 @@
8
8
  import { bridgeBackendPlayState, BrowserPolicyError, composeMixins, EventEmitter, GaplessTransitionStrategy, initPlayerCoreState, NotImplementedError, playerCoreMethods, resolvePlayerConstructor, } from '@nomercy-entertainment/nomercy-player-core';
9
9
  import { Html5VideoBackend } from './adapters/video-backend/html5.js';
10
10
  import { readItemImage } from './player/itemImage.js';
11
+ import { NextItemWarmup } from './player/next-item-warmup.js';
11
12
  import { normalizeVideoPlaylistItem } from './player/normalize-item.js';
12
13
  import { VideoPreloadStrategy } from './player/preload.js';
13
14
  import { pickStartItem } from './player/start-selection.js';
@@ -86,6 +87,10 @@ export class NMVideoPlayer extends EventEmitter {
86
87
  this.on('item', (data) => {
87
88
  const item = data?.item;
88
89
  this._applyPosterForRaw(readItemImage(item));
90
+ this._nextItemWarmup.onItemChange(item?.id);
91
+ });
92
+ this.on('time', ({ time, duration }) => {
93
+ this._nextItemWarmup.onTime(time, duration);
89
94
  });
90
95
  // Apply the incoming item's poster BEFORE backend.load() clears the
91
96
  // element src — this ensures the browser shows the new poster image
@@ -145,6 +150,18 @@ export class NMVideoPlayer extends EventEmitter {
145
150
  catch { /* backend may not be ready yet — ignore */ }
146
151
  });
147
152
  }
153
+ _nextItemWarmup = new NextItemWarmup({
154
+ leadSeconds: () => this.options?.preloadLeadSeconds ?? 0,
155
+ segments: () => this.options?.preloadSegments ?? 3,
156
+ next: () => this.peekNext(),
157
+ resolveUrl: async (item) => (await this.resolveUrl(item.url ?? '', 'media')).href,
158
+ backend: () => this._backend,
159
+ bufferedAhead: () => (this._backend ? this._backend.buffered() - this._backend.currentTime() : 0),
160
+ environment: () => ({
161
+ online: typeof navigator === 'undefined' || navigator.onLine !== false,
162
+ saveData: typeof navigator !== 'undefined' && Reflect.get(Reflect.get(navigator, 'connection') ?? {}, 'saveData') === true,
163
+ }),
164
+ });
148
165
  _languageMemoryInstance;
149
166
  /**
150
167
  * Carries the viewer's chosen audio / subtitle language across items. Built
@@ -782,6 +799,7 @@ composeMixins(NMVideoPlayer.prototype, ...playerCoreMethods);
782
799
  _instances.set(claimedId, this);
783
800
  return;
784
801
  }
802
+ this._nextItemWarmup.dispose();
785
803
  this._disposeBackend();
786
804
  };
787
805
  }
@@ -823,7 +841,7 @@ composeMixins(NMVideoPlayer.prototype, ...playerCoreMethods);
823
841
  // Video defaults to a hard cut between items (no crossfade) while still
824
842
  // preloading so the next item starts instantly. Consumer-supplied
825
843
  // strategies always win — only inject when absent.
826
- const leadSeconds = config.preloadLeadSeconds ?? 10;
844
+ const leadSeconds = config.preloadLeadSeconds ?? 60;
827
845
  const enrichedConfig = {
828
846
  crossfadeEnabled: false,
829
847
  ...config,