BlueGit

timfa filemanager

Files

filemanager / tests / shared-video-player.test.js

shared-video-player.test.js

0ecdfa02 History
shared-video-player.test.js 51.0 KiB Download Raw
1'use strict';
2
3const fs = require('fs');
4const path = require('path');
5const { JSDOM } = require('jsdom');
6
7function flushAsyncWork (window, rounds = 6)
8{
9 let chain = Promise.resolve();
10 for (let i = 0; i < rounds; i++)
11 {
12 chain = chain.then(() => new Promise((resolve) => window.setTimeout(resolve, 0)));
13 }
14 return chain;
15}
16
17function buildPlayerHarness (window)
18{
19 const registeredComponents = new Map();
20
21 class MockButton
22 {
23 constructor(player)
24 {
25 this._player = player;
26 this._el = null;
27 }
28
29 player ()
30 {
31 return this._player;
32 }
33
34 buildCSSClass ()
35 {
36 return 'vjs-control';
37 }
38
39 createEl ()
40 {
41 const el = window.document.createElement('button');
42 el.className = this.buildCSSClass();
43 return el;
44 }
45
46 el ()
47 {
48 if (!this._el) this._el = this.createEl();
49 return this._el;
50 }
51 }
52
53 registeredComponents.set('Button', MockButton);
54
55 const videojs = {
56 getComponent: (name) => registeredComponents.get(name),
57 registerComponent: (name, component) =>
58 {
59 registeredComponents.set(name, component);
60 },
61 };
62
63 const events = new Map();
64 const playerEl = window.document.createElement('div');
65 const progressControlEl = window.document.createElement('div');
66 progressControlEl.className = 'vjs-progress-control';
67 playerEl.appendChild(progressControlEl);
68 let currentTime = 0;
69 let durationSeconds = 10;
70 let bufferedEndSeconds = null;
71
72 const player = {
73 ready (cb)
74 {
75 if (typeof cb === 'function') cb();
76 },
77 on (type, fn)
78 {
79 if (!events.has(type)) events.set(type, new Set());
80 events.get(type).add(fn);
81 },
82 trigger (type)
83 {
84 const listeners = events.get(type);
85 if (!listeners) return;
86 for (const fn of Array.from(listeners)) fn();
87 },
88 currentTime ()
89 {
90 return currentTime;
91 },
92 setCurrentTime (next)
93 {
94 currentTime = Number(next);
95 },
96 duration (nextValue)
97 {
98 if (typeof nextValue === 'number')
99 {
100 durationSeconds = nextValue;
101 }
102 return durationSeconds;
103 },
104 bufferedEnd ()
105 {
106 return bufferedEndSeconds;
107 },
108 setBufferedEnd (next)
109 {
110 bufferedEndSeconds = Number.isFinite(next) ? Number(next) : null;
111 },
112 el ()
113 {
114 return playerEl;
115 },
116 getChild (name)
117 {
118 if (name !== 'controlBar') return null;
119 return {
120 addChild (componentName)
121 {
122 const Component = registeredComponents.get(componentName);
123 if (!Component) return null;
124 const instance = new Component(player);
125 playerEl.appendChild(instance.el());
126 return instance;
127 },
128 };
129 },
130 };
131
132 return { player, videojs };
133}
134
135function loadSharedVideoPlayer (window)
136{
137 const script = fs.readFileSync(path.join(__dirname, '../public/shared-video-player.js'), 'utf8');
138 window.eval(script);
139 return window.FilemanagerSharedVideoPlayer;
140}
141
142describe('shared image subtitle prefetching', () =>
143{
144 function createWindow ()
145 {
146 const dom = new JSDOM('<!doctype html><html><body></body></html>', {
147 url: 'http://localhost/',
148 runScripts: 'dangerously',
149 pretendToBeVisual: true,
150 });
151
152 dom.window.AbortController = AbortController;
153 dom.window.Response = Response;
154 dom.window.Headers = Headers;
155 dom.window.Request = Request;
156 dom.window.URL.createObjectURL = () => 'blob:subtitle';
157 dom.window.URL.revokeObjectURL = () => { };
158
159 return dom.window;
160 }
161
162 test('prefetches lookahead frames even when no subtitle is currently active', async () =>
163 {
164 const window = createWindow();
165 const helper = loadSharedVideoPlayer(window);
166 const { player, videojs } = buildPlayerHarness(window);
167 const requestedTimes = [];
168
169 window.fetch = jest.fn(async (url) =>
170 {
171 const parsed = new URL(url, 'http://localhost/');
172 requestedTimes.push(Number(parsed.searchParams.get('timeSeconds')));
173 return new Response(null, {
174 status: 204,
175 headers: { 'X-Subtitle-Frame-Status': 'none' },
176 });
177 });
178
179 helper.bindImageSubtitleOverlay(player, videojs, {}, {
180 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
181 }, {
182 lookaheadSeconds: 1,
183 buildFrameRequest: ({ currentTime, streamIndex }) => ({
184 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
185 }),
186 });
187
188 await flushAsyncWork(window);
189
190 expect(requestedTimes).toEqual(expect.arrayContaining([0, 0.5, 1]));
191
192 window.close();
193 });
194
195 test('prefetches subtitle frames through known video duration even with short lookahead', async () =>
196 {
197 const window = createWindow();
198 const helper = loadSharedVideoPlayer(window);
199 const { player, videojs } = buildPlayerHarness(window);
200 const requestedTimes = [];
201
202 player.duration(3);
203
204 window.fetch = jest.fn(async (url) =>
205 {
206 const parsed = new URL(url, 'http://localhost/');
207 requestedTimes.push(Number(parsed.searchParams.get('timeSeconds')));
208 return new Response(null, {
209 status: 204,
210 headers: { 'X-Subtitle-Frame-Status': 'none' },
211 });
212 });
213
214 helper.bindImageSubtitleOverlay(player, videojs, {}, {
215 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
216 }, {
217 lookaheadSeconds: 0.5,
218 buildFrameRequest: ({ currentTime, streamIndex }) => ({
219 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
220 }),
221 });
222
223 await flushAsyncWork(window, 18);
224
225 expect(requestedTimes).toEqual(expect.arrayContaining([0, 0.5, 1, 1.5, 2, 2.5, 3]));
226
227 window.close();
228 });
229
230 test('prefetches at least through the buffered video end', async () =>
231 {
232 const window = createWindow();
233 const helper = loadSharedVideoPlayer(window);
234 const { player, videojs } = buildPlayerHarness(window);
235 const requestedTimes = [];
236
237 player.setBufferedEnd(3);
238
239 window.fetch = jest.fn(async (url) =>
240 {
241 const parsed = new URL(url, 'http://localhost/');
242 requestedTimes.push(Number(parsed.searchParams.get('timeSeconds')));
243 return new Response(null, {
244 status: 204,
245 headers: { 'X-Subtitle-Frame-Status': 'none' },
246 });
247 });
248
249 helper.bindImageSubtitleOverlay(player, videojs, {}, {
250 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
251 }, {
252 lookaheadSeconds: 0.5,
253 buildFrameRequest: ({ currentTime, streamIndex }) => ({
254 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
255 }),
256 });
257
258 await flushAsyncWork(window, 12);
259
260 expect(requestedTimes).toEqual(expect.arrayContaining([0, 0.5, 1, 1.5, 2, 2.5, 3]));
261
262 window.close();
263 });
264
265 test('prefetch uses furthest buffered end when player.bufferedEnd under-reports', async () =>
266 {
267 const window = createWindow();
268 const helper = loadSharedVideoPlayer(window);
269 const { player, videojs } = buildPlayerHarness(window);
270 const requestedTimes = [];
271
272 player.setBufferedEnd(0);
273 player.tech = () => ({
274 el: () => ({
275 buffered: {
276 length: 1,
277 end: () => 6,
278 },
279 }),
280 });
281
282 window.fetch = jest.fn(async (url) =>
283 {
284 const parsed = new URL(url, 'http://localhost/');
285 requestedTimes.push(Number(parsed.searchParams.get('timeSeconds')));
286 return new Response(null, {
287 status: 204,
288 headers: { 'X-Subtitle-Frame-Status': 'none' },
289 });
290 });
291
292 helper.bindImageSubtitleOverlay(player, videojs, {}, {
293 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
294 }, {
295 lookaheadSeconds: 0,
296 initialPrefetchSeconds: 0,
297 buildFrameRequest: ({ currentTime, streamIndex }) => ({
298 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
299 }),
300 });
301
302 await flushAsyncWork(window, 16);
303
304 expect(requestedTimes).toEqual(expect.arrayContaining([0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6]));
305
306 window.close();
307 });
308
309 test('prefetch frontier jumps to current playback time instead of replaying stale lag', async () =>
310 {
311 const window = createWindow();
312 const helper = loadSharedVideoPlayer(window);
313 const { player, videojs } = buildPlayerHarness(window);
314 const requestedTimes = [];
315
316 player.setBufferedEnd(35);
317
318 window.fetch = jest.fn(async (url) =>
319 {
320 const parsed = new URL(url, 'http://localhost/');
321 const timeSeconds = Number(parsed.searchParams.get('timeSeconds'));
322 requestedTimes.push(timeSeconds);
323 return new Response(null, {
324 status: 204,
325 headers: { 'X-Subtitle-Frame-Status': 'none' },
326 });
327 });
328
329 helper.bindImageSubtitleOverlay(player, videojs, {}, {
330 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
331 }, {
332 lookaheadSeconds: 0,
333 initialPrefetchSeconds: 0,
334 buildFrameRequest: ({ currentTime, streamIndex }) => ({
335 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
336 }),
337 });
338
339 await flushAsyncWork(window, 8);
340 expect(requestedTimes).toEqual(expect.arrayContaining([0, 0.5]));
341
342 requestedTimes.length = 0;
343 player.setCurrentTime(20);
344 player.setBufferedEnd(40);
345 player.trigger('timeupdate');
346 await flushAsyncWork(window, 8);
347
348 expect(requestedTimes).toContain(20);
349 const prefetchAfterJump = requestedTimes.filter((value) => value > 20);
350 expect(prefetchAfterJump.length).toBeGreaterThan(0);
351 expect(Math.min(...prefetchAfterJump)).toBeGreaterThanOrEqual(20.5);
352
353 window.close();
354 });
355
356 test('does not restart current subtitle request while one is in flight', async () =>
357 {
358 const window = createWindow();
359 const helper = loadSharedVideoPlayer(window);
360 const { player, videojs } = buildPlayerHarness(window);
361 const pendingResolvers = [];
362 const requestTimes = [];
363
364 window.fetch = jest.fn((url, init = {}) =>
365 {
366 const parsed = new URL(url, 'http://localhost/');
367 requestTimes.push(Number(parsed.searchParams.get('timeSeconds')));
368
369 if (pendingResolvers.length === 0)
370 {
371 return new Promise((resolve) =>
372 {
373 pendingResolvers.push(() => resolve(new Response(null, {
374 status: 204,
375 headers: { 'X-Subtitle-Frame-Status': 'none' },
376 })));
377 });
378 }
379
380 expect(init.signal && init.signal.aborted).toBe(false);
381 return Promise.resolve(new Response(null, {
382 status: 204,
383 headers: { 'X-Subtitle-Frame-Status': 'none' },
384 }));
385 });
386
387 helper.bindImageSubtitleOverlay(player, videojs, {}, {
388 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
389 }, {
390 lookaheadSeconds: 0,
391 initialPrefetchSeconds: 0,
392 buildFrameRequest: ({ currentTime, streamIndex }) => ({
393 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
394 }),
395 });
396
397 await flushAsyncWork(window, 3);
398 expect(window.fetch).toHaveBeenCalledTimes(1);
399
400 player.setCurrentTime(1.5);
401 player.trigger('timeupdate');
402 player.setCurrentTime(2.25);
403 player.trigger('timeupdate');
404 await flushAsyncWork(window, 2);
405
406 expect(window.fetch).toHaveBeenCalledTimes(1);
407
408 pendingResolvers[0]();
409 await flushAsyncWork(window, 5);
410
411 expect(window.fetch.mock.calls.length).toBeGreaterThanOrEqual(2);
412 expect(requestTimes).toEqual(expect.arrayContaining([0, 2.25]));
413
414 window.close();
415 });
416
417 test('renders a prefetched frame for the current paused time without waiting for another timeupdate', async () =>
418 {
419 const window = createWindow();
420 const helper = loadSharedVideoPlayer(window);
421 const { player, videojs } = buildPlayerHarness(window);
422
423 player.duration(120);
424 player.setCurrentTime(118.95);
425
426 window.fetch = jest.fn(async (url) =>
427 {
428 const parsed = new URL(url, 'http://localhost/');
429 const timeSeconds = Number(parsed.searchParams.get('timeSeconds'));
430 const headers = {
431 'Content-Type': 'image/png',
432 };
433
434 if (Math.abs(timeSeconds - 118.95) < 0.001)
435 {
436 headers['X-Subtitle-Frame-Start-Time'] = '118.90';
437 headers['X-Subtitle-Frame-End-Time'] = '119.00';
438 headers['X-Subtitle-Frame-Width'] = '640';
439 headers['X-Subtitle-Frame-Height'] = '80';
440 headers['X-Subtitle-Frame-Canvas-Width'] = '1920';
441 headers['X-Subtitle-Frame-Canvas-Height'] = '1080';
442 return new Response(new Uint8Array([137, 80, 78, 71]), { status: 200, headers });
443 }
444
445 return new Response(null, {
446 status: 204,
447 headers: { 'X-Subtitle-Frame-Status': 'none' },
448 });
449 });
450
451 helper.bindImageSubtitleOverlay(player, videojs, {}, {
452 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
453 }, {
454 currentFetchEnabled: false,
455 cacheMissFallbackEnabled: false,
456 lookaheadSeconds: 0,
457 initialPrefetchSeconds: 0,
458 buildFrameRequest: ({ currentTime, streamIndex }) => ({
459 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
460 }),
461 });
462
463 await flushAsyncWork(window, 10);
464
465 const overlay = player.el().querySelector('.video-subtitle-overlay');
466 const overlayImg = overlay && overlay.querySelector('img');
467 expect(overlay).toBeTruthy();
468 expect(overlayImg).toBeTruthy();
469 expect(overlay.style.display).toBe('block');
470 expect(overlayImg.getAttribute('src')).toBe('blob:subtitle');
471
472 window.close();
473 });
474
475 test('aborts in-flight prefetch requests when the overlay is detached', async () =>
476 {
477 const window = createWindow();
478 const helper = loadSharedVideoPlayer(window);
479 const { player, videojs } = buildPlayerHarness(window);
480 const activeSignals = [];
481
482 window.fetch = jest.fn((url, init = {}) =>
483 {
484 const parsed = new URL(url, 'http://localhost/');
485 const timeSeconds = Number(parsed.searchParams.get('timeSeconds'));
486
487 if (timeSeconds === 0)
488 {
489 return Promise.resolve(new Response(null, {
490 status: 204,
491 headers: { 'X-Subtitle-Frame-Status': 'none' },
492 }));
493 }
494
495 activeSignals.push(init.signal || null);
496
497 return new Promise((resolve, reject) =>
498 {
499 if (init.signal && typeof init.signal.addEventListener === 'function')
500 {
501 init.signal.addEventListener('abort', () =>
502 {
503 reject(new DOMException('Aborted', 'AbortError'));
504 }, { once: true });
505 }
506 });
507 });
508
509 const controller = helper.bindImageSubtitleOverlay(player, videojs, {}, {
510 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
511 }, {
512 lookaheadSeconds: 1,
513 buildFrameRequest: ({ currentTime, streamIndex }) => ({
514 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
515 }),
516 });
517
518 await flushAsyncWork(window, 3);
519 expect(activeSignals.length).toBeGreaterThan(0);
520
521 controller.detach();
522 await flushAsyncWork(window, 2);
523
524 expect(activeSignals.every(signal => signal && signal.aborted)).toBe(true);
525
526 window.close();
527 });
528
529 test('logs current subtitle request lifecycle events and flushes them on detach', async () =>
530 {
531 const window = createWindow();
532 const helper = loadSharedVideoPlayer(window);
533 const { player, videojs } = buildPlayerHarness(window);
534 const sentBatches = [];
535
536 window.fetch = jest.fn(async () =>
537 {
538 return new Response('png-data', {
539 status: 200,
540 headers: {
541 'Content-Type': 'image/png',
542 'X-Subtitle-Frame-Status': 'ok',
543 'X-Subtitle-Request-Received-At-Ms': '1000',
544 'X-Subtitle-Response-Sent-At-Ms': '1012',
545 'X-Subtitle-Frame-Start-Time': '1.5',
546 'X-Subtitle-Frame-End-Time': '3.2',
547 'X-Subtitle-Frame-Width': '320',
548 'X-Subtitle-Frame-Height': '180',
549 'X-Subtitle-Frame-Canvas-Width': '640',
550 'X-Subtitle-Frame-Canvas-Height': '360',
551 },
552 });
553 });
554
555 const controller = helper.bindImageSubtitleOverlay(player, videojs, {}, {
556 sessionId: 'sess-1',
557 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
558 }, {
559 lookaheadSeconds: 0,
560 sendSubtitleLogBatch: (entries) =>
561 {
562 sentBatches.push(entries);
563 return Promise.resolve();
564 },
565 buildFrameRequest: ({ currentTime, streamIndex }) => ({
566 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
567 }),
568 });
569
570 await flushAsyncWork(window, 8);
571 controller.detach();
572 await flushAsyncWork(window, 4);
573
574 const flattened = sentBatches.flat();
575 expect(flattened.map((entry) => entry.eventType)).toEqual(expect.arrayContaining([
576 'subtitle_png_requested',
577 'subtitle_png_sent',
578 'subtitle_png_received',
579 ]));
580
581 window.close();
582 });
583
584 test('logs prefetch subtitle lifecycle events', async () =>
585 {
586 const window = createWindow();
587 const helper = loadSharedVideoPlayer(window);
588 const { player, videojs } = buildPlayerHarness(window);
589 const sentBatches = [];
590
591 window.fetch = jest.fn(async () =>
592 {
593 return new Response(null, {
594 status: 204,
595 headers: {
596 'X-Subtitle-Frame-Status': 'none',
597 'X-Subtitle-Request-Received-At-Ms': '1000',
598 'X-Subtitle-Response-Sent-At-Ms': '1010',
599 'X-Subtitle-Frame-Start-Time': '2',
600 'X-Subtitle-Frame-End-Time': '3',
601 },
602 });
603 });
604
605 const controller = helper.bindImageSubtitleOverlay(player, videojs, {}, {
606 sessionId: 'sess-1',
607 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
608 }, {
609 lookaheadSeconds: 1,
610 sendSubtitleLogBatch: (entries) =>
611 {
612 sentBatches.push(entries);
613 return Promise.resolve();
614 },
615 buildFrameRequest: ({ currentTime, streamIndex }) => ({
616 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
617 }),
618 });
619
620 await flushAsyncWork(window, 8);
621 controller.detach();
622 await flushAsyncWork(window, 4);
623
624 const flattened = sentBatches.flat();
625 const prefetchEvents = flattened.filter((entry) => entry.requestKind === 'prefetch').map((entry) => entry.eventType);
626 expect(prefetchEvents).toEqual(expect.arrayContaining([
627 'subtitle_png_requested',
628 'subtitle_png_sent',
629 'subtitle_png_not_available',
630 ]));
631
632 window.close();
633 });
634
635 test('cache-only current mode avoids direct current subtitle fetch requests', async () =>
636 {
637 const window = createWindow();
638 const helper = loadSharedVideoPlayer(window);
639 const { player, videojs } = buildPlayerHarness(window);
640 const sentBatches = [];
641
642 player.setCurrentTime(8);
643 window.fetch = jest.fn(async () =>
644 {
645 return new Response(null, {
646 status: 204,
647 headers: {
648 'X-Subtitle-Frame-Status': 'none',
649 'X-Subtitle-Request-Received-At-Ms': '1000',
650 'X-Subtitle-Response-Sent-At-Ms': '1010',
651 },
652 });
653 });
654
655 const controller = helper.bindImageSubtitleOverlay(player, videojs, {}, {
656 sessionId: 'sess-1',
657 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
658 }, {
659 currentFetchEnabled: false,
660 cacheMissFallbackEnabled: false,
661 lookaheadSeconds: 0,
662 sendSubtitleLogBatch: (entries) =>
663 {
664 sentBatches.push(entries);
665 return Promise.resolve();
666 },
667 buildFrameRequest: ({ currentTime, streamIndex }) => ({
668 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
669 }),
670 });
671
672 await flushAsyncWork(window, 8);
673 controller.detach();
674 await flushAsyncWork(window, 4);
675
676 const flattened = sentBatches.flat();
677 expect(flattened.length).toBeGreaterThan(0);
678 const requestKinds = new Set(flattened.map((entry) => entry.requestKind).filter(Boolean));
679 expect(requestKinds.has('prefetch')).toBe(true);
680 expect(requestKinds.has('current')).toBe(false);
681
682 window.close();
683 });
684
685 test('cache-only mode falls back to throttled current fetch on cache miss', async () =>
686 {
687 const window = createWindow();
688 const helper = loadSharedVideoPlayer(window);
689 const { player, videojs } = buildPlayerHarness(window);
690
691 let requestCount = 0;
692 window.fetch = jest.fn(async () =>
693 {
694 requestCount += 1;
695 if (requestCount === 1)
696 {
697 return new Response(new Uint8Array([137, 80, 78, 71]), {
698 status: 200,
699 headers: {
700 'Content-Type': 'image/png',
701 'X-Subtitle-Frame-Start-Time': '2.00',
702 'X-Subtitle-Frame-End-Time': '2.50',
703 'X-Subtitle-Frame-Width': '600',
704 'X-Subtitle-Frame-Height': '72',
705 'X-Subtitle-Frame-Canvas-Width': '1920',
706 'X-Subtitle-Frame-Canvas-Height': '1080',
707 },
708 });
709 }
710
711 return new Response(null, {
712 status: 204,
713 headers: { 'X-Subtitle-Frame-Status': 'none' },
714 });
715 });
716
717 player.setCurrentTime(2.2);
718
719 helper.bindImageSubtitleOverlay(player, videojs, {}, {
720 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
721 }, {
722 currentFetchEnabled: false,
723 cacheMissFallbackIntervalMs: 2000,
724 lookaheadSeconds: 0,
725 initialPrefetchSeconds: 0,
726 buildFrameRequest: ({ currentTime, streamIndex }) => ({
727 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
728 }),
729 });
730
731 await flushAsyncWork(window, 10);
732
733 const overlay = player.el().querySelector('.video-subtitle-overlay');
734 const overlayImg = overlay && overlay.querySelector('img');
735 expect(window.fetch).toHaveBeenCalled();
736 expect(overlay.style.display).toBe('block');
737 expect(overlayImg.getAttribute('src')).toBe('blob:subtitle');
738
739 window.close();
740 });
741
742 test('cache-miss fallback does not reset prefetch progress on repeated triggers', async () =>
743 {
744 const window = createWindow();
745 const helper = loadSharedVideoPlayer(window);
746 const { player, videojs } = buildPlayerHarness(window);
747
748 let nowMs = 1000;
749 const realNow = window.Date.now;
750 window.Date.now = () => nowMs;
751
752 let abortedCount = 0;
753 window.fetch = jest.fn((url, init = {}) =>
754 {
755 return new Promise((resolve, reject) =>
756 {
757 const signal = init && init.signal;
758 const onAbort = () =>
759 {
760 abortedCount += 1;
761 const err = new Error('aborted');
762 err.name = 'AbortError';
763 reject(err);
764 };
765
766 if (signal && typeof signal.addEventListener === 'function')
767 {
768 if (signal.aborted) return onAbort();
769 signal.addEventListener('abort', onAbort, { once: true });
770 }
771
772 window.setTimeout(() =>
773 {
774 if (signal && signal.aborted) return;
775 resolve(new Response(null, {
776 status: 204,
777 headers: { 'X-Subtitle-Frame-Status': 'none' },
778 }));
779 }, 80);
780 });
781 });
782
783 const controller = helper.bindImageSubtitleOverlay(player, videojs, {}, {
784 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
785 }, {
786 currentFetchEnabled: false,
787 cacheMissFallbackIntervalMs: 20,
788 lookaheadSeconds: 2,
789 initialPrefetchSeconds: 0,
790 buildFrameRequest: ({ currentTime, streamIndex }) => ({
791 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
792 }),
793 });
794
795 await flushAsyncWork(window, 4);
796
797 player.setCurrentTime(5);
798 player.trigger('timeupdate');
799 nowMs += 40;
800 player.setCurrentTime(5.5);
801 player.trigger('timeupdate');
802 nowMs += 40;
803 player.setCurrentTime(6);
804 player.trigger('timeupdate');
805
806 await flushAsyncWork(window, 12);
807 expect(abortedCount).toBe(0);
808
809 window.Date.now = realNow;
810 controller.detach();
811 window.close();
812 });
813
814 test('cache-only mode performs initial warmup prefetch window on load', async () =>
815 {
816 const window = createWindow();
817 const helper = loadSharedVideoPlayer(window);
818 const { player, videojs } = buildPlayerHarness(window);
819 const requestedTimes = [];
820
821 window.fetch = jest.fn(async (url) =>
822 {
823 const parsed = new URL(url, 'http://localhost/');
824 requestedTimes.push(Number(parsed.searchParams.get('timeSeconds')));
825 return new Response(null, {
826 status: 204,
827 headers: {
828 'X-Subtitle-Frame-Status': 'none',
829 'X-Subtitle-Request-Received-At-Ms': '1000',
830 'X-Subtitle-Response-Sent-At-Ms': '1010',
831 },
832 });
833 });
834
835 const controller = helper.bindImageSubtitleOverlay(player, videojs, {}, {
836 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
837 }, {
838 currentFetchEnabled: false,
839 lookaheadSeconds: 0,
840 initialPrefetchSeconds: 2,
841 buildFrameRequest: ({ currentTime, streamIndex }) => ({
842 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
843 }),
844 });
845
846 await flushAsyncWork(window, 12);
847
848 expect(requestedTimes).toEqual(expect.arrayContaining([0, 0.5, 1, 1.5, 2]));
849
850 controller.detach();
851 await flushAsyncWork(window, 2);
852 window.close();
853 });
854
855 test('renders requested and received subtitle markers on the seek bar', async () =>
856 {
857 const window = createWindow();
858 const helper = loadSharedVideoPlayer(window);
859 const { player, videojs } = buildPlayerHarness(window);
860
861 window.fetch = jest.fn(async () =>
862 {
863 return new Response('png-data', {
864 status: 200,
865 headers: {
866 'Content-Type': 'image/png',
867 'X-Subtitle-Frame-Status': 'ok',
868 'X-Subtitle-Request-Received-At-Ms': '1000',
869 'X-Subtitle-Response-Sent-At-Ms': '1012',
870 'X-Subtitle-Frame-Start-Time': '2.5',
871 'X-Subtitle-Frame-End-Time': '3.5',
872 'X-Subtitle-Frame-Width': '320',
873 'X-Subtitle-Frame-Height': '180',
874 'X-Subtitle-Frame-Canvas-Width': '640',
875 'X-Subtitle-Frame-Canvas-Height': '360',
876 },
877 });
878 });
879
880 player.duration(10);
881 const controller = helper.bindImageSubtitleOverlay(player, videojs, {}, {
882 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
883 }, {
884 lookaheadSeconds: 0,
885 buildFrameRequest: ({ currentTime, streamIndex }) => ({
886 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
887 }),
888 });
889
890 await flushAsyncWork(window, 8);
891
892 const requestedMarker = player.el().querySelector('.vjs-image-subtitle-seek-marker-right');
893 const receivedMarker = player.el().querySelector('.vjs-image-subtitle-seek-marker-left');
894 expect(requestedMarker).toBeTruthy();
895 expect(receivedMarker).toBeTruthy();
896 expect(requestedMarker.style.display).toBe('block');
897 expect(receivedMarker.style.display).toBe('block');
898 expect(requestedMarker.style.left).toBe('100.0000%');
899 expect(receivedMarker.style.left).toBe('25.0000%');
900 expect(requestedMarker.textContent).toBe(']');
901 expect(receivedMarker.textContent).toBe('[');
902
903 controller.detach();
904 await new Promise((resolve) => window.setTimeout(resolve, 300));
905 await flushAsyncWork(window, 2);
906
907 window.close();
908 });
909
910 test('advances both seek markers when subtitle request returns 204 without frame timing headers', async () =>
911 {
912 const window = createWindow();
913 const helper = loadSharedVideoPlayer(window);
914 const { player, videojs } = buildPlayerHarness(window);
915
916 player.duration(10);
917 player.setCurrentTime(4);
918 window.fetch = jest.fn(async () =>
919 {
920 return new Response(null, {
921 status: 204,
922 headers: {
923 'X-Subtitle-Frame-Status': 'none',
924 'X-Subtitle-Request-Received-At-Ms': '1000',
925 'X-Subtitle-Response-Sent-At-Ms': '1010',
926 },
927 });
928 });
929
930 const controller = helper.bindImageSubtitleOverlay(player, videojs, {}, {
931 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
932 }, {
933 lookaheadSeconds: 0,
934 buildFrameRequest: ({ currentTime, streamIndex }) => ({
935 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
936 }),
937 });
938
939 await flushAsyncWork(window, 8);
940
941 const requestedMarker = player.el().querySelector('.vjs-image-subtitle-seek-marker-right');
942 const receivedMarker = player.el().querySelector('.vjs-image-subtitle-seek-marker-left');
943 expect(requestedMarker).toBeTruthy();
944 expect(receivedMarker).toBeTruthy();
945 expect(requestedMarker.style.display).toBe('block');
946 expect(receivedMarker.style.display).toBe('block');
947 expect(requestedMarker.style.left).toBe('100.0000%');
948 expect(receivedMarker.style.left).toBe('100.0000%');
949 expect(requestedMarker.textContent).toBe(']');
950 expect(receivedMarker.textContent).toBe('[');
951
952 controller.detach();
953 await flushAsyncWork(window, 2);
954 window.close();
955 });
956
957 test('keeps existing marker positions while the next request is still in flight', async () =>
958 {
959 const window = createWindow();
960 const helper = loadSharedVideoPlayer(window);
961 const { player, videojs } = buildPlayerHarness(window);
962 let pendingResolve = null;
963
964 player.duration(10);
965 window.fetch = jest.fn((url) =>
966 {
967 const parsed = new URL(url, 'http://localhost/');
968 const timeSeconds = Number(parsed.searchParams.get('timeSeconds'));
969
970 if (timeSeconds === 0)
971 {
972 return Promise.resolve(new Response('png-data', {
973 status: 200,
974 headers: {
975 'Content-Type': 'image/png',
976 'X-Subtitle-Frame-Status': 'ok',
977 'X-Subtitle-Frame-Start-Time': '2',
978 'X-Subtitle-Frame-End-Time': '3',
979 'X-Subtitle-Frame-Width': '320',
980 'X-Subtitle-Frame-Height': '180',
981 'X-Subtitle-Frame-Canvas-Width': '640',
982 'X-Subtitle-Frame-Canvas-Height': '360',
983 },
984 }));
985 }
986
987 return new Promise((resolve) =>
988 {
989 pendingResolve = resolve;
990 });
991 });
992
993 const controller = helper.bindImageSubtitleOverlay(player, videojs, {}, {
994 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
995 }, {
996 lookaheadSeconds: 0,
997 buildFrameRequest: ({ currentTime, streamIndex }) => ({
998 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
999 }),
1000 });
1001
1002 await flushAsyncWork(window, 8);
1003
1004 const requestedMarker = player.el().querySelector('.vjs-image-subtitle-seek-marker-right');
1005 const receivedMarker = player.el().querySelector('.vjs-image-subtitle-seek-marker-left');
1006 expect(requestedMarker).toBeTruthy();
1007 expect(receivedMarker).toBeTruthy();
1008 expect(requestedMarker.style.left).toBe('0.0000%');
1009 expect(receivedMarker.style.left).toBe('20.0000%');
1010
1011 player.setCurrentTime(1.5);
1012 player.trigger('timeupdate');
1013 await flushAsyncWork(window, 2);
1014
1015 expect(requestedMarker.style.left).toBe('0.0000%');
1016 expect(receivedMarker.style.left).toBe('20.0000%');
1017
1018 pendingResolve(new Response(null, {
1019 status: 204,
1020 headers: {
1021 'X-Subtitle-Frame-Status': 'none',
1022 },
1023 }));
1024
1025 await flushAsyncWork(window, 8);
1026 expect(requestedMarker.style.display).toBe('block');
1027 expect(receivedMarker.style.display).toBe('block');
1028 expect(requestedMarker.style.left).toBe('15.0000%');
1029 expect(receivedMarker.style.left).toBe('20.0000%');
1030
1031 controller.detach();
1032 await flushAsyncWork(window, 2);
1033 window.close();
1034 });
1035
1036 test('keeps marker positions forward-only when later responses resolve with earlier times', async () =>
1037 {
1038 const window = createWindow();
1039 const helper = loadSharedVideoPlayer(window);
1040 const { player, videojs } = buildPlayerHarness(window);
1041 const requestedTimes = [];
1042
1043 player.duration(12);
1044 window.fetch = jest.fn(async (url) =>
1045 {
1046 const parsed = new URL(url, 'http://localhost/');
1047 const timeSeconds = Number(parsed.searchParams.get('timeSeconds'));
1048 requestedTimes.push(timeSeconds);
1049
1050 if (requestedTimes.length === 1)
1051 {
1052 return new Response('png-data', {
1053 status: 200,
1054 headers: {
1055 'Content-Type': 'image/png',
1056 'X-Subtitle-Frame-Status': 'ok',
1057 'X-Subtitle-Frame-Start-Time': '4',
1058 'X-Subtitle-Frame-End-Time': '5',
1059 'X-Subtitle-Frame-Width': '320',
1060 'X-Subtitle-Frame-Height': '180',
1061 'X-Subtitle-Frame-Canvas-Width': '640',
1062 'X-Subtitle-Frame-Canvas-Height': '360',
1063 },
1064 });
1065 }
1066
1067 return new Response('png-data', {
1068 status: 200,
1069 headers: {
1070 'Content-Type': 'image/png',
1071 'X-Subtitle-Frame-Status': 'ok',
1072 'X-Subtitle-Frame-Start-Time': '2',
1073 'X-Subtitle-Frame-End-Time': '3',
1074 'X-Subtitle-Frame-Width': '320',
1075 'X-Subtitle-Frame-Height': '180',
1076 'X-Subtitle-Frame-Canvas-Width': '640',
1077 'X-Subtitle-Frame-Canvas-Height': '360',
1078 },
1079 });
1080 });
1081
1082 const controller = helper.bindImageSubtitleOverlay(player, videojs, {}, {
1083 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
1084 }, {
1085 lookaheadSeconds: 0,
1086 buildFrameRequest: ({ currentTime, streamIndex }) => ({
1087 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
1088 }),
1089 });
1090
1091 await flushAsyncWork(window, 8);
1092
1093 const requestedMarker = player.el().querySelector('.vjs-image-subtitle-seek-marker-right');
1094 const receivedMarker = player.el().querySelector('.vjs-image-subtitle-seek-marker-left');
1095 expect(requestedMarker).toBeTruthy();
1096 expect(receivedMarker).toBeTruthy();
1097 expect(requestedMarker.style.left).toBe('100.0000%');
1098 expect(receivedMarker.style.left).toBe('33.3333%');
1099
1100 player.setCurrentTime(1.5);
1101 player.trigger('timeupdate');
1102 await flushAsyncWork(window, 8);
1103
1104 // Second response reports an older start time, but markers stay monotonic.
1105 expect(requestedMarker.style.left).toBe('100.0000%');
1106 expect(receivedMarker.style.left).toBe('33.3333%');
1107
1108 controller.detach();
1109 await flushAsyncWork(window, 2);
1110 window.close();
1111 });
1112
1113 test('continues current subtitle refreshes after a force-seek aborts the in-flight request', async () =>
1114 {
1115 const window = createWindow();
1116 const helper = loadSharedVideoPlayer(window);
1117 const { player, videojs } = buildPlayerHarness(window);
1118 const requestedTimes = [];
1119
1120 window.fetch = jest.fn((url, init = {}) =>
1121 {
1122 const parsed = new URL(url, 'http://localhost/');
1123 const timeSeconds = Number(parsed.searchParams.get('timeSeconds'));
1124 requestedTimes.push(timeSeconds);
1125
1126 if (requestedTimes.length === 1)
1127 {
1128 return new Promise((resolve, reject) =>
1129 {
1130 if (init.signal && typeof init.signal.addEventListener === 'function')
1131 {
1132 init.signal.addEventListener('abort', () =>
1133 {
1134 reject(new window.DOMException('Aborted', 'AbortError'));
1135 }, { once: true });
1136 }
1137 });
1138 }
1139
1140 return Promise.resolve(new Response(null, {
1141 status: 204,
1142 headers: {
1143 'X-Subtitle-Frame-Status': 'none',
1144 },
1145 }));
1146 });
1147
1148 const controller = helper.bindImageSubtitleOverlay(player, videojs, {}, {
1149 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
1150 }, {
1151 lookaheadSeconds: 0,
1152 currentRequestTimeoutMs: 300,
1153 logToConsole: false,
1154 buildFrameRequest: ({ currentTime, streamIndex }) => ({
1155 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
1156 }),
1157 });
1158
1159 await flushAsyncWork(window, 4);
1160 const afterInitialLoadCalls = window.fetch.mock.calls.length;
1161 expect(afterInitialLoadCalls).toBeGreaterThan(0);
1162
1163 player.setCurrentTime(5);
1164 player.trigger('seeking');
1165 await flushAsyncWork(window, 20);
1166
1167 expect(window.fetch.mock.calls.length).toBeGreaterThanOrEqual(2);
1168 expect(requestedTimes).toEqual(expect.arrayContaining([0, 5]));
1169
1170 controller.detach();
1171 await flushAsyncWork(window, 2);
1172 window.close();
1173 });
1174
1175 test('recovers when a current subtitle request hangs and times out', async () =>
1176 {
1177 const window = createWindow();
1178 const helper = loadSharedVideoPlayer(window);
1179 const { player, videojs } = buildPlayerHarness(window);
1180 const requestedTimes = [];
1181
1182 window.fetch = jest.fn((url, init = {}) =>
1183 {
1184 const parsed = new URL(url, 'http://localhost/');
1185 const timeSeconds = Number(parsed.searchParams.get('timeSeconds'));
1186 requestedTimes.push(timeSeconds);
1187
1188 if (requestedTimes.length === 1)
1189 {
1190 return new Promise((resolve, reject) =>
1191 {
1192 if (init.signal && typeof init.signal.addEventListener === 'function')
1193 {
1194 init.signal.addEventListener('abort', () =>
1195 {
1196 reject(new window.DOMException('Aborted', 'AbortError'));
1197 }, { once: true });
1198 }
1199 });
1200 }
1201
1202 return Promise.resolve(new Response(null, {
1203 status: 204,
1204 headers: { 'X-Subtitle-Frame-Status': 'none' },
1205 }));
1206 });
1207
1208 const controller = helper.bindImageSubtitleOverlay(player, videojs, {}, {
1209 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
1210 }, {
1211 lookaheadSeconds: 0,
1212 currentRequestTimeoutMs: 250,
1213 logToConsole: false,
1214 buildFrameRequest: ({ currentTime, streamIndex }) => ({
1215 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
1216 }),
1217 });
1218
1219 await flushAsyncWork(window, 3);
1220
1221 player.setCurrentTime(1.5);
1222 player.trigger('timeupdate');
1223
1224 await new Promise((resolve) => window.setTimeout(resolve, 320));
1225 player.trigger('timeupdate');
1226 await new Promise((resolve) => window.setTimeout(resolve, 220));
1227 await flushAsyncWork(window, 20);
1228
1229 expect(window.fetch.mock.calls.length).toBeGreaterThanOrEqual(2);
1230 expect(requestedTimes).toEqual(expect.arrayContaining([0, 1.5]));
1231
1232 controller.detach();
1233 await new Promise((resolve) => window.setTimeout(resolve, 200));
1234 await flushAsyncWork(window, 20);
1235 window.close();
1236 });
1237
1238 test('reuses cached subtitle frames after rewinding when server no longer has older frames', async () =>
1239 {
1240 const window = createWindow();
1241 const helper = loadSharedVideoPlayer(window);
1242 const { player, videojs } = buildPlayerHarness(window);
1243
1244 player.duration(10);
1245 player.setCurrentTime(2);
1246 window.fetch = jest.fn(async (url) =>
1247 {
1248 const parsed = new URL(url, 'http://localhost/');
1249 const timeSeconds = Number(parsed.searchParams.get('timeSeconds'));
1250
1251 if (Math.abs(timeSeconds - 2) < 1e-6)
1252 {
1253 return new Response('png-data', {
1254 status: 200,
1255 headers: {
1256 'Content-Type': 'image/png',
1257 'X-Subtitle-Frame-Status': 'ok',
1258 'X-Subtitle-Frame-Start-Time': '2',
1259 'X-Subtitle-Frame-End-Time': '3',
1260 'X-Subtitle-Frame-Width': '320',
1261 'X-Subtitle-Frame-Height': '180',
1262 'X-Subtitle-Frame-Canvas-Width': '640',
1263 'X-Subtitle-Frame-Canvas-Height': '360',
1264 },
1265 });
1266 }
1267
1268 return new Response(null, {
1269 status: 204,
1270 headers: {
1271 'X-Subtitle-Frame-Status': 'none',
1272 },
1273 });
1274 });
1275
1276 const controller = helper.bindImageSubtitleOverlay(player, videojs, {}, {
1277 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
1278 }, {
1279 lookaheadSeconds: 0,
1280 buildFrameRequest: ({ currentTime, streamIndex }) => ({
1281 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
1282 }),
1283 });
1284
1285 await flushAsyncWork(window, 8);
1286 const afterInitialLoadCalls = window.fetch.mock.calls.length;
1287 expect(afterInitialLoadCalls).toBeGreaterThan(0);
1288
1289 player.setCurrentTime(4);
1290 player.trigger('timeupdate');
1291 await flushAsyncWork(window, 8);
1292 const afterForwardSeekCalls = window.fetch.mock.calls.length;
1293 expect(afterForwardSeekCalls).toBeGreaterThanOrEqual(afterInitialLoadCalls);
1294
1295 const overlay = player.el().querySelector('.video-subtitle-overlay');
1296 expect(overlay).toBeTruthy();
1297 expect(overlay.style.display).toBe('none');
1298
1299 player.setCurrentTime(2.5);
1300 player.trigger('timeupdate');
1301 await flushAsyncWork(window, 8);
1302
1303 expect(window.fetch.mock.calls.length).toBe(afterForwardSeekCalls);
1304 expect(overlay.style.display).toBe('block');
1305
1306 controller.detach();
1307 await flushAsyncWork(window, 2);
1308 window.close();
1309 });
1310
1311 test('registers stream cache service worker once when supported', async () =>
1312 {
1313 const window = createWindow();
1314 const helper = loadSharedVideoPlayer(window);
1315 const register = jest.fn(async () => ({}));
1316 window.navigator.serviceWorker = { register };
1317
1318 const first = await helper.enableVideoStreamClientCache();
1319 const second = await helper.enableVideoStreamClientCache();
1320
1321 expect(first).toBe(true);
1322 expect(second).toBe(true);
1323 expect(register).toHaveBeenCalledTimes(1);
1324 expect(register).toHaveBeenCalledWith('/stream-cache-sw.js', {
1325 scope: '/',
1326 updateViaCache: 'none',
1327 });
1328
1329 window.close();
1330 });
1331
1332 test('stream-ahead prefetch follows playlists and fetches segment assets', async () =>
1333 {
1334 const window = createWindow();
1335 const helper = loadSharedVideoPlayer(window);
1336 const requestedUrls = [];
1337
1338 window.fetch = jest.fn(async (input) =>
1339 {
1340 const url = String(input && input.url ? input.url : input);
1341 requestedUrls.push(url);
1342
1343 if (url === 'http://localhost/master.m3u8')
1344 {
1345 return new Response('#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=100000\nstream_0.m3u8\n#EXT-X-ENDLIST\n', {
1346 status: 200,
1347 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1348 });
1349 }
1350
1351 if (url === 'http://localhost/stream_0.m3u8')
1352 {
1353 return new Response('#EXTM3U\n#EXTINF:4,\nseg0.ts\n#EXTINF:4,\nseg1.ts\n#EXT-X-ENDLIST\n', {
1354 status: 200,
1355 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1356 });
1357 }
1358
1359 if (url === 'http://localhost/seg0.ts' || url === 'http://localhost/seg1.ts')
1360 {
1361 return new Response(new Uint8Array([1, 2, 3, 4]), {
1362 status: 200,
1363 headers: { 'Content-Type': 'video/mp2t' },
1364 });
1365 }
1366
1367 return new Response(null, { status: 404 });
1368 });
1369
1370 const controller = helper.bindStreamAheadPrefetch({
1371 playlistUrl: 'http://localhost/master.m3u8',
1372 pollIntervalMs: 0,
1373 credentials: 'same-origin',
1374 });
1375
1376 expect(controller).toBeTruthy();
1377 await controller.done();
1378
1379 expect(requestedUrls).toEqual(expect.arrayContaining([
1380 'http://localhost/master.m3u8',
1381 'http://localhost/stream_0.m3u8',
1382 'http://localhost/seg0.ts',
1383 'http://localhost/seg1.ts',
1384 ]));
1385
1386 controller.stop();
1387 window.close();
1388 });
1389
1390 test('stream-ahead prefetch reports cached-through progress for fetched segments', async () =>
1391 {
1392 const window = createWindow();
1393 const helper = loadSharedVideoPlayer(window);
1394 const progressSamples = [];
1395
1396 window.fetch = jest.fn(async (input) =>
1397 {
1398 const url = String(input && input.url ? input.url : input);
1399
1400 if (url === 'http://localhost/master.m3u8')
1401 {
1402 return new Response('#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=100000\nstream_0.m3u8\n#EXT-X-ENDLIST\n', {
1403 status: 200,
1404 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1405 });
1406 }
1407
1408 if (url === 'http://localhost/stream_0.m3u8')
1409 {
1410 return new Response('#EXTM3U\n#EXTINF:4,\nseg0.ts\n#EXTINF:4,\nseg1.ts\n#EXT-X-ENDLIST\n', {
1411 status: 200,
1412 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1413 });
1414 }
1415
1416 if (url === 'http://localhost/seg0.ts' || url === 'http://localhost/seg1.ts')
1417 {
1418 return new Response(new Uint8Array([1, 2, 3, 4]), {
1419 status: 200,
1420 headers: { 'Content-Type': 'video/mp2t' },
1421 });
1422 }
1423
1424 return new Response(null, { status: 404 });
1425 });
1426
1427 const controller = helper.bindStreamAheadPrefetch({
1428 playlistUrl: 'http://localhost/master.m3u8',
1429 pollIntervalMs: 0,
1430 credentials: 'same-origin',
1431 });
1432
1433 expect(controller).toBeTruthy();
1434 const unsubscribe = controller.subscribe((status) =>
1435 {
1436 progressSamples.push(status && status.cachedThroughSeconds);
1437 });
1438
1439 await controller.done();
1440 unsubscribe();
1441
1442 expect(progressSamples.some((value) => Number.isFinite(value) && value >= 8)).toBe(true);
1443
1444 controller.stop();
1445 window.close();
1446 });
1447
1448 test('stream-ahead prefetch infers cached-through progress from segment filenames', async () =>
1449 {
1450 const window = createWindow();
1451 const helper = loadSharedVideoPlayer(window);
1452 const progressSamples = [];
1453
1454 window.fetch = jest.fn(async (input) =>
1455 {
1456 const url = String(input && input.url ? input.url : input);
1457
1458 if (url === 'http://localhost/master.m3u8')
1459 {
1460 return new Response('#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=100000\nstream_0.m3u8\n#EXT-X-ENDLIST\n', {
1461 status: 200,
1462 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1463 });
1464 }
1465
1466 if (url === 'http://localhost/stream_0.m3u8')
1467 {
1468 return new Response('#EXTM3U\nstream_0_segment_000000.ts\nstream_0_segment_000001.ts\n#EXT-X-ENDLIST\n', {
1469 status: 200,
1470 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1471 });
1472 }
1473
1474 if (url === 'http://localhost/stream_0_segment_000000.ts' || url === 'http://localhost/stream_0_segment_000001.ts')
1475 {
1476 return new Response(new Uint8Array([1, 2, 3, 4]), {
1477 status: 200,
1478 headers: { 'Content-Type': 'video/mp2t' },
1479 });
1480 }
1481
1482 return new Response(null, { status: 404 });
1483 });
1484
1485 const controller = helper.bindStreamAheadPrefetch({
1486 playlistUrl: 'http://localhost/master.m3u8',
1487 pollIntervalMs: 0,
1488 credentials: 'same-origin',
1489 });
1490
1491 expect(controller).toBeTruthy();
1492 const unsubscribe = controller.subscribe((status) =>
1493 {
1494 progressSamples.push(status && status.cachedThroughSeconds);
1495 });
1496
1497 await controller.done();
1498 unsubscribe();
1499
1500 expect(progressSamples.some((value) => Number.isFinite(value) && value >= 8)).toBe(true);
1501
1502 controller.stop();
1503 window.close();
1504 });
1505
1506 test('stream-ahead prefetch infers cached-through progress for m4s segment filenames', async () =>
1507 {
1508 const window = createWindow();
1509 const helper = loadSharedVideoPlayer(window);
1510 const progressSamples = [];
1511
1512 window.fetch = jest.fn(async (input) =>
1513 {
1514 const url = String(input && input.url ? input.url : input);
1515
1516 if (url === 'http://localhost/master.m3u8')
1517 {
1518 return new Response('#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=100000\nstream_0.m3u8\n#EXT-X-ENDLIST\n', {
1519 status: 200,
1520 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1521 });
1522 }
1523
1524 if (url === 'http://localhost/stream_0.m3u8')
1525 {
1526 return new Response('#EXTM3U\nstream_0_segment_000000.m4s\nstream_0_segment_000001.m4s\n#EXT-X-ENDLIST\n', {
1527 status: 200,
1528 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1529 });
1530 }
1531
1532 if (url === 'http://localhost/stream_0_segment_000000.m4s' || url === 'http://localhost/stream_0_segment_000001.m4s')
1533 {
1534 return new Response(new Uint8Array([1, 2, 3, 4]), {
1535 status: 200,
1536 headers: { 'Content-Type': 'video/mp4' },
1537 });
1538 }
1539
1540 return new Response(null, { status: 404 });
1541 });
1542
1543 const controller = helper.bindStreamAheadPrefetch({
1544 playlistUrl: 'http://localhost/master.m3u8',
1545 pollIntervalMs: 0,
1546 credentials: 'same-origin',
1547 });
1548
1549 expect(controller).toBeTruthy();
1550 const unsubscribe = controller.subscribe((status) =>
1551 {
1552 progressSamples.push(status && status.cachedThroughSeconds);
1553 });
1554
1555 await controller.done();
1556 unsubscribe();
1557
1558 expect(progressSamples.some((value) => Number.isFinite(value) && value >= 8)).toBe(true);
1559
1560 controller.stop();
1561 window.close();
1562 });
1563
1564 test('stream-ahead prefetch reports ratio progress from fetched sections when timing is unknown', async () =>
1565 {
1566 const window = createWindow();
1567 const helper = loadSharedVideoPlayer(window);
1568 const statusSamples = [];
1569
1570 window.fetch = jest.fn(async (input) =>
1571 {
1572 const url = String(input && input.url ? input.url : input);
1573
1574 if (url === 'http://localhost/master.m3u8')
1575 {
1576 return new Response('#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=100000\nstream_0.m3u8\n#EXT-X-ENDLIST\n', {
1577 status: 200,
1578 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1579 });
1580 }
1581
1582 if (url === 'http://localhost/stream_0.m3u8')
1583 {
1584 return new Response('#EXTM3U\nchunk-alpha.bin\nchunk-beta.bin\n#EXT-X-ENDLIST\n', {
1585 status: 200,
1586 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1587 });
1588 }
1589
1590 if (url === 'http://localhost/chunk-alpha.bin' || url === 'http://localhost/chunk-beta.bin')
1591 {
1592 return new Response(new Uint8Array([1, 2, 3, 4]), {
1593 status: 200,
1594 headers: { 'Content-Type': 'application/octet-stream' },
1595 });
1596 }
1597
1598 return new Response(null, { status: 404 });
1599 });
1600
1601 const controller = helper.bindStreamAheadPrefetch({
1602 playlistUrl: 'http://localhost/master.m3u8',
1603 pollIntervalMs: 0,
1604 credentials: 'same-origin',
1605 });
1606
1607 expect(controller).toBeTruthy();
1608 const unsubscribe = controller.subscribe((status) =>
1609 {
1610 statusSamples.push(status || {});
1611 });
1612
1613 await controller.done();
1614 unsubscribe();
1615
1616 const finalStatus = statusSamples[statusSamples.length - 1] || {};
1617 expect(finalStatus.totalSegmentCount).toBe(2);
1618 expect(finalStatus.fetchedSegmentCount).toBe(2);
1619 expect(finalStatus.cachedThroughRatio).toBe(1);
1620
1621 controller.stop();
1622 window.close();
1623 });
1624
1625 test('clears cached stream assets for a finished playlist session', async () =>
1626 {
1627 const window = createWindow();
1628 const helper = loadSharedVideoPlayer(window);
1629 const requests = [
1630 new window.Request('http://localhost/api/files/video-stream/sess-a/master.m3u8'),
1631 new window.Request('http://localhost/api/files/video-stream/sess-a/stream_0_segment_000001.ts'),
1632 new window.Request('http://localhost/api/files/video-stream/sess-b/master.m3u8'),
1633 ];
1634 const deleteCalls = [];
1635 const cache = {
1636 keys: jest.fn(async () => requests),
1637 delete: jest.fn(async (request) =>
1638 {
1639 deleteCalls.push(request.url);
1640 return true;
1641 }),
1642 };
1643 window.caches = {
1644 open: jest.fn(async () => cache),
1645 };
1646
1647 await helper.clearVideoStreamClientCache('http://localhost/api/files/video-stream/sess-a/master.m3u8');
1648
1649 expect(window.caches.open).toHaveBeenCalledWith('filemanager-stream-cache-v1');
1650 expect(cache.keys).toHaveBeenCalledTimes(1);
1651 expect(deleteCalls).toEqual(expect.arrayContaining([
1652 'http://localhost/api/files/video-stream/sess-a/master.m3u8',
1653 'http://localhost/api/files/video-stream/sess-a/stream_0_segment_000001.ts',
1654 ]));
1655 expect(deleteCalls).not.toContain('http://localhost/api/files/video-stream/sess-b/master.m3u8');
1656
1657 window.close();
1658 });
1659});