@swf2es/web 0.1.20 → 0.1.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,87 @@
1
+ // The fetches of an element's load: the SWF itself, and what its SWFs load,
2
+ // through an AIR application's files, the embedder's fetch or the browser's.
3
+ import type { FetchRequest, FetchResult } from "@swf2es/player";
4
+ import { configuration } from "./config.js";
5
+ import type { Session } from "./element.js";
6
+
7
+ /** The SWF at `url`, by the embedder's fetch where it gave one, and the URL a redirect took it to. */
8
+ export async function fetchMovie(
9
+ url: string,
10
+ signal: AbortSignal,
11
+ ): Promise<{ bytes: Uint8Array; url: string }> {
12
+ const fetchOf = configuration().fetch;
13
+ if (fetchOf) {
14
+ const result = await fetchOf(
15
+ { url, method: "GET", headers: [], body: null, purpose: "movie" },
16
+ signal,
17
+ );
18
+ if (!result.bytes) {
19
+ throw new Error(`swf2es: ${result.status} for ${url}`);
20
+ }
21
+
22
+ return { bytes: result.bytes, url: result.url ?? url };
23
+ }
24
+
25
+ const response = await fetch(url, { signal });
26
+ if (!response.ok) {
27
+ throw new Error(`swf2es: ${response.status} for ${url}`);
28
+ }
29
+
30
+ return { bytes: new Uint8Array(await response.arrayBuffer()), url: response.url || url };
31
+ }
32
+
33
+ /**
34
+ * What a session's SWFs load by: its AIR application's files, then the
35
+ * embedder's fetch or the browser's; `offline` (allowNetworking "none"),
36
+ * nothing past the application's own files, which are no network.
37
+ */
38
+ export function fetchFor(
39
+ session: Session,
40
+ offline: boolean,
41
+ ): (request: FetchRequest, signal: AbortSignal) => Promise<FetchResult> {
42
+ const fetchOf: (request: FetchRequest, signal: AbortSignal) => Promise<FetchResult> = offline
43
+ ? () => Promise.reject(new Error("allowNetworking is none"))
44
+ : (configuration().fetch ?? browserFetch);
45
+ const app = session.air?.app;
46
+ if (!app) {
47
+ return fetchOf;
48
+ }
49
+
50
+ return (request, signal) => {
51
+ const local = app.fetch(request, session.air?.files);
52
+ if (!local) {
53
+ return fetchOf(request, signal);
54
+ }
55
+
56
+ // A file the application does not hold, from the directory it came from: one the server
57
+ // has none of is a file that is not there, not its error's body.
58
+ const remote = local.bytes ? null : app.remote(request.url);
59
+ return remote
60
+ ? fetchOf({ ...request, url: remote, errorBody: false }, signal)
61
+ : Promise.resolve(local);
62
+ };
63
+ }
64
+
65
+ /** The host's fetch for what a SWF loads: the browser's, its status and headers as they come. */
66
+ async function browserFetch(request: FetchRequest, signal: AbortSignal): Promise<FetchResult> {
67
+ const response = await fetch(request.url, {
68
+ signal,
69
+ method: request.method,
70
+ headers: request.headers.map(([name, value]) => [name, value]),
71
+ body: request.body ? new Uint8Array(request.body).buffer : null,
72
+ });
73
+ const headers: [string, string][] = [];
74
+ response.headers.forEach((value, name) => {
75
+ headers.push([name, value]);
76
+ });
77
+
78
+ // An error's body only where it is asked for, as an AIR application's URLLoader reads it.
79
+ const read = response.ok || (!!request.errorBody && response.status >= 400);
80
+ return {
81
+ bytes: read ? new Uint8Array(await response.arrayBuffer()) : null,
82
+ status: response.status,
83
+ headers,
84
+ // Where a redirect took it: the SWF is judged and named by that.
85
+ ...(response.redirected ? { url: response.url } : {}),
86
+ };
87
+ }
package/src/index.ts CHANGED
@@ -10,6 +10,7 @@ import { defineElement } from "./element.js";
10
10
  // SWFs out for.
