BlueGit

timfa filemanager

Files

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

shared-video-player.test.js

Fix image subtitle prefetching
timfa Tim Falken · pushed by timfa · 5 months ago
30b12890 History
shared-video-player.test.js 5.6 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 let currentTime = 0;
66
67 const player = {
68 ready (cb)
69 {
70 if (typeof cb === 'function') cb();
71 },
72 on (type, fn)
73 {
74 if (!events.has(type)) events.set(type, new Set());
75 events.get(type).add(fn);
76 },
77 trigger (type)
78 {
79 const listeners = events.get(type);
80 if (!listeners) return;
81 for (const fn of Array.from(listeners)) fn();
82 },
83 currentTime ()
84 {
85 return currentTime;
86 },
87 setCurrentTime (next)
88 {
89 currentTime = Number(next);
90 },
91 el ()
92 {
93 return playerEl;
94 },
95 getChild (name)
96 {
97 if (name !== 'controlBar') return null;
98 return {
99 addChild (componentName)
100 {
101 const Component = registeredComponents.get(componentName);
102 if (!Component) return null;
103 const instance = new Component(player);
104 playerEl.appendChild(instance.el());
105 return instance;
106 },
107 };
108 },
109 };
110
111 return { player, videojs };
112}
113
114function loadSharedVideoPlayer (window)
115{
116 const script = fs.readFileSync(path.join(__dirname, '../public/shared-video-player.js'), 'utf8');
117 window.eval(script);
118 return window.FilemanagerSharedVideoPlayer;
119}
120
121describe('shared image subtitle prefetching', () =>
122{
123 function createWindow ()
124 {
125 const dom = new JSDOM('<!doctype html><html><body></body></html>', {
126 url: 'http://localhost/',
127 runScripts: 'dangerously',
128 pretendToBeVisual: true,
129 });
130
131 dom.window.AbortController = AbortController;
132 dom.window.Response = Response;
133 dom.window.Headers = Headers;
134 dom.window.Request = Request;
135 dom.window.URL.createObjectURL = () => 'blob:subtitle';
136 dom.window.URL.revokeObjectURL = () => {};
137
138 return dom.window;
139 }
140
141 test('prefetches lookahead frames even when no subtitle is currently active', async () =>
142 {
143 const window = createWindow();
144 const helper = loadSharedVideoPlayer(window);
145 const { player, videojs } = buildPlayerHarness(window);
146 const requestedTimes = [];
147
148 window.fetch = jest.fn(async (url) =>
149 {
150 const parsed = new URL(url, 'http://localhost/');
151 requestedTimes.push(Number(parsed.searchParams.get('timeSeconds')));
152 return new Response(null, {
153 status: 204,
154 headers: { 'X-Subtitle-Frame-Status': 'none' },
155 });
156 });
157
158 helper.bindImageSubtitleOverlay(player, videojs, {}, {
159 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
160 }, {
161 lookaheadSeconds: 1,
162 buildFrameRequest: ({ currentTime, streamIndex }) => ({
163 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
164 }),
165 });
166
167 await flushAsyncWork(window);
168
169 expect(requestedTimes).toEqual(expect.arrayContaining([0, 0.5, 1]));
170
171 window.close();
172 });
173
174 test('aborts in-flight prefetch requests when the overlay is detached', async () =>
175 {
176 const window = createWindow();
177 const helper = loadSharedVideoPlayer(window);
178 const { player, videojs } = buildPlayerHarness(window);
179 const activeSignals = [];
180
181 window.fetch = jest.fn((url, init = {}) =>
182 {
183 const parsed = new URL(url, 'http://localhost/');
184 const timeSeconds = Number(parsed.searchParams.get('timeSeconds'));
185
186 if (timeSeconds === 0)
187 {
188 return Promise.resolve(new Response(null, {
189 status: 204,
190 headers: { 'X-Subtitle-Frame-Status': 'none' },
191 }));
192 }
193
194 activeSignals.push(init.signal || null);
195
196 return new Promise((resolve, reject) =>
197 {
198 if (init.signal && typeof init.signal.addEventListener === 'function')
199 {
200 init.signal.addEventListener('abort', () =>
201 {
202 reject(new DOMException('Aborted', 'AbortError'));
203 }, { once: true });
204 }
205 });
206 });
207
208 const controller = helper.bindImageSubtitleOverlay(player, videojs, {}, {
209 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
210 }, {
211 lookaheadSeconds: 1,
212 buildFrameRequest: ({ currentTime, streamIndex }) => ({
213 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
214 }),
215 });
216
217 await flushAsyncWork(window, 3);
218 expect(activeSignals.length).toBeGreaterThan(0);
219
220 controller.detach();
221 await flushAsyncWork(window, 2);
222
223 expect(activeSignals.every(signal => signal && signal.aborted)).toBe(true);
224
225 window.close();
226 });
227});