@ac-kit/browser 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +35 -0
- package/README.md +258 -4
- package/dist/_race-abort.d.ts +2 -0
- package/dist/_race-abort.d.ts.map +1 -0
- package/dist/_race-abort.js +20 -0
- package/dist/_race-abort.js.map +1 -0
- package/dist/canvas/image-data-pixels.d.ts +61 -0
- package/dist/canvas/image-data-pixels.d.ts.map +1 -0
- package/dist/canvas/image-data-pixels.js +74 -0
- package/dist/canvas/image-data-pixels.js.map +1 -0
- package/dist/canvas/read-image-data.d.ts +120 -0
- package/dist/canvas/read-image-data.d.ts.map +1 -0
- package/dist/canvas/read-image-data.js +147 -0
- package/dist/canvas/read-image-data.js.map +1 -0
- package/dist/dom/index.d.ts +2 -0
- package/dist/dom/index.d.ts.map +1 -0
- package/dist/dom/index.js +2 -0
- package/dist/dom/index.js.map +1 -0
- package/dist/dom/web-animations/wait-for-transitions.d.ts +59 -0
- package/dist/dom/web-animations/wait-for-transitions.d.ts.map +1 -0
- package/dist/dom/web-animations/wait-for-transitions.js +44 -0
- package/dist/dom/web-animations/wait-for-transitions.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -1
- package/dist/media-capture/microphone-access.d.ts +116 -0
- package/dist/media-capture/microphone-access.d.ts.map +1 -0
- package/dist/media-capture/microphone-access.js +224 -0
- package/dist/media-capture/microphone-access.js.map +1 -0
- package/dist/testing/fake-audio-context.d.ts +174 -0
- package/dist/testing/fake-audio-context.d.ts.map +1 -0
- package/dist/testing/fake-audio-context.js +314 -0
- package/dist/testing/fake-audio-context.js.map +1 -0
- package/dist/testing/fake-media-devices.d.ts +90 -0
- package/dist/testing/fake-media-devices.d.ts.map +1 -0
- package/dist/testing/fake-media-devices.js +147 -0
- package/dist/testing/fake-media-devices.js.map +1 -0
- package/dist/testing/fake-web-midi.d.ts +25 -0
- package/dist/testing/fake-web-midi.d.ts.map +1 -0
- package/dist/testing/fake-web-midi.js +52 -0
- package/dist/testing/fake-web-midi.js.map +1 -0
- package/dist/testing/index.d.ts +4 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +4 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/web-audio/audio-clock-mapping.d.ts +124 -0
- package/dist/web-audio/audio-clock-mapping.d.ts.map +1 -0
- package/dist/web-audio/audio-clock-mapping.js +245 -0
- package/dist/web-audio/audio-clock-mapping.js.map +1 -0
- package/package.json +20 -6
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,40 @@
|
|
|
1
1
|
# @ac-kit/browser
|
|
2
2
|
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 065cf8d: - New `readImageData(createCanvas, source, { maxSize?, maxPixels?, maxSide?, smoothing?, contextSettings? })` returns the pixels of an image, a video's current frame, a canvas, an `ImageBitmap` or a `VideoFrame` as `ImageData`, drawn once with `drawImage` on the canvas `createCanvas(width, height)` returns, then read back whole; no global is read. `createCanvas` must return a fresh canvas (new, or resized by assigning its `width` and `height`).
|
|
8
|
+
- `maxSize`, a positive integer, scales a larger source down until its longer side is `maxSize`, the shorter one `round(maxSize / aspect)` (or `× aspect`) and at least 1; a source no larger is drawn at its own size, never scaled up. It bounds what is drawn and read, not what the browser decodes.
|
|
9
|
+
- The size drawn is held to `maxPixels` (a positive integer, default 16,777,216 = 4096 × 4096, the smallest canvas Safari on iOS allows) and `maxSide` (a positive integer, default 32,767, a conservative policy of this library, not a browser limit; raise it where wider canvases are known to work): beyond either, it throws `RangeError` before creating a canvas, rather than read back the blank canvas a browser gives when it cannot allocate one. Neither scales: that is `maxSize`'s job.
|
|
10
|
+
- `smoothing` is `false` (nearest neighbour) or an `ImageSmoothingQuality`, a fresh context's when absent. `contextSettings` go to `getContext("2d")` unchanged and so apply on a canvas's first context only; the pixels come back in the canvas's colour space, which the result's `colorSpace` names, 8-bit and not premultiplied (a translucent pixel's colour is quantized: the read is not lossless).
|
|
11
|
+
- New `ImageSourceUnavailableError`, thrown before any canvas is created for a source with nothing to draw: an image not `complete` (even with its size known) or broken, a video below `HAVE_CURRENT_DATA`, a closed `ImageBitmap` or `VideoFrame`, an empty canvas. Awaiting `image.decode()` remains the caller's precondition. `maxSize`, `maxPixels` or `maxSide` that is not a positive integer throws `RangeError`, a canvas giving no 2D context `UnsupportedError`, and a cross-origin image read without CORS the browser's `SecurityError`.
|
|
12
|
+
- New `imageDataPixels(imageData)` yields the pixels of 8-bit `ImageData` row by row from the top left, each a new `{ r8, g8, b8, a8 }` (`ImageDataPixel`, the shape of `@ac-kit/math-color`'s `Rgba8`), lazily; empty data yields nothing.
|
|
13
|
+
- New `forEachImageDataPixel(imageData, visit)` calls `visit(r8, g8, b8, a8, index)` for each pixel in the same order, allocating nothing, for loops over large images where one object per pixel costs.
|
|
14
|
+
- Both pixel readers accept a `Uint8ClampedArray` from any realm (an iframe's) and throw `TypeError` at the call, before any pixel, for any other data, `ImageData` with `pixelFormat: "rgba-float16"` included.
|
|
15
|
+
- New subpath `@ac-kit/browser/dom`, for what works on a document's elements, with `waitForTransitions(element, { subtree?, properties?, signal? })`: it resolves once the CSS transitions in a snapshot of `element.getAnimations({ subtree })`, taken at the call after pending style changes, have ended. None running resolves at once; a delayed transition counts even at zero duration; a cancelled one counts as ended; one started after the call is not waited for. `subtree` adds the descendants' transitions and those of pseudo-elements, and `properties` restricts it to transitions of the CSS properties named. An aborted `signal` rejects with its reason — already aborted, aborted during the call, or aborted while waiting, even if another listener stops the `abort` event; an `abort` event dispatched by hand on a signal not aborted is ignored.
|
|
16
|
+
- 065cf8d: - New `requestMicrophoneStream(navigator, { deviceId?, sampleRate?, signal? })` opens audio only, for analysis: `getUserMedia` with echo cancellation, noise suppression, auto gain control and voice isolation off, one channel and `sampleRate` as ideals, no video. It resolves with `{ stream, isDefaultInstead }`; the caller owns the stream and stops its tracks.
|
|
17
|
+
- A `deviceId` is asked for as `exact`; when the browser rejects it with an `OverconstrainedError` whose `constraint` is `"deviceId"`, empty or absent (the specification has the browser withhold it as `""` before the page may see device information, and `deviceId` is the only `exact` constraint asked), the same request without `deviceId` is made once more, and `isDefaultInstead: true` says the stream is the browser's choice. An `OverconstrainedError` naming another constraint, or any one without a `deviceId`, goes through unchanged.
|
|
18
|
+
- New `MicrophoneUnsupportedError` (no `navigator.mediaDevices.getUserMedia`), `MicrophoneDeniedError` (`NotAllowedError`, `SecurityError`, `PermissionDeniedError`), `MicrophoneNotFoundError` (`NotFoundError`, `DevicesNotFoundError`) and `MicrophoneInUseError` (`NotReadableError`, `AbortError`, `TrackStartError`), each with the browser's error as `cause`, the retry's included; any other rejection, a non-error value included, goes through unchanged.
|
|
19
|
+
- An aborted `signal` rejects with its reason: at the call without asking the browser, while waiting (a prompt left open), before the retry, which is then not made, and when the stream has been opened but not yet returned. A stream opened after the abort has its tracks stopped.
|
|
20
|
+
- New `queryMicrophonePermission(navigator, { signal? })` resolves with `"granted"`, `"denied"`, `"prompt"` (also when the browser has no Permissions API or cannot query `"microphone"`) or `"unsupported"` without `getUserMedia`; it never opens the microphone. An aborted `signal` rejects with its reason, before or during the query.
|
|
21
|
+
- New `listMicrophones(navigator, { signal? })` resolves with the `audioinput` devices `{ deviceId, label }` in the browser's order, leaving out those with an empty `deviceId` (withheld before the page was given a microphone); empty when `enumerateDevices` is missing or rejects. An aborted `signal` rejects with its reason, before or while listing, rather than resolving empty.
|
|
22
|
+
- New `MicrophoneNavigator`, the `navigator` members these three read, each optional: no global is read. New `MicrophoneQueryOptions`, `{ signal? }`.
|
|
23
|
+
- New `AudioClockMapping({ windowMs, jumpMs, steadyMs, readyTicks, biasMs? })` maps an audio clock onto the page's from ticks `observe(audioMs, pageMs)`: its `offsetMs` is the least `pageMs − audioMs` of the ticks of the last `windowMs` of page time, less `biasMs` (default 0), once `readyTicks` ticks have come since it last started (`undefined` before); `toPageMs` and `toAudioMs` convert with it and throw `Error` before it is ready.
|
|
24
|
+
- It starts again (`resetCount` + 1, not ready until `readyTicks` more ticks) on `reset()`, on an audio time below the previous tick's, on a tick whose offset is more than `jumpMs` below the window's least, and on `readyTicks` ticks in a row, all within the window, each more than `jumpMs` above the least of the window's ticks before it, whose offsets span at most `steadyMs` and fall by at most `steadyMs / 2`; it then keeps those ticks and is ready on them. When `readyTicks` ticks do not fit in the window, no step up is taken: the window takes the new offset as the older ticks leave it.
|
|
25
|
+
- A time that is not finite, or a `pageMs` below the previous tick's, throws `RangeError` and leaves the mapping as it was; so does an option out of range (`windowMs` positive, `jumpMs` and `steadyMs` non-negative and finite, `readyTicks` a positive integer, `biasMs` finite).
|
|
26
|
+
- O(n) time per tick and per conversion, n the ticks in the window, and O(n) memory, the most ticks the window held, in a ring buffer growing by doubling: a tick allocates nothing otherwise. It reads no clock and no global.
|
|
27
|
+
- New subpath `@ac-kit/browser/testing`, stand-ins for tests under Node that import no test runner and record their calls as data: `FakeMediaDevices` (`getUserMedia` answering outcomes in turn — `"ok"`, a `DOMException` name, or `{ thrown }` — with `requests`, `tracks`, `liveTracks`, `holdNext`, `enumerateDevices` over `devices`, `changeDevices` dispatching `devicechange`), `FakeMediaStream`, `FakeMediaStreamTrack` (settings, `stop`, `end`, `mute`, `unmute`, `listenerCount`); `FakeAudioEnvironment` (`createContext`, `createWorkletNode`, refused rates, held `addModule` and `resume`), `FakeAudioContext`, `FakeAudioWorkletNode`, `FakeMessagePort` (records what the page posts, then hands it to `onPostMessage`), `FakeMediaStreamSource`, `FakeAudioNode`, `FakeGainNode`, `FakeBufferSource`, `FakeAudioBuffer`; `FakeMidiAccess` and `FakeMidiInput`.
|
|
28
|
+
|
|
29
|
+
### Patch Changes
|
|
30
|
+
|
|
31
|
+
- Updated dependencies [065cf8d]
|
|
32
|
+
- Updated dependencies [065cf8d]
|
|
33
|
+
- Updated dependencies [065cf8d]
|
|
34
|
+
- Updated dependencies [065cf8d]
|
|
35
|
+
- @ac-kit/async@0.7.0
|
|
36
|
+
- @ac-kit/core@0.11.0
|
|
37
|
+
|
|
3
38
|
## 0.1.1
|
|
4
39
|
|
|
5
40
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -3,12 +3,18 @@
|
|
|
3
3
|
Browser extensions and zero-dependency wrappers over browser APIs, the
|
|
4
4
|
browser's counterpart of `@ac-kit/node`: IndexedDB as promises, with versioned
|
|
5
5
|
upgrades; Web MIDI, with access asked for and the input port a person chose
|
|
6
|
-
followed by its name across reloads and hot-plugs;
|
|
7
|
-
|
|
6
|
+
followed by its name across reloads and hot-plugs; the microphone opened for
|
|
7
|
+
analysis, its permission and its devices; an audio clock mapped onto the
|
|
8
|
+
page's; requests over
|
|
9
|
+
`XMLHttpRequest` that report their upload progress, which `fetch` cannot; an
|
|
10
|
+
image's pixels read through a canvas, scaled down; and the wait for an
|
|
11
|
+
element's CSS transitions to end.
|
|
8
12
|
|
|
9
13
|
Every function takes the browser object it works through — `indexedDB`,
|
|
10
|
-
`navigator`, a `MIDIAccess`, `XMLHttpRequest
|
|
11
|
-
so it also runs in tests against a stand-in such
|
|
14
|
+
`navigator`, a `MIDIAccess`, `XMLHttpRequest`, a canvas factory, an element —
|
|
15
|
+
rather than reading a global, so it also runs in tests against a stand-in such
|
|
16
|
+
as `fake-indexeddb` or those of `@ac-kit/browser/testing`. What works on a document's elements is imported from
|
|
17
|
+
`@ac-kit/browser/dom`; everything else, workers included, from the root.
|
|
12
18
|
|
|
13
19
|
## IndexedDB
|
|
14
20
|
|
|
@@ -133,6 +139,95 @@ if ((await queryWebMidiPermission(navigator)) !== "unsupported") {
|
|
|
133
139
|
- `isSameMidiPort` — whether two port identities (name and manufacturer) are
|
|
134
140
|
the same device; a port's id changes between sessions, its identity does not.
|
|
135
141
|
|
|
142
|
+
## Microphone
|
|
143
|
+
|
|
144
|
+
```ts
|
|
145
|
+
import {
|
|
146
|
+
listMicrophones,
|
|
147
|
+
MicrophoneDeniedError,
|
|
148
|
+
queryMicrophonePermission,
|
|
149
|
+
requestMicrophoneStream,
|
|
150
|
+
} from "@ac-kit/browser";
|
|
151
|
+
|
|
152
|
+
if ((await queryMicrophonePermission(navigator)) !== "unsupported") {
|
|
153
|
+
try {
|
|
154
|
+
const { stream, isDefaultInstead } = await requestMicrophoneStream(
|
|
155
|
+
navigator,
|
|
156
|
+
{ deviceId: chosen?.deviceId, sampleRate: 48_000, signal },
|
|
157
|
+
);
|
|
158
|
+
if (isDefaultInstead) showDefaultMicrophoneNotice();
|
|
159
|
+
analyse(stream);
|
|
160
|
+
} catch (error) {
|
|
161
|
+
if (error instanceof MicrophoneDeniedError) showHowToAllow();
|
|
162
|
+
else throw error;
|
|
163
|
+
}
|
|
164
|
+
const devices = await listMicrophones(navigator);
|
|
165
|
+
}
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
- `requestMicrophoneStream(navigator, { deviceId?, sampleRate?, signal? })` —
|
|
169
|
+
audio only, for analysis: echo cancellation, noise suppression, auto gain
|
|
170
|
+
and voice isolation off, one channel and `sampleRate` asked for as ideals. A
|
|
171
|
+
`deviceId` is insisted on (`exact`); when the browser cannot open it (an
|
|
172
|
+
`OverconstrainedError` on `deviceId`, or on a constraint it withholds, as
|
|
173
|
+
before the page was given a microphone), it asks once more without it, and
|
|
174
|
+
`isDefaultInstead: true` says the stream is the browser's choice. It may
|
|
175
|
+
prompt, so call it from a user gesture. The caller owns the stream: stop its
|
|
176
|
+
tracks to release the microphone. Fails with `MicrophoneUnsupportedError`
|
|
177
|
+
without audio capture (outside a secure context), `MicrophoneDeniedError`
|
|
178
|
+
when refused, `MicrophoneNotFoundError` without a microphone and
|
|
179
|
+
`MicrophoneInUseError` when another application holds it, each with the
|
|
180
|
+
browser's error as `cause`; any other error goes through unchanged.
|
|
181
|
+
Aborting `signal` rejects with its reason, until the call returns: a
|
|
182
|
+
microphone the browser opens afterwards is stopped at once.
|
|
183
|
+
- `queryMicrophonePermission(navigator, { signal? })` — `"granted"`,
|
|
184
|
+
`"prompt"` (also when the browser cannot say), `"denied"`, or
|
|
185
|
+
`"unsupported"` without audio capture; it never opens the microphone.
|
|
186
|
+
- `listMicrophones(navigator, { signal? })` — the audio inputs
|
|
187
|
+
`{ deviceId, label }` the browser lists, without those whose id it withholds
|
|
188
|
+
before the page was given a microphone; empty when it cannot list them.
|
|
189
|
+
Aborting `signal` rejects both with its reason.
|
|
190
|
+
|
|
191
|
+
## Audio clock
|
|
192
|
+
|
|
193
|
+
```ts
|
|
194
|
+
import { AudioClockMapping } from "@ac-kit/browser";
|
|
195
|
+
|
|
196
|
+
const mapping = new AudioClockMapping({
|
|
197
|
+
windowMs: 2000,
|
|
198
|
+
jumpMs: 50,
|
|
199
|
+
steadyMs: 5,
|
|
200
|
+
readyTicks: 5,
|
|
201
|
+
});
|
|
202
|
+
// The AudioWorklet posts the frame it is at every few render quanta.
|
|
203
|
+
node.port.onmessage = ({ data }) => {
|
|
204
|
+
mapping.observe((data.frame / context.sampleRate) * 1000, performance.now());
|
|
205
|
+
};
|
|
206
|
+
context.addEventListener("statechange", () => mapping.reset());
|
|
207
|
+
if (mapping.isReady) {
|
|
208
|
+
showNoteAt(mapping.toPageMs(noteAudioMs));
|
|
209
|
+
}
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
- `AudioClockMapping` — the offset between an audio clock (the samples an
|
|
213
|
+
`AudioContext` or an `AudioWorklet` processed) and `performance.now()`, from
|
|
214
|
+
ticks the audio thread posts, each noted with the page time it arrived. A
|
|
215
|
+
tick only ever arrives late, so the offset is the least `page − audio` over
|
|
216
|
+
the last `windowMs` of ticks, less `biasMs`: the page's jank falls out, a
|
|
217
|
+
slow drift is followed. It starts again, and is not ready until
|
|
218
|
+
`readyTicks` more ticks, on `reset()` (a context suspended and resumed, a
|
|
219
|
+
worklet restarted), when the audio clock goes backwards, on a tick more
|
|
220
|
+
than `jumpMs` below the window's least `page − audio`, or on `readyTicks`
|
|
221
|
+
ticks in a row more than `jumpMs` above it whose offsets differ by at most `steadyMs` and do not keep
|
|
222
|
+
falling (a backlog draining after a freeze does). `toPageMs` and
|
|
223
|
+
`toAudioMs` convert either way once ready, and throw before; `resetCount`
|
|
224
|
+
counts the restarts. A tick arriving before the previous one, or a time not
|
|
225
|
+
finite, throws `RangeError`. The ticks of a step up must all lie in the
|
|
226
|
+
window: when `readyTicks` of them do not fit, the window takes the new
|
|
227
|
+
offset on its own once the older ticks leave it. It reads no clock: it runs
|
|
228
|
+
in a worker or under Node as well. O(n) per tick and per conversion, n the
|
|
229
|
+
ticks in the window, held in a ring buffer: a tick allocates nothing.
|
|
230
|
+
|
|
136
231
|
## Upload progress
|
|
137
232
|
|
|
138
233
|
```ts
|
|
@@ -173,6 +268,160 @@ rules, as for `fetch`. `fetch` cannot report an upload's progress, and streams
|
|
|
173
268
|
a request body only without its declared length; reach for `fetch` for
|
|
174
269
|
everything else.
|
|
175
270
|
|
|
271
|
+
## Image pixels
|
|
272
|
+
|
|
273
|
+
```ts
|
|
274
|
+
import {
|
|
275
|
+
forEachImageDataPixel,
|
|
276
|
+
imageDataPixels,
|
|
277
|
+
readImageData,
|
|
278
|
+
} from "@ac-kit/browser";
|
|
279
|
+
import { rgb8ToRgb1 } from "@ac-kit/math-color";
|
|
280
|
+
|
|
281
|
+
const image = new Image();
|
|
282
|
+
image.src = url;
|
|
283
|
+
await image.decode();
|
|
284
|
+
const imageData = readImageData(
|
|
285
|
+
(width, height) => new OffscreenCanvas(width, height),
|
|
286
|
+
image,
|
|
287
|
+
{ maxSize: 80, contextSettings: { colorSpace: "display-p3" } },
|
|
288
|
+
);
|
|
289
|
+
const colors = Array.from(imageDataPixels(imageData), rgb8ToRgb1);
|
|
290
|
+
|
|
291
|
+
let opaque = 0;
|
|
292
|
+
forEachImageDataPixel(imageData, (r8, g8, b8, a8) => {
|
|
293
|
+
if (a8 === 255) opaque++;
|
|
294
|
+
});
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
- `readImageData(createCanvas, source, options?)` — the pixels of an image, a
|
|
298
|
+
video's frame, a canvas, an `ImageBitmap` or a `VideoFrame` as `ImageData`,
|
|
299
|
+
drawn once with `drawImage` on the canvas `createCanvas(width, height)`
|
|
300
|
+
returns, which must be fresh: a new `OffscreenCanvas` (in a page or a
|
|
301
|
+
worker) or `<canvas>`, or one resized by assigning its `width` and `height`,
|
|
302
|
+
which clears it and resets its drawing state.
|
|
303
|
+
- `maxSize` scales a larger source down until its longer side fits, keeping
|
|
304
|
+
its aspect ratio, and never scales one up. It bounds what is drawn and
|
|
305
|
+
read back, not what the browser decodes.
|
|
306
|
+
- `maxPixels` (default 16,777,216, 4096 × 4096: the smallest canvas Safari
|
|
307
|
+
on iOS allows) and `maxSide` (default 32,767, a conservative policy of
|
|
308
|
+
this library rather than a browser's limit: Chromium draws wider) bound
|
|
309
|
+
what is read: beyond them it throws `RangeError` rather than read back the
|
|
310
|
+
blank canvas a browser gives when it cannot allocate one. Pass a
|
|
311
|
+
`maxSize`, or raise them for browsers known to allow more.
|
|
312
|
+
- `smoothing` picks the resampling (`false` for nearest neighbour, or a
|
|
313
|
+
quality), a fresh context's (`"low"`) when absent.
|
|
314
|
+
- `contextSettings` go to `getContext("2d")` as they are, and so apply on a
|
|
315
|
+
canvas's first context only: `colorSpace: "display-p3"` keeps a
|
|
316
|
+
wide-gamut photo's colours. The pixels come back converted to the canvas's
|
|
317
|
+
colour space, named by the result's `colorSpace`.
|
|
318
|
+
- The source must be ready: await `image.decode()` first. It throws
|
|
319
|
+
`ImageSourceUnavailableError` for an image not complete or broken, a video
|
|
320
|
+
without its current frame, or a closed bitmap or frame — what it can tell
|
|
321
|
+
synchronously; a source the browser cannot draw for another reason reads
|
|
322
|
+
back transparent. It throws `UnsupportedError` when the canvas gives no 2D
|
|
323
|
+
context; a cross-origin image loaded without CORS fails with the browser's
|
|
324
|
+
`SecurityError`.
|
|
325
|
+
- `imageDataPixels(imageData)` — the pixels of 8-bit `ImageData`, row by row,
|
|
326
|
+
each a new `{ r8, g8, b8, a8 }`: `@ac-kit/math-color`'s `Rgba8`, its
|
|
327
|
+
conversions' input. Lazy; none for an empty one. One object per pixel costs:
|
|
328
|
+
on a full-HD image it is several times slower than
|
|
329
|
+
`forEachImageDataPixel`.
|
|
330
|
+
- `forEachImageDataPixel(imageData, visit)` — calls `visit(r8, g8, b8, a8,
|
|
331
|
+
index)` for each pixel, allocating nothing: the loop for a large image.
|
|
332
|
+
|
|
333
|
+
Both read `ImageData` from any realm (an iframe's), and throw a `TypeError` for
|
|
334
|
+
`ImageData` holding 16-bit floats (`pixelFormat: "rgba-float16"`).
|
|
335
|
+
|
|
336
|
+
The pixels are the browser's `drawImage` resampling: the same image and options
|
|
337
|
+
give the same pixels in the same browser. They are 8-bit and not premultiplied
|
|
338
|
+
by alpha, while a canvas stores its colours premultiplied: a translucent
|
|
339
|
+
pixel's colour comes back quantized, so the read is not lossless, even at full
|
|
340
|
+
size.
|
|
341
|
+
|
|
342
|
+
## CSS transitions
|
|
343
|
+
|
|
344
|
+
```ts
|
|
345
|
+
import { waitForTransitions } from "@ac-kit/browser/dom";
|
|
346
|
+
|
|
347
|
+
panel.classList.add("is-hidden");
|
|
348
|
+
await waitForTransitions(panel, { signal });
|
|
349
|
+
panel.replaceChildren(next);
|
|
350
|
+
panel.classList.remove("is-hidden");
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
- `waitForTransitions(element, { subtree?, properties?, signal? })` — resolves
|
|
354
|
+
once the CSS transitions the element runs at the call have ended: a snapshot
|
|
355
|
+
of `element.getAnimations()`, taken after the style changes made before the
|
|
356
|
+
call. A transition that never starts — no change, no duration nor delay — is
|
|
357
|
+
not waited for (a delayed one is, even of zero duration), one cancelled
|
|
358
|
+
meanwhile counts as ended, and one started after the call is not waited for.
|
|
359
|
+
A `transitionend` listener would wait forever for the first two, and end
|
|
360
|
+
early on a descendant's. `subtree` waits for the descendants' transitions
|
|
361
|
+
too, their pseudo-elements' (`::before`, `::after`) included, as
|
|
362
|
+
`getAnimations({ subtree: true })` lists them; `properties` only for those
|
|
363
|
+
changing the CSS properties named. Aborting `signal`, even during the
|
|
364
|
+
call, rejects with its reason. A hidden page's rendering, and its
|
|
365
|
+
transitions with it, may be paused: bound the wait with
|
|
366
|
+
`AbortSignal.timeout()`, or `@ac-kit/async`'s `withTimeout`, where that
|
|
367
|
+
matters.
|
|
368
|
+
|
|
369
|
+
## Testing
|
|
370
|
+
|
|
371
|
+
```ts
|
|
372
|
+
import {
|
|
373
|
+
MicrophoneDeniedError,
|
|
374
|
+
requestMicrophoneStream,
|
|
375
|
+
} from "@ac-kit/browser";
|
|
376
|
+
import {
|
|
377
|
+
FakeAudioEnvironment,
|
|
378
|
+
FakeMediaDevices,
|
|
379
|
+
} from "@ac-kit/browser/testing";
|
|
380
|
+
import { expect, it } from "vitest";
|
|
381
|
+
|
|
382
|
+
it("tells a refusal", async () => {
|
|
383
|
+
const mediaDevices = new FakeMediaDevices(["NotAllowedError"]);
|
|
384
|
+
|
|
385
|
+
await expect(
|
|
386
|
+
requestMicrophoneStream({ mediaDevices }),
|
|
387
|
+
).rejects.toBeInstanceOf(MicrophoneDeniedError);
|
|
388
|
+
expect(mediaDevices.requests).toHaveLength(1);
|
|
389
|
+
});
|
|
390
|
+
|
|
391
|
+
it("hears the worklet", async () => {
|
|
392
|
+
const audio = new FakeAudioEnvironment();
|
|
393
|
+
// Code under test receives audio.createContext and audio.createWorkletNode.
|
|
394
|
+
const input = createInput(audio.createContext, audio.createWorkletNode);
|
|
395
|
+
await input.start();
|
|
396
|
+
audio.node.emit({ type: "level", rms: 0.1 });
|
|
397
|
+
});
|
|
398
|
+
```
|
|
399
|
+
|
|
400
|
+
`@ac-kit/browser/testing` holds stand-ins for the browser objects these
|
|
401
|
+
helpers, and code built on them, take — for tests under Node, not for a page:
|
|
402
|
+
|
|
403
|
+
- `FakeMediaDevices` — `getUserMedia` answering given outcomes in turn (a
|
|
404
|
+
`DOMException` by name, or a value thrown as it is), holding a call until
|
|
405
|
+
let go (`holdNext`) as a prompt does, devices listed and changed with a
|
|
406
|
+
`devicechange` event; its `FakeMediaStream`s and `FakeMediaStreamTrack`s
|
|
407
|
+
(settings, `ended`, `mute`, listeners counted).
|
|
408
|
+
- `FakeAudioEnvironment` — the `createContext` and `createWorkletNode`
|
|
409
|
+
factories to inject, making `FakeAudioContext`s (state and `statechange`,
|
|
410
|
+
`resume` held until a gesture, refused sampling rates, failing modules, the
|
|
411
|
+
sources and sounds made) and `FakeAudioWorkletNode`s whose `port`, a
|
|
412
|
+
`FakeMessagePort`, keeps what the page posts (`posted`, `postedOf(type)`),
|
|
413
|
+
hands it to `port.onPostMessage` where the test runs the processor's logic,
|
|
414
|
+
and delivers what the test `emit`s.
|
|
415
|
+
- `FakeMidiAccess` and `FakeMidiInput` — ports plugged in and out, messages
|
|
416
|
+
sent with their time stamps.
|
|
417
|
+
|
|
418
|
+
They import no test runner: calls are recorded as data (`requests`,
|
|
419
|
+
`posted`, `modules`, `connections`, `stopCount`, `closeCount`…), and a
|
|
420
|
+
runner's own spy wraps any method where more is needed:
|
|
421
|
+
`vi.spyOn(mediaDevices, "getUserMedia")`. A spy whose implementation replaces
|
|
422
|
+
the method's loses that record: to answer what the page posts to a worklet,
|
|
423
|
+
set `port.onPostMessage` rather than mock `port.postMessage`.
|
|
424
|
+
|
|
176
425
|
Browser-bound: it needs a page's (or a worker's) browser APIs, and depends on
|
|
177
426
|
`@ac-kit/core` and `@ac-kit/async` only. Its Node counterpart is
|
|
178
427
|
`@ac-kit/node`.
|
|
@@ -185,4 +434,9 @@ for the full reference.
|
|
|
185
434
|
|
|
186
435
|
- [Indexed Database API 3.0](https://www.w3.org/TR/IndexedDB/)
|
|
187
436
|
- [Web MIDI API](https://webaudio.github.io/web-midi-api/)
|
|
437
|
+
- [Media Capture and Streams](https://www.w3.org/TR/mediacapture-streams/)
|
|
438
|
+
- [Web Audio API](https://www.w3.org/TR/webaudio/)
|
|
188
439
|
- [XMLHttpRequest Standard](https://xhr.spec.whatwg.org/)
|
|
440
|
+
- [HTML Standard: the 2D rendering context](https://html.spec.whatwg.org/multipage/canvas.html#2dcontext)
|
|
441
|
+
- [Web Animations](https://www.w3.org/TR/web-animations-1/)
|
|
442
|
+
- [CSS Transitions](https://www.w3.org/TR/css-transitions-1/)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_race-abort.d.ts","sourceRoot":"","sources":["../src/_race-abort.ts"],"names":[],"mappings":"AAIA,wBAAsB,UAAU,CAAC,CAAC,EACjC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,EAChB,MAAM,EAAE,WAAW,GACjB,OAAO,CAAC,CAAC,CAAC,CAaZ"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// Settles as `work`, or rejects with `signal`'s reason once it aborts. It
|
|
2
|
+
// listens on a signal of its own following `signal`, which the browser aborts
|
|
3
|
+
// with it: a listener on `signal` calling `stopImmediatePropagation`, or an
|
|
4
|
+
// `abort` event dispatched by hand, cannot reach it.
|
|
5
|
+
export async function raceAbort_(work, signal) {
|
|
6
|
+
const following = AbortSignal.any([signal]);
|
|
7
|
+
following.throwIfAborted();
|
|
8
|
+
const aborted = Promise.withResolvers();
|
|
9
|
+
const onAbort = () => {
|
|
10
|
+
aborted.reject(following.reason);
|
|
11
|
+
};
|
|
12
|
+
following.addEventListener("abort", onAbort, { once: true });
|
|
13
|
+
try {
|
|
14
|
+
return await Promise.race([work, aborted.promise]);
|
|
15
|
+
}
|
|
16
|
+
finally {
|
|
17
|
+
following.removeEventListener("abort", onAbort);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
//# sourceMappingURL=_race-abort.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_race-abort.js","sourceRoot":"","sources":["../src/_race-abort.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,8EAA8E;AAC9E,4EAA4E;AAC5E,qDAAqD;AACrD,MAAM,CAAC,KAAK,UAAU,UAAU,CAC/B,IAAgB,EAChB,MAAmB;IAEnB,MAAM,SAAS,GAAG,WAAW,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;IAC5C,SAAS,CAAC,cAAc,EAAE,CAAC;IAC3B,MAAM,OAAO,GAAG,OAAO,CAAC,aAAa,EAAS,CAAC;IAC/C,MAAM,OAAO,GAAG,GAAS,EAAE;QAC1B,OAAO,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;IAClC,CAAC,CAAC;IACF,SAAS,CAAC,gBAAgB,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;IAC7D,IAAI,CAAC;QACJ,OAAO,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC;IACpD,CAAC;YAAS,CAAC;QACV,SAAS,CAAC,mBAAmB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IACjD,CAAC;AACF,CAAC"}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { Callable } from "@ac-kit/core";
|
|
2
|
+
/**
|
|
3
|
+
* One pixel of 8-bit `ImageData`, each component in [0, 255]: the shape of
|
|
4
|
+
* `@ac-kit/math-color`'s `Rgba8`, so it goes to its conversions as it is.
|
|
5
|
+
*/
|
|
6
|
+
export type ImageDataPixel = {
|
|
7
|
+
r8: number;
|
|
8
|
+
g8: number;
|
|
9
|
+
b8: number;
|
|
10
|
+
a8: number;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* The pixels of 8-bit `ImageData`, row by row from the top left, each a new
|
|
14
|
+
* object: `width × height` of them, none for an empty one. Its `colorSpace`
|
|
15
|
+
* says which RGB they are in; their colour is not premultiplied by alpha.
|
|
16
|
+
*
|
|
17
|
+
* Lazy, O(1) time per pixel, but one object allocated for each: on a full-HD
|
|
18
|
+
* image, several times slower than {@link forEachImageDataPixel}, which
|
|
19
|
+
* allocates nothing, and a load on the garbage collector. Reach for it where
|
|
20
|
+
* the pixels are kept as objects anyway.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* const colors = Array.from(imageDataPixels(imageData), (pixel) =>
|
|
24
|
+
* rgb8ToRgb1(pixel),
|
|
25
|
+
* );
|
|
26
|
+
*
|
|
27
|
+
* @param imageData `ImageData`, or anything holding its `data`.
|
|
28
|
+
* @throws {TypeError} When `data` is not a `Uint8ClampedArray` — `ImageData`
|
|
29
|
+
* with `pixelFormat: "rgba-float16"` holds a `Float16Array` — at the call,
|
|
30
|
+
* before any pixel.
|
|
31
|
+
*/
|
|
32
|
+
export declare function imageDataPixels(imageData: Pick<ImageData, "data">): IterableIterator<ImageDataPixel>;
|
|
33
|
+
/**
|
|
34
|
+
* Calls `visit` with the components of each pixel of 8-bit `ImageData`, row by
|
|
35
|
+
* row from the top left, and its index in that order (`y × width + x`): never
|
|
36
|
+
* for an empty one. Its `colorSpace` says which RGB they are in; their colour
|
|
37
|
+
* is not premultiplied by alpha.
|
|
38
|
+
*
|
|
39
|
+
* O(1) time per pixel and no allocation of its own: the form for a loop over
|
|
40
|
+
* every pixel of a large image. {@link imageDataPixels} yields objects
|
|
41
|
+
* instead.
|
|
42
|
+
*
|
|
43
|
+
* @example
|
|
44
|
+
* let opaque = 0;
|
|
45
|
+
* forEachImageDataPixel(imageData, (r8, g8, b8, a8) => {
|
|
46
|
+
* if (a8 === 255) opaque++;
|
|
47
|
+
* });
|
|
48
|
+
*
|
|
49
|
+
* @param imageData `ImageData`, or anything holding its `data`.
|
|
50
|
+
* @throws {TypeError} When `data` is not a `Uint8ClampedArray` — `ImageData`
|
|
51
|
+
* with `pixelFormat: "rgba-float16"` holds a `Float16Array` — before any
|
|
52
|
+
* pixel. What `visit` throws goes through, ending the loop.
|
|
53
|
+
*/
|
|
54
|
+
export declare function forEachImageDataPixel(imageData: Pick<ImageData, "data">, visit: Callable<[
|
|
55
|
+
r8: number,
|
|
56
|
+
g8: number,
|
|
57
|
+
b8: number,
|
|
58
|
+
a8: number,
|
|
59
|
+
index: number
|
|
60
|
+
]>): void;
|
|
61
|
+
//# sourceMappingURL=image-data-pixels.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"image-data-pixels.d.ts","sourceRoot":"","sources":["../../src/canvas/image-data-pixels.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAE7C;;;GAGG;AACH,MAAM,MAAM,cAAc,GAAG;IAC5B,EAAE,EAAE,MAAM,CAAC;IACX,EAAE,EAAE,MAAM,CAAC;IACX,EAAE,EAAE,MAAM,CAAC;IACX,EAAE,EAAE,MAAM,CAAC;CACX,CAAC;AAEF;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,eAAe,CAC9B,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,MAAM,CAAC,GAChC,gBAAgB,CAAC,cAAc,CAAC,CAKlC;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,qBAAqB,CACpC,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,MAAM,CAAC,EAClC,KAAK,EAAE,QAAQ,CACd;IAAC,EAAE,EAAE,MAAM;IAAE,EAAE,EAAE,MAAM;IAAE,EAAE,EAAE,MAAM;IAAE,EAAE,EAAE,MAAM;IAAE,KAAK,EAAE,MAAM;CAAC,CAC/D,GACC,IAAI,CAYN"}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The pixels of 8-bit `ImageData`, row by row from the top left, each a new
|
|
3
|
+
* object: `width × height` of them, none for an empty one. Its `colorSpace`
|
|
4
|
+
* says which RGB they are in; their colour is not premultiplied by alpha.
|
|
5
|
+
*
|
|
6
|
+
* Lazy, O(1) time per pixel, but one object allocated for each: on a full-HD
|
|
7
|
+
* image, several times slower than {@link forEachImageDataPixel}, which
|
|
8
|
+
* allocates nothing, and a load on the garbage collector. Reach for it where
|
|
9
|
+
* the pixels are kept as objects anyway.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* const colors = Array.from(imageDataPixels(imageData), (pixel) =>
|
|
13
|
+
* rgb8ToRgb1(pixel),
|
|
14
|
+
* );
|
|
15
|
+
*
|
|
16
|
+
* @param imageData `ImageData`, or anything holding its `data`.
|
|
17
|
+
* @throws {TypeError} When `data` is not a `Uint8ClampedArray` — `ImageData`
|
|
18
|
+
* with `pixelFormat: "rgba-float16"` holds a `Float16Array` — at the call,
|
|
19
|
+
* before any pixel.
|
|
20
|
+
*/
|
|
21
|
+
export function imageDataPixels(imageData) {
|
|
22
|
+
const { data } = imageData;
|
|
23
|
+
assertUint8Clamped_(data);
|
|
24
|
+
return pixels_(data);
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Calls `visit` with the components of each pixel of 8-bit `ImageData`, row by
|
|
28
|
+
* row from the top left, and its index in that order (`y × width + x`): never
|
|
29
|
+
* for an empty one. Its `colorSpace` says which RGB they are in; their colour
|
|
30
|
+
* is not premultiplied by alpha.
|
|
31
|
+
*
|
|
32
|
+
* O(1) time per pixel and no allocation of its own: the form for a loop over
|
|
33
|
+
* every pixel of a large image. {@link imageDataPixels} yields objects
|
|
34
|
+
* instead.
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* let opaque = 0;
|
|
38
|
+
* forEachImageDataPixel(imageData, (r8, g8, b8, a8) => {
|
|
39
|
+
* if (a8 === 255) opaque++;
|
|
40
|
+
* });
|
|
41
|
+
*
|
|
42
|
+
* @param imageData `ImageData`, or anything holding its `data`.
|
|
43
|
+
* @throws {TypeError} When `data` is not a `Uint8ClampedArray` — `ImageData`
|
|
44
|
+
* with `pixelFormat: "rgba-float16"` holds a `Float16Array` — before any
|
|
45
|
+
* pixel. What `visit` throws goes through, ending the loop.
|
|
46
|
+
*/
|
|
47
|
+
export function forEachImageDataPixel(imageData, visit) {
|
|
48
|
+
const { data } = imageData;
|
|
49
|
+
assertUint8Clamped_(data);
|
|
50
|
+
for (let offset = 0, index = 0; offset + 3 < data.length; offset += 4) {
|
|
51
|
+
visit(data[offset], data[offset + 1], data[offset + 2], data[offset + 3], index++);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function* pixels_(data) {
|
|
55
|
+
for (let offset = 0; offset + 3 < data.length; offset += 4) {
|
|
56
|
+
yield {
|
|
57
|
+
r8: data[offset],
|
|
58
|
+
g8: data[offset + 1],
|
|
59
|
+
b8: data[offset + 2],
|
|
60
|
+
a8: data[offset + 3],
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
// %TypedArray%.prototype[@@toStringTag] reads the internal [[TypedArrayName]]
|
|
65
|
+
// slot: true of a `Uint8ClampedArray` from any realm (an iframe's), unlike
|
|
66
|
+
// `instanceof`, and of nothing merely claiming the name.
|
|
67
|
+
const typedArrayName_ = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get;
|
|
68
|
+
// The typings say `Uint8ClampedArray` even of a `Float16Array`.
|
|
69
|
+
function assertUint8Clamped_(data) {
|
|
70
|
+
if (typedArrayName_.call(data) !== "Uint8ClampedArray") {
|
|
71
|
+
throw new TypeError("ImageData pixels are not 8-bit (rgba-unorm8)");
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
//# sourceMappingURL=image-data-pixels.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"image-data-pixels.js","sourceRoot":"","sources":["../../src/canvas/image-data-pixels.ts"],"names":[],"mappings":"AAaA;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,UAAU,eAAe,CAC9B,SAAkC;IAElC,MAAM,EAAE,IAAI,EAAE,GAAG,SAAS,CAAC;IAC3B,mBAAmB,CAAC,IAAI,CAAC,CAAC;IAE1B,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC;AACtB,CAAC;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,UAAU,qBAAqB,CACpC,SAAkC,EAClC,KAEC;IAED,MAAM,EAAE,IAAI,EAAE,GAAG,SAAS,CAAC;IAC3B,mBAAmB,CAAC,IAAI,CAAC,CAAC;IAC1B,KAAK,IAAI,MAAM,GAAG,CAAC,EAAE,KAAK,GAAG,CAAC,EAAE,MAAM,GAAG,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,MAAM,IAAI,CAAC,EAAE,CAAC;QACvE,KAAK,CACJ,IAAI,CAAC,MAAM,CAAE,EACb,IAAI,CAAC,MAAM,GAAG,CAAC,CAAE,EACjB,IAAI,CAAC,MAAM,GAAG,CAAC,CAAE,EACjB,IAAI,CAAC,MAAM,GAAG,CAAC,CAAE,EACjB,KAAK,EAAE,CACP,CAAC;IACH,CAAC;AACF,CAAC;AAED,QAAQ,CAAC,CAAC,OAAO,CAAC,IAAuB;IACxC,KAAK,IAAI,MAAM,GAAG,CAAC,EAAE,MAAM,GAAG,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,MAAM,IAAI,CAAC,EAAE,CAAC;QAC5D,MAAM;YACL,EAAE,EAAE,IAAI,CAAC,MAAM,CAAE;YACjB,EAAE,EAAE,IAAI,CAAC,MAAM,GAAG,CAAC,CAAE;YACrB,EAAE,EAAE,IAAI,CAAC,MAAM,GAAG,CAAC,CAAE;YACrB,EAAE,EAAE,IAAI,CAAC,MAAM,GAAG,CAAC,CAAE;SACrB,CAAC;IACH,CAAC;AACF,CAAC;AAED,8EAA8E;AAC9E,2EAA2E;AAC3E,yDAAyD;AACzD,MAAM,eAAe,GAAG,MAAM,CAAC,wBAAwB,CACtD,MAAM,CAAC,cAAc,CAAC,UAAU,CAAC,SAAS,CAAW,EACrD,MAAM,CAAC,WAAW,CACjB,CAAC,GAAI,CAAC;AAER,gEAAgE;AAChE,SAAS,mBAAmB,CAAC,IAAa;IACzC,IAAI,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,mBAAmB,EAAE,CAAC;QACxD,MAAM,IAAI,SAAS,CAAC,8CAA8C,CAAC,CAAC;IACrE,CAAC;AACF,CAAC"}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { type Callable } from "@ac-kit/core";
|
|
2
|
+
/**
|
|
3
|
+
* What {@link readImageData} draws: an image, a video's current frame, a
|
|
4
|
+
* canvas, an `ImageBitmap` or a `VideoFrame` — every `CanvasImageSource` but an
|
|
5
|
+
* SVG `<image>`, whose size in pixels it cannot tell.
|
|
6
|
+
*/
|
|
7
|
+
export type ImageDataSource = HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | OffscreenCanvas | ImageBitmap | VideoFrame;
|
|
8
|
+
/** The members of a 2D context {@link readImageData} draws and reads through. */
|
|
9
|
+
export type ImageDataContext = Pick<CanvasRenderingContext2D, "drawImage" | "getImageData" | "imageSmoothingEnabled" | "imageSmoothingQuality">;
|
|
10
|
+
/**
|
|
11
|
+
* A canvas {@link readImageData} draws on: an `HTMLCanvasElement`, an
|
|
12
|
+
* `OffscreenCanvas`, or a stand-in.
|
|
13
|
+
*/
|
|
14
|
+
export type ImageDataCanvas = {
|
|
15
|
+
getContext(contextId: "2d", settings?: CanvasRenderingContext2DSettings): ImageDataContext | null;
|
|
16
|
+
};
|
|
17
|
+
/** How {@link readImageData} draws the image before reading it. */
|
|
18
|
+
export type ReadImageDataOptions = {
|
|
19
|
+
/**
|
|
20
|
+
* The most pixels either side of the result may have, a positive integer. A
|
|
21
|
+
* larger source is drawn scaled down so that its longer side is `maxSize`,
|
|
22
|
+
* keeping its aspect ratio, its shorter side rounded and at least 1; a
|
|
23
|
+
* smaller one is drawn at its own size, never scaled up. It bounds what is
|
|
24
|
+
* drawn and read back, not what the browser decodes: the source is whole in
|
|
25
|
+
* memory already. Default: no limit but `maxSide` and `maxPixels`.
|
|
26
|
+
*/
|
|
27
|
+
readonly maxSize?: number;
|
|
28
|
+
/**
|
|
29
|
+
* The most pixels the result may have, a positive integer: a larger one
|
|
30
|
+
* throws rather than risk a canvas the browser cannot allocate, which reads
|
|
31
|
+
* back blank instead of failing. Default: 16,777,216 (4096 × 4096), the
|
|
32
|
+
* smallest canvas area current browsers allow (Safari on iOS); Chromium,
|
|
33
|
+
* Firefox and desktop Safari allow far more.
|
|
34
|
+
*/
|
|
35
|
+
readonly maxPixels?: number;
|
|
36
|
+
/**
|
|
37
|
+
* The most pixels either side of the result may have, a positive integer: a
|
|
38
|
+
* longer one throws, for the same reason as `maxPixels`. Unlike `maxSize`, it
|
|
39
|
+
* never scales. Default: 32,767, this library's conservative choice (2¹⁵ − 1,
|
|
40
|
+
* a side the major browsers all draw), not a limit of any one browser; raise
|
|
41
|
+
* it where the target browsers are known to draw wider canvases, as Chromium
|
|
42
|
+
* does.
|
|
43
|
+
*/
|
|
44
|
+
readonly maxSide?: number;
|
|
45
|
+
/**
|
|
46
|
+
* How the image is resampled when scaled: `false` for nearest neighbour, or
|
|
47
|
+
* the `imageSmoothingQuality` of a smoothed one (`"low"`, `"medium"`,
|
|
48
|
+
* `"high"`). Default: a fresh context's, smoothed at `"low"`.
|
|
49
|
+
*/
|
|
50
|
+
readonly smoothing?: false | ImageSmoothingQuality;
|
|
51
|
+
/**
|
|
52
|
+
* Given to `getContext("2d")` as they are, and so applied only by a canvas's
|
|
53
|
+
* first context. `colorSpace` is the space the pixels are converted to and
|
|
54
|
+
* returned in: `"display-p3"` keeps a wide-gamut image's colours, where the
|
|
55
|
+
* browser supports it.
|
|
56
|
+
*/
|
|
57
|
+
readonly contextSettings?: CanvasRenderingContext2DSettings;
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* The source has no pixels to draw yet: an image still loading, or broken; a
|
|
61
|
+
* video without its current frame; a closed `ImageBitmap` or `VideoFrame`; an
|
|
62
|
+
* empty canvas.
|
|
63
|
+
*/
|
|
64
|
+
export declare class ImageSourceUnavailableError extends Error {
|
|
65
|
+
constructor(options?: ErrorOptions);
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Reads the pixels of an image as `ImageData`, scaled down to fit `maxSize`
|
|
69
|
+
* when it is larger: for analysing an image's colours in a page or a worker
|
|
70
|
+
* without walking all of its pixels. The image is drawn once with `drawImage`
|
|
71
|
+
* on the canvas `createCanvas` returns, which is then read back whole.
|
|
72
|
+
*
|
|
73
|
+
* The pixels are the browser's resampling of the source, converted to the
|
|
74
|
+
* canvas's colour space (the result's `colorSpace`): 8-bit, not premultiplied
|
|
75
|
+
* by alpha. A canvas holds its colours premultiplied, so a translucent pixel's
|
|
76
|
+
* colour comes back quantized; the read is not lossless, even at full size.
|
|
77
|
+
*
|
|
78
|
+
* The source must be ready to draw: await `image.decode()` on an image,
|
|
79
|
+
* `"loadeddata"` on a video. What can be told synchronously is checked — an
|
|
80
|
+
* image not complete or broken, a video without a current frame, a source of no
|
|
81
|
+
* size — and throws; a source the browser cannot draw for another reason reads
|
|
82
|
+
* back transparent.
|
|
83
|
+
*
|
|
84
|
+
* Time and memory are linear in the pixels read, plus the browser's resampling
|
|
85
|
+
* of the source.
|
|
86
|
+
*
|
|
87
|
+
* @example
|
|
88
|
+
* const image = new Image();
|
|
89
|
+
* image.src = url;
|
|
90
|
+
* await image.decode();
|
|
91
|
+
* const imageData = readImageData(
|
|
92
|
+
* (width, height) => new OffscreenCanvas(width, height),
|
|
93
|
+
* image,
|
|
94
|
+
* { maxSize: 80, contextSettings: { colorSpace: "display-p3" } },
|
|
95
|
+
* );
|
|
96
|
+
*
|
|
97
|
+
* @param createCanvas Returns a fresh canvas `width` × `height` pixels large,
|
|
98
|
+
* as `(width, height) => new OffscreenCanvas(width, height)` does. A canvas
|
|
99
|
+
* drawn on before is cleared, and its context's state (transform, clip,
|
|
100
|
+
* compositing) reset, only by assigning its `width` and `height`; and it
|
|
101
|
+
* keeps the colour space of its first context whatever `contextSettings`
|
|
102
|
+
* say.
|
|
103
|
+
* @param source Its own size is read from `naturalWidth` and `naturalHeight`
|
|
104
|
+
* for an image, `videoWidth` and `videoHeight` for a video, `displayWidth`
|
|
105
|
+
* and `displayHeight` for a `VideoFrame`, and `width` and `height`
|
|
106
|
+
* otherwise.
|
|
107
|
+
* @returns `ImageData` of the size `source` was drawn at, in the canvas's
|
|
108
|
+
* colour space.
|
|
109
|
+
* @throws {ImageSourceUnavailableError} When `source` has no pixels to draw
|
|
110
|
+
* yet, before any canvas is created.
|
|
111
|
+
* @throws {RangeError} When `maxSize`, `maxPixels` or `maxSide` is not a
|
|
112
|
+
* positive integer, or the size to draw at exceeds `maxPixels` or `maxSide`;
|
|
113
|
+
* pass a `maxSize`, or raise them, then.
|
|
114
|
+
* @throws {UnsupportedError} When the canvas gives no 2D context.
|
|
115
|
+
* @throws A `DOMException` named `"SecurityError"` when `source` is a
|
|
116
|
+
* cross-origin image loaded without CORS, which the browser does not let a
|
|
117
|
+
* page read.
|
|
118
|
+
*/
|
|
119
|
+
export declare function readImageData(createCanvas: Callable<[width: number, height: number], ImageDataCanvas>, source: ImageDataSource, options?: ReadImageDataOptions): ImageData;
|
|
120
|
+
//# sourceMappingURL=read-image-data.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"read-image-data.d.ts","sourceRoot":"","sources":["../../src/canvas/read-image-data.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,QAAQ,EAAoB,MAAM,cAAc,CAAC;AAE/D;;;;GAIG;AACH,MAAM,MAAM,eAAe,GACxB,gBAAgB,GAChB,gBAAgB,GAChB,iBAAiB,GACjB,eAAe,GACf,WAAW,GACX,UAAU,CAAC;AAEd,iFAAiF;AACjF,MAAM,MAAM,gBAAgB,GAAG,IAAI,CAClC,wBAAwB,EACtB,WAAW,GACX,cAAc,GACd,uBAAuB,GACvB,uBAAuB,CACzB,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,eAAe,GAAG;IAC7B,UAAU,CACT,SAAS,EAAE,IAAI,EACf,QAAQ,CAAC,EAAE,gCAAgC,GACzC,gBAAgB,GAAG,IAAI,CAAC;CAC3B,CAAC;AAEF,mEAAmE;AACnE,MAAM,MAAM,oBAAoB,GAAG;IAClC;;;;;;;OAOG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B;;;;;;OAMG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B;;;;;;;OAOG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B;;;;OAIG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,KAAK,GAAG,qBAAqB,CAAC;IACnD;;;;;OAKG;IACH,QAAQ,CAAC,eAAe,CAAC,EAAE,gCAAgC,CAAC;CAC5D,CAAC;AAEF;;;;GAIG;AACH,qBAAa,2BAA4B,SAAQ,KAAK;IACrD,YAAY,OAAO,CAAC,EAAE,YAAY,EAGjC;CACD;AAOD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmDG;AACH,wBAAgB,aAAa,CAC5B,YAAY,EAAE,QAAQ,CAAC,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,eAAe,CAAC,EACxE,MAAM,EAAE,eAAe,EACvB,OAAO,CAAC,EAAE,oBAAoB,GAC5B,SAAS,CAwDX"}
|