11
11
  export { filtersGreyOutFiles } from "@swf2es/player";
12
12
  export { AirApp, type AirAppFile, openAirApp } from "./air.js";
13
+ export { parseColor, parseFlashVars, scriptAccess } from "./attributes.js";
13
14
  export {
14
15
  type Configuration,
15
16
  configuration,
@@ -17,15 +18,7 @@ export {
17
18
  type SocketProxy,
18
19
  type WindowFullScreen,
19
20
  } from "./config.js";
20
- export {
21
- defineElement,
22
- parseColor,
23
- parseFlashVars,
24
- Swf2esPlayerElement,
25
- type SwfSource,
26
- scriptAccess,
27
- TAG,
28
- } from "./element.js";
21
+ export { defineElement, Swf2esPlayerElement, type SwfSource, TAG } from "./element.js";
29
22
  export { ExternalInterfaceError, type PageValue } from "./external.js";
30
23
  export { type Placement, place, type ScaleMode, scaleMode } from "./layout.js";
31
24
  export { flashAttributes, isFlash, replaceFlash, watchFlash } from "./replace.js";
package/src/playback.ts CHANGED
@@ -51,6 +51,15 @@ export class Playback {
51
51
  private destroyed = false;
52
52
  /** The stage's quality it last drew by. */
53
53
  private quality = "";
54
+ /** The last animation frame's time. */
55
+ private frameTime: number | null = null;
56
+ /**
57
+ * performance.now() as the last animation frame that came in time ended, by which the timer
58
+ * tells that they stopped: a minimized window's come a second apart, which is not in time.
59
+ */
60
+ private framed = Number.NEGATIVE_INFINITY;
61
+ /** The timer that plays on while no animation frame comes. */
62
+ private pump: ReturnType<typeof setTimeout> | undefined;
54
63
 
55
64
  private constructor(
56
65
  private readonly box: HTMLElement,
@@ -131,10 +140,11 @@ export class Playback {
131
140
  return this.view.gl;
132
141
  }
133
142
 
134
- /** Play and draw on every animation frame, from now. */
143
+ /** Play and draw on every animation frame, from now; play on by a timer while none comes. */
135
144
  run(): void {
136
145
  if (!this.destroyed && !this.frame) {
137
146
  this.frame = requestAnimationFrame(this.tick);
147
+ this.pump = setTimeout(this.idle, STALL_MS);
138
148
  }
139
149
  }
140
150
 
@@ -157,6 +167,35 @@ export class Playback {
157
167
 
158
168
  private readonly tick = (now: number) => {
159
169
  this.frame = requestAnimationFrame(this.tick);
170
+ const steady = this.frameTime !== null && now - this.frameTime < STALL_MS;
171
+ this.frameTime = now;
172
+ this.step(now, true);
173
+ if (steady) {
174
+ this.framed = performance.now();
175
+ }
176
+ };
177
+
178
+ /**
179
+ * A hidden page gets no animation frames: a minimized window's, or on Windows one another
180
+ * window covers, Electron's included, and an Electron window that is never throttled gets
181
+ * one a second while minimized. Played only by them, the player stopped dead: no timer
182
+ * fired, nothing went out, and what its sockets received piled up, all of it handled, and
183
+ * answered, in the first frame once shown, a burst a server may take for a flood, after a
184
+ * silence it may take for a lost client. Flash kept a hidden SWF playing; here a timer plays
185
+ * the frames while they do not come in time, at the SWF's rate as far as the page's timers
186
+ * may run (a browser slows a hidden page's to one a second), and draws nothing.
187
+ */
188
+ private readonly idle = () => {
189
+ const now = performance.now();
190
+ const stalled = now - this.framed >= STALL_MS;
191
+ // Set before the step, as tick asks for its next frame first: a destroy inside clears it.
192
+ this.pump = setTimeout(this.idle, stalled ? 1000 / (this.player.frameRate || 24) : STALL_MS);
193
+ if (stalled) {
194
+ this.step(now, false);
195
+ }
196
+ };
197
+
198
+ private step(now: number, show: boolean): void {
160
199
  const dt = this.last === null ? 0 : now - this.last;
161
200
  this.last = now;
162
201
  // Moved to a display of another density, or zoomed: drawn anew for its pixels.
@@ -179,10 +218,10 @@ export class Playback {
179
218
  this.requality();
180
219
  }
181
220
 
182
- if (this.player.changes !== this.drawn || this.dirty) {
221
+ if (show && (this.player.changes !== this.drawn || this.dirty)) {
183
222
  this.draw();
184
223
  }
185
- };
224
+ }
186
225
 
187
226
  /**
188
227
  * Drawn by the stage's quality as a script or the page changes it:
@@ -364,6 +403,7 @@ export class Playback {
364
403
 
365
404
  this.destroyed = true;
366
405
  cancelAnimationFrame(this.frame);
406
+ clearTimeout(this.pump);
367
407
  this.resize.disconnect();
368
408
  for (const unbind of this.unbind.splice(0)) {
369
409
  unbind();
@@ -402,6 +442,12 @@ function stageAround(
402
442
  };
403
443
  }
404
444
 
445
+ /**
446
+ * How long without an animation frame, in ms, before the timer plays one: well past a frame
447
+ * at any display's rate or a slow one's draw, so that it never plays between frames that come.
448
+ */
449
+ const STALL_MS = 250;
450
+
405
451
  /** The most a canvas's multisampled buffers may take, colour and depth-stencil together. */
406
452
  const STAGE_BYTES = 256 * 1024 * 1024;
407
453
 
package/src/workers.ts ADDED
@@ -0,0 +1,56 @@
1
+ // A SWF's Web Workers as the element starts them: whether its ActionScript
2
+ // names WorkerDomain, the host, and how long its first frame waits for them.
3
+ import { type Swf, tags } from "@swf2es/format";
4
+ import type { WebWorkerHost } from "@swf2es/player-hosts/workers";
5
+ import { workerHostForPlayer } from "./config.js";
6
+
7
+ /** The bytes of "WorkerDomain", the class a SWF's ActionScript names to start a worker. */
8
+ const WORKER_DOMAIN = new TextEncoder().encode("WorkerDomain");
9
+
10
+ /**
11
+ * Whether a SWF's ActionScript names WorkerDomain, in its ABCs' strings:
12
+ * one that does may start a worker and wait for it in the same script,
13
+ * which only a Web Worker started ahead can answer.
14
+ */
15
+ export function namesWorkers(swf: Swf): boolean {
16
+ const bytes = swf.bytes;
17
+ const first = WORKER_DOMAIN[0];
18
+ for (const tag of swf.tags) {
19
+ if (tag.code !== tags.DoABC && tag.code !== tags.DoABC2) {
20
+ continue;
21
+ }
22
+
23
+ const end = tag.offset + tag.length - WORKER_DOMAIN.length;
24
+ for (let at = bytes.indexOf(first, tag.offset); at !== -1 && at <= end; ) {
25
+ let k = 1;
26
+ while (k < WORKER_DOMAIN.length && bytes[at + k] === WORKER_DOMAIN[k]) {
27
+ k++;
28
+ }
29
+
30
+ if (k === WORKER_DOMAIN.length) {
31
+ return true;
32
+ }
33
+
34
+ at = bytes.indexOf(first, at + 1);
35
+ }
36
+ }
37
+
38
+ return false;
39
+ }
40
+
41
+ /**
42
+ * How long a SWF that names workers waits for the Web Workers started
43
+ * ahead before its first frame: past it, it plays on, and a worker it
44
+ * starts takes one still loading.
45
+ */
46
+ export const READY_WAIT = 10_000;
47
+
48
+ /** A player's Web Workers, or none where their module does not load, as under an import map that does not name it. */
49
+ export async function workersOrNone(ahead: boolean): Promise<WebWorkerHost | null> {
50
+ try {
51
+ return await workerHostForPlayer(ahead);
52
+ } catch (error) {
53
+ console.warn(`swf2es: workers are off, as their host did not load: ${error}`);
54
+ return null;
55
+ }
56
+ }