BlueGit

timfa filemanager

Files

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

shared-video-player.test.js

da0df941 History
shared-video-player.test.js 49.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-only mode performs initial warmup prefetch window on load', async () =>
743 {
744 const window = createWindow();
745 const helper = loadSharedVideoPlayer(window);
746 const { player, videojs } = buildPlayerHarness(window);
747 const requestedTimes = [];
748
749 window.fetch = jest.fn(async (url) =>
750 {
751 const parsed = new URL(url, 'http://localhost/');
752 requestedTimes.push(Number(parsed.searchParams.get('timeSeconds')));
753 return new Response(null, {
754 status: 204,
755 headers: {
756 'X-Subtitle-Frame-Status': 'none',
757 'X-Subtitle-Request-Received-At-Ms': '1000',
758 'X-Subtitle-Response-Sent-At-Ms': '1010',
759 },
760 });
761 });
762
763 const controller = helper.bindImageSubtitleOverlay(player, videojs, {}, {
764 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
765 }, {
766 currentFetchEnabled: false,
767 lookaheadSeconds: 0,
768 initialPrefetchSeconds: 2,
769 buildFrameRequest: ({ currentTime, streamIndex }) => ({
770 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
771 }),
772 });
773
774 await flushAsyncWork(window, 12);
775
776 expect(requestedTimes).toEqual(expect.arrayContaining([0, 0.5, 1, 1.5, 2]));
777
778 controller.detach();
779 await flushAsyncWork(window, 2);
780 window.close();
781 });
782
783 test('renders requested and received subtitle markers on the seek bar', async () =>
784 {
785 const window = createWindow();
786 const helper = loadSharedVideoPlayer(window);
787 const { player, videojs } = buildPlayerHarness(window);
788
789 window.fetch = jest.fn(async () =>
790 {
791 return new Response('png-data', {
792 status: 200,
793 headers: {
794 'Content-Type': 'image/png',
795 'X-Subtitle-Frame-Status': 'ok',
796 'X-Subtitle-Request-Received-At-Ms': '1000',
797 'X-Subtitle-Response-Sent-At-Ms': '1012',
798 'X-Subtitle-Frame-Start-Time': '2.5',
799 'X-Subtitle-Frame-End-Time': '3.5',
800 'X-Subtitle-Frame-Width': '320',
801 'X-Subtitle-Frame-Height': '180',
802 'X-Subtitle-Frame-Canvas-Width': '640',
803 'X-Subtitle-Frame-Canvas-Height': '360',
804 },
805 });
806 });
807
808 player.duration(10);
809 const controller = helper.bindImageSubtitleOverlay(player, videojs, {}, {
810 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
811 }, {
812 lookaheadSeconds: 0,
813 buildFrameRequest: ({ currentTime, streamIndex }) => ({
814 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
815 }),
816 });
817
818 await flushAsyncWork(window, 8);
819
820 const requestedMarker = player.el().querySelector('.vjs-image-subtitle-seek-marker-right');
821 const receivedMarker = player.el().querySelector('.vjs-image-subtitle-seek-marker-left');
822 expect(requestedMarker).toBeTruthy();
823 expect(receivedMarker).toBeTruthy();
824 expect(requestedMarker.style.display).toBe('block');
825 expect(receivedMarker.style.display).toBe('block');
826 expect(requestedMarker.style.left).toBe('100.0000%');
827 expect(receivedMarker.style.left).toBe('25.0000%');
828 expect(requestedMarker.textContent).toBe(']');
829 expect(receivedMarker.textContent).toBe('[');
830
831 controller.detach();
832 await new Promise((resolve) => window.setTimeout(resolve, 300));
833 await flushAsyncWork(window, 2);
834
835 window.close();
836 });
837
838 test('advances both seek markers when subtitle request returns 204 without frame timing headers', async () =>
839 {
840 const window = createWindow();
841 const helper = loadSharedVideoPlayer(window);
842 const { player, videojs } = buildPlayerHarness(window);
843
844 player.duration(10);
845 player.setCurrentTime(4);
846 window.fetch = jest.fn(async () =>
847 {
848 return new Response(null, {
849 status: 204,
850 headers: {
851 'X-Subtitle-Frame-Status': 'none',
852 'X-Subtitle-Request-Received-At-Ms': '1000',
853 'X-Subtitle-Response-Sent-At-Ms': '1010',
854 },
855 });
856 });
857
858 const controller = helper.bindImageSubtitleOverlay(player, videojs, {}, {
859 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
860 }, {
861 lookaheadSeconds: 0,
862 buildFrameRequest: ({ currentTime, streamIndex }) => ({
863 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
864 }),
865 });
866
867 await flushAsyncWork(window, 8);
868
869 const requestedMarker = player.el().querySelector('.vjs-image-subtitle-seek-marker-right');
870 const receivedMarker = player.el().querySelector('.vjs-image-subtitle-seek-marker-left');
871 expect(requestedMarker).toBeTruthy();
872 expect(receivedMarker).toBeTruthy();
873 expect(requestedMarker.style.display).toBe('block');
874 expect(receivedMarker.style.display).toBe('block');
875 expect(requestedMarker.style.left).toBe('100.0000%');
876 expect(receivedMarker.style.left).toBe('100.0000%');
877 expect(requestedMarker.textContent).toBe(']');
878 expect(receivedMarker.textContent).toBe('[');
879
880 controller.detach();
881 await flushAsyncWork(window, 2);
882 window.close();
883 });
884
885 test('keeps existing marker positions while the next request is still in flight', async () =>
886 {
887 const window = createWindow();
888 const helper = loadSharedVideoPlayer(window);
889 const { player, videojs } = buildPlayerHarness(window);
890 let pendingResolve = null;
891
892 player.duration(10);
893 window.fetch = jest.fn((url) =>
894 {
895 const parsed = new URL(url, 'http://localhost/');
896 const timeSeconds = Number(parsed.searchParams.get('timeSeconds'));
897
898 if (timeSeconds === 0)
899 {
900 return Promise.resolve(new Response('png-data', {
901 status: 200,
902 headers: {
903 'Content-Type': 'image/png',
904 'X-Subtitle-Frame-Status': 'ok',
905 'X-Subtitle-Frame-Start-Time': '2',
906 'X-Subtitle-Frame-End-Time': '3',
907 'X-Subtitle-Frame-Width': '320',
908 'X-Subtitle-Frame-Height': '180',
909 'X-Subtitle-Frame-Canvas-Width': '640',
910 'X-Subtitle-Frame-Canvas-Height': '360',
911 },
912 }));
913 }
914
915 return new Promise((resolve) =>
916 {
917 pendingResolve = resolve;
918 });
919 });
920
921 const controller = helper.bindImageSubtitleOverlay(player, videojs, {}, {
922 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
923 }, {
924 lookaheadSeconds: 0,
925 buildFrameRequest: ({ currentTime, streamIndex }) => ({
926 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
927 }),
928 });
929
930 await flushAsyncWork(window, 8);
931
932 const requestedMarker = player.el().querySelector('.vjs-image-subtitle-seek-marker-right');
933 const receivedMarker = player.el().querySelector('.vjs-image-subtitle-seek-marker-left');
934 expect(requestedMarker).toBeTruthy();
935 expect(receivedMarker).toBeTruthy();
936 expect(requestedMarker.style.left).toBe('0.0000%');
937 expect(receivedMarker.style.left).toBe('20.0000%');
938
939 player.setCurrentTime(1.5);
940 player.trigger('timeupdate');
941 await flushAsyncWork(window, 2);
942
943 expect(requestedMarker.style.left).toBe('0.0000%');
944 expect(receivedMarker.style.left).toBe('20.0000%');
945
946 pendingResolve(new Response(null, {
947 status: 204,
948 headers: {
949 'X-Subtitle-Frame-Status': 'none',
950 },
951 }));
952
953 await flushAsyncWork(window, 8);
954 expect(requestedMarker.style.display).toBe('block');
955 expect(receivedMarker.style.display).toBe('block');
956 expect(requestedMarker.style.left).toBe('15.0000%');
957 expect(receivedMarker.style.left).toBe('20.0000%');
958
959 controller.detach();
960 await flushAsyncWork(window, 2);
961 window.close();
962 });
963
964 test('keeps marker positions forward-only when later responses resolve with earlier times', async () =>
965 {
966 const window = createWindow();
967 const helper = loadSharedVideoPlayer(window);
968 const { player, videojs } = buildPlayerHarness(window);
969 const requestedTimes = [];
970
971 player.duration(12);
972 window.fetch = jest.fn(async (url) =>
973 {
974 const parsed = new URL(url, 'http://localhost/');
975 const timeSeconds = Number(parsed.searchParams.get('timeSeconds'));
976 requestedTimes.push(timeSeconds);
977
978 if (requestedTimes.length === 1)
979 {
980 return new Response('png-data', {
981 status: 200,
982 headers: {
983 'Content-Type': 'image/png',
984 'X-Subtitle-Frame-Status': 'ok',
985 'X-Subtitle-Frame-Start-Time': '4',
986 'X-Subtitle-Frame-End-Time': '5',
987 'X-Subtitle-Frame-Width': '320',
988 'X-Subtitle-Frame-Height': '180',
989 'X-Subtitle-Frame-Canvas-Width': '640',
990 'X-Subtitle-Frame-Canvas-Height': '360',
991 },
992 });
993 }
994
995 return new Response('png-data', {
996 status: 200,
997 headers: {
998 'Content-Type': 'image/png',
999 'X-Subtitle-Frame-Status': 'ok',
1000 'X-Subtitle-Frame-Start-Time': '2',
1001 'X-Subtitle-Frame-End-Time': '3',
1002 'X-Subtitle-Frame-Width': '320',
1003 'X-Subtitle-Frame-Height': '180',
1004 'X-Subtitle-Frame-Canvas-Width': '640',
1005 'X-Subtitle-Frame-Canvas-Height': '360',
1006 },
1007 });
1008 });
1009
1010 const controller = helper.bindImageSubtitleOverlay(player, videojs, {}, {
1011 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
1012 }, {
1013 lookaheadSeconds: 0,
1014 buildFrameRequest: ({ currentTime, streamIndex }) => ({
1015 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
1016 }),
1017 });
1018
1019 await flushAsyncWork(window, 8);
1020
1021 const requestedMarker = player.el().querySelector('.vjs-image-subtitle-seek-marker-right');
1022 const receivedMarker = player.el().querySelector('.vjs-image-subtitle-seek-marker-left');
1023 expect(requestedMarker).toBeTruthy();
1024 expect(receivedMarker).toBeTruthy();
1025 expect(requestedMarker.style.left).toBe('100.0000%');
1026 expect(receivedMarker.style.left).toBe('33.3333%');
1027
1028 player.setCurrentTime(1.5);
1029 player.trigger('timeupdate');
1030 await flushAsyncWork(window, 8);
1031
1032 // Second response reports an older start time, but markers stay monotonic.
1033 expect(requestedMarker.style.left).toBe('100.0000%');
1034 expect(receivedMarker.style.left).toBe('33.3333%');
1035
1036 controller.detach();
1037 await flushAsyncWork(window, 2);
1038 window.close();
1039 });
1040
1041 test('continues current subtitle refreshes after a force-seek aborts the in-flight request', async () =>
1042 {
1043 const window = createWindow();
1044 const helper = loadSharedVideoPlayer(window);
1045 const { player, videojs } = buildPlayerHarness(window);
1046 const requestedTimes = [];
1047
1048 window.fetch = jest.fn((url, init = {}) =>
1049 {
1050 const parsed = new URL(url, 'http://localhost/');
1051 const timeSeconds = Number(parsed.searchParams.get('timeSeconds'));
1052 requestedTimes.push(timeSeconds);
1053
1054 if (requestedTimes.length === 1)
1055 {
1056 return new Promise((resolve, reject) =>
1057 {
1058 if (init.signal && typeof init.signal.addEventListener === 'function')
1059 {
1060 init.signal.addEventListener('abort', () =>
1061 {
1062 reject(new window.DOMException('Aborted', 'AbortError'));
1063 }, { once: true });
1064 }
1065 });
1066 }
1067
1068 return Promise.resolve(new Response(null, {
1069 status: 204,
1070 headers: {
1071 'X-Subtitle-Frame-Status': 'none',
1072 },
1073 }));
1074 });
1075
1076 const controller = helper.bindImageSubtitleOverlay(player, videojs, {}, {
1077 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
1078 }, {
1079 lookaheadSeconds: 0,
1080 currentRequestTimeoutMs: 300,
1081 logToConsole: false,
1082 buildFrameRequest: ({ currentTime, streamIndex }) => ({
1083 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
1084 }),
1085 });
1086
1087 await flushAsyncWork(window, 4);
1088 const afterInitialLoadCalls = window.fetch.mock.calls.length;
1089 expect(afterInitialLoadCalls).toBeGreaterThan(0);
1090
1091 player.setCurrentTime(5);
1092 player.trigger('seeking');
1093 await flushAsyncWork(window, 20);
1094
1095 expect(window.fetch.mock.calls.length).toBeGreaterThanOrEqual(2);
1096 expect(requestedTimes).toEqual(expect.arrayContaining([0, 5]));
1097
1098 controller.detach();
1099 await flushAsyncWork(window, 2);
1100 window.close();
1101 });
1102
1103 test('recovers when a current subtitle request hangs and times out', async () =>
1104 {
1105 const window = createWindow();
1106 const helper = loadSharedVideoPlayer(window);
1107 const { player, videojs } = buildPlayerHarness(window);
1108 const requestedTimes = [];
1109
1110 window.fetch = jest.fn((url, init = {}) =>
1111 {
1112 const parsed = new URL(url, 'http://localhost/');
1113 const timeSeconds = Number(parsed.searchParams.get('timeSeconds'));
1114 requestedTimes.push(timeSeconds);
1115
1116 if (requestedTimes.length === 1)
1117 {
1118 return new Promise((resolve, reject) =>
1119 {
1120 if (init.signal && typeof init.signal.addEventListener === 'function')
1121 {
1122 init.signal.addEventListener('abort', () =>
1123 {
1124 reject(new window.DOMException('Aborted', 'AbortError'));
1125 }, { once: true });
1126 }
1127 });
1128 }
1129
1130 return Promise.resolve(new Response(null, {
1131 status: 204,
1132 headers: { 'X-Subtitle-Frame-Status': 'none' },
1133 }));
1134 });
1135
1136 const controller = helper.bindImageSubtitleOverlay(player, videojs, {}, {
1137 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
1138 }, {
1139 lookaheadSeconds: 0,
1140 currentRequestTimeoutMs: 250,
1141 logToConsole: false,
1142 buildFrameRequest: ({ currentTime, streamIndex }) => ({
1143 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
1144 }),
1145 });
1146
1147 await flushAsyncWork(window, 3);
1148
1149 player.setCurrentTime(1.5);
1150 player.trigger('timeupdate');
1151
1152 await new Promise((resolve) => window.setTimeout(resolve, 320));
1153 player.trigger('timeupdate');
1154 await new Promise((resolve) => window.setTimeout(resolve, 220));
1155 await flushAsyncWork(window, 20);
1156
1157 expect(window.fetch.mock.calls.length).toBeGreaterThanOrEqual(2);
1158 expect(requestedTimes).toEqual(expect.arrayContaining([0, 1.5]));
1159
1160 controller.detach();
1161 await new Promise((resolve) => window.setTimeout(resolve, 200));
1162 await flushAsyncWork(window, 20);
1163 window.close();
1164 });
1165
1166 test('reuses cached subtitle frames after rewinding when server no longer has older frames', async () =>
1167 {
1168 const window = createWindow();
1169 const helper = loadSharedVideoPlayer(window);
1170 const { player, videojs } = buildPlayerHarness(window);
1171
1172 player.duration(10);
1173 player.setCurrentTime(2);
1174 window.fetch = jest.fn(async (url) =>
1175 {
1176 const parsed = new URL(url, 'http://localhost/');
1177 const timeSeconds = Number(parsed.searchParams.get('timeSeconds'));
1178
1179 if (Math.abs(timeSeconds - 2) < 1e-6)
1180 {
1181 return new Response('png-data', {
1182 status: 200,
1183 headers: {
1184 'Content-Type': 'image/png',
1185 'X-Subtitle-Frame-Status': 'ok',
1186 'X-Subtitle-Frame-Start-Time': '2',
1187 'X-Subtitle-Frame-End-Time': '3',
1188 'X-Subtitle-Frame-Width': '320',
1189 'X-Subtitle-Frame-Height': '180',
1190 'X-Subtitle-Frame-Canvas-Width': '640',
1191 'X-Subtitle-Frame-Canvas-Height': '360',
1192 },
1193 });
1194 }
1195
1196 return new Response(null, {
1197 status: 204,
1198 headers: {
1199 'X-Subtitle-Frame-Status': 'none',
1200 },
1201 });
1202 });
1203
1204 const controller = helper.bindImageSubtitleOverlay(player, videojs, {}, {
1205 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
1206 }, {
1207 lookaheadSeconds: 0,
1208 buildFrameRequest: ({ currentTime, streamIndex }) => ({
1209 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
1210 }),
1211 });
1212
1213 await flushAsyncWork(window, 8);
1214 const afterInitialLoadCalls = window.fetch.mock.calls.length;
1215 expect(afterInitialLoadCalls).toBeGreaterThan(0);
1216
1217 player.setCurrentTime(4);
1218 player.trigger('timeupdate');
1219 await flushAsyncWork(window, 8);
1220 const afterForwardSeekCalls = window.fetch.mock.calls.length;
1221 expect(afterForwardSeekCalls).toBeGreaterThanOrEqual(afterInitialLoadCalls);
1222
1223 const overlay = player.el().querySelector('.video-subtitle-overlay');
1224 expect(overlay).toBeTruthy();
1225 expect(overlay.style.display).toBe('none');
1226
1227 player.setCurrentTime(2.5);
1228 player.trigger('timeupdate');
1229 await flushAsyncWork(window, 8);
1230
1231 expect(window.fetch.mock.calls.length).toBe(afterForwardSeekCalls);
1232 expect(overlay.style.display).toBe('block');
1233
1234 controller.detach();
1235 await flushAsyncWork(window, 2);
1236 window.close();
1237 });
1238
1239 test('registers stream cache service worker once when supported', async () =>
1240 {
1241 const window = createWindow();
1242 const helper = loadSharedVideoPlayer(window);
1243 const register = jest.fn(async () => ({}));
1244 window.navigator.serviceWorker = { register };
1245
1246 const first = await helper.enableVideoStreamClientCache();
1247 const second = await helper.enableVideoStreamClientCache();
1248
1249 expect(first).toBe(true);
1250 expect(second).toBe(true);
1251 expect(register).toHaveBeenCalledTimes(1);
1252 expect(register).toHaveBeenCalledWith('/stream-cache-sw.js', {
1253 scope: '/',
1254 updateViaCache: 'none',
1255 });
1256
1257 window.close();
1258 });
1259
1260 test('stream-ahead prefetch follows playlists and fetches segment assets', async () =>
1261 {
1262 const window = createWindow();
1263 const helper = loadSharedVideoPlayer(window);
1264 const requestedUrls = [];
1265
1266 window.fetch = jest.fn(async (input) =>
1267 {
1268 const url = String(input && input.url ? input.url : input);
1269 requestedUrls.push(url);
1270
1271 if (url === 'http://localhost/master.m3u8')
1272 {
1273 return new Response('#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=100000\nstream_0.m3u8\n#EXT-X-ENDLIST\n', {
1274 status: 200,
1275 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1276 });
1277 }
1278
1279 if (url === 'http://localhost/stream_0.m3u8')
1280 {
1281 return new Response('#EXTM3U\n#EXTINF:4,\nseg0.ts\n#EXTINF:4,\nseg1.ts\n#EXT-X-ENDLIST\n', {
1282 status: 200,
1283 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1284 });
1285 }
1286
1287 if (url === 'http://localhost/seg0.ts' || url === 'http://localhost/seg1.ts')
1288 {
1289 return new Response(new Uint8Array([1, 2, 3, 4]), {
1290 status: 200,
1291 headers: { 'Content-Type': 'video/mp2t' },
1292 });
1293 }
1294
1295 return new Response(null, { status: 404 });
1296 });
1297
1298 const controller = helper.bindStreamAheadPrefetch({
1299 playlistUrl: 'http://localhost/master.m3u8',
1300 pollIntervalMs: 0,
1301 credentials: 'same-origin',
1302 });
1303
1304 expect(controller).toBeTruthy();
1305 await controller.done();
1306
1307 expect(requestedUrls).toEqual(expect.arrayContaining([
1308 'http://localhost/master.m3u8',
1309 'http://localhost/stream_0.m3u8',
1310 'http://localhost/seg0.ts',
1311 'http://localhost/seg1.ts',
1312 ]));
1313
1314 controller.stop();
1315 window.close();
1316 });
1317
1318 test('stream-ahead prefetch reports cached-through progress for fetched segments', async () =>
1319 {
1320 const window = createWindow();
1321 const helper = loadSharedVideoPlayer(window);
1322 const progressSamples = [];
1323
1324 window.fetch = jest.fn(async (input) =>
1325 {
1326 const url = String(input && input.url ? input.url : input);
1327
1328 if (url === 'http://localhost/master.m3u8')
1329 {
1330 return new Response('#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=100000\nstream_0.m3u8\n#EXT-X-ENDLIST\n', {
1331 status: 200,
1332 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1333 });
1334 }
1335
1336 if (url === 'http://localhost/stream_0.m3u8')
1337 {
1338 return new Response('#EXTM3U\n#EXTINF:4,\nseg0.ts\n#EXTINF:4,\nseg1.ts\n#EXT-X-ENDLIST\n', {
1339 status: 200,
1340 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1341 });
1342 }
1343
1344 if (url === 'http://localhost/seg0.ts' || url === 'http://localhost/seg1.ts')
1345 {
1346 return new Response(new Uint8Array([1, 2, 3, 4]), {
1347 status: 200,
1348 headers: { 'Content-Type': 'video/mp2t' },
1349 });
1350 }
1351
1352 return new Response(null, { status: 404 });
1353 });
1354
1355 const controller = helper.bindStreamAheadPrefetch({
1356 playlistUrl: 'http://localhost/master.m3u8',
1357 pollIntervalMs: 0,
1358 credentials: 'same-origin',
1359 });
1360
1361 expect(controller).toBeTruthy();
1362 const unsubscribe = controller.subscribe((status) =>
1363 {
1364 progressSamples.push(status && status.cachedThroughSeconds);
1365 });
1366
1367 await controller.done();
1368 unsubscribe();
1369
1370 expect(progressSamples.some((value) => Number.isFinite(value) && value >= 8)).toBe(true);
1371
1372 controller.stop();
1373 window.close();
1374 });
1375
1376 test('stream-ahead prefetch infers cached-through progress from segment filenames', async () =>
1377 {
1378 const window = createWindow();
1379 const helper = loadSharedVideoPlayer(window);
1380 const progressSamples = [];
1381
1382 window.fetch = jest.fn(async (input) =>
1383 {
1384 const url = String(input && input.url ? input.url : input);
1385
1386 if (url === 'http://localhost/master.m3u8')
1387 {
1388 return new Response('#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=100000\nstream_0.m3u8\n#EXT-X-ENDLIST\n', {
1389 status: 200,
1390 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1391 });
1392 }
1393
1394 if (url === 'http://localhost/stream_0.m3u8')
1395 {
1396 return new Response('#EXTM3U\nstream_0_segment_000000.ts\nstream_0_segment_000001.ts\n#EXT-X-ENDLIST\n', {
1397 status: 200,
1398 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1399 });
1400 }
1401
1402 if (url === 'http://localhost/stream_0_segment_000000.ts' || url === 'http://localhost/stream_0_segment_000001.ts')
1403 {
1404 return new Response(new Uint8Array([1, 2, 3, 4]), {
1405 status: 200,
1406 headers: { 'Content-Type': 'video/mp2t' },
1407 });
1408 }
1409
1410 return new Response(null, { status: 404 });
1411 });
1412
1413 const controller = helper.bindStreamAheadPrefetch({
1414 playlistUrl: 'http://localhost/master.m3u8',
1415 pollIntervalMs: 0,
1416 credentials: 'same-origin',
1417 });
1418
1419 expect(controller).toBeTruthy();
1420 const unsubscribe = controller.subscribe((status) =>
1421 {
1422 progressSamples.push(status && status.cachedThroughSeconds);
1423 });
1424
1425 await controller.done();
1426 unsubscribe();
1427
1428 expect(progressSamples.some((value) => Number.isFinite(value) && value >= 8)).toBe(true);
1429
1430 controller.stop();
1431 window.close();
1432 });
1433
1434 test('stream-ahead prefetch infers cached-through progress for m4s segment filenames', async () =>
1435 {
1436 const window = createWindow();
1437 const helper = loadSharedVideoPlayer(window);
1438 const progressSamples = [];
1439
1440 window.fetch = jest.fn(async (input) =>
1441 {
1442 const url = String(input && input.url ? input.url : input);
1443
1444 if (url === 'http://localhost/master.m3u8')
1445 {
1446 return new Response('#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=100000\nstream_0.m3u8\n#EXT-X-ENDLIST\n', {
1447 status: 200,
1448 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1449 });
1450 }
1451
1452 if (url === 'http://localhost/stream_0.m3u8')
1453 {
1454 return new Response('#EXTM3U\nstream_0_segment_000000.m4s\nstream_0_segment_000001.m4s\n#EXT-X-ENDLIST\n', {
1455 status: 200,
1456 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1457 });
1458 }
1459
1460 if (url === 'http://localhost/stream_0_segment_000000.m4s' || url === 'http://localhost/stream_0_segment_000001.m4s')
1461 {
1462 return new Response(new Uint8Array([1, 2, 3, 4]), {
1463 status: 200,
1464 headers: { 'Content-Type': 'video/mp4' },
1465 });
1466 }
1467
1468 return new Response(null, { status: 404 });
1469 });
1470
1471 const controller = helper.bindStreamAheadPrefetch({
1472 playlistUrl: 'http://localhost/master.m3u8',
1473 pollIntervalMs: 0,
1474 credentials: 'same-origin',
1475 });
1476
1477 expect(controller).toBeTruthy();
1478 const unsubscribe = controller.subscribe((status) =>
1479 {
1480 progressSamples.push(status && status.cachedThroughSeconds);
1481 });
1482
1483 await controller.done();
1484 unsubscribe();
1485
1486 expect(progressSamples.some((value) => Number.isFinite(value) && value >= 8)).toBe(true);
1487
1488 controller.stop();
1489 window.close();
1490 });
1491
1492 test('stream-ahead prefetch reports ratio progress from fetched sections when timing is unknown', async () =>
1493 {
1494 const window = createWindow();
1495 const helper = loadSharedVideoPlayer(window);
1496 const statusSamples = [];
1497
1498 window.fetch = jest.fn(async (input) =>
1499 {
1500 const url = String(input && input.url ? input.url : input);
1501
1502 if (url === 'http://localhost/master.m3u8')
1503 {
1504 return new Response('#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=100000\nstream_0.m3u8\n#EXT-X-ENDLIST\n', {
1505 status: 200,
1506 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1507 });
1508 }
1509
1510 if (url === 'http://localhost/stream_0.m3u8')
1511 {
1512 return new Response('#EXTM3U\nchunk-alpha.bin\nchunk-beta.bin\n#EXT-X-ENDLIST\n', {
1513 status: 200,
1514 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1515 });
1516 }
1517
1518 if (url === 'http://localhost/chunk-alpha.bin' || url === 'http://localhost/chunk-beta.bin')
1519 {
1520 return new Response(new Uint8Array([1, 2, 3, 4]), {
1521 status: 200,
1522 headers: { 'Content-Type': 'application/octet-stream' },
1523 });
1524 }
1525
1526 return new Response(null, { status: 404 });
1527 });
1528
1529 const controller = helper.bindStreamAheadPrefetch({
1530 playlistUrl: 'http://localhost/master.m3u8',
1531 pollIntervalMs: 0,
1532 credentials: 'same-origin',
1533 });
1534
1535 expect(controller).toBeTruthy();
1536 const unsubscribe = controller.subscribe((status) =>
1537 {
1538 statusSamples.push(status || {});
1539 });
1540
1541 await controller.done();
1542 unsubscribe();
1543
1544 const finalStatus = statusSamples[statusSamples.length - 1] || {};
1545 expect(finalStatus.totalSegmentCount).toBe(2);
1546 expect(finalStatus.fetchedSegmentCount).toBe(2);
1547 expect(finalStatus.cachedThroughRatio).toBe(1);
1548
1549 controller.stop();
1550 window.close();
1551 });
1552
1553 test('clears cached stream assets for a finished playlist session', async () =>
1554 {
1555 const window = createWindow();
1556 const helper = loadSharedVideoPlayer(window);
1557 const requests = [
1558 new window.Request('http://localhost/api/files/video-stream/sess-a/master.m3u8'),
1559 new window.Request('http://localhost/api/files/video-stream/sess-a/stream_0_segment_000001.ts'),
1560 new window.Request('http://localhost/api/files/video-stream/sess-b/master.m3u8'),
1561 ];
1562 const deleteCalls = [];
1563 const cache = {
1564 keys: jest.fn(async () => requests),
1565 delete: jest.fn(async (request) =>
1566 {
1567 deleteCalls.push(request.url);
1568 return true;
1569 }),
1570 };
1571 window.caches = {
1572 open: jest.fn(async () => cache),
1573 };
1574
1575 await helper.clearVideoStreamClientCache('http://localhost/api/files/video-stream/sess-a/master.m3u8');
1576
1577 expect(window.caches.open).toHaveBeenCalledWith('filemanager-stream-cache-v1');
1578 expect(cache.keys).toHaveBeenCalledTimes(1);
1579 expect(deleteCalls).toEqual(expect.arrayContaining([
1580 'http://localhost/api/files/video-stream/sess-a/master.m3u8',
1581 'http://localhost/api/files/video-stream/sess-a/stream_0_segment_000001.ts',
1582 ]));
1583 expect(deleteCalls).not.toContain('http://localhost/api/files/video-stream/sess-b/master.m3u8');
1584
1585 window.close();
1586 });
1587});