stork-live 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
package/README.md CHANGED
@@ -1,3 +1,125 @@
1
- # Temporary Holding Version
1
+ # Stork Live
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A talking avatar that the browser draws itself.
4
+
5
+ The avatar is a file of about 8 MB. Once it has loaded, the page needs 16 numbers per video frame to make it speak.
6
+ There is no video stream and no rendering server.
7
+
8
+ > Status: version 0.1. Numbers below were measured on 2026-12-01 and 2026-12-02.
9
+
10
+ ## Use it
11
+
12
+ ```html
13
+ <canvas id="avatar"></canvas>
14
+ <script type="module">
15
+ import { StorkLive } from 'https://cdn.jsdelivr.net/npm/stork-live@0.1/src/stork-live.js' // or: npm install stork-live, then import from 'stork-live'
16
+
17
+ // 'a', 'b', 'c', 'd' are faces from Stork's free library. No key, no account.
18
+ const live = await StorkLive.mount(document.getElementById('avatar'), { avatar: 'a' })
19
+
20
+ // lips follow any sound you give it: an <audio> element, a WebRTC track or stream, or an AudioBuffer
21
+ await live.speak(document.querySelector('audio'))
22
+ </script>
23
+ ```
24
+
25
+ In React:
26
+
27
+ ```jsx
28
+ import { StorkLiveAvatar } from 'stork-live/react'
29
+ <StorkLiveAvatar avatar="a" audio={agentAudioTrack} style={{ width: 360 }} />
30
+ ```
31
+
32
+ For LiveKit, Pipecat and OpenAI Realtime see [docs/voice-agents.md](docs/voice-agents.md).
33
+
34
+ Between calls to `speak` she blinks, moves her head and keeps her mouth at rest. That part needs nothing from a server.
35
+
36
+ | Call | What it does |
37
+ |---|---|
38
+ | `StorkLive.mount(canvas, options)` | Loads the avatar and starts drawing. Returns when the first frame is on screen. |
39
+ | `live.speak(source)` | Plays the sound and moves the lips in step with it. Resolves when the sound ends. |
40
+ | `live.stop()` | Stops speaking; the avatar goes back to idling. |
41
+ | `live.destroy()` | Stops drawing and frees the worker. |
42
+
43
+ Options for `mount`:
44
+
45
+ | Option | Meaning |
46
+ |---|---|
47
+ | `avatar` | A library face by name (`'a'`), or the address of your own avatar file (`…/name` for `name.json` + `name.bin`). |
48
+ | `motion` | Default `{ local: true }`: a small model in the page, no server. `{ server: 'wss://…' }` uses a motion server instead. |
49
+ | `delay` | Seconds the sound is held back so lips and voice line up. Default about 0.3 for the in-page model, 0.7 for a server. |
50
+
51
+ ## Where the mouth numbers come from
52
+
53
+ Two interchangeable sources:
54
+
55
+ - **A model in the page** (`src/local-motion.js`, the default). A network of 0.88 million parameters turns the sound into the 16 mouth numbers on the device, 155 ms ahead of what it shows. It is plain JavaScript: no WebAssembly and no ML runtime. Nothing leaves the device and there is nothing to pay per minute. The model file is 3.3 MB compressed.
56
+ - **A motion server.** Speech goes up a WebSocket as it is spoken, the numbers come back. Useful when the page cannot run the model.
57
+
58
+ Any avatar can be driven by either. Avatars other than the first presenter carry a small translation table, so one motion model serves every face.
59
+
60
+ ## Driving it from a voice agent
61
+
62
+ `speak` takes whatever the agent's voice arrives as:
63
+
64
+ ```js
65
+ // a WebRTC or LiveKit audio track
66
+ await live.speak(new MediaStream([remoteAudioTrack]))
67
+
68
+ // a text-to-speech reply fetched as a file
69
+ const clip = await audioContext.decodeAudioData(await (await fetch(ttsUrl)).arrayBuffer())
70
+ await live.speak(clip)
71
+ ```
72
+
73
+ The avatar plays the sound itself, delayed by about a third of a second so the lips line up. Mute the original element or track so it is not heard twice.
74
+
75
+ ## In an app
76
+
77
+ The renderer is a web page, so on iOS and Android it runs inside the system web view: `WKWebView` on iOS, `WebView` on Android, with the page and avatar files bundled in the app or loaded from a server. It needs WebGL2, which every phone from the last several years has.
78
+
79
+ ## Measured
80
+
81
+ | | Result |
82
+ |---|---|
83
+ | Avatar download | 8.1 to 8.5 MB (compressed transfer) |
84
+ | In-page motion model | 3.3 MB compressed; about 20 ms of processor time per second of speech |
85
+ | Lip movement against FlashHead on 18 unseen clips | 0.71 for the in-page model; FlashHead agrees with itself at about 0.90 |
86
+ | Draw rate, iPhone 15 Pro Max, Safari | 60 frames a second |
87
+ | Draw rate, Pixel 6 Pro, Chrome | 60 frames a second |
88
+ | Picture against the reference GPU renderer | 45 dB (compact file), 52 dB (full file) |
89
+
90
+ ## How it is built
91
+
92
+ - The avatar is about 137,600 small 3D Gaussians. Half are attached to a face mesh of 478 tracked points plus a short skirt past the jawline; the rest carry hair, neck, shoulders and background.
93
+ - 19 controls (16 mouth, 3 eyes) and 7 head-pose numbers set the mesh. Each Gaussian follows its triangle.
94
+ - A tiny network turns the controls into 24 blend weights, which mix stored offsets for the Gaussians that move with the face.
95
+ - The graphics chip does all of that in one vertex shader. JavaScript only moves the mesh and sorts the Gaussians back to front, in a worker.
96
+
97
+ ## Files
98
+
99
+ | File | Purpose |
100
+ |---|---|
101
+ | `src/stork-live.js` | The public API, idle behaviour, audio timing. |
102
+ | `src/gpu.js` | The WebGL2 renderer. |
103
+ | `src/order.js`, `src/orderWorker.js` | Back-to-front draw order, off the main thread. |
104
+ | `src/pack.js` | Loader for avatar and model packs. |
105
+ | `src/local-motion.js` | The in-page motion model. |
106
+ | `assets/idle.*` | Head-movement track, resting mouth, eye shapes. |
107
+ | `assets/motion.*` | The in-page motion model's weights. |
108
+ | `examples/` | A page with a sample sentence and a microphone demo. |
109
+
110
+ ## Free and paid
111
+
112
+ | | Price | What it is |
113
+ |---|---|---|
114
+ | Free | $0 | Stork's presenter library. Unlimited minutes and viewers, no account, no key. The picture carries "Powered by stork.ai", with Stork's bird landing on it |
115
+ | Your own avatar | $29 a month, flat | A face of your own, from a photo or made for you, without the Stork name. Any traffic |
116
+
117
+ The mark is part of the free avatar file, and free avatars may only be shown with it. Avatar files say they are AI-generated (`__format.ai_generated`); in the EU, people must also be told when they are talking to an AI, which is the page owner's job once the Stork mark is gone.
118
+
119
+ ## The avatar file format
120
+
121
+ Version 1 is frozen. A file made today will be read by every later version of this client, and you may host avatar files yourself.
122
+
123
+ ## Licence
124
+
125
+ Apache-2.0 for the code in this folder. Avatar files are licensed separately: free library avatars carry the Stork mark inside the file and may be used only with the mark showing; your own avatar files have no mark.
Binary file
@@ -0,0 +1 @@
1
+ {"head": {"dtype": "float32", "shape": [2500, 7], "offset": 0, "bytes": 70000}, "rest": {"dtype": "float32", "shape": [16], "offset": 70000, "bytes": 64}, "eye_open": {"dtype": "float32", "shape": [3], "offset": 70064, "bytes": 12}, "eye_closed": {"dtype": "float32", "shape": [3], "offset": 70076, "bytes": 12}}
Binary file
@@ -0,0 +1 @@
1
+ {"pill": [180.0, 38.0], "disc": [19.0, 19.0, 13.0], "bird_disc": [220.0, 127.5, 129.0], "bird": [350, 256]}
Binary file
Binary file
@@ -0,0 +1 @@
1
+ {"meta": {"dtype": "float32", "shape": [2], "offset": 0, "bytes": 8}, "fb": {"dtype": "float32", "shape": [80, 257], "offset": 8, "bytes": 82240}, "mmu": {"dtype": "float32", "shape": [80], "offset": 82248, "bytes": 320}, "msd": {"dtype": "float32", "shape": [80], "offset": 82568, "bytes": 320}, "ymu": {"dtype": "float32", "shape": [16], "offset": 82888, "bytes": 64}, "ysd": {"dtype": "float32", "shape": [16], "offset": 82952, "bytes": 64}, "gain": {"dtype": "float32", "shape": [16], "offset": 83016, "bytes": 64}, "c1w": {"dtype": "float32", "shape": [128, 80, 4], "offset": 83080, "bytes": 163840}, "c1b": {"dtype": "float32", "shape": [128], "offset": 246920, "bytes": 512}, "c2w": {"dtype": "float32", "shape": [192, 128, 4], "offset": 247432, "bytes": 393216}, "c2b": {"dtype": "float32", "shape": [192], "offset": 640648, "bytes": 768}, "g0wi": {"dtype": "float32", "shape": [768, 192], "offset": 641416, "bytes": 589824}, "g0wh": {"dtype": "float32", "shape": [768, 256], "offset": 1231240, "bytes": 786432}, "g0bi": {"dtype": "float32", "shape": [768], "offset": 2017672, "bytes": 3072}, "g0bh": {"dtype": "float32", "shape": [768], "offset": 2020744, "bytes": 3072}, "g1wi": {"dtype": "float32", "shape": [768, 256], "offset": 2023816, "bytes": 786432}, "g1wh": {"dtype": "float32", "shape": [768, 256], "offset": 2810248, "bytes": 786432}, "g1bi": {"dtype": "float32", "shape": [768], "offset": 3596680, "bytes": 3072}, "g1bh": {"dtype": "float32", "shape": [768], "offset": 3599752, "bytes": 3072}, "ow": {"dtype": "float32", "shape": [16, 256], "offset": 3602824, "bytes": 16384}, "ob": {"dtype": "float32", "shape": [16], "offset": 3619208, "bytes": 64}}
package/llms.txt ADDED
@@ -0,0 +1,34 @@
1
+ # Stork Live
2
+
3
+ > A talking human avatar drawn in the browser. Give it any audio and the lips follow. No server, no API key, no account, no per-minute fee.
4
+
5
+ Use it when a page, app or voice agent should have a face that speaks.
6
+
7
+ ## Facts
8
+
9
+ - Install: `npm install stork-live` (plain ES modules, no build step needed; React component at `stork-live/react`)
10
+ - No install: `import { StorkLive } from 'https://cdn.jsdelivr.net/npm/stork-live@0.1/src/stork-live.js'` works in any page
11
+ - No sign-up and no key: the avatar is a file the browser downloads once (about 8 MB) and draws itself with WebGL2
12
+ - The lip model runs in the page (0.88 million parameters, plain JavaScript, 3.3 MB). Audio never leaves the device
13
+ - Free: Stork's presenter library (`avatar: 'a'`, `'b'`, `'c'`, `'d'`), unlimited minutes and viewers. Free avatars show "Powered by stork.ai"
14
+ - Paid: your own avatar without the Stork name, $29 a month flat, any traffic
15
+ - Works with any voice source: a WebRTC track (LiveKit, Pipecat, OpenAI Realtime), an audio element, a decoded clip, a microphone
16
+ - Runs in Chrome, Safari and mobile browsers; in native apps through the system web view
17
+ - Licence: client code Apache-2.0; avatar files licensed separately
18
+
19
+ ## Quickstart
20
+
21
+ ```html
22
+ <canvas id="face" style="width:360px;aspect-ratio:1"></canvas>
23
+ <script type="module">
24
+ import { StorkLive } from 'stork-live'
25
+ const live = await StorkLive.mount(document.getElementById('face'), { avatar: 'a' })
26
+ // she idles on her own; make her speak with any audio:
27
+ await live.speak(audioElementOrTrackOrBuffer)
28
+ </script>
29
+ ```
30
+
31
+ ## Docs
32
+
33
+ - [README](README.md): options, methods, measurements
34
+ - [Voice agents](docs/voice-agents.md): LiveKit, Pipecat, OpenAI Realtime
package/package.json CHANGED
@@ -1,6 +1,14 @@
1
1
  {
2
2
  "name": "stork-live",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "A talking avatar drawn in the browser. Lips follow any audio. No server, no API key.",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "homepage": "https://stork.ai",
8
+ "repository": { "type": "git", "url": "git+https://github.com/jupiterspins/stork-live.git" },
9
+ "exports": { ".": "./src/stork-live.js", "./react": "./src/react.js" },
10
+ "files": ["src", "assets", "README.md", "LICENSE", "llms.txt"],
11
+ "keywords": ["avatar", "talking avatar", "lip sync", "voice agent", "gaussian splatting", "webgl", "livekit", "pipecat", "realtime"],
12
+ "peerDependencies": { "react": ">=17" },
13
+ "peerDependenciesMeta": { "react": { "optional": true } }
14
+ }
package/src/gpu.js ADDED
@@ -0,0 +1,332 @@
1
+ // Stork Live prototype, GPU path: the graphics chip rebuilds the Gaussians itself.
2
+ // Per frame the processor only does: 478 mesh vertices, ~900 triangle frames, 24 blend weights, one depth per Gaussian, a sort.
3
+ // Pass 1 mixes the stored offsets (24 fetches per output texel) into a small float texture.
4
+ // Pass 2 draws the splats; its vertex shader places each Gaussian (mesh-bound or free), adds its offsets, and projects it.
5
+
6
+ import { depthFace, depthFree, exactZ, sortBackToFront } from './order.js'
7
+ const silu = (x) => x / (1 + Math.exp(-x))
8
+
9
+ const VS_FULL = `#version 300 es
10
+ void main() { vec2 p = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2)); gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0); }`
11
+
12
+ const FS_OFF = `#version 300 es
13
+ precision highp float; precision highp int; precision highp sampler2DArray;
14
+ uniform sampler2DArray uB; uniform vec4 uCk[96]; out vec4 o;
15
+ void main() {
16
+ ivec2 xy = ivec2(gl_FragCoord.xy); int g = xy.x & 3; vec4 s = vec4(0.0);
17
+ for (int k = 0; k < 24; k++) s += uCk[k * 4 + g] * texelFetch(uB, ivec3(xy, k), 0);
18
+ o = s;
19
+ }`
20
+
21
+ const VS = `#version 300 es
22
+ precision highp float; precision highp int; precision highp sampler2D;
23
+ uniform sampler2D uStat, uTri, uOff; uniform float uSize, uC, uD, uS; uniform mat3 uR; uniform vec3 uTw;
24
+ layout(location=0) in vec2 aCorner; layout(location=1) in uint aIndex;
25
+ out vec2 vCenter; out vec3 vConic; out vec4 vColor;
26
+ vec4 st(int i, int k) { int t = i * 5 + k; return texelFetch(uStat, ivec2(t & 2047, t >> 11), 0); }
27
+ vec4 tr(int i, int k) { int t = i * 8 + k; return texelFetch(uTri, ivec2(t & 1023, t >> 10), 0); }
28
+ vec4 of(int i, int k) { int t = i * 4 + k; return texelFetch(uOff, ivec2(t & 1023, t >> 10), 0); }
29
+ float sig(float x) { return 1.0 / (1.0 + exp(-x)); }
30
+ void main() {
31
+ int i = int(aIndex);
32
+ vec4 s0 = st(i, 0), s1 = st(i, 1), s2 = st(i, 2), s3 = st(i, 3), s4 = st(i, 4);
33
+ vec3 p; vec4 q;
34
+ if (s4.w < 0.5) { // bound to a triangle of the face mesh
35
+ int t = int(s0.w + 0.5);
36
+ vec4 a = tr(t, 0), b = tr(t, 1), c = tr(t, 2), e1 = tr(t, 3), e2 = tr(t, 4), n = tr(t, 5);
37
+ p = s0.x * a.xyz + s0.y * b.xyz + s0.z * c.xyz + e1.xyz * s1.x + e2.xyz * s1.y + n.xyz * s1.z;
38
+ vec4 q1 = vec4(a.w, b.w, c.w, e1.w), q2 = s2; // wxyz
39
+ q = vec4(q1.x * q2.x - q1.y * q2.y - q1.z * q2.z - q1.w * q2.w, q1.x * q2.y + q1.y * q2.x + q1.z * q2.w - q1.w * q2.z,
40
+ q1.x * q2.z - q1.y * q2.w + q1.z * q2.x + q1.w * q2.y, q1.x * q2.w + q1.y * q2.z - q1.z * q2.y + q1.w * q2.x);
41
+ } else { // free: follows the head by its weight
42
+ vec3 r = s0.xyz, m = uS * (uR * vec3(r.xy, r.z - uD)) + uTw + vec3(0.0, 0.0, uD);
43
+ p = mix(r, m, s0.w); q = s2;
44
+ }
45
+ vec3 ls = s3.xyz, col = s4.xyz; float op = s1.w;
46
+ int ai = int(s3.w + 0.5) - 1;
47
+ if (ai >= 0) {
48
+ vec4 o0 = of(ai, 0), o1 = of(ai, 1), o2 = of(ai, 2), o3 = of(ai, 3);
49
+ p += 6.0 * tanh(o0.xyz); ls += 0.35 * tanh(vec3(o0.w, o1.x, o1.y)); q += 0.2 * vec4(o1.z, o1.w, o2.x, o2.y);
50
+ col += 2.0 * tanh(vec3(o2.z, o2.w, o3.x)); op += 2.0 * tanh(o3.y);
51
+ }
52
+ q = normalize(q); vec3 s = clamp(exp(ls), 0.3, 60.0);
53
+ float w = q.x, x = q.y, y = q.z, z = q.w;
54
+ mat3 R = mat3(1.0 - 2.0 * (y * y + z * z), 2.0 * (x * y + w * z), 2.0 * (x * z - w * y),
55
+ 2.0 * (x * y - w * z), 1.0 - 2.0 * (x * x + z * z), 2.0 * (y * z + w * x),
56
+ 2.0 * (x * z + w * y), 2.0 * (y * z - w * x), 1.0 - 2.0 * (x * x + y * y));
57
+ mat3 M = R * mat3(s.x, 0.0, 0.0, 0.0, s.y, 0.0, 0.0, 0.0, s.z);
58
+ mat3 S3 = M * transpose(M);
59
+ float iz = 1.0 / p.z, f = uD;
60
+ vec3 j0 = vec3(f * iz, 0.0, -f * p.x * iz * iz), j1 = vec3(0.0, f * iz, -f * p.y * iz * iz);
61
+ vec3 t0 = S3 * j0, t1 = S3 * j1;
62
+ float A = dot(j0, t0) + 0.3, B = dot(j0, t1), Cc = dot(j1, t1) + 0.3, det = A * Cc - B * B;
63
+ if (det <= 0.0 || p.z < 10.0) { gl_Position = vec4(2.0, 2.0, 2.0, 1.0); return; }
64
+ vConic = vec3(Cc, -B, A) / det;
65
+ float mid = 0.5 * (A + Cc), lam = mid + sqrt(max(0.1, mid * mid - det)), radius = ceil(3.33 * sqrt(lam));
66
+ vCenter = vec2(f * p.x * iz + uC, f * p.y * iz + uC);
67
+ vColor = vec4(vec3(sig(col.x), sig(col.y), sig(col.z)), sig(op));
68
+ vec2 px = vCenter + aCorner * radius;
69
+ gl_Position = vec4(px.x / uSize * 2.0 - 1.0, 1.0 - px.y / uSize * 2.0, 0.0, 1.0);
70
+ }`
71
+ const FS = `#version 300 es
72
+ precision highp float;
73
+ uniform float uSize;
74
+ in vec2 vCenter; in vec3 vConic; in vec4 vColor; out vec4 o;
75
+ void main() {
76
+ vec2 d = vec2(gl_FragCoord.x, uSize - gl_FragCoord.y) - vCenter;
77
+ float sigma = 0.5 * (vConic.x * d.x * d.x + vConic.z * d.y * d.y) + vConic.y * d.x * d.y;
78
+ if (sigma < 0.0) discard;
79
+ float alpha = min(0.999, vColor.a * exp(-sigma));
80
+ if (alpha < 1.0 / 255.0) discard;
81
+ o = vec4(vColor.rgb * alpha, alpha);
82
+ }`
83
+ const FS_COPY = `#version 300 es
84
+ precision highp float; uniform sampler2D uImg, uWm; uniform vec4 uWmRect; uniform float uWmOn; out vec4 o;
85
+ void main() {
86
+ vec3 c = texelFetch(uImg, ivec2(gl_FragCoord.xy), 0).rgb;
87
+ vec2 uv = (gl_FragCoord.xy - uWmRect.xy) / uWmRect.zw; // the free tier's mark is composited here, in the same pass that puts the picture on screen
88
+ if (uWmOn > 0.5 && uv.x >= 0.0 && uv.x <= 1.0 && uv.y >= 0.0 && uv.y <= 1.0) { vec4 w = texture(uWm, vec2(uv.x, 1.0 - uv.y)); c = mix(c, w.rgb, w.a); }
89
+ o = vec4(c, 1.0);
90
+ }`
91
+
92
+ function prog(gl, vs, fs) {
93
+ const p = gl.createProgram()
94
+ for (const [t, src] of [[gl.VERTEX_SHADER, vs], [gl.FRAGMENT_SHADER, fs]]) {
95
+ const s = gl.createShader(t); gl.shaderSource(s, src); gl.compileShader(s)
96
+ if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s))
97
+ gl.attachShader(p, s)
98
+ }
99
+ gl.linkProgram(p); if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(p))
100
+ const u = {}; const n = gl.getProgramParameter(p, gl.ACTIVE_UNIFORMS)
101
+ for (let i = 0; i < n; i++) { const nm = gl.getActiveUniform(p, i).name.replace('[0]', ''); u[nm] = gl.getUniformLocation(p, nm) }
102
+ return { p, u }
103
+ }
104
+ function ftex(gl, w, h, internal, format, type, data) {
105
+ const t = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, t); gl.texImage2D(gl.TEXTURE_2D, 0, internal, w, h, 0, format, type, data)
106
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
107
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
108
+ return t
109
+ }
110
+
111
+ export class GpuAvatar {
112
+ constructor(canvas, A, opt = {}) {
113
+ this.opt = opt
114
+ const gl = this.gl = canvas.getContext('webgl2', { antialias: false, alpha: false, premultipliedAlpha: false, preserveDrawingBuffer: true, powerPreference: 'high-performance' })
115
+ if (!gl) throw new Error('no WebGL2')
116
+ if (!gl.getExtension('EXT_color_buffer_float') && !gl.getExtension('EXT_color_buffer_half_float')) throw new Error('no float render target')
117
+ this.A = A
118
+ const [SIZE, C, D, fps, zdim, NF, NR] = A.meta
119
+ Object.assign(this, { SIZE, C, D, fps, zdim, NF, NR, N: NF + NR })
120
+ const N = this.N, K = this.K = A.__shape.Bq[1], NA = this.NA = A.act.length
121
+ if (K !== 24) throw new Error('shader is written for 24 blend sets')
122
+ this.KM = A.__shape.rig_Bm[0]; this.KE = A.__shape.rig_Be[0]; this.NB = this.KM + this.KE; this.NV = A.__shape.rig_mean[0]; this.NT = A.__shape.tri[0]
123
+ const e = gl.getExtension('WEBGL_debug_renderer_info'); this.gpu = e ? gl.getParameter(e.UNMASKED_RENDERER_WEBGL) : 'unknown'
124
+ // ---- static per-Gaussian data: 5 texels each
125
+ const actOf = new Int32Array(N).fill(-1); for (let a = 0; a < NA; a++) actOf[A.act[a]] = a
126
+ this.sH = Math.ceil(N * 5 / 2048); const sd = new Float32Array(2048 * this.sH * 4)
127
+ for (let i = 0; i < N; i++) {
128
+ const b = i * 20, face = i < NF, j = i - NF
129
+ if (face) { sd[b] = A.bary[i * 3]; sd[b + 1] = A.bary[i * 3 + 1]; sd[b + 2] = A.bary[i * 3 + 2]; sd[b + 3] = A.tid[i]
130
+ sd[b + 4] = A.f_off[i * 3]; sd[b + 5] = A.f_off[i * 3 + 1]; sd[b + 6] = A.f_off[i * 3 + 2]; sd[b + 7] = A.f_op[i]
131
+ for (let d = 0; d < 4; d++) sd[b + 8 + d] = A.f_q[i * 4 + d]
132
+ for (let d = 0; d < 3; d++) { sd[b + 12 + d] = A.f_ls[i * 3 + d]; sd[b + 16 + d] = A.f_col[i * 3 + d] }
133
+ } else { sd[b] = A.r_pos[j * 3]; sd[b + 1] = A.r_pos[j * 3 + 1]; sd[b + 2] = A.r_pos[j * 3 + 2]; sd[b + 3] = A.r_w[j]; sd[b + 7] = A.r_op[j]
134
+ for (let d = 0; d < 4; d++) sd[b + 8 + d] = A.r_q[j * 4 + d]
135
+ for (let d = 0; d < 3; d++) { sd[b + 12 + d] = A.r_ls[j * 3 + d]; sd[b + 16 + d] = A.r_col[j * 3 + d] }
136
+ }
137
+ sd[b + 15] = actOf[i] + 1; sd[b + 19] = face ? 0 : 1
138
+ }
139
+ this.tStat = ftex(gl, 2048, this.sH, gl.RGBA32F, gl.RGBA, gl.FLOAT, sd)
140
+ // ---- the stored offsets: one layer per blend set, 4 texels (16 slots, 14 used) per moving Gaussian, signed bytes
141
+ this.oH = Math.ceil(NA * 4 / 1024); const bq = new Int8Array(1024 * this.oH * 4 * K), Bq = A.Bq
142
+ // size experiments (address-bar options): drop whole attributes, keep fewer bits, keep only the strongest blend sets
143
+ const dropAttr = new Uint8Array(14); for (const d of (opt.drop || [])) dropAttr[d] = 1
144
+ const shift = 8 - (opt.bits || 8), keepSet = new Uint8Array(K).fill(1)
145
+ if (opt.sets && opt.sets < K) { const en = []; for (let k = 0; k < K; k++) { let e = 0; for (let n = 0; n < NA; n += 7) for (let c = 0; c < 14; c++) { const v = Bq[(n * K + k) * 14 + c] * A.Bscale[k * 14 + c]; e += v * v } en.push([e, k]) } en.sort((x, y) => y[0] - x[0]); keepSet.fill(0); for (let i = 0; i < opt.sets; i++) keepSet[en[i][1]] = 1 }
146
+ const qz = (v, k, c) => (dropAttr[c] || !keepSet[k]) ? 0 : (shift ? Math.max(-127, Math.min(127, Math.round(v / (1 << shift)) * (1 << shift))) : v)
147
+ for (let k = 0; k < K; k++) { const lo = k * 1024 * this.oH * 4; for (let n = 0; n < NA; n++) { const s = (n * K + k) * 14, d = lo + n * 16; for (let c = 0; c < 14; c++) bq[d + c] = qz(Bq[s + c], k, c) } }
148
+ this.tB = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D_ARRAY, this.tB)
149
+ gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, gl.RGBA8_SNORM, 1024, this.oH, K, 0, gl.RGBA, gl.BYTE, bq)
150
+ gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
151
+ this.tOff = opt.f32 ? ftex(gl, 1024, this.oH, gl.RGBA32F, gl.RGBA, gl.FLOAT, null) : ftex(gl, 1024, this.oH, gl.RGBA16F, gl.RGBA, gl.HALF_FLOAT, null)
152
+ this.fOff = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, this.fOff); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.tOff, 0)
153
+ if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) throw new Error('offset target not usable')
154
+ // ---- per-frame triangle data: 8 texels per triangle
155
+ this.tH = Math.ceil(this.NT * 8 / 1024); this.triData = new Float32Array(1024 * this.tH * 4)
156
+ this.tTri = ftex(gl, 1024, this.tH, gl.RGBA32F, gl.RGBA, gl.FLOAT, this.triData)
157
+ // ---- picture target (16-bit float so thin layers do not band)
158
+ this.tImg = ftex(gl, SIZE, SIZE, gl.RGBA16F, gl.RGBA, gl.HALF_FLOAT, null)
159
+ this.fImg = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, this.fImg); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.tImg, 0)
160
+ if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) throw new Error('picture target not usable')
161
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null)
162
+ this.pOff = prog(gl, VS_FULL, FS_OFF); this.pDraw = prog(gl, VS, FS); this.pCopy = prog(gl, VS_FULL, FS_COPY)
163
+ this.vao = gl.createVertexArray(); gl.bindVertexArray(this.vao)
164
+ const quad = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, quad); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW)
165
+ gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0)
166
+ this.order = new Uint32Array(N); this.ibuf = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.ibuf); gl.bufferData(gl.ARRAY_BUFFER, this.order.byteLength, gl.DYNAMIC_DRAW)
167
+ gl.enableVertexAttribArray(1); gl.vertexAttribIPointer(1, 1, gl.UNSIGNED_INT, 0, 0); gl.vertexAttribDivisor(1, 1)
168
+ this.vaoNone = gl.createVertexArray()
169
+ // scratch
170
+ this.can = new Float32Array(this.NV * 3); this.V = new Float32Array(this.NV * 3); this.zs = new Float32Array(N)
171
+ this.keys = new Uint16Array(N); this.counts = new Uint32Array(65536); this.cond = new Float32Array(this.NB + 7 + zdim); this.ck = new Float32Array(96 * 4)
172
+ this.R = new Float32Array(9); this.t = [0, 0, 0]; this.fc = 0; this.c2 = new Float32Array(K); this.haveOrder = false; this.busy = false; this.lag = [0, 0, 0] // [orders applied, frames of lag summed, worker ms summed]
173
+ // depth offsets only (one byte per blend set per moving Gaussian), for the draw order
174
+ const Bz = new Int8Array(NA * K); for (let n = 0; n < NA; n++) for (let k = 0; k < K; k++) Bz[n * K + k] = qz(A.Bq[(n * K + k) * 14 + 2], k, 2)
175
+ const keep = ['rig_mean', 'rig_lower', 'rig_eyes', 'rig_Bm', 'rig_Be', 'rig_std', 'tri', 'W0', 'b0', 'W1', 'b1', 'W2', 'b2', 'Bscale']
176
+ this.skirt = A.meta[7] || 0; this.skIdx = A.skirt_idx ? A.skirt_idx.slice() : new Int32Array(0); this.nSk = this.skirt > 0 ? this.skIdx.length : 0
177
+ this.V = new Float32Array((this.NV + this.nSk) * 3)
178
+ const ord = { tid: A.tid.slice(), bary: A.bary.slice(), f_off: A.f_off.slice(), r_pos: A.r_pos.slice(), r_w: A.r_w.slice(), act: A.act.slice(), Bz, NF, NR, NA, K, D }
179
+ // from here on keep only small copies, so the 27 MB download buffer and the upload staging arrays can be freed
180
+ const small = {}; for (const k of keep) small[k] = A[k].slice(); this.A = small
181
+ if (!opt.worker) this.ord = ord
182
+ if (opt.worker) {
183
+ const wu = new URL('./orderWorker.js', import.meta.url)
184
+ // a page may not start a worker from another site (a CDN, say), so in that case start one that imports it
185
+ try { this.worker = new Worker(wu, { type: 'module' }) } catch (e) { this.worker = new Worker(URL.createObjectURL(new Blob([`import ${JSON.stringify(wu.href)}`], { type: 'text/javascript' })), { type: 'module' }) }
186
+ this.worker.postMessage({ init: ord }, [ord.tid.buffer, ord.bary.buffer, ord.f_off.buffer, ord.r_pos.buffer, ord.r_w.buffer, ord.act.buffer, ord.Bz.buffer])
187
+ this.worker.onmessage = (e) => {
188
+ const m = e.data; if (m.ready) { this.workerReady = true; if (this.onWorkerReady) this.onWorkerReady(); return }
189
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.ibuf); gl.bufferSubData(gl.ARRAY_BUFFER, 0, m.order)
190
+ this.lag[0]++; this.lag[1] += this.fc - 1 - m.seq; this.lag[2] += m.ms; this.applied = m.seq; this.busy = false; this.haveOrder = true
191
+ if (this.waiters) { const w = this.waiters; this.waiters = null; w.forEach((f) => f()) }
192
+ }
193
+ }
194
+ }
195
+
196
+ frame(bs, pose) {
197
+ const t0 = performance.now(); const A = this.A, gl = this.gl, { C, D, NF, NR, NV, NT, KM, KE, K, N } = this
198
+ const P = this.parts = this.parts || new Float64Array(8); let tp = t0; const lap = (i) => { const n = performance.now(); P[i] += n - tp; tp = n }; P[7]++
199
+ // ---- head transform
200
+ const rx = pose[0] / 5, ry = pose[1] / 5, rz = pose[2] / 5, th = Math.hypot(rx, ry, rz), R = this.R
201
+ if (th < 1e-8) { R.fill(0); R[0] = R[4] = R[8] = 1 } else {
202
+ const x = rx / th, y = ry / th, z = rz / th, c = Math.cos(th), s = Math.sin(th), t = 1 - c
203
+ R[0] = c + x * x * t; R[1] = x * y * t - z * s; R[2] = x * z * t + y * s; R[3] = y * x * t + z * s; R[4] = c + y * y * t; R[5] = y * z * t - x * s; R[6] = z * x * t - y * s; R[7] = z * y * t + x * s; R[8] = c + z * z * t
204
+ }
205
+ const tx = pose[3] * 50, ty = pose[4] * 50, tz = pose[5] * 50, sc = 1 + pose[6] / 10
206
+ // ---- face mesh from the controls, posed, in world units
207
+ const can = this.can; can.set(A.rig_mean); const lower = A.rig_lower, eyes = A.rig_eyes, std = A.rig_std
208
+ for (let k = 0; k < KM; k++) { const w = bs[k] * std[k], o = k * lower.length * 3; for (let i = 0; i < lower.length; i++) { const v = lower[i] * 3, b = o + i * 3; can[v] += w * A.rig_Bm[b]; can[v + 1] += w * A.rig_Bm[b + 1]; can[v + 2] += w * A.rig_Bm[b + 2] } }
209
+ for (let k = 0; k < KE; k++) { const w = bs[KM + k] * std[KM + k], o = k * eyes.length * 3; for (let i = 0; i < eyes.length; i++) { const v = eyes[i] * 3, b = o + i * 3; can[v] += w * A.rig_Be[b]; can[v + 1] += w * A.rig_Be[b + 1]; can[v + 2] += w * A.rig_Be[b + 2] } }
210
+ const V = this.V
211
+ for (let i = 0; i < NV; i++) { const x = can[i * 3], y = can[i * 3 + 1], z = can[i * 3 + 2]
212
+ V[i * 3] = sc * (R[0] * x + R[1] * y + R[2] * z) + tx - C; V[i * 3 + 1] = sc * (R[3] * x + R[4] * y + R[5] * z) + ty - C; V[i * 3 + 2] = sc * (R[6] * x + R[7] * y + R[8] * z) + tz + D }
213
+ if (this.nSk) { // skirt: extra vertices pushed outwards from the lower face outline, so the chin's rim moves with the jaw
214
+ let cx = 0, cy = 0; for (let i = 0; i < 468; i++) { cx += V[i * 3]; cy += V[i * 3 + 1] } cx /= 468; cy /= 468
215
+ const sk = this.skIdx, d = this.skirt
216
+ for (let i = 0; i < this.nSk; i++) { const b = sk[i] * 3, o = (NV + i) * 3; let ux = V[b] - cx, uy = V[b + 1] - cy; const l = Math.max(Math.hypot(ux, uy), 1e-6); V[o] = V[b] + d * ux / l; V[o + 1] = V[b + 1] + d * uy / l; V[o + 2] = V[b + 2] }
217
+ }
218
+ // ---- triangles: corners, frame (e1, e2, n) and the frame's quaternion
219
+ const tri = A.tri, td = this.triData
220
+ for (let t = 0; t < NT; t++) {
221
+ const a = tri[t * 3] * 3, b = tri[t * 3 + 1] * 3, c = tri[t * 3 + 2] * 3, o = t * 32
222
+ let e1x = V[b] - V[a], e1y = V[b + 1] - V[a + 1], e1z = V[b + 2] - V[a + 2], l = Math.max(Math.hypot(e1x, e1y, e1z), 1e-12); e1x /= l; e1y /= l; e1z /= l
223
+ const cx = V[c] - V[a], cy = V[c + 1] - V[a + 1], cz = V[c + 2] - V[a + 2]
224
+ let nx = e1y * cz - e1z * cy, ny = e1z * cx - e1x * cz, nz = e1x * cy - e1y * cx; l = Math.max(Math.hypot(nx, ny, nz), 1e-12); nx /= l; ny /= l; nz /= l
225
+ const e2x = ny * e1z - nz * e1y, e2y = nz * e1x - nx * e1z, e2z = nx * e1y - ny * e1x
226
+ let w = Math.sqrt(Math.max(1 + e1x + e2y + nz, 1e-8)) / 2, x = Math.sqrt(Math.max(1 + e1x - e2y - nz, 1e-8)) / 2, y = Math.sqrt(Math.max(1 - e1x + e2y - nz, 1e-8)) / 2, z = Math.sqrt(Math.max(1 - e1x - e2y + nz, 1e-8)) / 2
227
+ if (e2z - ny < 0) x = -x; if (nx - e1z < 0) y = -y; if (e1y - e2x < 0) z = -z; l = Math.hypot(w, x, y, z)
228
+ td[o] = V[a]; td[o + 1] = V[a + 1]; td[o + 2] = V[a + 2]; td[o + 3] = w / l
229
+ td[o + 4] = V[b]; td[o + 5] = V[b + 1]; td[o + 6] = V[b + 2]; td[o + 7] = x / l
230
+ td[o + 8] = V[c]; td[o + 9] = V[c + 1]; td[o + 10] = V[c + 2]; td[o + 11] = y / l
231
+ td[o + 12] = e1x; td[o + 13] = e1y; td[o + 14] = e1z; td[o + 15] = z / l
232
+ td[o + 16] = e2x; td[o + 17] = e2y; td[o + 18] = e2z; td[o + 20] = nx; td[o + 21] = ny; td[o + 22] = nz
233
+ }
234
+ lap(0)
235
+ // ---- blend weights from the small network
236
+ const cond = this.cond; cond.fill(0); cond.set(bs.subarray(0, this.NB), 0); cond.set(pose.subarray(0, 7), this.NB)
237
+ const dense = (W, b, x, act) => { const no = b.length, ni = x.length, y = new Float32Array(no); for (let o = 0; o < no; o++) { let s = b[o]; const r = o * ni; for (let i = 0; i < ni; i++) s += W[r + i] * x[i]; y[o] = act ? silu(s) : s } return y }
238
+ const coef = dense(A.W2, A.b2, dense(A.W1, A.b1, dense(A.W0, A.b0, cond, true), true), false), ck = this.ck, Bs = A.Bscale
239
+ for (let k = 0; k < K; k++) for (let d = 0; d < 14; d++) ck[k * 16 + d] = coef[k] * Bs[k * 14 + d]
240
+ lap(1)
241
+ // ---- one depth per Gaussian (before offsets) for the back-to-front order
242
+ const twx = sc * (R[0] * C + R[1] * C) + tx - C, twy = sc * (R[3] * C + R[4] * C) + ty - C, twz = sc * (R[6] * C + R[7] * C) + tz
243
+ const c2 = this.c2; for (let k = 0; k < K; k++) c2[k] = this.opt.exactz ? ck[k * 16 + 2] / 127 : 0
244
+ const seq = this.fc++; let fresh = false
245
+ if (this.worker) {
246
+ // the draw order is worked out off the main thread; this frame is drawn with the newest order that has arrived
247
+ if (this.workerReady && !this.busy) { this.busy = true; this.sent = seq; this.worker.postMessage({ td: td.slice(0, NT * 32), R: Array.from(R), sc, twz, c2: Array.from(c2), seq }) }
248
+ } else if (seq % (this.opt.sortEvery || 1) === 0) {
249
+ const zs = this.zs, O = this.ord
250
+ depthFace(zs, O.tid, O.bary, O.f_off, td, NF); depthFree(zs, O.r_pos, O.r_w, R, sc, twz, D, NF, NR); exactZ(zs, O.Bz, O.act, c2, this.NA, K)
251
+ sortBackToFront(zs, this.keys, this.counts, this.order, N); fresh = true
252
+ }
253
+ lap(4)
254
+ const t1 = performance.now()
255
+ // ---- uploads: triangle data and the draw order
256
+ gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, this.tTri); gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, 1024, this.tH, gl.RGBA, gl.FLOAT, td)
257
+ if (fresh) { gl.bindBuffer(gl.ARRAY_BUFFER, this.ibuf); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.order) }
258
+ lap(5)
259
+ // ---- pass 1: mix the offsets
260
+ gl.disable(gl.BLEND); gl.bindFramebuffer(gl.FRAMEBUFFER, this.fOff); gl.viewport(0, 0, 1024, this.oH)
261
+ gl.useProgram(this.pOff.p); gl.bindVertexArray(this.vaoNone); gl.activeTexture(gl.TEXTURE3); gl.bindTexture(gl.TEXTURE_2D_ARRAY, this.tB)
262
+ gl.uniform1i(this.pOff.u.uB, 3); gl.uniform4fv(this.pOff.u.uCk, ck); gl.drawArrays(gl.TRIANGLES, 0, 3)
263
+ // ---- pass 2: place, offset, project and blend every Gaussian
264
+ gl.bindFramebuffer(gl.FRAMEBUFFER, this.fImg); gl.viewport(0, 0, this.SIZE, this.SIZE); gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT)
265
+ gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); const d = this.pDraw; gl.useProgram(d.p); gl.bindVertexArray(this.vao)
266
+ gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, this.tStat); gl.activeTexture(gl.TEXTURE2); gl.bindTexture(gl.TEXTURE_2D, this.tOff)
267
+ gl.uniform1i(d.u.uStat, 0); gl.uniform1i(d.u.uTri, 1); gl.uniform1i(d.u.uOff, 2)
268
+ gl.uniform1f(d.u.uSize, this.SIZE); gl.uniform1f(d.u.uC, C); gl.uniform1f(d.u.uD, D); gl.uniform1f(d.u.uS, sc)
269
+ gl.uniformMatrix3fv(d.u.uR, true, R); gl.uniform3f(d.u.uTw, twx, twy, twz)
270
+ gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, N)
271
+ // ---- copy to the canvas
272
+ if (this.wm) this._wmDraw((performance.now() - this.wm.t0) / 1000)
273
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.disable(gl.BLEND); gl.viewport(0, 0, this.SIZE, this.SIZE); gl.useProgram(this.pCopy.p); gl.bindVertexArray(this.vaoNone)
274
+ gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, this.tImg); gl.uniform1i(this.pCopy.u.uImg, 0)
275
+ gl.activeTexture(gl.TEXTURE4); gl.bindTexture(gl.TEXTURE_2D, this.tWm || this.tImg); gl.uniform1i(this.pCopy.u.uWm, 4); gl.uniform1f(this.pCopy.u.uWmOn, this.tWm && this.wmOn ? 1 : 0)
276
+ if (this.wmRect) gl.uniform4fv(this.pCopy.u.uWmRect, this.wmRect)
277
+ gl.drawArrays(gl.TRIANGLES, 0, 3)
278
+ lap(6)
279
+ return [t1 - t0, performance.now() - t1]
280
+ }
281
+
282
+ // resolves once the order for the most recently requested frame has been applied
283
+ settle() { return new Promise((res) => { if (!this.worker || !this.busy) return res(); (this.waiters = this.waiters || []).push(res) }) }
284
+ // resolves when the background worker is up (the first frame drawn after this requests the first order)
285
+ workerUp() { return new Promise((res) => { if (!this.worker || this.workerReady) return res(); this.onWorkerReady = res }) }
286
+
287
+ // The mark a free avatar carries: a "Powered by stork.ai" lockup, bottom right, and Stork's bird, which flies in over the picture,
288
+ // lands on the lockup's orange disc, and every so often takes off and comes back. Both images come from the avatar file.
289
+ async setWatermark(pillUrl, birdUrl, meta) {
290
+ const load = async (u) => { const im = new Image(); im.src = u; await im.decode(); return im }
291
+ const S = this.SIZE, c = document.createElement('canvas'); c.width = c.height = S
292
+ const [pw, ph, dx, dy, dr, bcx, bcy, br] = meta, px = S - pw - 12, py = S - ph - 12
293
+ this.wm = { c, x: c.getContext('2d'), pill: await load(pillUrl), bird: await load(birdUrl), px, py, pw, ph, LX: px + dx, LY: py + dy, k: dr / br, bcx, bcy, t0: performance.now(), state: '' }
294
+ const gl = this.gl; this.tWm = gl.createTexture(); gl.activeTexture(gl.TEXTURE4); gl.bindTexture(gl.TEXTURE_2D, this.tWm)
295
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
296
+ this.wmRect = new Float32Array([0, 0, S, S]); this.wmOn = true; this.wmLink = [px, py, pw, ph]; this._wmDraw(0)
297
+ }
298
+ // t: seconds since the mark appeared. One round is 26 s: fly in and land (1.7 s), rest, take off at 22 s, away until the next round.
299
+ _wmDraw(t) {
300
+ const w = this.wm, S = this.SIZE, p = t % 26, x = w.x
301
+ const state = p < 1.7 || (p >= 22 && p < 23.3) ? 'fly' : p < 22 ? (t < 2.4 ? 'fly' : 'rest') : 'away'
302
+ if (state !== 'fly' && state === w.state) return
303
+ w.state = state
304
+ const io = (e) => e < 0.5 ? 2 * e * e : 1 - 2 * (1 - e) * (1 - e), cl = (v) => Math.max(0, Math.min(1, v))
305
+ const bez = (a, b, c, d, e) => { const m = 1 - e; return [m * m * m * a[0] + 3 * m * m * e * b[0] + 3 * m * e * e * c[0] + e * e * e * d[0], m * m * m * a[1] + 3 * m * m * e * b[1] + 3 * m * e * e * c[1] + e * e * e * d[1]] }
306
+ x.clearRect(0, 0, S, S); x.globalAlpha = cl(t / 0.5); x.drawImage(w.pill, w.px, w.py, w.pw, w.ph); x.globalAlpha = 1
307
+ let pos = null, sc = 1, rot = 0, flap = 1, al = 1
308
+ const L = [w.LX, w.LY]
309
+ if (p < 1.7) { // in from the upper left, across the picture, down onto the disc
310
+ const e = io(p / 1.7) * 0.9 + (p / 1.7) * 0.1, P = [[-0.1 * S, 0.22 * S], [0.34 * S, 0.16 * S], [0.42 * S, 0.8 * S], L]
311
+ pos = bez(...P, e); const n = bez(...P, Math.min(1, e + 0.02)); rot = Math.atan2(n[1] - pos[1], n[0] - pos[0]) * 0.4 * (1 - e); sc = 2.6 - 1.6 * e; flap = 1 + Math.sin(p * 22) * 0.07 * (1 - e * e); al = cl(p / 0.15)
312
+ } else if (p < 22) pos = L
313
+ else if (p < 23.3) { // up and out to the right
314
+ const e = io((p - 22) / 1.3), P = [L, [0.74 * S, 0.84 * S], [0.86 * S, 0.62 * S], [1.12 * S, 0.44 * S]]
315
+ pos = bez(...P, e); rot = -0.3 * e; sc = 1 + 1.4 * e; flap = 1 + Math.sin(p * 22) * 0.07 * e; al = 1 - cl((p - 23.1) / 0.2)
316
+ }
317
+ if (pos) {
318
+ const k = w.k * sc
319
+ x.save(); x.globalAlpha = al; x.translate(pos[0], pos[1]); x.rotate(rot); x.scale(1, flap)
320
+ if (sc > 1.02) { x.shadowColor = 'rgba(0,0,0,0.45)'; x.shadowBlur = 6; x.shadowOffsetY = 2 }
321
+ x.drawImage(w.bird, -w.bcx * k, -w.bcy * k, w.bird.width * k, w.bird.height * k); x.restore()
322
+ }
323
+ const gl = this.gl; gl.activeTexture(gl.TEXTURE4); gl.bindTexture(gl.TEXTURE_2D, this.tWm); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, w.c)
324
+ }
325
+
326
+ read() {
327
+ const gl = this.gl, S = this.SIZE, px = new Uint8Array(S * S * 4); gl.readPixels(0, 0, S, S, gl.RGBA, gl.UNSIGNED_BYTE, px)
328
+ const out = new Uint8Array(S * S * 3)
329
+ for (let y = 0; y < S; y++) for (let x = 0; x < S; x++) { const a = ((S - 1 - y) * S + x) * 4, b = (y * S + x) * 3; out[b] = px[a]; out[b + 1] = px[a + 1]; out[b + 2] = px[a + 2] }
330
+ return out
331
+ }
332
+ }
@@ -0,0 +1,89 @@
1
+ // Stork Live: mouth motion computed in this page, with no server.
2
+ // A small network (two strided convolutions + two GRU layers) turns 16 kHz speech into the 16 mouth controls, 25 times a second.
3
+ // Everything here is plain arithmetic on typed arrays: no WebAssembly, no ML runtime.
4
+ import { loadPack } from './pack.js'
5
+
6
+ const NFFT = 512, WIN = 400, HOP = 160, NMEL = 80, KM = 16
7
+
8
+ function fftReal(re, im) { // in-place radix-2 FFT, length 512
9
+ const n = re.length
10
+ for (let i = 1, j = 0; i < n; i++) { let bit = n >> 1; for (; j & bit; bit >>= 1) j ^= bit; j ^= bit; if (i < j) { const t = re[i]; re[i] = re[j]; re[j] = t; const u = im[i]; im[i] = im[j]; im[j] = u } }
11
+ for (let len = 2; len <= n; len <<= 1) {
12
+ const ang = -2 * Math.PI / len, wr = Math.cos(ang), wi = Math.sin(ang)
13
+ for (let i = 0; i < n; i += len) { let cr = 1, ci = 0
14
+ for (let k = 0; k < len / 2; k++) { const a = i + k, b = a + len / 2, xr = re[b] * cr - im[b] * ci, xi = re[b] * ci + im[b] * cr; re[b] = re[a] - xr; im[b] = im[a] - xi; re[a] += xr; im[a] += xi; const t = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = t } }
15
+ }
16
+ }
17
+ const sigmoid = (x) => 1 / (1 + Math.exp(-x)), silu = (x) => x / (1 + Math.exp(-x))
18
+
19
+ /** The network itself. push(pcm) returns [[videoFrameIndex, Float32Array(16)], …] for every frame that became computable. */
20
+ export class Student {
21
+ constructor(P) {
22
+ this.P = P; this.LA = P.meta[0]; this.H = P.meta[1]
23
+ this.hann = new Float32Array(WIN); for (let i = 0; i < WIN; i++) this.hann[i] = 0.5 - 0.5 * Math.cos(2 * Math.PI * i / WIN)
24
+ // sparse mel filters: for each band, the first bin and its weights
25
+ this.fbStart = new Int32Array(NMEL); this.fbW = []
26
+ for (let m = 0; m < NMEL; m++) { let a = -1, b = -1; for (let k = 0; k < 257; k++) if (P.fb[m * 257 + k] > 0) { if (a < 0) a = k; b = k } this.fbStart[m] = Math.max(a, 0); this.fbW.push(a < 0 ? new Float32Array(0) : P.fb.slice(m * 257 + a, m * 257 + b + 1)) }
27
+ this.re = new Float32Array(NFFT); this.im = new Float32Array(NFFT)
28
+ this.reset()
29
+ }
30
+ reset() {
31
+ this.buf = new Float32Array(0); this.base = 0 // samples not yet fully consumed; base = stream index of buf[0]
32
+ this.mel = []; this.melBase = 0; this.nMel = 0 // normalised mel frames still needed by conv1
33
+ this.c1 = []; this.c1Base = 0; this.nC1 = 0; this.nOut = 0
34
+ this.h1 = new Float32Array(this.H); this.h2 = new Float32Array(this.H)
35
+ }
36
+ _mel(off) { // one normalised log-mel frame from buf[off .. off+400)
37
+ const { re, im, hann, buf, P } = this; re.fill(0); im.fill(0); for (let i = 0; i < WIN; i++) re[i] = buf[off + i] * hann[i]
38
+ fftReal(re, im); const out = new Float32Array(NMEL)
39
+ for (let m = 0; m < NMEL; m++) { const w = this.fbW[m], s0 = this.fbStart[m]; let s = 0; for (let k = 0; k < w.length; k++) { const b = s0 + k; s += w[k] * (re[b] * re[b] + im[b] * im[b]) } out[m] = (Math.log(Math.max(s, 1e-5)) - P.mmu[m]) / P.msd[m] }
40
+ return out
41
+ }
42
+ _conv(frames, W, b, cin, cout) { // kernel 4 over 4 queued frames -> one output frame, SiLU
43
+ const out = new Float32Array(cout)
44
+ for (let o = 0; o < cout; o++) { let s = b[o]; const wo = o * cin * 4; for (let c = 0; c < cin; c++) { const wc = wo + c * 4; s += W[wc] * frames[0][c] + W[wc + 1] * frames[1][c] + W[wc + 2] * frames[2][c] + W[wc + 3] * frames[3][c] } out[o] = silu(s) }
45
+ return out
46
+ }
47
+ _gru(x, h, Wi, Wh, bi, bh, nin) { // PyTorch gate order: reset, update, new
48
+ const H = this.H, gi = new Float32Array(3 * H), gh = new Float32Array(3 * H)
49
+ for (let r = 0; r < 3 * H; r++) { let a = bi[r], wi = r * nin; for (let c = 0; c < nin; c++) a += Wi[wi + c] * x[c]; gi[r] = a; let d = bh[r], wh = r * H; for (let c = 0; c < H; c++) d += Wh[wh + c] * h[c]; gh[r] = d }
50
+ for (let j = 0; j < H; j++) { const r = sigmoid(gi[j] + gh[j]), z = sigmoid(gi[H + j] + gh[H + j]), n = Math.tanh(gi[2 * H + j] + r * gh[2 * H + j]); h[j] = (1 - z) * n + z * h[j] }
51
+ }
52
+ push(pcm) {
53
+ const P = this.P, nb = new Float32Array(this.buf.length + pcm.length); nb.set(this.buf); nb.set(pcm, this.buf.length); this.buf = nb; const res = []
54
+ while (this.nMel * HOP + WIN <= this.base + this.buf.length) { this.mel.push(this._mel(this.nMel * HOP - this.base)); this.nMel++ } // mel frame t = samples [160 t, 160 t + 400)
55
+ while (this.nC1 * 2 + 4 <= this.nMel) { const i = this.nC1 * 2 - this.melBase; this.c1.push(this._conv(this.mel.slice(i, i + 4), P.c1w, P.c1b, NMEL, 128)); this.nC1++ } // conv1 j = mel 2j .. 2j+3
56
+ let d = this.nC1 * 2 - this.melBase; if (d > 0) { this.mel.splice(0, d); this.melBase += d }
57
+ while (this.nOut * 2 + 4 <= this.nC1) { // conv2 f = conv1 2f .. 2f+3
58
+ const i = this.nOut * 2 - this.c1Base, x = this._conv(this.c1.slice(i, i + 4), P.c2w, P.c2b, 128, 192)
59
+ this._gru(x, this.h1, P.g0wi, P.g0wh, P.g0bi, P.g0bh, 192); this._gru(this.h1, this.h2, P.g1wi, P.g1wh, P.g1bi, P.g1bh, this.H)
60
+ const y = new Float32Array(KM); for (let o = 0; o < KM; o++) { let s = P.ob[o]; const wo = o * this.H; for (let c = 0; c < this.H; c++) s += P.ow[wo + c] * this.h2[c]; y[o] = P.ymu[o] + P.gain[o] * s * P.ysd[o] }
61
+ const frame = this.nOut - this.LA; if (frame >= 0) res.push([frame, y]); this.nOut++ // network row f is video frame f - LA
62
+ }
63
+ d = this.nOut * 2 - this.c1Base; if (d > 0) { this.c1.splice(0, d); this.c1Base += d }
64
+ const keep = Math.max(0, this.nMel * HOP - this.base); if (keep > 0) { this.buf = this.buf.slice(keep); this.base += keep }
65
+ return res
66
+ }
67
+ }
68
+
69
+ /** A motion source for StorkLive.mount({ motion: new LocalMotion(url) }): same interface as the server one, nothing leaves the device. */
70
+ export class LocalMotion {
71
+ constructor(url, { rest } = {}) { this.url = url; this.rest = rest || null; this.onFrames = null; this.net = null; this.delay = 0.3 }
72
+ async open() {
73
+ if (!this.net) { this.net = new Student(await loadPack(this.url)); this.delay = (this.net.LA * 40 + 75 + 60) / 1000 } else this.net.reset()
74
+ this.rms = []; this.acc = new Float32Array(0); this.gate = 0
75
+ }
76
+ push(pcm) {
77
+ // loudness per 40 ms frame, for the silence gate (same rule as the server: speech within 2 frames back / 3 ahead opens it at once)
78
+ const a = new Float32Array(this.acc.length + pcm.length); a.set(this.acc); a.set(pcm, this.acc.length); let o = 0
79
+ for (; o + 640 <= a.length; o += 640) { let s = 0; for (let i = 0; i < 640; i++) s += a[o + i] * a[o + i]; this.rms.push(Math.sqrt(s / 640)) } this.acc = a.slice(o)
80
+ const out = this.net.push(pcm); if (!out.length || !this.onFrames) return
81
+ const v = new Float32Array(out.length * KM)
82
+ out.forEach(([f, y], i) => {
83
+ if (this.rest) { let loud = 0; for (let k = Math.max(0, f - 2); k < Math.min(this.rms.length, f + 4); k++) loud = Math.max(loud, this.rms[k]); const tgt = loud > 0.012 ? 1 : 0; this.gate = tgt > this.gate ? tgt : Math.max(0, this.gate - 0.17); for (let j = 0; j < KM; j++) y[j] = this.rest[j] + this.gate * (y[j] - this.rest[j]) }
84
+ v.set(y, i * KM)
85
+ })
86
+ this.onFrames(out[0][0], v)
87
+ }
88
+ close() {}
89
+ }
package/src/order.js ADDED
@@ -0,0 +1,21 @@
1
+ // Draw order (back to front). Shared by the page and by the background worker.
2
+ // Hot loops live in their own small functions: phone JavaScript engines do not fully optimise one very large function.
3
+ export function depthFace(zs, tid, bary, foff, td, NF) {
4
+ for (let i = 0; i < NF; i++) { const o = tid[i] * 32, i3 = i * 3; zs[i] = bary[i3] * td[o + 2] + bary[i3 + 1] * td[o + 6] + bary[i3 + 2] * td[o + 10] + td[o + 14] * foff[i3] + td[o + 18] * foff[i3 + 1] + td[o + 22] * foff[i3 + 2] }
5
+ }
6
+ export function depthFree(zs, rp, rw, R, sc, twz, D, NF, NR) {
7
+ const r6 = R[6], r7 = R[7], r8 = R[8]
8
+ for (let j = 0; j < NR; j++) { const j3 = j * 3, z0 = rp[j3 + 2], w = rw[j]; zs[NF + j] = w * (sc * (r6 * rp[j3] + r7 * rp[j3 + 1] + r8 * (z0 - D)) + twz + D) + (1 - w) * z0 }
9
+ }
10
+ // Bz holds only each moving Gaussian's depth offsets: one signed byte per blend set
11
+ export function exactZ(zs, Bz, act, c2, NA, K) {
12
+ for (let n = 0; n < NA; n++) { let s = 0; const b = n * K; for (let k = 0; k < K; k++) s += c2[k] * Bz[b + k]; zs[act[n]] += 6 * Math.tanh(s) }
13
+ }
14
+ export function sortBackToFront(zs, keys, counts, order, N) {
15
+ let zmin = Infinity, zmax = -Infinity; for (let i = 0; i < N; i++) { const z = zs[i]; if (z < zmin) zmin = z; if (z > zmax) zmax = z }
16
+ const kk = 65535 / Math.max(zmax - zmin, 1e-6); counts.fill(0)
17
+ for (let i = 0; i < N; i++) { const key = 65535 - ((zs[i] - zmin) * kk | 0); keys[i] = key; counts[key]++ }
18
+ let acc = 0; for (let j = 0; j < 65536; j++) { const n = counts[j]; counts[j] = acc; acc += n }
19
+ for (let i = 0; i < N; i++) order[counts[keys[i]]++] = i
20
+ }
21
+
@@ -0,0 +1,12 @@
1
+ // Works out the back-to-front draw order off the main thread, so a slow phone never stalls a frame on it.
2
+ // It is handed only the few arrays it needs (about 4 MB), not the whole avatar.
3
+ import { depthFace, depthFree, exactZ, sortBackToFront } from './order.js'
4
+ let I = null, zs, keys, counts
5
+ onmessage = (e) => {
6
+ const m = e.data
7
+ if (m.init) { I = m.init; const N = I.NF + I.NR; zs = new Float32Array(N); keys = new Uint16Array(N); counts = new Uint32Array(65536); postMessage({ ready: true }); return }
8
+ const t = performance.now(), N = I.NF + I.NR, order = new Uint32Array(N)
9
+ depthFace(zs, I.tid, I.bary, I.f_off, m.td, I.NF); depthFree(zs, I.r_pos, I.r_w, m.R, m.sc, m.twz, I.D, I.NF, I.NR); exactZ(zs, I.Bz, I.act, m.c2, I.NA, I.K)
10
+ sortBackToFront(zs, keys, counts, order, N)
11
+ postMessage({ order, seq: m.seq, ms: performance.now() - t }, [order.buffer])
12
+ }
package/src/pack.js ADDED
@@ -0,0 +1,26 @@
1
+ // Loads a Stork Live data pack (a .json index + a .bin blob) and unpacks the compact number formats.
2
+ export const FORMAT_VERSION = 1
3
+ export async function loadPack(base) {
4
+ const man = await (await fetch(base + '.json')).json()
5
+ const buf = await (await fetch(base + '.bin')).arrayBuffer()
6
+ const T = { float32: Float32Array, int32: Int32Array, int8: Int8Array, uint8: Uint8Array, uint16: Uint16Array }
7
+ const out = { __bytes: buf.byteLength, __shape: {} }
8
+ // Avatar files say which format they are. Version 1 is frozen: a later client will always read a version-1 file.
9
+ const fmt = man.__format; if (fmt && fmt.version > FORMAT_VERSION) throw new Error(`this avatar file is format version ${fmt.version}; this client reads up to ${FORMAT_VERSION}. Update stork-live.`)
10
+ out.__format = fmt || null
11
+ for (const [k, m] of Object.entries(man)) {
12
+ if (k.startsWith('__')) continue
13
+ const n = m.shape.reduce((a, b) => a * b, 1); let a = new T[m.dtype](buf, m.offset, n); let shape = m.shape
14
+ if (m.q16) { // 16-bit numbers with a per-column range -> floats
15
+ const cols = n / m.shape[0], f = new Float32Array(n), lo = m.q16.lo, sc = m.q16.scale
16
+ for (let i = 0; i < n; i++) { const c = i % cols; f[i] = lo[c] + a[i] * sc[c] } a = f
17
+ } else if (m.bary2) { // two barycentric weights stored, the third is what is left
18
+ const r = m.shape[0], f = new Float32Array(r * 3); for (let i = 0; i < r; i++) { const u = a[i * 2] / 65535, v = a[i * 2 + 1] / 65535; f[i * 3] = u; f[i * 3 + 1] = v; f[i * 3 + 2] = 1 - u - v } a = f; shape = [r, 3]
19
+ } else if (m.as === 'int32') { a = Int32Array.from(a)
20
+ } else if (m.attrs) { // offsets stored for some attributes only -> the full 14 the renderer indexes, zeros elsewhere
21
+ const [NA, K, C] = m.shape, f = new Int8Array(NA * K * 14); for (let i = 0; i < NA * K; i++) for (let c = 0; c < C; c++) f[i * 14 + m.attrs[c]] = a[i * C + c]; a = f; shape = [NA, K, 14]
22
+ }
23
+ out[k] = a; out.__shape[k] = shape
24
+ }
25
+ return out
26
+ }
package/src/react.js ADDED
@@ -0,0 +1,24 @@
1
+ // Stork Live for React.
2
+ //
3
+ // import { StorkLiveAvatar } from 'stork-live/react'
4
+ // <StorkLiveAvatar avatar="a" audio={agentAudioTrack} style={{ width: 360 }} />
5
+ //
6
+ // `audio` is whatever the voice arrives as: a MediaStreamTrack or MediaStream (WebRTC, LiveKit, a microphone),
7
+ // an <audio> element, or an AudioBuffer. While it is null the avatar idles: she blinks and moves her head.
8
+ import { createElement, useEffect, useRef } from 'react'
9
+ import { StorkLive } from './stork-live.js'
10
+
11
+ export function StorkLiveAvatar({ avatar = 'a', audio = null, motion, delay, onReady, onError, style, className }) {
12
+ const canvas = useRef(null), live = useRef(null), wanted = useRef(audio)
13
+ wanted.current = audio
14
+ useEffect(() => {
15
+ let gone = false, mine = null
16
+ StorkLive.mount(canvas.current, { avatar, motion, delay }).then((l) => {
17
+ if (gone) return l.destroy()
18
+ mine = live.current = l; if (onReady) onReady(l); if (wanted.current) l.speak(wanted.current)
19
+ }).catch((e) => { if (onError) onError(e); else console.error('stork-live:', e) })
20
+ return () => { gone = true; if (mine) mine.destroy(); if (live.current === mine) live.current = null }
21
+ }, [avatar])
22
+ useEffect(() => { const l = live.current; if (!l) return; if (audio) l.speak(audio); else l.stop() }, [audio])
23
+ return createElement('canvas', { ref: canvas, width: 512, height: 512, className, style: { aspectRatio: '1 / 1', ...style } })
24
+ }
@@ -0,0 +1,135 @@
1
+ // Stork Live: a talking avatar drawn in the browser.
2
+ //
3
+ // import { StorkLive } from './stork-live.js'
4
+ // const live = await StorkLive.mount(canvas, { avatar: 'https://…/avatar_a_c5', motion: { server: 'wss://…/ws' } })
5
+ // await live.speak(audioElementOrStreamOrBuffer) // her lips follow the sound; the sound is played in step with them
6
+ //
7
+ // The page draws everything itself. Per video frame it needs 16 mouth numbers; they come from a "motion source":
8
+ // a motion server (speech goes up a WebSocket, numbers come back) or a small model running in this page.
9
+ // Blinks, head movement and the resting face are produced here, so the avatar is alive before, between and after speech.
10
+ import { loadPack } from './pack.js'
11
+ import { GpuAvatar } from './gpu.js'
12
+ import { LocalMotion } from './local-motion.js'
13
+ export { LocalMotion }
14
+
15
+ const FPS = 25, KM = 16
16
+ export const LIBRARY = 'https://cdn.jsdelivr.net/npm/stork-live-avatars@1/' // Stork's free library: the npm package stork-live-avatars, served by jsDelivr
17
+ const MARK_LINK = 'https://stork.ai/?ref=live-mark' // where the mark on a free avatar leads
18
+
19
+ /** Motion from a server: 16 kHz speech up, mouth numbers down. */
20
+ export class ServerMotion {
21
+ constructor(url) { this.url = url; this.delay = 0.7; this.onFrames = null; this.sock = null }
22
+ async open() {
23
+ const s = this.sock = new WebSocket(this.url); s.binaryType = 'arraybuffer'
24
+ await new Promise((res, rej) => { s.onopen = res; s.onerror = () => rej(new Error('cannot reach the motion server')) })
25
+ s.onmessage = (e) => {
26
+ if (typeof e.data === 'string') { const m = JSON.parse(e.data); if (m.hello) this.hello = m; return }
27
+ const f0 = new Int32Array(e.data, 0, 1)[0], v = new Float32Array(e.data, 4), w = this.hello ? this.hello.cfg.controls + 7 : 26, n = v.length / w
28
+ const out = new Float32Array(n * KM); for (let i = 0; i < n; i++) out.set(v.subarray(i * w, i * w + KM), i * KM)
29
+ if (this.onFrames) this.onFrames(f0, out)
30
+ }
31
+ }
32
+ push(pcm) { const i16 = new Int16Array(pcm.length); for (let i = 0; i < pcm.length; i++) i16[i] = Math.max(-32768, Math.min(32767, pcm[i] * 32768)); if (this.sock && this.sock.readyState === 1) this.sock.send(i16.buffer) }
33
+ close() { try { this.sock && this.sock.close() } catch (e) {} this.sock = null }
34
+ }
35
+
36
+ export class StorkLive {
37
+ /** canvas: a <canvas>; opts.avatar: address of the avatar pack without extension; opts.motion: { server } or a motion-source object;
38
+ * opts.assets: where idle.json/idle.bin live (default: next to this file, ../assets/idle) */
39
+ static async mount(canvas, opts = {}) {
40
+ const live = new StorkLive(); await live._init(canvas, opts); return live
41
+ }
42
+
43
+ async _init(canvas, opts) {
44
+ this.opts = opts; canvas.width = canvas.height = 512
45
+ // a bare name ('a', 'b', …) is a face from Stork's free library; anything with a slash is an address of your own
46
+ let A = await loadPack(/[/:]/.test(opts.avatar) ? opts.avatar : LIBRARY + opts.avatar)
47
+ this.g = new GpuAvatar(canvas, A, { exactz: true, worker: true })
48
+ const idle = await loadPack(opts.assets || new URL('../assets/idle', import.meta.url).href)
49
+ // An avatar other than the first presenter carries a translation table: motion is always made for the first presenter's controls.
50
+ this.rt = A.rt_W ? { W: A.rt_W.slice(), pm: A.rt_pred_mean.slice(), gain: A.rt_gain.slice(), mean: A.rt_mean.slice() } : null
51
+ this.rest = (A.rt_rest || idle.rest).slice(); this.eyeOpen = (A.rt_eye_open || idle.eye_open).slice(); this.eyeClosed = (A.rt_eye_closed || idle.eye_closed).slice()
52
+ this.KE = this.eyeOpen.length; this.head = idle.head; this.nHead = idle.__shape.head[0]
53
+ this.bytes = A.__bytes; const png = (v) => URL.createObjectURL(new Blob([v.slice()], { type: 'image/png' })), wm = A.wm_pill_png ? [png(A.wm_pill_png), png(A.wm_bird_png), A.wm_meta.slice()] : null; A = null
54
+ // motion: { local: true | address } runs the small model in this page (nothing leaves the device); { server: 'wss://…' } asks a motion server
55
+ const mo = opts.motion || { local: true }
56
+ this.motionSrc = mo.push ? mo : mo.local ? new LocalMotion(mo.local === true ? new URL('../assets/motion', import.meta.url).href : mo.local, { rest: idle.rest.slice() }) : null
57
+ if (wm) { // free avatars carry the "Powered by stork.ai" mark in the file itself; your own, licensed avatar files have none
58
+ await this.g.setWatermark(...wm)
59
+ const hit = (e) => { const r = canvas.getBoundingClientRect(), k = 512 / r.width, x = (e.clientX - r.left) * k, y = (e.clientY - r.top) * k, [px, py, pw, ph] = this.g.wmLink; return x >= px && x <= px + pw && y >= py && y <= py + ph }
60
+ canvas.addEventListener('click', (e) => { if (hit(e)) window.open(MARK_LINK, '_blank', 'noopener') })
61
+ canvas.addEventListener('mousemove', (e) => { canvas.style.cursor = hit(e) ? 'pointer' : '' })
62
+ }
63
+ await this.g.workerUp()
64
+ this.bs = new Float32Array(KM + this.KE); this.mouth = new Float32Array(KM); this.tmp = new Float32Array(KM)
65
+ this.frames = new Map(); this.speaking = null; this.blend = 0; this.lastMouth = this.rest.slice()
66
+ this.t0 = performance.now(); this.shown = -1; this.nextBlink = 40; this.headI = Math.floor(Math.random() * (this.nHead - 600)); this.stats = { drawn: 0, late: 0 }
67
+ this._tick = this._tick.bind(this); this.alive = true; requestAnimationFrame(this._tick)
68
+ }
69
+
70
+ _retarget(m) { // first presenter's 16 mouth controls -> this avatar's
71
+ if (!this.rt) return m
72
+ const { W, pm, gain, mean } = this.rt, o = this.tmp
73
+ for (let j = 0; j < KM; j++) { let s = W[KM * KM + j]; for (let i = 0; i < KM; i++) s += m[i] * W[i * KM + j]; o[j] = mean[j] + (s - pm[j]) * gain[j] }
74
+ return o
75
+ }
76
+
77
+ _tick() {
78
+ if (!this.alive) return
79
+ const i = Math.floor((performance.now() - this.t0) / 1000 * FPS)
80
+ if (i !== this.shown) {
81
+ this.shown = i
82
+ // mouth: the speech frame due now if it has arrived, else ease back to rest
83
+ let m = null; const sp = this.speaking
84
+ if (sp) { const f = Math.floor((sp.ctx.currentTime - sp.tPlay) * FPS) + 1; if (f >= 0) { m = this.frames.get(f) || null; if (m) this.stats.drawn++; else if (sp.sent) this.stats.late++; for (const k of this.frames.keys()) { if (k < f - 2) this.frames.delete(k); else break } } }
85
+ if (m) { this.lastMouth = this._retarget(m).slice(); this.blend = Math.min(1, this.blend + 0.34) } else this.blend = Math.max(0, this.blend - 0.2)
86
+ for (let j = 0; j < KM; j++) this.bs[j] = this.rest[j] + this.blend * (this.lastMouth[j] - this.rest[j])
87
+ // eyes: a blink is four frames (closing, closed, opening, nearly open), every 2.5 to 5 seconds
88
+ const b = i - this.nextBlink, w = b >= 0 && b < 4 ? [0.55, 1, 0.75, 0.25][b] : 0; if (b >= 4) this.nextBlink = i + 62 + Math.floor(Math.random() * 63)
89
+ for (let k = 0; k < this.KE; k++) this.bs[KM + k] = this.eyeOpen[k] + w * (this.eyeClosed[k] - this.eyeOpen[k])
90
+ // head: a looping track of real head movement
91
+ this.headI = this.headI + 1 < this.nHead ? this.headI + 1 : 50
92
+ this.g.frame(this.bs, this.head.subarray(this.headI * 7, this.headI * 7 + 7))
93
+ }
94
+ requestAnimationFrame(this._tick)
95
+ }
96
+
97
+ /** source: a MediaStream or one audio track (microphone, WebRTC, a voice agent), an <audio>/<video> element, or an AudioBuffer. Resolves when it ends (never, for a stream; call stop()). */
98
+ async speak(source, { seconds } = {}) {
99
+ this.stop()
100
+ if (typeof MediaStreamTrack !== 'undefined' && source instanceof MediaStreamTrack) source = new MediaStream([source])
101
+ const AC = window.AudioContext || window.webkitAudioContext, ctx = this.ctx || (this.ctx = new AC({ sampleRate: 16000 })); if (ctx.state !== 'running') await ctx.resume()
102
+ const motion = this.motionSrc || new ServerMotion(this.opts.motion.server)
103
+ await motion.open(); const delay = this.opts.delay || motion.delay || 0.7
104
+ let node, ended = null
105
+ if (source instanceof AudioBuffer) { node = ctx.createBufferSource(); node.buffer = source; ended = new Promise((r) => { node.onended = r }) }
106
+ else if (source instanceof MediaStream) {
107
+ // Chrome only feeds a WebRTC stream into Web Audio while some media element is also playing it; this one is silent
108
+ const keep = this._keep || (this._keep = new Audio()); keep.muted = true; keep.srcObject = source; keep.play().catch(() => {})
109
+ node = ctx.createMediaStreamSource(source)
110
+ }
111
+ else { node = this._elNode && this._el === source ? this._elNode : (this._el = source, this._elNode = ctx.createMediaElementSource(source)); ended = new Promise((r) => source.addEventListener('ended', r, { once: true })) }
112
+ const proc = ctx.createScriptProcessor(1024, 1, 1), dl = ctx.createDelay(3); dl.delayTime.value = delay
113
+ const sp = this.speaking = { ctx, motion, node, proc, dl, tPlay: Infinity, sent: 0 }; this.frames.clear(); this.stats = { drawn: 0, late: 0 }
114
+ motion.onFrames = (f0, v) => { if (this.speaking !== sp) return; for (let i = 0; i < v.length / KM; i++) this.frames.set(f0 + i, v.slice(i * KM, (i + 1) * KM)) }
115
+ proc.onaudioprocess = (e) => {
116
+ const d = e.inputBuffer.getChannelData(0); e.outputBuffer.getChannelData(0).set(d) // pass the sound through; it is heard `delay` later, in step with the lips
117
+ if (sp.tPlay === Infinity) sp.tPlay = e.playbackTime + delay // sample 0 of the stream is heard at this audio-clock time
118
+ motion.push(d); sp.sent += d.length
119
+ }
120
+ node.connect(proc); proc.connect(dl); dl.connect(ctx.destination)
121
+ if (source instanceof AudioBuffer) node.start(); else if (source.play) { try { await source.play() } catch (e) {} }
122
+ if (seconds) ended = new Promise((r) => setTimeout(r, seconds * 1000))
123
+ if (!ended) return
124
+ await ended; await new Promise((r) => setTimeout(r, (delay + 0.4) * 1000)); if (this.speaking === sp) this.stop()
125
+ }
126
+
127
+ stop() {
128
+ const sp = this.speaking; if (!sp) return
129
+ this.speaking = null
130
+ try { sp.proc.onaudioprocess = null; sp.node.disconnect(); sp.proc.disconnect(); setTimeout(() => { try { sp.dl.disconnect() } catch (e) {} }, 1500); if (sp.node.stop) sp.node.stop() } catch (e) {}
131
+ if (!this.motionSrc) sp.motion.close()
132
+ }
133
+
134
+ destroy() { this.stop(); this.alive = false; if (this.g.worker) this.g.worker.terminate() }
135
+ }