@starfold/web 0.0.0-stage → 0.3.2
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/COPYING-dav1d +23 -0
- package/COPYING-wasi-libc +267 -0
- package/LICENSE +22 -0
- package/audio.js +1 -0
- package/dav1d.js +17 -0
- package/dav1d.wasm +0 -0
- package/index.d.ts +89 -0
- package/index.js +2 -0
- package/package.json +14 -5
- package/types.d.ts +100 -0
- package/worker.js +1 -0
- package/README.md +0 -3
package/COPYING-dav1d
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
Copyright © 2018-2025, VideoLAN and dav1d authors
|
|
2
|
+
All rights reserved.
|
|
3
|
+
|
|
4
|
+
Redistribution and use in source and binary forms, with or without
|
|
5
|
+
modification, are permitted provided that the following conditions are met:
|
|
6
|
+
|
|
7
|
+
1. Redistributions of source code must retain the above copyright notice, this
|
|
8
|
+
list of conditions and the following disclaimer.
|
|
9
|
+
|
|
10
|
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
|
11
|
+
this list of conditions and the following disclaimer in the documentation
|
|
12
|
+
and/or other materials provided with the distribution.
|
|
13
|
+
|
|
14
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
|
15
|
+
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
|
16
|
+
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
17
|
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
|
18
|
+
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
|
19
|
+
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
|
20
|
+
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
|
21
|
+
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
22
|
+
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
|
23
|
+
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
==== LICENSE
|
|
2
|
+
|
|
3
|
+
wasi-libc as a whole is multi-licensed under the
|
|
4
|
+
Apache License v2.0 with LLVM Exceptions, the Apache License v2.0, and
|
|
5
|
+
the MIT License. See the LICENSE-APACHE-LLVM, LICENSE-APACHE and LICENSE-MIT
|
|
6
|
+
files, respectively, for details.
|
|
7
|
+
|
|
8
|
+
Portions of this software are derived from third-party works covered by
|
|
9
|
+
their own licenses:
|
|
10
|
+
|
|
11
|
+
dlmalloc/ - CC0; see the notice in malloc.c for details
|
|
12
|
+
emmalloc/ - MIT; see the notice in emmalloc.c for details
|
|
13
|
+
libc-bottom-half/cloudlibc/ - BSD-2-Clause; see the LICENSE file for details
|
|
14
|
+
libc-top-half/musl/ - MIT; see the COPYRIGHT file for details
|
|
15
|
+
fts/musl-fts/ - BSD-3-Clause; see the COPYING file for details
|
|
16
|
+
|
|
17
|
+
wasi-libc's changes to these files are multi-licensed under the
|
|
18
|
+
Apache License v2.0 with LLVM Exceptions, the Apache License v2.0,
|
|
19
|
+
the MIT License, and the original licenses of the third-party works.
|
|
20
|
+
|
|
21
|
+
==== LICENSE-MIT
|
|
22
|
+
|
|
23
|
+
Permission is hereby granted, free of charge, to any
|
|
24
|
+
person obtaining a copy of this software and associated
|
|
25
|
+
documentation files (the "Software"), to deal in the
|
|
26
|
+
Software without restriction, including without
|
|
27
|
+
limitation the rights to use, copy, modify, merge,
|
|
28
|
+
publish, distribute, sublicense, and/or sell copies of
|
|
29
|
+
the Software, and to permit persons to whom the Software
|
|
30
|
+
is furnished to do so, subject to the following
|
|
31
|
+
conditions:
|
|
32
|
+
|
|
33
|
+
The above copyright notice and this permission notice
|
|
34
|
+
shall be included in all copies or substantial portions
|
|
35
|
+
of the Software.
|
|
36
|
+
|
|
37
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
|
38
|
+
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
|
39
|
+
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
|
40
|
+
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
|
41
|
+
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
|
42
|
+
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
|
43
|
+
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
|
44
|
+
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
|
45
|
+
DEALINGS IN THE SOFTWARE.
|
|
46
|
+
|
|
47
|
+
==== libc-top-half/musl/COPYRIGHT
|
|
48
|
+
|
|
49
|
+
musl as a whole is licensed under the following standard MIT license:
|
|
50
|
+
|
|
51
|
+
----------------------------------------------------------------------
|
|
52
|
+
Copyright © 2005-2020 Rich Felker, et al.
|
|
53
|
+
|
|
54
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
|
55
|
+
a copy of this software and associated documentation files (the
|
|
56
|
+
"Software"), to deal in the Software without restriction, including
|
|
57
|
+
without limitation the rights to use, copy, modify, merge, publish,
|
|
58
|
+
distribute, sublicense, and/or sell copies of the Software, and to
|
|
59
|
+
permit persons to whom the Software is furnished to do so, subject to
|
|
60
|
+
the following conditions:
|
|
61
|
+
|
|
62
|
+
The above copyright notice and this permission notice shall be
|
|
63
|
+
included in all copies or substantial portions of the Software.
|
|
64
|
+
|
|
65
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
66
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
67
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
|
68
|
+
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
|
69
|
+
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
|
70
|
+
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
|
71
|
+
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
72
|
+
----------------------------------------------------------------------
|
|
73
|
+
|
|
74
|
+
Authors/contributors include:
|
|
75
|
+
|
|
76
|
+
A. Wilcox
|
|
77
|
+
Ada Worcester
|
|
78
|
+
Alex Dowad
|
|
79
|
+
Alex Suykov
|
|
80
|
+
Alexander Monakov
|
|
81
|
+
Andre McCurdy
|
|
82
|
+
Andrew Kelley
|
|
83
|
+
Anthony G. Basile
|
|
84
|
+
Aric Belsito
|
|
85
|
+
Arvid Picciani
|
|
86
|
+
Bartosz Brachaczek
|
|
87
|
+
Benjamin Peterson
|
|
88
|
+
Bobby Bingham
|
|
89
|
+
Boris Brezillon
|
|
90
|
+
Brent Cook
|
|
91
|
+
Chris Spiegel
|
|
92
|
+
Clément Vasseur
|
|
93
|
+
Daniel Micay
|
|
94
|
+
Daniel Sabogal
|
|
95
|
+
Daurnimator
|
|
96
|
+
David Carlier
|
|
97
|
+
David Edelsohn
|
|
98
|
+
Denys Vlasenko
|
|
99
|
+
Dmitry Ivanov
|
|
100
|
+
Dmitry V. Levin
|
|
101
|
+
Drew DeVault
|
|
102
|
+
Emil Renner Berthing
|
|
103
|
+
Fangrui Song
|
|
104
|
+
Felix Fietkau
|
|
105
|
+
Felix Janda
|
|
106
|
+
Gianluca Anzolin
|
|
107
|
+
Hauke Mehrtens
|
|
108
|
+
He X
|
|
109
|
+
Hiltjo Posthuma
|
|
110
|
+
Isaac Dunham
|
|
111
|
+
Jaydeep Patil
|
|
112
|
+
Jens Gustedt
|
|
113
|
+
Jeremy Huntwork
|
|
114
|
+
Jo-Philipp Wich
|
|
115
|
+
Joakim Sindholt
|
|
116
|
+
John Spencer
|
|
117
|
+
Julien Ramseier
|
|
118
|
+
Justin Cormack
|
|
119
|
+
Kaarle Ritvanen
|
|
120
|
+
Khem Raj
|
|
121
|
+
Kylie McClain
|
|
122
|
+
Leah Neukirchen
|
|
123
|
+
Luca Barbato
|
|
124
|
+
Luka Perkov
|
|
125
|
+
Lynn Ochs
|
|
126
|
+
M Farkas-Dyck (Strake)
|
|
127
|
+
Mahesh Bodapati
|
|
128
|
+
Markus Wichmann
|
|
129
|
+
Masanori Ogino
|
|
130
|
+
Michael Clark
|
|
131
|
+
Michael Forney
|
|
132
|
+
Mikhail Kremnyov
|
|
133
|
+
Natanael Copa
|
|
134
|
+
Nicholas J. Kain
|
|
135
|
+
orc
|
|
136
|
+
Pascal Cuoq
|
|
137
|
+
Patrick Oppenlander
|
|
138
|
+
Petr Hosek
|
|
139
|
+
Petr Skocik
|
|
140
|
+
Pierre Carrier
|
|
141
|
+
Reini Urban
|
|
142
|
+
Rich Felker
|
|
143
|
+
Richard Pennington
|
|
144
|
+
Ryan Fairfax
|
|
145
|
+
Samuel Holland
|
|
146
|
+
Segev Finer
|
|
147
|
+
Shiz
|
|
148
|
+
sin
|
|
149
|
+
Solar Designer
|
|
150
|
+
Stefan Kristiansson
|
|
151
|
+
Stefan O'Rear
|
|
152
|
+
Szabolcs Nagy
|
|
153
|
+
Timo Teräs
|
|
154
|
+
Trutz Behn
|
|
155
|
+
Will Dietz
|
|
156
|
+
William Haddon
|
|
157
|
+
William Pitcock
|
|
158
|
+
|
|
159
|
+
Portions of this software are derived from third-party works licensed
|
|
160
|
+
under terms compatible with the above MIT license:
|
|
161
|
+
|
|
162
|
+
The TRE regular expression implementation (src/regex/reg* and
|
|
163
|
+
src/regex/tre*) is Copyright © 2001-2008 Ville Laurikari and licensed
|
|
164
|
+
under a 2-clause BSD license (license text in the source files). The
|
|
165
|
+
included version has been heavily modified by Rich Felker in 2012, in
|
|
166
|
+
the interests of size, simplicity, and namespace cleanliness.
|
|
167
|
+
|
|
168
|
+
Much of the math library code (src/math/* and src/complex/*) is
|
|
169
|
+
Copyright © 1993,2004 Sun Microsystems or
|
|
170
|
+
Copyright © 2003-2011 David Schultz or
|
|
171
|
+
Copyright © 2003-2009 Steven G. Kargl or
|
|
172
|
+
Copyright © 2003-2009 Bruce D. Evans or
|
|
173
|
+
Copyright © 2008 Stephen L. Moshier or
|
|
174
|
+
Copyright © 2017-2018 Arm Limited
|
|
175
|
+
and labelled as such in comments in the individual source files. All
|
|
176
|
+
have been licensed under extremely permissive terms.
|
|
177
|
+
|
|
178
|
+
The ARM memcpy code (src/string/arm/memcpy.S) is Copyright © 2008
|
|
179
|
+
The Android Open Source Project and is licensed under a two-clause BSD
|
|
180
|
+
license. It was taken from Bionic libc, used on Android.
|
|
181
|
+
|
|
182
|
+
The AArch64 memcpy and memset code (src/string/aarch64/*) are
|
|
183
|
+
Copyright © 1999-2019, Arm Limited.
|
|
184
|
+
|
|
185
|
+
The implementation of DES for crypt (src/crypt/crypt_des.c) is
|
|
186
|
+
Copyright © 1994 David Burren. It is licensed under a BSD license.
|
|
187
|
+
|
|
188
|
+
The implementation of blowfish crypt (src/crypt/crypt_blowfish.c) was
|
|
189
|
+
originally written by Solar Designer and placed into the public
|
|
190
|
+
domain. The code also comes with a fallback permissive license for use
|
|
191
|
+
in jurisdictions that may not recognize the public domain.
|
|
192
|
+
|
|
193
|
+
The smoothsort implementation (src/stdlib/qsort.c) is Copyright © 2011
|
|
194
|
+
Lynn Ochs and is licensed under an MIT-style license.
|
|
195
|
+
|
|
196
|
+
The x86_64 port was written by Nicholas J. Kain and is licensed under
|
|
197
|
+
the standard MIT terms.
|
|
198
|
+
|
|
199
|
+
The mips and microblaze ports were originally written by Richard
|
|
200
|
+
Pennington for use in the ellcc project. The original code was adapted
|
|
201
|
+
by Rich Felker for build system and code conventions during upstream
|
|
202
|
+
integration. It is licensed under the standard MIT terms.
|
|
203
|
+
|
|
204
|
+
The mips64 port was contributed by Imagination Technologies and is
|
|
205
|
+
licensed under the standard MIT terms.
|
|
206
|
+
|
|
207
|
+
The powerpc port was also originally written by Richard Pennington,
|
|
208
|
+
and later supplemented and integrated by John Spencer. It is licensed
|
|
209
|
+
under the standard MIT terms.
|
|
210
|
+
|
|
211
|
+
All other files which have no copyright comments are original works
|
|
212
|
+
produced specifically for use as part of this library, written either
|
|
213
|
+
by Rich Felker, the main author of the library, or by one or more
|
|
214
|
+
contibutors listed above. Details on authorship of individual files
|
|
215
|
+
can be found in the git version control history of the project. The
|
|
216
|
+
omission of copyright and license comments in each file is in the
|
|
217
|
+
interest of source tree size.
|
|
218
|
+
|
|
219
|
+
In addition, permission is hereby granted for all public header files
|
|
220
|
+
(include/* and arch/*/bits/*) and crt files intended to be linked into
|
|
221
|
+
applications (crt/*, ldso/dlstart.c, and arch/*/crt_arch.h) to omit
|
|
222
|
+
the copyright notice and permission notice otherwise required by the
|
|
223
|
+
license, and to use these files without any requirement of
|
|
224
|
+
attribution. These files include substantial contributions from:
|
|
225
|
+
|
|
226
|
+
Bobby Bingham
|
|
227
|
+
John Spencer
|
|
228
|
+
Nicholas J. Kain
|
|
229
|
+
Rich Felker
|
|
230
|
+
Richard Pennington
|
|
231
|
+
Stefan Kristiansson
|
|
232
|
+
Szabolcs Nagy
|
|
233
|
+
|
|
234
|
+
all of whom have explicitly granted such permission.
|
|
235
|
+
|
|
236
|
+
This file previously contained text expressing a belief that most of
|
|
237
|
+
the files covered by the above exception were sufficiently trivial not
|
|
238
|
+
to be subject to copyright, resulting in confusion over whether it
|
|
239
|
+
negated the permissions granted in the license. In the spirit of
|
|
240
|
+
permissive licensing, and of not having licensing issues being an
|
|
241
|
+
obstacle to adoption, that text has been removed.
|
|
242
|
+
|
|
243
|
+
==== libc-bottom-half/cloudlibc/LICENSE
|
|
244
|
+
|
|
245
|
+
Copyright (c) 2015-2017 Nuxi (https://nuxi.nl/) and contributors.
|
|
246
|
+
|
|
247
|
+
Redistribution and use in source and binary forms, with or without
|
|
248
|
+
modification, are permitted provided that the following conditions
|
|
249
|
+
are met:
|
|
250
|
+
1. Redistributions of source code must retain the above copyright
|
|
251
|
+
notice, this list of conditions and the following disclaimer.
|
|
252
|
+
2. Redistributions in binary form must reproduce the above copyright
|
|
253
|
+
notice, this list of conditions and the following disclaimer in the
|
|
254
|
+
documentation and/or other materials provided with the distribution.
|
|
255
|
+
|
|
256
|
+
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
|
|
257
|
+
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
258
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
|
259
|
+
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
|
|
260
|
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
261
|
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
|
|
262
|
+
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
|
|
263
|
+
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
|
264
|
+
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
|
|
265
|
+
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
|
266
|
+
SUCH DAMAGE.
|
|
267
|
+
|
package/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 kyora
|
|
4
|
+
Copyright (c) 2026 Tembo
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
in the Software without restriction, including without limitation the rights
|
|
9
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
SOFTWARE.
|
package/audio.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";(()=>{var h=class extends AudioWorkletProcessor{cap=48e3;l=new Float32Array(this.cap);r=new Float32Array(this.cap);rd=0;wr=0;fill=0;target=2400;priming=!0;constructor(){super(),this.port.addEventListener("message",i=>{let r=i.data.port;r&&(r.addEventListener("message",t=>this.push(t.data)),r.start())}),this.port.start()}push({l:i,r}){for(let t=0;t<i.length;t++)this.l[this.wr]=i[t],this.r[this.wr]=r?r[t]:i[t],this.wr=(this.wr+1)%this.cap;if(this.fill+=i.length,this.fill>this.target*3){let t=this.fill-this.target;this.rd=(this.rd+t)%this.cap,this.fill-=t}}process(i,r){let t=r[0],e=t[0].length;if(this.priming){if(this.fill<this.target)return!0;this.priming=!1}if(this.fill<e)return this.priming=!0,!0;for(let s=0;s<e;s++)t[0][s]=this.l[this.rd],t[1]&&(t[1][s]=this.r[this.rd]),this.rd=(this.rd+1)%this.cap;return this.fill-=e,!0}};registerProcessor("pcm-player",h);})();
|
package/dav1d.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"use strict";(()=>{function y(c,e){let[o,n]=c===5||c===6?[.299,.114]:[.2126,.0722],i=1-o-n,t=e?1:255/219,a=e?1:255/224;return{m:[t,0,2*(1-o)*a,t,-2*n*(1-n)/i*a,-2*o*(1-o)/i*a,t,2*(1-n)*a,0],off:[e?0:16/255,128/255,128/255]}}var T=`#version 300 es
|
|
2
|
+
out vec2 uv;
|
|
3
|
+
void main() {
|
|
4
|
+
vec2 p = vec2(float(gl_VertexID & 1), float(gl_VertexID >> 1));
|
|
5
|
+
uv = vec2(p.x, 1.0 - p.y);
|
|
6
|
+
gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);
|
|
7
|
+
}`,R=`#version 300 es
|
|
8
|
+
precision highp float;
|
|
9
|
+
uniform sampler2D ty, tu, tv;
|
|
10
|
+
uniform mat3 m;
|
|
11
|
+
uniform vec3 off;
|
|
12
|
+
in vec2 uv;
|
|
13
|
+
out vec4 color;
|
|
14
|
+
void main() {
|
|
15
|
+
vec3 yuv = vec3(texture(ty, uv).r, texture(tu, uv).r, texture(tv, uv).r);
|
|
16
|
+
color = vec4(clamp(m * (yuv - off), 0.0, 1.0), 1.0);
|
|
17
|
+
}`;function U(){let c=new OffscreenCanvas(1,1),e=c.getContext("webgl2",{alpha:!1,antialias:!1,depth:!1,preserveDrawingBuffer:!0});if(!e)return null;let o=(t,a)=>{let r=e.createShader(t);return e.shaderSource(r,a),e.compileShader(r),r},n=e.createProgram();if(e.attachShader(n,o(e.VERTEX_SHADER,T)),e.attachShader(n,o(e.FRAGMENT_SHADER,R)),e.linkProgram(n),!e.getProgramParameter(n,e.LINK_STATUS))return null;e.useProgram(n),e.bindVertexArray(e.createVertexArray());let i=["ty","tu","tv"].map((t,a)=>{let r=e.createTexture();e.activeTexture(e.TEXTURE0+a),e.bindTexture(e.TEXTURE_2D,r);let s=a?e.LINEAR:e.NEAREST;return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,s),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,s),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.uniform1i(e.getUniformLocation(n,t),a),r});return e.pixelStorei(e.UNPACK_ALIGNMENT,1),{gl:e,canvas:c,m:e.getUniformLocation(n,"m"),off:e.getUniformLocation(n,"off"),tex:i}}var g=class{g;image=null;constructor(){try{this.g=U()}catch{this.g=null}}get backend(){return this.g?"webgl2":"2d"}draw(e,o,n,i,t){i<=0||t<=0||(this.g?this.drawGl(this.g,e,o,n,i,t):this.draw2d(e,o,n,i,t))}drawGl(e,o,n,i,t,a){let{gl:r,canvas:s}=e;(s.width!==t||s.height!==a)&&(s.width=t,s.height=a),r.viewport(0,0,t,a);let l=t+1>>1,u=a+1>>1;[[n.y,n.strideY,t,a],[n.u,n.strideUV,l,u],[n.v,n.strideUV,l,u]].forEach(([d,b,h,f],_)=>{r.activeTexture(r.TEXTURE0+_),r.bindTexture(r.TEXTURE_2D,e.tex[_]),r.pixelStorei(r.UNPACK_ROW_LENGTH,b),r.texImage2D(r.TEXTURE_2D,0,r.R8,h,f,0,r.RED,r.UNSIGNED_BYTE,n.heap,d)});let{m:v,off:m}=y(n.matrix,n.fullRange);r.uniformMatrix3fv(e.m,!0,v),r.uniform3fv(e.off,m),r.drawArrays(r.TRIANGLE_STRIP,0,4),o.drawImage(s,0,i)}draw2d(e,o,n,i,t){(!this.image||this.image.width!==i||this.image.height!==t)&&(this.image=new ImageData(i,t));let a=this.image.data,{m:r,off:s}=y(o.matrix,o.fullRange),l=o.heap;for(let u=0;u<t;u++){let E=o.y+u*o.strideY,v=(u>>1)*o.strideUV;for(let m=0;m<i;m++){let d=l[E+m]/255-s[0],b=l[o.u+v+(m>>1)]/255-s[1],h=l[o.v+v+(m>>1)]/255-s[2],f=(u*i+m)*4;a[f]=(r[0]*d+r[1]*b+r[2]*h)*255,a[f+1]=(r[3]*d+r[4]*b+r[5]*h)*255,a[f+2]=(r[6]*d+r[7]*b+r[8]*h)*255,a[f+3]=255}}e.putImageData(this.image,0,n)}};var x=class{constructor(e,o,n,i){this.x=e;this.r=o;this.pic=n;this.timestamp=i}draw(e,o,n,i){if(!this.pic)return;let t=new Uint32Array(this.x.memory.buffer,this.pic,9);this.r.draw(e,{heap:new Uint8Array(this.x.memory.buffer),strideY:t[2],strideUV:t[3],y:t[4],u:t[5],v:t[6],matrix:t[7],fullRange:t[8]!==0},o,Math.min(n,t[0]),Math.min(i,t[1]))}close(){this.pic&&this.x.sf_release(this.pic),this.pic=0}},p=class{constructor(e,o,n,i){this.x=e;this.err=o;this.r=n;this.sink=i;if(this.ctx=e.sf_open(),!this.ctx)throw new Error("dav1d: no decoder")}implementation="dav1d-wasm";queued=0;ctx;decode(e,o,n){if(!this.ctx)throw new Error("dav1d: decoder closed");let i=this.x,t=i.sf_alloc(e.length);if(!t)return this.fail("out of memory");new Uint8Array(i.memory.buffer,t,e.length).set(e);let a=i.sf_decode(this.ctx,t,e.length,this.err),r=new Int32Array(i.memory.buffer,this.err,1)[0];a?this.sink.output(new x(i,this.r,a,n)):r?this.fail(`decode error ${r}`):this.sink.none(n)}fail(e){let o=this.sink;queueMicrotask(()=>o.error(new Error(`dav1d: ${e}`)))}close(){this.ctx&&this.x.sf_close(this.ctx),this.ctx=0}};async function w(c){let e=null,o={wasi_snapshot_preview1:{clock_time_get:(s,l,u)=>(new DataView(e.buffer).setBigUint64(u,BigInt(Math.round(performance.now()*1e6)),!0),0)}},{instance:n}=await WebAssembly.instantiateStreaming(fetch(c,{credentials:"same-origin"}),o),i=n.exports;e=i.memory,i._initialize();let t=i.sf_alloc(4),a=i.sf_open();if(!t||!a)throw new Error("dav1d: initialization failed");i.sf_close(a);let r=new g;return{renderer:r.backend,open:s=>new p(i,t,r,s)}}self.starfoldDav1d={load:w};})();
|
package/dav1d.wasm
ADDED
|
Binary file
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import type { ConnectFailure, Preamble, ReconnectEvent, ReconnectOptions, Status } from './types.js';
|
|
2
|
+
export type { ConnectFailure, Preamble, ReconnectEvent, ReconnectOptions, ReconnectWhy, Status, } from './types.js';
|
|
3
|
+
export { NO_COMMON_CODEC, PROTOCOL_ERROR, UNMOUNTED, WORKER_FAILED, } from './types.js';
|
|
4
|
+
export interface ConnectOptions {
|
|
5
|
+
/** The WebSocket URL, used exactly as given (no query string is added). */
|
|
6
|
+
url: string;
|
|
7
|
+
/** WebSocket subprotocols. */
|
|
8
|
+
protocols?: string | string[];
|
|
9
|
+
/**
|
|
10
|
+
* Text message(s) sent first on every connection, before anything of starfold's; called
|
|
11
|
+
* before every connect. What it gives is copied, posted to the worker, sent once the socket
|
|
12
|
+
* opens and then dropped; it is never logged or passed to a callback.
|
|
13
|
+
*/
|
|
14
|
+
preamble?: Preamble;
|
|
15
|
+
}
|
|
16
|
+
export interface MountOptions {
|
|
17
|
+
connect: ConnectOptions;
|
|
18
|
+
/**
|
|
19
|
+
* The directory with worker.js, dav1d.js, dav1d.wasm and audio.js (a trailing slash is
|
|
20
|
+
* added if missing), resolved against this module's URL; default: this module's directory.
|
|
21
|
+
* It must be on the page's own origin: browsers start a worker only from a same-origin
|
|
22
|
+
* script, and a worker that fails to load ends the attempt with `connect-failed`.
|
|
23
|
+
*/
|
|
24
|
+
assetBase?: string | URL;
|
|
25
|
+
/** Play the desktop's audio (after the first user gesture). Default off. */
|
|
26
|
+
audio?: boolean;
|
|
27
|
+
/**
|
|
28
|
+
* Called once for every connection whose socket was asked for, with the close frame's code
|
|
29
|
+
* and reason as the server sent them (a reason is the server's text: a server that echoes a
|
|
30
|
+
* ticket there leaks it itself); `PROTOCOL_ERROR` (4000) when the client could not handle
|
|
31
|
+
* what the server sent; `NO_COMMON_CODEC` (4001) when the server found no codec this browser
|
|
32
|
+
* decodes, and the client closed the socket; `WORKER_FAILED` (4002) when the worker failed
|
|
33
|
+
* at run time, and the client stopped it (no connect follows); `UNMOUNTED` (1001) when
|
|
34
|
+
* `unmount()` ended it. `unmount()` stops the worker at once, so the server sees the socket
|
|
35
|
+
* drop without a close frame, and a close the server sent at the same moment is reported as
|
|
36
|
+
* `UNMOUNTED`.
|
|
37
|
+
*/
|
|
38
|
+
onClose?(code: number, reason: string): void;
|
|
39
|
+
/**
|
|
40
|
+
* `preamble-failed` and `connect-failed` carry a fixed `ConnectFailure`, never the
|
|
41
|
+
* preamble's own error. Each connect ends in exactly one of `onClose`, `preamble-failed`
|
|
42
|
+
* or `connect-failed`, unless a newer `connect()` or `unmount()` came first while it was
|
|
43
|
+
* still waiting for its preamble. After `onClose`, `onStatus('closed')` follows, except
|
|
44
|
+
* after `unmount()`; with `reconnect`, `reconnecting` follows instead while another attempt
|
|
45
|
+
* is coming (it then reports `connecting` and `open` as any connect), and `gave-up` then
|
|
46
|
+
* `closed` when none is. A reconnect attempt that ends in `preamble-failed` or
|
|
47
|
+
* `connect-failed` is followed by `gave-up` and `closed`. With `reconnect`, a worker that
|
|
48
|
+
* fails after a socket was asked for, or while waiting to reconnect, also ends in `gave-up`
|
|
49
|
+
* and `closed`; one that fails while the host's own connect() waits for its preamble ends in
|
|
50
|
+
* `connect-failed` alone, as without it.
|
|
51
|
+
*/
|
|
52
|
+
onStatus?(status: Status, detail?: ConnectFailure): void;
|
|
53
|
+
/**
|
|
54
|
+
* Reconnect after a close worth another attempt, as the host would: the same `connect()`,
|
|
55
|
+
* the preamble called again for each attempt. `true` takes the defaults; an object sets the
|
|
56
|
+
* limits (`ReconnectOptions`). Default off: every close ends the connection, as before. Which
|
|
57
|
+
* close codes reconnect is in the README's embedding section. A reconnect is a new viewer to
|
|
58
|
+
* the server (a new negotiation, then a keyframe).
|
|
59
|
+
*/
|
|
60
|
+
reconnect?: true | ReconnectOptions;
|
|
61
|
+
/**
|
|
62
|
+
* With `reconnect`: `reconnecting` (the attempt number, its delay and the code of the close
|
|
63
|
+
* that caused it), `reconnected` (an attempt reached open, with the code of the close it
|
|
64
|
+
* followed) and `gave-up` (why, and the last close's code). Each comes after the `onStatus` of
|
|
65
|
+
* the same name (`open` for `reconnected`). No close reason is in them: onClose has it.
|
|
66
|
+
*/
|
|
67
|
+
onReconnect?(e: ReconnectEvent): void;
|
|
68
|
+
}
|
|
69
|
+
export interface Handle {
|
|
70
|
+
/**
|
|
71
|
+
* Connects, calling the preamble first. While the preamble of an earlier connect is
|
|
72
|
+
* pending, starts over (the earlier answer is dropped); while waiting to reconnect,
|
|
73
|
+
* connects now and the reconnect count starts over; while a socket is open or being made,
|
|
74
|
+
* does nothing; after `unmount()`, does nothing.
|
|
75
|
+
*/
|
|
76
|
+
connect(): void;
|
|
77
|
+
/**
|
|
78
|
+
* Stops the worker at once (its socket drops), removes everything `mount` added, and
|
|
79
|
+
* then, if a socket had been asked for, reports `onClose(UNMOUNTED)`. After it returns no
|
|
80
|
+
* socket is opened, no message is sent, and no callback other than that one runs.
|
|
81
|
+
*/
|
|
82
|
+
unmount(): void;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Shows a starfold desktop in `container` and connects once; see `Handle` for the rest.
|
|
86
|
+
* Callbacks always run after the call that caused them has returned, from a queued task; a
|
|
87
|
+
* throwing callback is passed to `reportError` and changes nothing.
|
|
88
|
+
*/
|
|
89
|
+
export declare function mount(container: HTMLElement, options: MountOptions): Handle;
|
package/index.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var we=new Set(["a","v","au","kf","po"]);function J(t,e){return t.readOnly&&!we.has(e.split(",")[0])}function Z(t,e="audio.js"){let r=!1,o=!1,n=null;async function i(){if(!o){if(n&&n.state==="suspended"){n.resume().catch(()=>{});return}if(!(r||typeof AudioDecoder>"u")){r=!0;try{if(n=new AudioContext({latencyHint:"interactive",sampleRate:48e3}),await n.audioWorklet.addModule(e),o)return;let c=new AudioWorkletNode(n,"pcm-player",{outputChannelCount:[2]});c.connect(n.destination);let d=new MessageChannel;c.port.postMessage({port:d.port2},[d.port2]),t.post({t:"audioPort",port:d.port1},[d.port1]),n.state!=="running"&&n.resume().catch(()=>{})}catch(c){console.warn("[starfold] audio unavailable",c)}}}}function u(){o=!0,n?.close().catch(()=>{}),n=null}return{start:i,close:u}}function ee(t){let e=null,r=null;function o(){r===null||!navigator.clipboard||t.inIframe&&!document.hasFocus()||n(r)}async function n(i){try{if(typeof i=="string")await navigator.clipboard.writeText(i);else if(typeof ClipboardItem<"u")await navigator.clipboard.write([new ClipboardItem({"image/png":i})]);else return;r===i&&(r=null)}catch{}}return window.addEventListener("focus",o),{flush:o,onRemoteText(i){i!==e&&(e=i,r=i,o())},onRemoteImage(i){r=new Blob([new Uint8Array(i,1)],{type:"image/png"}),o()},noteLocal(i){e=i},dispose(){window.removeEventListener("focus",o)}}}function te(t){let e=null,r=document.createElement("canvas");function o(){if(!e)return;let n=new DataView(e),i=n.getUint16(2),u=n.getUint16(4),c=n.getUint16(6),d=n.getUint16(8);if(!i||!u){t.surface.style.cursor="none";return}let f=document.createElement("canvas");f.width=i,f.height=u,f.getContext("2d").putImageData(new ImageData(new Uint8ClampedArray(e,14,i*u*4),i,u),0,0);let x=window.devicePixelRatio||1,C=Math.max(i,u),m=Math.min(Math.max(t.view.scale,24/C),128/C),O=Math.max(1,Math.round(i*m)),A=Math.max(1,Math.round(u*m)),S=Math.max(1,Math.round(O*x)),l=Math.max(1,Math.round(A*x));r.width=S,r.height=l;let h=r.getContext("2d");h.imageSmoothingQuality="high",h.clearRect(0,0,S,l),h.drawImage(f,0,0,S,l);let a=r.toDataURL("image/png"),g=Math.round(c*m),R=Math.round(d*m);t.surface.style.cursor=x>1?`-webkit-image-set(url(${a}) ${x}x) ${g} ${R}, url(${a}) ${g} ${R}, default`:`url(${a}) ${g} ${R}, default`,x>1&&!t.surface.style.cursor&&(t.surface.style.cursor=`url(${a}) ${g} ${R}, default`)}return{set(n){e=n,o()},apply:o}}var ne={Video:1,VideoV2:5,Audio:2,Cursor:3,ClipImage:4,ClipImageUp:17,MicOpus:18,MicPcm:19},M={ack:t=>`a,${t}`,move:(t,e)=>`m,${t},${e}`,button:(t,e)=>`b,${t},${e?1:0}`,scroll:(t,e)=>`sp,${t.toFixed(1)},${e.toFixed(1)}`,key:(t,e)=>`k,${t},${e?1:0}`,releaseAll:"r",clipboard:t=>`c,${t}`,video:t=>`v,${t?1:0}`,audio:t=>`au,${t?1:0}`,mic:t=>`mi,${t?1:0}`,resize:(t,e)=>`sz,${t},${e}`,keyframe:"kf",pong:t=>`po,${t}`};function B(){let t=[];return{on(e,r,o,n){let i=o;e.addEventListener(r,i,n),t.push(()=>e.removeEventListener(r,i,n))},off(){for(let e of t.splice(0))e()}}}var j={Backspace:65288,Tab:65289,Enter:65293,Escape:65307,Delete:65535,Home:65360,ArrowLeft:65361,ArrowUp:65362,ArrowRight:65363,ArrowDown:65364,PageUp:65365,PageDown:65366,End:65367,Insert:65379,CapsLock:65509,NumLock:65407,ScrollLock:65300,Pause:65299,PrintScreen:65377,ContextMenu:65383,AltGraph:65027," ":32};for(let t=1;t<=24;t++)j["F"+t]=65469+t;var ke=65288,re=65293,Ee=65535,oe=t=>t>=32&&t<=126||t>=160&&t<=255?t:16777216+t;async function Me(t){if(t.type==="image/png")return t.arrayBuffer();let e=await createImageBitmap(t),r=new OffscreenCanvas(e.width,e.height);return r.getContext("2d").drawImage(e,0,0),(await r.convertToBlob({type:"image/png"})).arrayBuffer()}function ie(t,e,r,o=!1){let{kbd:n,surface:i,send:u,isMac:c}=t,d=B(),f=!1,x=65507,C=65508,m=65515,O=65516,A={ShiftLeft:65505,ShiftRight:65506,AltLeft:65513,AltRight:65514,NumpadEnter:65293};function S(s){let p=s.startsWith("Control"),k=s.startsWith("Meta")||s.startsWith("OS");if(!p&&!k)return;let P=s.endsWith("Right"),F=P?C:x,y=P?O:m;return t.remoteMac?c===p?F:y:c&&s.startsWith("Meta")||p?F:y}function l(s){let p=S(s.code);if(p!==void 0)return p;if(A[s.code]!==void 0)return s.code==="AltRight"&&s.key==="AltGraph"?65027:A[s.code];let k=s.key;return j[k]!==void 0?j[k]:!k||k==="Dead"||k==="Unidentified"||k==="Process"||[...k].length!==1?0:oe(k.codePointAt(0))}let h=new Map,a=null,g=0,R=(s,p)=>{h.set(s,p),u(M.key(p,!0))},L=s=>{u(M.key(s,!0)),u(M.key(s,!1))};function b(s){let p=h.get(s);p!==void 0&&(h.delete(s),u(M.key(p,!1)))}function E(){h.clear(),u(M.releaseAll)}function T(){a&&clearTimeout(a.timer),a=null}function w(s=a){if(!s||a!==s)return;if(a=null,clearTimeout(s.timer),!s.released)return R(s.code,s.ks);let k=[...h.keys()].some(P=>c?/^(Meta|OS)/.test(P):P.startsWith("Control"))?void 0:S(c?"MetaLeft":"ControlLeft");k&&u(M.key(k,!0)),L(s.ks),k&&u(M.key(k,!1))}function W(s){if(s.isComposing)return;r();let p=l(s);if(!p)return;let k=c?s.metaKey:s.ctrlKey;if(s.repeat&&a?.code===s.code){s.preventDefault();return}if(k&&!s.altKey&&(s.key==="v"||s.key==="V")&&!s.repeat){T();let F={code:s.code,ks:p,timer:setTimeout(()=>w(F),150),converting:!1,released:!1};a=F;return}s.preventDefault();let P=h.get(s.code);if(s.repeat&&P!==void 0){u(M.key(P,!0));return}R(s.code,p)}function D(s){if(s.preventDefault(),a?.code===s.code&&(a.converting?a.released=!0:w()),b(s.code),c&&(s.code==="MetaLeft"||s.code==="MetaRight"))for(let p of h.keys())/^(Shift|Control|Alt|Meta)/.test(p)||b(p)}for(let s of[n,i])d.on(s,"keydown",W),d.on(s,"keyup",D);d.on(n,"paste",s=>{s.preventDefault();let p=++g,k=s.clipboardData,P=k?.getData("text/plain");if(P){e.noteLocal(P),u(M.clipboard(P)),w();return}let F=k?[...k.items].find(I=>I.kind==="file"&&I.type.startsWith("image/"))?.getAsFile():null;if(!F){w();return}let y=a;y&&(clearTimeout(y.timer),y.converting=!0,y.timer=setTimeout(()=>w(y),3e3));function v(I){f||p!==g||(t.sendBin(ne.ClipImageUp,new Uint8Array(I)),y&&w(y))}function _(I){console.warn("[starfold] image paste failed",I),y&&a===y&&T()}Me(F).then(v,_)});function U(s){for(let p of s)L(p===`
|
|
2
|
+
`?re:oe(p.codePointAt(0)))}return d.on(n,"compositionend",s=>{s.data&&U(s.data),n.value=""}),d.on(n,"input",s=>{let p=s;p.isComposing||(p.inputType==="insertText"&&p.data?U(p.data):p.inputType==="deleteContentBackward"?L(ke):p.inputType==="deleteContentForward"?L(Ee):(p.inputType==="insertLineBreak"||p.inputType==="insertParagraph")&&L(re),n.value="")}),d.on(window,"blur",E),o&&d.on(n,"blur",()=>{T(),g++;for(let s of h.keys())b(s)}),d.on(i,"focus",()=>n.focus({preventScroll:!0})),!o&&!t.inIframe&&n.focus({preventScroll:!0}),{releaseAll:E,dispose(){f=!0,d.off(),T()}}}var Re=10,Ce=550,Se=400,Te=24,Ae=32;function se(t,e){let{send:r}=t,o=new Map,n=null,i={x:0,y:0},u="",c,d=[0,0],f=null,x=()=>{let a=t.surface.getBoundingClientRect();return`${a.left},${a.top},${a.width},${a.height},${e.deskPerPx()}`},C=()=>{let a=0,g=0;for(let R of o.values())a+=R.x,g+=R.y;return[a/o.size,g/o.size]},m=a=>{r(M.button(a,!0)),r(M.button(a,!1))};function O(a){try{t.surface.setPointerCapture(a.pointerId)}catch{}o.set(a.pointerId,{x:a.clientX,y:a.clientY}),o.size===1?(n="pending",i={x:a.clientX,y:a.clientY},u=x(),f&&f.geometry!==u&&(f=null),c=setTimeout(()=>{n==="pending"&&(f=null,e.moveTo(i.x,i.y),m(3),n="done",navigator.vibrate?.(10))},Ce)):o.size===2&&(clearTimeout(c),f=null,n==="drag"&&r(M.button(1,!1)),n="scroll",d=C())}function A(a){let g=o.get(a.pointerId);if(g){if(g.x=a.clientX,g.y=a.clientY,n==="pending"&&Math.hypot(g.x-i.x,g.y-i.y)>Re&&(clearTimeout(c),f=null,n="drag",e.moveTo(i.x,i.y),r(M.button(1,!0))),n==="drag")e.moveTo(g.x,g.y);else if(n==="scroll"&&o.size>=2){let R=C(),L=e.deskPerPx();e.queueScroll((d[0]-R[0])*L,(d[1]-R[1])*L),d=R}}}function S(a){if(o.delete(a.pointerId)){if(n==="pending"){clearTimeout(c);let g=performance.now(),R=x(),L=f?Math.hypot(i.x-f.x,i.y-f.y):1/0,b=f&&f.geometry===R&&u===R&&g-f.t<Se&&L<Te&&L*e.deskPerPx()<Ae?f:i;f={x:b.x,y:b.y,t:g,geometry:R},e.moveTo(b.x,b.y),m(1),e.tapped?.(),n="done"}else n==="drag"?(r(M.button(1,!1)),n="done"):n==="scroll"&&o.size<2&&(n="done");o.size===0&&(n=null)}}function l(a){clearTimeout(c),f=null,n==="drag"&&r(M.button(1,!1)),o.delete(a.pointerId),o.size===0&&(n=null)}function h(){clearTimeout(c),c=void 0}return{down:O,move:A,up:S,cancel:l,dispose:h}}var ae=[1,2,3,8,9];function ce(t,e,r){let{surface:o,send:n}=t,i=B();function u(l){let h=o.getBoundingClientRect(),a=Math.round((l.clientX-h.left)*t.desk.w/h.width),g=Math.round((l.clientY-h.top)*t.desk.h/h.height);return[Math.max(0,Math.min(t.desk.w-1,a)),Math.max(0,Math.min(t.desk.h-1,g))]}let c="";function d(l,h=!1){if(!t.desk.w)return;let a=M.move(...u(l));(a!==c||h)&&(c=a,n(a))}let f=0,x=0,C=!1,m=0;function O(l,h){f+=l,x+=h,!C&&(C=!0,m=requestAnimationFrame(()=>{C=!1,!(Math.abs(f)<.5&&Math.abs(x)<.5)&&(n(M.scroll(f,x)),f=0,x=0)}))}let A=()=>t.desk.w/o.getBoundingClientRect().width,S=se(t,{moveTo:(l,h)=>d({clientX:l,clientY:h},!0),queueScroll:O,deskPerPx:A,tapped:r});return i.on(o,"pointermove",l=>{l.pointerType==="touch"?S.move(l):d(l)}),i.on(o,"pointerdown",l=>{if(l.preventDefault(),e(),l.pointerType==="touch"){S.down(l);return}t.kbd.focus({preventScroll:!0}),d(l);try{o.setPointerCapture(l.pointerId)}catch{}n(M.button(ae[l.button]||1,!0))}),i.on(o,"pointerup",l=>{if(l.preventDefault(),l.pointerType==="touch"){S.up(l);return}d(l),n(M.button(ae[l.button]||1,!1))}),i.on(o,"pointercancel",l=>{l.pointerType==="touch"?S.cancel(l):n(M.releaseAll)}),i.on(o,"contextmenu",l=>l.preventDefault()),i.on(o,"wheel",l=>{l.preventDefault(),d(l);let h=(l.deltaMode===1?40:l.deltaMode===2?800:1)*A();O(l.deltaX*h,l.deltaY*h)},{passive:!1}),{dispose(){i.off(),C&&cancelAnimationFrame(m),C=!1,S.dispose()}}}function le(t,e){if(t.writing){t.next?.close(),t.next=e;return}t.writing=!0,t.writer.write(e).catch(()=>{}).finally(()=>{t.writing=!1;let r=t.next;r&&(t.next=null,le(t,r))})}var ue=(t,e)=>e?ue(e,t%e):t;function de(t,e,r,o,n,i=()=>({w:window.innerWidth,h:window.innerHeight}),u={},c=!1){let d=[],f=[[0,1]],x=!1,C=!1,m=null,O=r?"video":"canvas",A=()=>{e.style.display=O==="canvas"?"":"none";for(let b of d)b.video.style.display=O==="video"?"":"none"};A();function S(){for(let b of d)b.video.srcObject=null,b.gen.stop(),b.next?.close(),b.next=null,b.video.remove();d=[],x=!1}function l(b){f=b,S()}function h(){for(let[b,E]of f){let T=new MediaStreamTrackGenerator({kind:"video"}),w=document.createElement("video");w.className="stripe",Object.assign(w.style,u),w.muted=!0,w.autoplay=!0,w.playsInline=!0,w.disablePictureInPicture=!0,w.style.top=`${b/t.desk.h*100}%`,w.style.height=`${E/t.desk.h*100}%`,w.srcObject=new MediaStream([T]),t.surface.appendChild(w),w.play().catch(()=>{}),d.push({video:w,gen:T,writer:T.writable.getWriter(),writing:!1,next:null})}}function a(b){if(!r){for(let E of b)E.frame.close();return}if(d.length||h(),!C&&!x&&d[0]&&b.length){x=!0;let E=d[0].video,T=()=>{E.isConnected&&(C=!0,n())};"requestVideoFrameCallback"in E?m={v:E,id:E.requestVideoFrameCallback(T),frame:!1}:m={v:E,id:requestAnimationFrame(T),frame:!0}}for(let E of b){let T=d[E.i];T?le(T,E.frame):E.frame.close()}}function g(b){O=r?b:"canvas",O==="canvas"&&S(),A()}function R(){let{w:b,h:E}=t.desk;if(!b)return;let{w:T,h:w}=i(),W=window.devicePixelRatio||1,D=E/f.reduce((k,[P])=>ue(k,P),E),U=(Math.min(T/b,w/E)||1)*E*W,s=Math.floor(U/D)*D,p=c&&s<D?U:Math.max(D,s);t.view.scale=p/W/E,t.surface.style.width=`${b*t.view.scale}px`,t.surface.style.height=`${E*t.view.scale}px`,o()}function L(){m?.frame?cancelAnimationFrame(m.id):m&&m.v.cancelVideoFrameCallback(m.id),m=null,S()}return{build:l,present:a,layout:R,setSurface:g,dispose:L}}function fe(t){if(t.length<10)return;let e=t.slice(1).map((o,n)=>o-t[n]).filter(o=>o>0);if(e.sort((o,n)=>o-n),e.length<9)return;let r=e.slice(e.length>>2,e.length-(e.length>>2));return Math.round(1e3*r.length/r.reduce((o,n)=>o+n,0))}var Oe=t=>{typeof globalThis.reportError=="function"?globalThis.reportError(t):setTimeout(()=>{throw t})},$=class{constructor(e=Oe){this.report=e}queue=[];scheduled=!1;sealed=!1;call(e){this.sealed||(this.queue.push(e),this.schedule())}seal(e){this.sealed=!0,this.queue=e?[e]:[],e&&this.schedule()}schedule(){this.scheduled||(this.scheduled=!0,queueMicrotask(()=>this.flush()))}flush(){for(this.scheduled=!1;this.queue.length;){let e=this.queue.shift();try{e()}catch(r){this.report(r)}}}};var Y=t=>({kind:"preamble-failed",cause:t,message:{threw:"the preamble threw",rejected:"the preamble's promise rejected","not-text":"the preamble gave something other than a string or an array of strings"}[t]}),Q={kind:"connect-failed",message:"the WebSocket could not be created (check the URL and the subprotocols)"};async function pe(t){let e;try{e=t?t():[]}catch{return{ok:!1,failure:Y("threw")}}try{e=await e}catch{return{ok:!1,failure:Y("rejected")}}try{return{ok:!0,msgs:Pe(e)}}catch{return{ok:!1,failure:Y("not-text")}}}function Pe(t){if(typeof t=="string")return[t];if(!Array.isArray(t))throw new TypeError("not text");let e=t.length,r=[];for(let o=0;o<e;o++){let n=t[o];if(typeof n!="string")throw new TypeError("not text");r.push(n)}return r}var H={code:1001,reason:"unmounted"},Le={code:4e3,reason:"starfold: protocol error"},Fe={code:4001,reason:"starfold: no common codec"},V={code:4002,reason:"starfold: worker failed"};var K=class{constructor(e,r){this.port=e;this.o=r;this.dispatch=new $(r.report),e.addEventListener("message",this.listener),e.start()}id=0;phase="idle";live=!0;ended=!1;closeQueued=!1;dispatch;listener=e=>this.onUp(e.data);lastCode=0;connect(){!this.live||this.phase==="socket"||(this.o.reconnect?.reset(),this.attempt())}attempt(){this.id++,this.phase="asking",this.down({t:"connect",id:this.id}),this.status("connecting")}workerFailed(){if(!this.live)return;let e=this.phase,r=this.o.reconnect?.pending??!1;this.phase="idle",this.live=!1,this.port.removeEventListener("message",this.listener),this.port.close(),e==="socket"?this.closed(V.code,V.reason):e==="asking"?this.failed("connect-failed",Q):r&&this.giveUp("connect-failed"),this.o.reconnect?.reset()}end(){if(this.ended)return;this.ended=!0,this.o.reconnect?.reset();let e=this.live&&this.phase==="socket"||this.closeQueued;this.live=!1,this.phase="idle",this.port.removeEventListener("message",this.listener),this.port.close();let r=this.o.onClose;this.dispatch.seal(e&&r?()=>r(H.code,H.reason):void 0)}onUp(e){if(!(!this.live||e.id!==this.id))switch(e.t){case"preamble":this.phase==="asking"&&this.answer(e.id);break;case"open":if(this.phase!=="socket")return;if(this.o.opened?.(),this.status("open"),this.o.reconnect){let r=this.o.reconnect;r.reconnecting&&this.event({kind:"reconnected",attempt:r.attempt,code:this.lastCode}),r.opened()}break;case"closed":if(this.phase!=="socket")return;this.phase="idle",this.closed(e.code,e.reason,e.openMs);break;case"connectFailed":if(this.phase!=="socket")return;this.phase="idle",this.failed("connect-failed",Q);break}}async answer(e){let r=await pe(this.o.preamble);if(!this.live||e!==this.id||this.phase!=="asking")return;if(!r.ok){this.phase="idle",this.down({t:"preambleFailed",id:e}),this.failed("preamble-failed",r.failure);return}let o=()=>{!this.live||e!==this.id||this.phase!=="asking"||(this.phase="socket",this.down({t:"preamble",id:e,msgs:r.msgs}))},n=this.o.reconnect;n?.reconnecting?n.hold(o,()=>this.expireAsking(e)):o()}expireAsking(e){!this.live||e!==this.id||this.phase!=="asking"||(this.phase="idle",this.down({t:"preambleFailed",id:e}),this.giveUp("time"))}failed(e,r){let o=this.o.reconnect,n=o?.reconnecting??!1;this.status(e,r),n&&this.giveUp(e),o?.reset()}closed(e,r,o){let n=this.o.onClose;n&&(this.closeQueued=!0,this.dispatch.call(()=>{this.closeQueued=!1,n(e,r)})),this.lastCode=e;let i=this.o.reconnect;if(!i){this.status("closed");return}if(!this.live){this.giveUp("code");return}let u=this.id,c;try{c=i.closed(e,r,o)}catch(d){this.dispatch.call(()=>{throw d}),c={t:"give-up",why:"code"}}if(!(!this.live||this.id!==u||this.phase!=="idle")){if(c.t==="give-up"){this.giveUp(c.why);return}this.status("reconnecting"),this.event({kind:"reconnecting",attempt:c.attempt,delayMs:c.delayMs,code:e}),i.schedule(c.delayMs,()=>{if(!this.live||this.phase!=="idle")return;this.attempt();let d=this.id;i.guard(()=>this.expireAsking(d))},()=>{this.live&&this.phase==="idle"&&this.giveUp("time")})}}giveUp(e){this.o.reconnect?.reset(),this.status("gave-up"),this.event({kind:"gave-up",why:e,code:this.lastCode}),this.status("closed")}event(e){let r=this.o.onReconnect;r&&this.dispatch.call(()=>r(e))}status(e,r){let o=this.o.onStatus;o&&this.dispatch.call(()=>o(e,r))}down(e){this.port.postMessage(e,[])}};var z=class{list=[];done=!1;undone=[];add(e,r){if(this.done){r(),this.undone.push(e);return}this.list.push({name:e,undo:r})}get registered(){return this.list.map(e=>e.name)}run(){if(this.done)return;this.done=!0;let e=null;for(let r of this.list){try{r.undo()}catch(o){e??=o}this.undone.push(r.name)}if(e)throw e}};var N={initialMs:500,factor:2,capMs:3e4,maxAttempts:10,maxMs:3e5};function De(t){return t===1006||t===1001||t===1012||t===1013?!0:G(t)&&t!==4406}var G=t=>t>=4400&&t<=4499;function Ue(t,e,r){let o=Math.min(e.capMs,e.initialMs*e.factor**(t-1));return Math.floor(r()*o)}function me(){return{now:()=>Date.now(),setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t),random:Math.random,hidden:()=>document.visibilityState==="hidden",online:()=>navigator.onLine!==!1,onWake(t){return document.addEventListener("visibilitychange",t),window.addEventListener("online",t),window.addEventListener("offline",t),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",t),window.removeEventListener("offline",t)}}}}function _e(t){let e=t===!0?{}:t,r={initialMs:e.initialMs??N.initialMs,factor:e.factor??N.factor,capMs:e.capMs??N.capMs,maxAttempts:e.maxAttempts??N.maxAttempts,maxMs:e.maxMs??N.maxMs};for(let[o,n]of Object.entries(r))if(!(typeof n=="number"&&Number.isFinite(n)&&(o==="factor"?n>=1:n>0)&&(o!=="maxAttempts"||Number.isInteger(n))))throw new TypeError(`starfold: reconnect.${o} must be a positive number`);return r}var X=class{constructor(e,r){this.env=r;this.o=_e(e),this.should=e===!0?void 0:e.shouldReconnect}o;should;run=null;openedAt=null;wait=null;get reconnecting(){return this.run!==null&&this.run.attempts>0}get attempt(){return this.run?.attempts??0}get pending(){return this.wait!==null}get expired(){return this.run!==null&&this.left()<=0}opened(){this.openedAt=this.env.now(),this.run&&(this.run.neverOpened=0)}closed(e,r,o){let n=this.env.now(),i=o!==void 0?o:this.openedAt===null?null:n-this.openedAt;this.openedAt=null,i!==null&&i>=1e4&&(this.run=null);let u=this.run??={start:n,attempts:0,neverOpened:0,last44xx:null},c=i!==null&&i<1e4,d=c&&G(e)&&u.last44xx===e;return u.last44xx=c&&G(e)?e:null,u.neverOpened=e===1006&&i===null?u.neverOpened+1:0,(this.should?this.should(e,r):De(e))?d?{t:"give-up",why:"repeated-close"}:u.neverOpened>=3?{t:"give-up",why:"never-opened"}:u.attempts>=this.o.maxAttempts?{t:"give-up",why:"attempts"}:this.left()<=0?{t:"give-up",why:"time"}:(u.attempts++,{t:"retry",attempt:u.attempts,delayMs:Ue(u.attempts,this.o,this.env.random)}):{t:"give-up",why:"code"}}left(){return this.run?this.o.maxMs-(this.env.now()-this.run.start):1/0}awake(){return!this.env.hidden()&&this.env.online()}schedule(e,r,o){let n=!this.env.online();this.start(o,()=>n&&this.awake(),r);let i=this.wait;i.delay=this.env.setTimeout(()=>{i.delay=null,n=!0,this.check()},e),this.wake=()=>{this.env.online()||(n=!0)}}hold(e,r){this.start(r,()=>this.awake(),e),this.check()}guard(e){this.start(e,()=>!1,()=>{}),this.check()}ready=()=>!1;onReady=()=>{};onExpire=()=>{};wake=()=>{};start(e,r,o){this.cancel(),this.ready=r,this.onReady=o,this.onExpire=e,this.wake=()=>{};let n={delay:null,deadline:null,stop:()=>{}};this.wait=n;let i=()=>{n.deadline=this.env.setTimeout(()=>{n.deadline=null,this.expired?this.check():i()},Math.max(0,this.left()))};Number.isFinite(this.left())&&i(),n.stop=this.env.onWake(()=>{this.wake(),this.check()})}check(){if(this.wait){if(this.expired){let e=this.onExpire;this.cancel(),e()}else if(this.ready()){let e=this.onReady;this.cancel(),e()}}}cancel(){let e=this.wait;this.wait=null,e&&(e.delay!==null&&this.env.clearTimeout(e.delay),e.deadline!==null&&this.env.clearTimeout(e.deadline),e.stop())}reset(){this.cancel(),this.run=null,this.openedAt=null}};function he(t,e){switch(t.t){case"frames":return e.frames(t);case"surface":return e.surface(t);case"hello":return e.hello(t);case"codec":return e.codec(t);case"cursor":return e.cursor(t)}}var ve={position:"relative",outline:"none",touchAction:"none"},be={position:"absolute",inset:"0",width:"100%",height:"100%",display:"block",pointerEvents:"none"},ge={position:"absolute",left:"0",width:"100%",display:"block",pointerEvents:"none",objectFit:"fill"},ye={position:"fixed",left:"0",bottom:"0",width:"1px",height:"1px",opacity:"0.01",border:"0",padding:"0",resize:"none",pointerEvents:"none",fontSize:"16px"};function q(t,e){Object.assign(t.style,e)}function xe(t,e){let r=new URL(String(t??"."),e);return r.pathname.endsWith("/")||(r.pathname+="/"),r}function Rt(t,e){if(!window.isSecureContext)throw new Error("starfold: browsers only decode video on secure pages (HTTPS or localhost)");let r=xe(e.assetBase,import.meta.url),o=e.reconnect?new X(e.reconnect,me()):void 0,n=document.createElement("canvas");if(!n.transferControlToOffscreen)throw new Error("starfold: this browser lacks OffscreenCanvas support");let i=new Worker(new URL("worker.js",r)),u=!1,c=new z;c.add("worker",()=>i.terminate());let d=new MessageChannel;c.add("life port",()=>d.port1.close());let f=document.createElement("div");f.tabIndex=0,q(f,ve),q(n,be),f.append(n);let x=document.createElement("textarea");x.setAttribute("aria-hidden","true"),q(x,ye),t.append(f,x),c.add("elements",()=>{f.remove(),x.remove()});let C=(y,v=[])=>{u||i.postMessage(y,v)},m={worker:i,post:C,send:y=>{J(m,y)||C({t:"send",d:y})},sendBin:(y,v)=>{if(m.readOnly)return;let _=new Uint8Array(v.byteLength+1);_[0]=y,_.set(v,1),C({t:"sendBin",d:_.buffer},[_.buffer])},surface:f,kbd:x,tools:document.createElement("div"),isMac:/Mac|iPhone|iPad/.test(navigator.platform||navigator.userAgent),remoteMac:!1,readOnly:!1,inIframe:window!==window.top,desk:{w:0,h:0},view:{scale:1}},O=[],A=0,S=y=>{if(u)return;if(O.push(y),y-O[0]<500){A=requestAnimationFrame(S);return}A=0;let v=fe(O);v&&C({t:"hz",hz:v})};A=requestAnimationFrame(S),c.add("refresh-rate frame",()=>{A&&cancelAnimationFrame(A)});let l=te(m),h=typeof MediaStreamTrackGenerator<"u",a=de(m,n,h,l.apply,()=>{},()=>({w:t.clientWidth,h:t.clientHeight}),ge,!0);c.add("video",()=>a.dispose());let g=ee(m);c.add("clipboard",()=>g.dispose());let R=e.audio?Z(m,new URL("audio.js",r)):null;R&&c.add("audio",()=>R.close());let L=()=>{R?.start(),g.flush()},b=ce(m,L,()=>x.focus({preventScroll:!0}));c.add("pointer",()=>b.dispose());let E=ie(m,g,L,!0);c.add("keyboard",()=>E.dispose());let T=null,w=(y=!1)=>{let v=!document.hidden&&t.clientWidth>0&&t.clientHeight>0;(v!==T||y)&&(T=v,C({t:"video",on:v}))},W=()=>{u||(w(),document.hidden&&m.send(M.releaseAll))};document.addEventListener("visibilitychange",W),c.add("visibilitychange",()=>document.removeEventListener("visibilitychange",W));let D=new ResizeObserver(()=>{u||(a.layout(),w())});D.observe(t),c.add("resize observer",()=>D.disconnect());let U=new K(d.port1,{preamble:e.connect.preamble,onClose:e.onClose,onStatus:e.onStatus,onReconnect:e.onReconnect,reconnect:o,opened:()=>w(!0)}),s=y=>{u||(y.preventDefault(),i.terminate(),U.workerFailed())};i.addEventListener("error",s),c.add("worker error listener",()=>i.removeEventListener("error",s));let p=y=>{u||he(y.data,{frames:v=>a.present(v.parts),surface:v=>a.setSurface(v.s),hello:v=>{m.desk.w=v.w,m.desk.h=v.h,m.remoteMac=v.os==="macos",m.readOnly=!!v.readOnly,a.build(v.stripes&&v.stripes.length?v.stripes:[[0,v.h]]),a.layout()},codec:v=>{v.error===void 0&&(m.desk.w=v.w,m.desk.h=v.h,a.build(v.stripes.map(_=>[_.y,_.h])),a.layout())},cursor:v=>l.set(v.buf)})};i.addEventListener("message",p),c.add("worker message listener",()=>i.removeEventListener("message",p));let k=n.transferControlToOffscreen(),P=e.connect.protocols;C({t:"init",canvas:k,url:e.connect.url,presentToMain:h,embed:{protocols:P===void 0?void 0:[].concat(P),life:d.port2}},[k,d.port2]),w();let F={connect(){u||U.connect()},unmount(){if(!u){u=!0;try{c.run()}finally{U.end()}}}};return F.connect(),F}export{Fe as NO_COMMON_CODEC,Le as PROTOCOL_ERROR,H as UNMOUNTED,V as WORKER_FAILED,Rt as mount};
|
package/package.json
CHANGED
|
@@ -1,6 +1,15 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@starfold/web",
|
|
3
|
+
"version": "0.3.2",
|
|
4
|
+
"description": "starfold's browser client, to mount in another page",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "index.js",
|
|
7
|
+
"types": "index.d.ts",
|
|
8
|
+
"license": "MIT AND BSD-2-Clause",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/kyora-sh/starfold.git",
|
|
12
|
+
"directory": "packages/web"
|
|
13
|
+
},
|
|
14
|
+
"sideEffects": false
|
|
15
|
+
}
|
package/types.d.ts
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/** Text message(s) to send before anything of starfold's: a ticket, say. Called before every connect. */
|
|
2
|
+
export type Preamble = () => string | string[] | Promise<string | string[]>;
|
|
3
|
+
/**
|
|
4
|
+
* Why a connect failed before any socket existed. Fixed values: the preamble's own error (or
|
|
5
|
+
* the URL) is never passed on, since it may hold a credential.
|
|
6
|
+
*/
|
|
7
|
+
export type ConnectFailure = {
|
|
8
|
+
kind: 'preamble-failed';
|
|
9
|
+
/** The preamble threw, its promise rejected, or it gave something other than text. */
|
|
10
|
+
cause: 'threw' | 'rejected' | 'not-text';
|
|
11
|
+
message: string;
|
|
12
|
+
} | {
|
|
13
|
+
kind: 'connect-failed';
|
|
14
|
+
message: string;
|
|
15
|
+
};
|
|
16
|
+
export type Status = 'connecting' | 'open' | 'closed' | 'preamble-failed' | 'connect-failed' | 'reconnecting' | 'gave-up';
|
|
17
|
+
/**
|
|
18
|
+
* The `reconnect` option's limits. The delay before attempt n is a random time below
|
|
19
|
+
* min(capMs, initialMs * factor^(n-1)); a run gives up after maxAttempts attempts or maxMs
|
|
20
|
+
* since its first close on the wall clock (offline, hidden or suspended time included),
|
|
21
|
+
* whichever comes first. A connection that stays open for 10 s ends the run. Each limit is a
|
|
22
|
+
* positive number, maxAttempts a whole one and factor at least 1, or mount() throws.
|
|
23
|
+
*/
|
|
24
|
+
export interface ReconnectOptions {
|
|
25
|
+
/** Default 500. */
|
|
26
|
+
initialMs?: number;
|
|
27
|
+
/** Default 2. */
|
|
28
|
+
factor?: number;
|
|
29
|
+
/** Default 30000. */
|
|
30
|
+
capMs?: number;
|
|
31
|
+
/** Default 10. */
|
|
32
|
+
maxAttempts?: number;
|
|
33
|
+
/** Default 300000 (5 min). */
|
|
34
|
+
maxMs?: number;
|
|
35
|
+
/**
|
|
36
|
+
* Whether a close with this code and reason is worth another attempt; replaces the default
|
|
37
|
+
* table. Called at once, not queued; one that throws counts as false (and is reported).
|
|
38
|
+
*/
|
|
39
|
+
shouldReconnect?(code: number, reason: string): boolean;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Why reconnecting stopped: `code`, a close not worth another attempt; `repeated-close`, two
|
|
43
|
+
* closes in a row with the same 44xx code, each within 10 s of its open; `never-opened`, three
|
|
44
|
+
* 1006 closes in a row that never reached open (an upgrade the server refuses looks like this);
|
|
45
|
+
* `attempts` or `time`, a limit; `preamble-failed` or `connect-failed`, a reconnect attempt that
|
|
46
|
+
* ended so.
|
|
47
|
+
*/
|
|
48
|
+
export type ReconnectWhy = 'code' | 'repeated-close' | 'never-opened' | 'attempts' | 'time' | 'preamble-failed' | 'connect-failed';
|
|
49
|
+
/**
|
|
50
|
+
* What `onReconnect` gets; `code` is the last close's. The close's reason is not in it: it is
|
|
51
|
+
* the server's or a gateway's text, and only onClose and shouldReconnect get it.
|
|
52
|
+
*/
|
|
53
|
+
export type ReconnectEvent = {
|
|
54
|
+
kind: 'reconnecting';
|
|
55
|
+
attempt: number;
|
|
56
|
+
delayMs: number;
|
|
57
|
+
code: number;
|
|
58
|
+
} | {
|
|
59
|
+
kind: 'reconnected';
|
|
60
|
+
attempt: number;
|
|
61
|
+
code: number;
|
|
62
|
+
} | {
|
|
63
|
+
kind: 'gave-up';
|
|
64
|
+
why: ReconnectWhy;
|
|
65
|
+
code: number;
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* What onClose gets when unmount() ends a connection whose socket was asked for: 1001, "going
|
|
69
|
+
* away". unmount() stops the worker at once, so the server sees the socket drop without a
|
|
70
|
+
* close frame, and a close the server sent at the same moment is reported as this.
|
|
71
|
+
*/
|
|
72
|
+
export declare const UNMOUNTED: {
|
|
73
|
+
readonly code: 1001;
|
|
74
|
+
readonly reason: "unmounted";
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* What onClose gets when the client could not handle what the server sent (a message that is
|
|
78
|
+
* not an object, a malformed offer): the client closes the socket and reports this, whatever
|
|
79
|
+
* the socket's own close says.
|
|
80
|
+
*/
|
|
81
|
+
export declare const PROTOCOL_ERROR: {
|
|
82
|
+
readonly code: 4000;
|
|
83
|
+
readonly reason: "starfold: protocol error";
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* What onClose gets when the server finds no codec this browser decodes (its `codec` message
|
|
87
|
+
* carries an error): nothing could be shown, so the client closes the socket with this code.
|
|
88
|
+
*/
|
|
89
|
+
export declare const NO_COMMON_CODEC: {
|
|
90
|
+
readonly code: 4001;
|
|
91
|
+
readonly reason: "starfold: no common codec";
|
|
92
|
+
};
|
|
93
|
+
/**
|
|
94
|
+
* What onClose gets when the worker fails at run time after its socket was asked for: the
|
|
95
|
+
* worker is stopped, so the server sees the socket drop without a close frame.
|
|
96
|
+
*/
|
|
97
|
+
export declare const WORKER_FAILED: {
|
|
98
|
+
readonly code: 4002;
|
|
99
|
+
readonly reason: "starfold: worker failed";
|
|
100
|
+
};
|
package/worker.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";(()=>{var K=class{constructor(e){this.max=e}frames=new Map;order=[];newest=null;cutoff=null;get size(){return this.order.length}has(e){return this.frames.has(e)}seen(e){return(this.newest===null||(e-this.newest|0)>0)&&(this.newest=e),this.cutoff===null||(e-this.cutoff|0)>=0}cut(){return this.clear(),this.newest!==null&&(this.cutoff=this.newest+1>>>0),this.newest}open(e,r,n){return this.frames.has(e)?!0:this.order.length>=this.max?!1:(this.frames.set(e,{need:r,got:[],t0:n}),this.order.push(e),!0)}skip(e){let r=this.frames.get(e);r&&r.need--}add(e,r){let n=this.frames.get(e);return n?(n.got.push(r),!0):!1}flush(e){for(;this.order.length;){let r=this.order[0],n=this.frames.get(r);if(n.got.length<n.need)return;this.order.shift(),this.frames.delete(r),e(r,n.got,n.t0)}}clear(){for(let e of this.frames.values())for(let r of e.got)r.pic.close();this.frames.clear(),this.order.length=0}reset(){this.clear(),this.newest=null,this.cutoff=null}},J=class{sorted=[];add(e){let r=this.sorted;if(r.length>=1e4)return;let n=0,o=r.length;for(;n<o;){let i=n+o>>1;r[i]<=e?n=i+1:o=i}r.splice(n,0,e)}take(){let e=this.sorted;this.sorted=[];let r=n=>e.length?e[Math.min(e.length-1,Math.ceil(n*e.length)-1)]:0;return{p50:r(.5),p95:r(.95)}}};function Me(t){let e=[];for(let r=0;r+3<=t.length;r++)t[r]===0&&t[r+1]===0&&t[r+2]===1&&(e.push(r+3),r+=2);return e.map((r,n)=>{let o=n+1<e.length?e[n+1]-3:t.length;for(;n+1<e.length&&o>r&&t[o-1]===0;)o--;return t.subarray(r,o)}).filter(r=>r.length>0)}var ie=t=>t.toString(16).padStart(2,"0");function ae(t){let e=Me(t).find(r=>(r[0]&31)===7&&r.length>=4);return e?`avc1.${ie(e[1])}${ie(e[2])}${ie(e[3])}`:null}function yt(t,e){let r=[],n=0;for(let o=e;o<t.length;o++){let i=t[o];if(n>=2&&i===3){n=0;continue}n=i===0?n+1:0,r.push(i)}return Uint8Array.from(r)}function wt(t){let e=0;for(let r=0;r<32;r++)e=e<<1|t>>>r&1;return e>>>0}function vt(t){let e=Me(t).find(s=>(s[0]>>1&63)===33);if(!e)return null;let r=yt(e,2);if(r.length<13)return null;let n=r.subarray(1,13),o=["","A","B","C"][n[0]>>6],i=n[0]&32?"H":"L",a=wt((n[1]<<24|n[2]<<16|n[3]<<8|n[4])>>>0),d=[...n.subarray(5,11)];for(;d.length&&d[d.length-1]===0;)d.pop();return`hvc1.${o}${n[0]&31}.${a.toString(16).toUpperCase()}.${i}${n[11]}`+d.map(s=>"."+s.toString(16).toUpperCase()).join("")}var se=class{constructor(e){this.d=e}pos=0;bit(){let e=this.pos>>3;if(e>=this.d.length)throw new RangeError("sequence header ends early");let r=this.d[e]>>7-(this.pos&7)&1;return this.pos++,r}f(e){let r=0;for(let n=0;n<e;n++)r=r*2+this.bit();return r}uvlc(){let e=0;for(;!this.bit();)e++;return e>=32?2**32-1:2**e-1+this.f(e)}};function xt(t,e){let r=0;for(let n=0;n<8&&e<t.length;n++){let o=t[e++];if(r+=(o&127)*2**(7*n),!(o&128))return[r,e]}throw new RangeError("bad leb128")}function kt(t){let e=0;for(;e<t.length;){let r=t[e],n=r>>3&15,o=e+1+(r>>2&1),i=t.length-o;if(r&2&&([i,o]=xt(t,o)),o+i>t.length)return null;if(n===1)return t.subarray(o,o+i);e=o+i}return null}var H=t=>String(t).padStart(2,"0");function St(t){try{let e=kt(t);return e?Mt(e):null}catch{return null}}function Mt(t){let e=new se(t),r=e.f(3);e.f(1);let n=e.f(1),o=0,i=0;if(n)o=e.f(5);else{let O=0,q=0;e.f(1)&&(e.f(32),e.f(32),e.f(1)&&e.uvlc(),O=e.f(1),O&&(q=e.f(5)+1,e.f(32),e.f(5),e.f(5)));let ht=e.f(1),bt=e.f(5)+1;for(let oe=0;oe<bt;oe++){e.f(12);let Se=e.f(5),gt=Se>7?e.f(1):0;oe===0&&(o=Se,i=gt),O&&e.f(1)&&(e.f(q),e.f(q),e.f(1)),ht&&e.f(1)&&e.f(4)}}let a=e.f(4)+1,d=e.f(4)+1;if(e.f(a),e.f(d),!n&&e.f(1)&&(e.f(4),e.f(3)),e.f(3),!n){e.f(4);let O=e.f(1);O&&e.f(2),(e.f(1)?2:e.f(1))>0&&!e.f(1)&&e.f(1),O&&e.f(3)}e.f(3);let s=e.f(1),c=r===2&&s?e.f(1)?12:10:s?10:8,M=r===1?0:e.f(1),[R,re,ne]=[2,2,2];e.f(1)&&([R,re,ne]=[e.f(8),e.f(8),e.f(8)]);let N=0,[A,P,ve]=[1,1,0];M?N=e.f(1):R===1&&re===13&&ne===0?(N=1,[A,P]=[0,0]):(N=e.f(1),r===1?[A,P]=[0,0]:r===2&&(c===12?(A=e.f(1),P=A?e.f(1):0):[A,P]=[1,0]),A&&P&&(ve=e.f(2)));let xe=`av01.${r}.${H(o)}${i?"H":"M"}.${H(c)}`,ke=`${M}.${A}${P}${ve}.${H(R)}.${H(re)}.${H(ne)}.${N}`;return ke==="0.110.01.01.01.0"?xe:`${xe}.${ke}`}function Ae(t,e){return t==="h264"?ae(e):t==="hevc"?vt(e):St(e)}function De(t){return t.startsWith("avc1.")||t.startsWith("avc3.")?"h264":t.startsWith("hvc1.")||t.startsWith("hev1.")?"hevc":t.startsWith("av01.")?"av1":null}var ce=class{constructor(e){this.frame=e}taken=!1;take(e,r){this.taken=!0;let n=this.frame,o=n.visibleRect,i=Math.min(e,n.displayWidth),a=Math.min(r,n.displayHeight);if(!o||i===n.displayWidth&&a===n.displayHeight)return n;try{let d=new VideoFrame(n,{visibleRect:{x:o.x,y:o.y,width:i,height:a}});return n.close(),d}catch{return n}}get timestamp(){return this.frame.timestamp}draw(e,r,n,o){let i=Math.min(n,this.frame.displayWidth),a=Math.min(o,this.frame.displayHeight);e.drawImage(this.frame,0,0,i,a,0,r,i,a)}close(){this.taken||this.frame.close()}},Y=class{implementation="webcodecs";dec;pending=0;constructor(e,r){this.dec=new VideoDecoder({output:n=>{this.pending=Math.max(0,this.pending-1),r.output(new ce(n))},error:n=>r.error(n)}),this.dec.configure(e)}get queued(){return this.pending}decode(e,r,n){this.dec.decode(new EncodedVideoChunk({type:r?"key":"delta",timestamp:n,data:e})),this.pending++}close(){if(this.dec.state!=="closed")try{this.dec.close()}catch{}}};var j={Binary:0,Text:1},le=64<<20,At=new TextEncoder,Dt=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});function Ce(t,e){if(e.length+1>le)throw new RangeError(`a framed message of ${e.length+1} bytes`);let r=new Uint8Array(e.length+1);return r[0]=t,r.set(e,1),r}var Ee=le-1,Pe=t=>Ce(j.Text,At.encode(t)),Oe=t=>Ce(j.Binary,t instanceof Uint8Array?t:new Uint8Array(t));function $e(t){if(t.byteLength>le)throw new RangeError(`a framed message of ${t.byteLength} bytes`);let e=new Uint8Array(t);if(e.length===0)throw new TypeError("an empty framed message");switch(e[0]){case j.Binary:return{t:"binary",b:t.slice(1)};case j.Text:return{t:"text",s:Dt.decode(e.subarray(1))}}throw new TypeError(`unknown framed message kind ${e[0]}`)}var de={code:4e3,reason:"starfold: protocol error"},ue={code:4001,reason:"starfold: no common codec"};function Ue(t,e){t.addEventListener("message",r=>{let n=r.data;switch(n.t){case"connect":e.request(n.id);break;case"preamble":e.preamble(n.id,n.msgs);break;case"preambleFailed":e.refused(n.id);break;case"cancel":e.cancel();break}}),t.start()}var Q=class{constructor(e,r,n,o=WebSocket,i=1e3){this.url=e;this.mode=r;this.h=n;this.Socket=o;this.retryMs=i}sock=null;pending=null;outgoing=null;aborted=null;start(){this.mode.embed||this.open(0,null)}request(e){return!this.mode.embed||this.sock?!1:(this.pending=e,this.h.askPreamble(e),!0)}preamble(e,r){!this.mode.embed||this.pending!==e||this.sock||(this.pending=null,this.open(e,r))}refused(e){this.pending===e&&(this.pending=null)}cancel(){this.pending=null,this.outgoing=null,this.sock?.close(1e3)}abort(e,r){let n=this.sock;!this.mode.embed||!n||(this.aborted={sock:n,code:e,reason:r},this.outgoing=null,n.close(e,r))}get holdsPreamble(){return this.outgoing!==null}open(e,r){let n;if(this.mode.embed){try{n=new this.Socket(this.url,this.mode.protocols)}catch{this.h.connectFailed(e);return}this.outgoing=r}else n=new this.Socket(this.url);this.sock=n,n.binaryType="arraybuffer",this.h.opening(n),this.attach(n,e)}attach(e,r){e.addEventListener("open",()=>{this.sock===e&&this.sendPreamble(e),this.h.open(r)}),e.addEventListener("close",n=>{this.sock===e&&(this.sock=null,this.outgoing=null);let o=this.aborted?.sock===e?this.aborted:null;o&&(this.aborted=null),this.h.closed(r,o?.code??n.code,o?.reason??n.reason),this.mode.embed||setTimeout(()=>this.open(0,null),this.retryMs)}),e.addEventListener("message",n=>this.h.message(n.data))}sendPreamble(e){let r=this.outgoing??[];this.outgoing=null;for(let n=0;n<r.length;n++)e.send(r[n])}};var Ve=16,Ct=250,L=class{last;intervalMs;note(e){let r=this.last===void 0?void 0:e-this.last;this.last=e,!(r===void 0||r<=0||r>=1e3)&&(this.intervalMs=this.intervalMs===void 0?r:this.intervalMs*.9+r*.1)}maxQueued(){return this.intervalMs===void 0?Ve:Math.max(Ve,Math.round(Ct/this.intervalMs))}},Et=1e4,W=class{at;told=!1;note(e){let r=this.at!==void 0&&e-this.at<=Et;return this.at=e,!r||this.told?!1:(this.told=!0,!0)}};var F=t=>`${t.codec}/${t.codedWidth}x${t.codedHeight}`;function T(t,e){return{codec:t.codec,codedWidth:t.codedWidth,codedHeight:t.codedHeight,optimizeForLatency:!0,hardwareAcceleration:e}}async function Re(t,e){let r=new Map;for(let s of t)for(let c of s.stripes)r.set(F(c.config),{c:c.config,av1:s.codec==="av1"});let n=await Promise.all([...r].map(async([s,{c,av1:M}])=>{let R=await Pt(c,M,e);return{k:s,c,av1:M,hw:R}})),o=new Map,i=[];for(let s of n)s.hw&&(o.set(s.k,{implementation:"webcodecs",hardwareAcceleration:s.hw}),i.push({...s.c,implementation:"webcodecs",hardwareAcceleration:s.hw}));let a=t.some(s=>s.stripes.every(c=>o.has(F(c.config)))),d=new Map;for(let s of t)if(s.codec==="av1"&&s.stripes.every(c=>e.dav1dDecodes(c.config.codec)))for(let c of s.stripes)d.set(F(c.config),c.config);if(!a&&d.size>0&&await e.dav1d())for(let[s,c]of d)o.set(s,{implementation:"dav1d-wasm"}),i.push({...c,implementation:"dav1d-wasm"});return{decode:i,accepted:o}}async function Pt(t,e,r){return r.noHardware&&e?null:!r.noHardware&&await r.supported(T(t,"prefer-hardware"))?"prefer-hardware":await r.supported(T(t,"no-preference"))?"no-preference":null}function fe(t){let e=t.split(".");return e[0]==="av01"&&e[1]==="0"&&e[3]==="08"&&(e[4]===void 0||e[4]==="0")&&(e[5]===void 0||e[5].startsWith("11"))}var D={Video:1,VideoV2:5,Audio:2,Cursor:3,ClipImage:4,ClipImageUp:17,MicOpus:18,MicPcm:19},g={ack:t=>`a,${t}`,move:(t,e)=>`m,${t},${e}`,button:(t,e)=>`b,${t},${e?1:0}`,scroll:(t,e)=>`sp,${t.toFixed(1)},${e.toFixed(1)}`,key:(t,e)=>`k,${t},${e?1:0}`,releaseAll:"r",clipboard:t=>`c,${t}`,video:t=>`v,${t?1:0}`,audio:t=>`au,${t?1:0}`,mic:t=>`mi,${t?1:0}`,resize:(t,e)=>`sz,${t},${e}`,keyframe:"kf",pong:t=>`po,${t}`},m={hello:(t,e,r)=>JSON.stringify({t:"hello",v:2,offer:t,decode:e,hz:r}),slow:()=>JSON.stringify({t:"slow"}),hz:t=>JSON.stringify({t:"hz",hz:t}),ready:t=>JSON.stringify({t:"codec-ready",epoch:t}),error:(t,e)=>JSON.stringify({t:"codec-error",epoch:t,reason:e}),ack:(t,e)=>JSON.stringify({t:"ack",epoch:t,frame:e}),keyframe:t=>JSON.stringify({t:"keyframe",epoch:t})};function He(t){let e=r=>(t[r]<<24|t[r+1]<<16|t[r+2]<<8|t[r+3])>>>0;return{key:(t[1]&1)===1,frame:e(2),pipe:e(6),stripe:t[10],parts:t[12],epoch:t[0]===D.VideoV2?e(16):void 0}}var Le=16,We=20;function Fe(t,e,r,n){let o=t.epoch!==void 0;return o!==(e===2)?!1:!o||n&&t.epoch===r}var Ye=new URLSearchParams(self.location.search),Te=Ye.has("nodraw"),je=Ye.has("nohwdecode"),Ot=32,$t=1e3,Qe=!1,Ie=null,_e=!1,y=null,Ge="",V=!1,$=null,w=null,C=null,I=null,Xe=null,Be=0,pe=!0,Ze=!1,f=0,X=!1,et=0;function tt(t){if(C)return C;try{return t.getContext("2d",{alpha:!1,desynchronized:!0})}catch{try{return t.getContext("2d")}catch{return l({t:"log",s:"no video: the canvas has no 2d context"}),null}}}var x=0,_=null,b=0,E=!1,ee=[],te=null,rt=new Map,B=[],U=null,ze=null,me,nt=()=>{},Ut=new Promise(t=>{nt=t,setTimeout(t,$t)}),Z=!1,he=new L,be=new W,v=[],ge=0,k=[],h=new K(Ot),Ne=0,ot=new J,u={frames:0,bytes:0,decodeMs:0,pipeMs:0,lastReport:performance.now(),dropped:0},Vt=new TextEncoder;function it(t){return!V||t<=Ee?!0:(console.warn(`[starfold] not sent: a ${t}-byte message is over the limit`),!1)}function p(t){!y||y.readyState!==WebSocket.OPEN||V&&!it(Vt.encode(t).byteLength)||y.send(V?Pe(t):t)}function l(t,e=[]){self.postMessage(t,e)}var S=null;function G(t){S?.postMessage(t,[])}function st(t){if(!S)throw t;$?.abort(de.code,de.reason)}var at=t=>e=>{S&&t!==x||st(e)};function qe(t){return new Q(Ge,t,{opening(e){y=e,x++,he=new L,be=new W,Z=!1,_=null},open(e){_=performance.now(),S?G({t:"open",id:e}):l({t:"status",s:"open"}),p(g.audio(Ze))},closed(e,r,n){let o=_===null?null:performance.now()-_;_=null,S?G({t:"closed",id:e,code:r,reason:n,openMs:o}):l({t:"status",s:"closed"}),f=0,X=!1,b=0,E=!1,te=null,z()},askPreamble(e){G({t:"preamble",id:e})},connectFailed(e){G({t:"connectFailed",id:e})},message(e){let r=e;if(V)try{if(typeof e=="string")throw new TypeError("a text message");let n=$e(e);r=n.t==="text"?n.s:n.b}catch(n){l({t:"log",s:`framed socket: ${n}`}),y?.close(4003,"not a framed message");return}try{Rt(r)}catch(n){st(n)}}})}function Rt(t){if(typeof t=="string")return Ht(t);let e=new Uint8Array(t);switch(e[0]){case D.Video:case D.VideoV2:qt(e);break;case D.Audio:Kt(e);break;case D.Cursor:l({t:"cursor",buf:t},[t]);break;case D.ClipImage:l({t:"clipImage",buf:t},[t]);break}}function Ht(t){let e;try{e=JSON.parse(t)}catch{return}if(e.t==="ping"){p(g.pong(e.s));return}if(e.t==="close"){try{y?.close()}catch{}return}if(e.t==="codec"){Tt(e);return}e.t==="hello"&&Lt(e),l(e)}function ct(t,e,r){w&&((w.width!==t||w.height!==e)&&(w.width=t,w.height=e),C=tt(w),v=r,ge=t)}function lt(){X||(X=!0,p(g.video(pe)))}function Lt(t){if(t.protocol!==2||!Array.isArray(t.videoOffers)){f=1,typeof VideoDecoder>"u"&&l({t:"log",s:"no video: this browser has no WebCodecs"}),ct(t.w,t.h,t.stripes&&t.stripes.length?t.stripes:[[0,t.h]]),z(),lt();return}f=2,Ft(x,++et,t.offer,t.videoOffers).catch(at(x))}async function dt(t){if(typeof VideoDecoder>"u")return!1;try{return!!(await VideoDecoder.isConfigSupported(t)).supported}catch{return!1}}function Wt(){return ze??=(async()=>{try{importScripts(new URL("dav1d.js",self.location.href).href),U=await self.starfoldDav1d.load(new URL("dav1d.wasm",self.location.href).href),l({t:"log",s:`dav1d-wasm ready (${U.renderer})`})}catch(t){l({t:"log",s:`dav1d-wasm unavailable: ${t}`})}return U})(),ze}async function Ft(t,e,r,n){let o=await Re(n,{supported:dt,dav1d:async()=>!!await Wt(),dav1dDecodes:fe,noHardware:je});if(await Ut,!(t!==x||e!==et||f!==2)){for(let[i,a]of o.accepted)rt.set(i,a);p(m.hello(r,o.decode,me)),Z=me===void 0,lt()}}function Tt(t){if(!(f!==2||t.epoch<=b)){if(b=t.epoch,E=!1,te=null,B=[],z(),t.error!==void 0){if(S){$?.abort(ue.code,ue.reason);return}l({t:"log",s:`no video: ${t.error}`}),l(t);return}_t(x,t).catch(at(x))}}async function It(t){return Promise.all(t.stripes.map(async e=>{let r=rt.get(F(e.config));if(r?.implementation==="dav1d-wasm")return U&&t.codec==="av1"&&fe(e.config.codec)?{implementation:"dav1d-wasm",config:T(e.config,"no-preference")}:null;let n=r?.hardwareAcceleration??"no-preference",o=T(e.config,n);return je&&t.codec==="av1"?null:await dt(o)?{implementation:"webcodecs",config:o,hardwareAcceleration:n}:null}))}async function _t(t,e){let r=await It(e);if(!(t!==x||e.epoch!==b)){if(!r.every(n=>n!==null)){p(m.error(e.epoch,"unsupported"));return}ee=r,te=e.backend?`${e.backend} (${e.hardware?"hw":"sw"})`:null,ct(e.w,e.h,e.stripes.map(n=>[n.y,n.h])),E=!0,p(m.ready(e.epoch)),l(e)}}function ut(){for(let t of k)t.dec?.close();k.length=0}function z(){h.reset(),ut()}function we(){let t=h.cut();ut(),t!==null&&p(f===2?m.ack(b,t):g.ack(t)),ft()}function ft(){let t=performance.now();t-Ne>500&&(Ne=t,p(f===2?m.keyframe(b):g.keyframe))}function pt(t){return k[t]||(k[t]={dec:null,codec:null,waitingKey:!0,ts:0,ids:new Map})}function mt(t,e,r,n){if(l({t:"log",s:`stripe ${t} decoder error: ${n.message}`}),k[t]===e){if(f===2&&r===b&&E){let o=performance.now();if(B=B.filter(i=>o-i<1e4),B.push(o),B.length>=3){E=!1,z(),p(m.error(r,"decode-error"));return}}we()}}function Bt(t,e){let r=pt(t),n=b,o={output:i=>{let a=r.ids.get(i.timestamp);if(r.ids.delete(i.timestamp),k[t]!==r||a===void 0||!h.add(a,{i:t,y:v[t]?v[t][0]:0,pic:i})){i.close();return}ye()},none:i=>{let a=r.ids.get(i);r.ids.delete(i),!(k[t]!==r||a===void 0)&&(h.skip(a),ye())},error:i=>mt(t,r,n,i)};if(e.implementation==="dav1d-wasm"){if(!U)throw new Error("dav1d-wasm is not loaded");return U.open(o)}return new Y(e.config,o)}function Ke(t){t!==Ie&&(Ie=t,l({t:"surface",s:t}))}function zt(t,e,r){if(Qe&&e.length&&e.every(o=>o.pic.take)){Ke("video");let o=e.map(i=>({i:i.i,y:i.y,frame:i.pic.take(ge||1/0,v[i.i]?v[i.i][1]:1/0)}));l({t:"frames",parts:o},o.map(i=>i.frame))}else if(e.length){Ke("canvas");for(let o of e){let i=v[o.i]?v[o.i][1]:1/0;C&&!Te&&o.pic.draw(C,o.y,ge||1/0,i),o.pic.close()}!_e&&(C||Te)&&(_e=!0,l({t:"painted"}))}p(f===2?m.ack(b,t):g.ack(t));let n=performance.now()-r;u.frames++,u.decodeMs+=n,ot.add(n)}function ye(){h.flush(zt)}function Je(){u.dropped+=h.size,we()}function Nt(t,e){if(f!==2)return{implementation:"webcodecs",config:{codec:ae(e)||"avc1.640034",optimizeForLatency:!0,hardwareAcceleration:"no-preference"}};let r=ee[t],n=De(r.config.codec),o=n&&Ae(n,e);return o&&o!==r.config.codec?{...r,config:{...r.config,codec:o}}:r}function qt(t){let e=He(t);if(!Fe(e,f,b,E)||f===2&&!ee[e.stripe]||f!==2&&typeof VideoDecoder>"u"||!h.seen(e.frame))return;let r=f===2,n=t.subarray(r?We:Le);u.bytes+=t.length;let o=!h.has(e.frame);if(!h.open(e.frame,e.parts,performance.now())){be.note(performance.now())&&p(m.slow()),Je();return}o&&(u.pipeMs+=e.pipe/10,he.note(performance.now()));let i=pt(e.stripe);if(i.waitingKey&&!e.key){h.skip(e.frame),u.dropped++,ft(),ye();return}if(e.key){let s=Nt(e.stripe,n),c=`${s.implementation}/${s.config.codec}`;if(!i.dec||c!==i.codec){i.dec?.close(),i.dec=null,i.codec=c,i.ids.clear();try{i.dec=Bt(e.stripe,s)}catch(M){mt(e.stripe,i,b,new Error(`configure failed: ${M}`));return}}i.waitingKey=!1}let a=i.dec;if(a.queued>=he.maxQueued()){l({t:"log",s:`stripe ${e.stripe} decoder fell behind`}),be.note(performance.now())&&p(m.slow()),Je();return}let d=++i.ts;i.ids.set(d,e.frame);try{a.decode(n,e.key,d)}catch(s){l({t:"log",s:"decode threw "+s}),we()}}function Kt(t){let e=Xe;if(!(!e||typeof AudioDecoder>"u")){I||(I=new AudioDecoder({output:r=>{let n=r.numberOfFrames,o={l:new Float32Array(n),r:new Float32Array(n)};r.copyTo(o.l,{planeIndex:0,format:"f32-planar"}),r.numberOfChannels>1?r.copyTo(o.r,{planeIndex:1,format:"f32-planar"}):o.r.set(o.l),r.close(),e.postMessage(o,[o.l.buffer,o.r.buffer])},error:()=>{I=null}}),I.configure({codec:"opus",sampleRate:48e3,numberOfChannels:2})),Be+=1e4;try{I.decode(new EncodedAudioChunk({type:"key",timestamp:Be,data:t.subarray(1)}))}catch{}}}setInterval(()=>{let t=performance.now(),e=(t-u.lastReport)/1e3,r=u.frames,{p50:n,p95:o}=ot.take(),i=k[0],a=f===2?ee[0]:void 0,d={t:"stats",fps:r/e,kbps:u.bytes*8/1e3/e,decodeMs:r?u.decodeMs/r:0,decodeP50:n,decodeP95:o,pipeMs:r?u.pipeMs/r:0,codec:i?.codec?i.codec.slice(i.codec.indexOf("/")+1):null,encoder:te,implementation:i?.dec?.implementation??null,hw:i?.dec?.implementation==="webcodecs"?a?.hardwareAcceleration??"no-preference":null,stripes:v.length,dropped:u.dropped,queue:h.size};l(d),u.frames=0,u.bytes=0,u.decodeMs=0,u.pipeMs=0,u.lastReport=t},1e3);self.addEventListener("message",t=>{let e=t.data;switch(e.t){case"init":w=e.canvas,Ge=e.url,V=e.framed===!0,Qe=e.presentToMain,C=tt(w),e.embed?(S=e.embed.life,$=qe({embed:!0,protocols:e.embed.protocols}),Ue(S,$)):$=qe({embed:!1}),$.start();break;case"send":p(e.d);break;case"sendBin":y&&y.readyState===WebSocket.OPEN&&it(e.d.byteLength)&&y.send(V?Oe(e.d):e.d);break;case"video":pe!==e.on&&(pe=e.on,e.on&&(z(),f===2&&(E=!1)),X&&p(g.video(e.on)));break;case"hz":me=e.hz,nt(),Z&&p(m.hz(e.hz)),Z=!1;break;case"audioPort":Xe=e.port,Ze=!0,p(g.audio(!0));break}});})();
|
package/README.md
DELETED