@nomercy-entertainment/nomercy-video-player 2.5.0 → 2.6.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,20 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [2.6.0] — 2026-11-01
6
+
7
+ ### Added
8
+
9
+ - 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.
10
+
11
+ ### Changed
12
+
13
+ - `preloadLeadSeconds` defaults to 60 for video (was 10). The subtitle and font prefetch starts earlier with it.
14
+
15
+ ### Fixed
16
+
17
+ - The ASS renderer redraws the carried selection from the `item` event, so a late media load no longer leaves the selection without a renderer.
18
+
5
19
  ## [2.5.0] — 2026-11-01
6
20
 
7
21
  ### Fixed
@@ -157,6 +157,12 @@ export interface IVideoBackend {
157
157
  * here once, at backend construction; unset means the backend's own default.
158
158
  */
159
159
  setHdrOnSdrFallback?(fallback: HdrOnSdrFallback): void;
160
+ /** 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. */
161
+ warm?(url: string, opts?: {
162
+ segments?: number;
163
+ }): Promise<void>;
164
+ /** Abort an in-flight `warm()` and drop what it held. Idempotent. */
165
+ cancelWarm?(): void;
160
166
  play(): Promise<void>;
161
167
  pause(): void;
162
168
  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;
@@ -6,7 +6,10 @@
6
6
  // SPDX-License-Identifier: Apache-2.0
7
7
  // -----------------------------------------------------------------------------
8
8
  import { abrCeiling, appendAuthTokenParam, createAuthorizationXhrSetup, destroyHlsInstance, detectDisplayHdr, hdrDecision, isHls, MediaElementBackend, MediaFormatError, mediaFormatError, panePixels, resetMediaElement, sizeAbrCeiling, supportsNativeHls, } from '@nomercy-entertainment/nomercy-player-core';
9
+ import { createWarmLoader, HlsWarmCache } from './hls-warm-cache.js';
9
10
  import { isMediaAbsentStatus, MEDIA_ABSENT, 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;
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,