@swf2es/native
v0.1.24
Published
swf2es's WebAssembly modules: bitmap kernels, MP3, ADPCM and Nellymoser decoding, zlib and LZMA, fill and line tessellation, and ATF textures
Maintainers
Readme
@swf2es/native
swf2es's WebAssembly modules, built with the repository's pinned Zig:
@swf2es/native/render: what the renderer computes natively, each a wrapper over an instance of its own: double-precision libtess2 fill tessellation (Tessellator), a shape layer's lines built in one call (LineBuilder), BitmapData's filters and pixel operations (BitmapKernel), and whole-level DXT1/DXT5 texture encoding (DxtEncoder).@swf2es/native/compress: synchronous zlib and LZMA, and the PNG and JPEG encoders' passes over a bitmap.@swf2es/native/mp3: synchronous MP3 frame decoding with minimp3.@swf2es/native/audio: synchronous ADPCM and Nellymoser decoding, in Zig alone.@swf2es/native/atf: Stage3D's ATF textures, read and decoded to what a desktop GPU takes, their JPEG XR images by jxrlib; and JPEG XR files written as Flash'sBitmapData.encodewrites them, by jxrlib's encoder.
The package depends on no other package and uses no DOM or node APIs.
compress, mp3, audio and atf each compile their own module. What the renderer
computes is one module, render (src/render/), compiled once; each user
instantiates it apart, so each has its own memory and lifetime, and a large
bitmap job never grows the tessellator's memory, nor does disposing one
take the other down. Within an instance, every part allocates from one
arena (src/render/arena.zig), which each call resets.
render requires wasm SIMD, which every current browser ships (Chrome 91,
Firefox 89, Safari 16.4 on): it is built with SIMD throughout and has no
scalar build. An engine without it refuses the module, as one without Wasm
or under a CSP without 'wasm-unsafe-eval' does: the player then plays
nothing, as its fills, lines and bitmap convolution need the module.
Building
The package is one Zig project inside the npm package: build.zig at its
root builds every binary, and each binary's Zig source, in src/<binary>/,
sits beside its generated binary.ts and its TypeScript wrapper
(index.ts). tsc compiles only the .ts files, and only dist/ and
LICENSE.third-party are published, so the Zig and C sources are in the
repository but not in the npm tarball. include/ holds the libc headers
the vendored C includes, which wasm32-freestanding lacks: string.h maps
memcpy, memmove and memset to clang's builtins, which become bulk
memory instructions, and the rest declare only what the C calls.
The binaries are checked in, so ordinary builds need no compiler. pnpm
build verifies each one's input digest and the notices. To rebuild after
changing the sources or an upstream pin:
pnpm --filter @swf2es/native build:wasmThis runs the bitmap kernel's tests (zig build test) and then zig
build here with Zig 0.17.0, from the PATH or else downloaded once into
~/.cache/swf2es by tools/zig.ts and checked against its SHA-256, with
fresh caches, and writes each module into its src/<binary>/binary.ts
and the vendored C's notices, verbatim, into LICENSE.third-party. CI
rebuilds and compares the generated bytes. zig build alone, in this
folder, builds zig-out/bin/*.wasm like any Zig project (.zig-cache/ and
zig-out/ are ignored).
Licences
The wrappers, the Zig and the build are Apache-2.0. LICENSE.third-party
carries each vendored library's notice: zlib is under the zlib license,
the LZMA SDK files are in the public domain, minimp3 is CC0-1.0,
libtess2 is under SGI Free Software License B, and jxrlib is under the BSD
2-Clause License; and those of the code derived from FFmpeg's Nellymoser
decoder (src/audio/nellymoser.zig), under the MIT License, and of the code
derived from SVG 1.1's feTurbulence (src/render/pixels.zig's
perlinNoise), under the W3C Software and Document License.
bitmap
BitmapKernel is BitmapData's CPU filters: convolve() a convolution
(src/render/convolve.zig), blur() a blur, and layer() a glow, a
drop shadow, a bevel or a gradient glow or bevel (src/render/blur.zig).
The player filters through it alone: AS3's and AVM1's
BitmapData.applyFilter call the one BitmapKernel of their realm
(packages/player/src/bitmap/kernel.ts), made at the first filter or
operation that needs it, which compiles the module; where it traps, the
call is made again in a new instance, and where that fails too, nothing
is written. A displacement map and GPU filters are unchanged. These three
return owned premultiplied ARGB Uint32Array pixels, or null where they
would not fit or the instance trapped. No source pixels are changed.
Results survive later calls, memory growth, rejection and disposal.
It also runs the loops of BitmapData's pixel operations
(src/render/pixels.zig, driven by pixel-ops.ts): copy() for
copyChannel, merge, paletteMap and a colour matrix filter, transform()
for colorTransform, noise() and perlin(). These work in place: they
write into the caller's arrays, the source too where it is the
destination, and return whether they did. They go a band of rows of about
1 MiB at a time, each copied in and back before the next, which reads
what the bands before it wrote; where the source is the destination and a
band's rows of the two overlap, both go in as one block, so that a pixel
reads what the pixels before it wrote, as in Flash. A band that traps is
made again in a new instance, the bands before it not twice; where it
fails again, the call returns false with the bands before it written.
words() makes a run of 32-bit words a bitmap's pixels or their values,
four at a time, for setPixels, getPixels, copyPixelsToByteArray and
getVector: alpha 255 for an opaque bitmap, premultiplied or divided back
for a transparent one, the bytes reversed where the values are big-endian.
It takes bytes, at any offset, and returns how many it made, from the
first: fewer than all where the module refused the rest, which the caller
makes itself.
blur() takes the rect to blur, layer() the rect to place a layer on
and the offsets it reads the source's alpha from (one, or a bevel's two, on
and back); the wrapper copies in the blocks of the source each reads, 0
past the bitmap, a layer's alpha a byte a pixel. A large rect is filtered
in tiles, each read as far round as the blur reaches, so a call's scratch
stays within 4 MiB, and an instance kept between frames, wherever the
reach lets it: a tile is four times the reach a side at least, and its
blocks are cut to the bitmap and the reach round it, past which every pass
holds nothing. Each takes values within the ranges the player's filter
objects keep, blurs 0 to 255 or NaN, quality 0 to 15, strength 0 to 255,
alphas 0 to 1, colours of 24 bits, and refuses others (null), in the
wrapper and again in blur.zig; the player brings a filter from a SWF's
tags, which may hold more, within them first.
blur.zig keeps the JS's arithmetic, in the same order in f64, converting
to an int as JS converts, so its pixels are the JS's to the bit: a blur's
box runs truncated to 8 bits each, a glow's alpha from the blur so
truncated times strength, a bevel's from the difference of two reads of
it, placed as adl places them. Planes are bytes, which every value fits,
so a call's scratch is a few bytes a pixel; runs along y go four columns a
lane, and reads by whole pixels are row copies. Against the JS in node, on
a 512-pixel square, a blur is 1.7 to 1.9 times as fast, a glow 1.4, an
inner glow 2.1, a drop shadow 2.0 and a bevel 1.5.
The wrapper convolves a rect a band of rows at a time, about 1 MiB of
input and output a call: it copies each band's rows plus the kernel's halo
and the coefficients in, and the band's output out before scratch is
reused. The kernel keeps straight-colour planes for only the kernel's rows,
so a call's scratch stays near 2 MiB even 4096 pixels wide, and a player
filtering large bitmaps every frame keeps its instance. The player handles
clipping, destination writing and notifications. Strict double arithmetic
and Flash's fixed-point 3×3 quirks are adl's, as the JS the player had
computed them. The kernel uses explicit f64x2 wasm SIMD, as all of
render may. Traps discard the instance, and normal rejection can reuse
its arena.
Wasm memory has a 128 MiB maximum. Instances above 8 MiB are dropped after a
call; new BitmapKernel({ retainMemory: bytes }) adjusts that threshold.
Arena reset reuses capacity; only dropping the instance permits its memory
to be collected.
The package's build first runs the kernels' Zig tests on the host (zig
build test in this folder): exact pixels for small cases, and every
allocation failing in turn. The kernels, src/render/convolve.zig,
src/render/blur.zig and src/render/pixels.zig, take any std.mem.Allocator or slices;
src/render/bitmap.zig wraps them in the Wasm module's bump arena. No external dependency is needed.
node --test tests/unit/native-bitmap.test.ts holds the convolution to
the JS the player had (tests/unit/player/bitmap/convolution-reference.ts),
bit for bit on thousands of random filters, special numbers among them,
and checks ownership, rejection and traps; native-blur.test.ts holds
applyFilter's blurs, glows, shadows and bevels to theirs
(blur-reference.ts), and takes SWF2ES_FUZZ_STEPS and
SWF2ES_FUZZ_SEED for longer runs; native-pixels.test.ts holds the
pixel operations to theirs (pixels-reference.ts), bit for bit, onto
their own bitmaps too and across bands, and a band that traps. The player's references
(apply-filter, convolution) hold it to Flash's own pixels.
DXT encoding
DxtEncoder.encode(rgba, dxt5, width, height) compresses a whole texture
level in one call, into DXT1 or DXT5 blocks identical to
@swf2es/context3d's TypeScript encoder. It takes tightly packed top-down
RGBA, repeats edge pixels for partial 4×4 blocks, and keeps the reference's
double arithmetic and tie breaking. Four colour distances are compared
together with integer SIMD. DXT5 alpha endpoints choose their exact palette
entry directly (entry zero wins equal-endpoint ties); other values retain the
nearest distance while searching. Uniform 4×4 blocks emit equal colour endpoints
and zero indices immediately: DXT1 ignores alpha for this check, while DXT5
requires all four channels to match. The check stops at the first differing
pixel; other blocks keep the general colour fit. It returns null for invalid dimensions or
input sizes, failed allocation, a refused module or a trap, so the caller
can use the TypeScript path.
Each encoder owns an instance. Input and output share one reserved block,
grown only when a larger level needs it: one encoding crossing per level,
plus an arena reset on allocation or growth. The result is a view of that
memory, valid until the next call; upload or copy it before encoding again.
release() drops the instance, and a level that grew it beyond 32 MiB
causes it to be replaced before the next call. That budget keeps a 2048²
DXT5 upload's workspace between calls. A trap also drops the instance.
The host Zig tests cover flat blocks and edge repetition;
tests/unit/native-dxt.test.ts compares blocks against the TypeScript
reference on thousands of levels and all 32,896 alpha endpoint pairs, including
nearby palette values. It checks that each was encoded in wasm and exercises
rejection, traps and release.
node tests/bench/dxt.ts before-checkout after-checkout --json compares two built
native encoders, alternating A/B and B/A after warmup and checking their bytes
against the TypeScript reference. It includes opaque and binary-alpha textures
as well as flat, gradient and random RGBA, coloured tiles, mixed flat/noisy
blocks and constant RGB with varying alpha; --large selects 2048-square levels.
Without checkout paths it compares TypeScript with the current native encoder.
--crossings checks one encoding export per warmed level separately from timing.
compress
Synchronous zlib and LZMA for SWF bodies, bitmaps and ByteArray, in one
WebAssembly module that imports nothing. Its upstream sources are pinned
submodules of swf2es's own repositories: zlib 1.3.2 in
vendor/zlib (https://github.com/swf2es/zlib, a fork
of madler/zlib, at tag v1.3.2), and the LZMA SDK 26.05 in
vendor/lzma-sdk
(https://github.com/swf2es/lzma-sdk at tag v26.05: the release as
published, line endings made LF, whose README names the archive and its
SHA-256). Of the SDK only the encoder and the decoder are compiled, all
public domain:
| File | SHA-256 |
|---|---|
| C/7zTypes.h | a5d03b8cb65cd3a2a56bde46dd68fb356d2ebacd9d70283e7d4d20b4e0a64713 |
| C/Compiler.h | d5e42be77d26beaa8c81d3e62ef99fc5685736cfc079779fdb9154d05fa8bc4a |
| C/CpuArch.h | 259145c6f4b085f44284014574f39f3f562fc78466746bfb388efe06b4dd59b4 |
| C/LzFind.c | f73da68845094a85b006a0d2da80b3ecdec92a1ca0f85df637e565c642e8d5ba |
| C/LzFind.h | 42732b38df9bb18f82866d7deaa8663f6c6f9cb10e2a2cdfa9e6f420c2e2f239 |
| C/LzHash.h | 42d146d2130dfe49d0b21d15cc6f0fe9d79ac0ebb629985fe3aedde7b2bee80e |
| C/LzmaEnc.c | 67f23656339b5e19015acac41acbcf36ea7787a8419907dce91c1dd336a2fb0f |
| C/LzmaEnc.h | c5e78398309363dd181840b7ba0bcb856f66619f755d5e2f5e04f7437186ba5f |
| C/Precomp.h | c8903f2e36a771a272d8981e1e9ffed5ba16ca3d2f3dca6d1414d2340a6829d0 |
| C/LzmaDec.c | 4e6ec665a6df01f1722e2b2fc36dc5e3aa7c3890e0f8cb11c6a07c9a01f3309b |
| C/LzmaDec.h | 3aaf07b4ae4173a2d103179455dc7089b5ddbc7fc3db3c0e40964a7499c69266 |
src/compress/root.zig exports the module's calls, gives zlib and the SDK a bump
arena through their allocator callbacks, and calls them through bindings
that build.zig translates from zlib.h, LzmaEnc.h and LzmaDec.h
(Zig 0.17 has no @cImport), with the same defines as it compiles the C
with, so a define cannot change a struct's layout on one side only.
wasm32-freestanding has no libc headers, so include/ declares what the
C calls. Zig compiles C there with -ffreestanding, which would leave
memcpy, memset and memmove calls to compiler-rt's loops, so
include/string.h maps them to clang's builtins, which become bulk memory
instructions; memcmp and strlen come from Zig's compiler-rt.
Upstream sources stay unchanged.
inflate(data, raw, limit)inflates a zlib or raw deflate stream to at mostlimitbytes, stopping at the stream's end.deflate(data, level, raw)deflates as zlib does at that level.pngEncode(pixels, width, height, channels, level, filter)makes a PNG's IDAT stream of a bitmap's premultiplied ARGB pixels in one pass (png.zig): each row is made RGBA or RGB, its colours divided out of alpha; withfilter, given the filter of PNG's five whose output sums smallest, libpng's heuristic, sixteen bytes at a time (Wasm SIMD); and handed to the deflate.jpegEncode(pixels, width, height, quality)makes a JPEG file of a bitmap's ARGB pixels, alpha left out, as Flash's encoder does (jpeg.zig, Zig alone): JFIF, 4:2:0, Annex K's quantization tables scaled to the quality as the IJG scales them and its Huffman tables. Colours are converted eight pixels at a time and the DCTs run eight and sixteen columns at a time (Wasm SIMD); a chroma block is the low half of its MCU's 16 by 16 DCT, as libjpeg scales since version 7.lzmaDecode(stream, size)decodes an LZMA stream, its 5 property bytes first, tosizebytes or to its end marker.lzmaEncode(data)writesByteArray's LZMA: properties, an 8-byte length and the stream, at level 9 with a 1 MB dictionary as avmplus, or a smaller one for less data.
Decoders return a status, the bytes decoded and how much input they read,
and can leave room before their output so that a SWF's header needs no
second copy. A failure gives the bytes decoded before it only when the
caller asks (partial), so a bomb that fails is never copied out of the
module; an output the page cannot allocate is NO_MEMORY. An instance
whose call threw is dropped too.
The module is compiled synchronously on first use from the base64 in
src/compress/binary.ts. Each call resets a bump arena in the module's memory,
copies its input in and its output out; outputs of unknown size grow in
place at the arena's top, so they are never copied as they grow. Memory
never shrinks, so an instance whose memory grew past 8 MiB, which LZMA
encoding of more than a few hundred KB does, is dropped after its call and the next call
instantiates a new one.
mp3
Synchronous MP3 frame decoding with minimp3, in one WebAssembly module that
imports nothing. Its upstream source is the pinned submodule
vendor/minimp3 (https://github.com/swf2es/minimp3,
a fork of lieff/minimp3, at commit ea99364), compiled unchanged.
Call await prepareMp3() before running scripts. It compiles the embedded
WASM binary once, without instantiating a decoder or decoding any audio.
An Mp3Decoder then decodes a sequence of whole frames synchronously.
Its pcm view is overwritten by the next read(); copy samples out before
reading again. Each decoder owns a fixed 128 KiB workspace and imports
nothing from the host. The module is shared, but decoder state is not.
The player uses this only for Sound.extract(). It keeps the samples weakly
by sound, decodes on the first extraction, and preserves Flash's untrimmed
MP3 frame counts. Playback still uses the audio host's decoder.
minimp3 is a single header. build.zig translates its declarations for
src/mp3/root.zig (Zig 0.17 has no @cImport) and compiles its implementation
from a generated one-line C file that defines MINIMP3_IMPLEMENTATION and
includes it, both with the same defines (MINIMP3_ONLY_MP3,
MINIMP3_NO_SIMD, MINIMP3_FLOAT_OUTPUT), so the sample type cannot
differ between the two. The implementation stays C, compiled by Zig's
clang with -ffp-contract=off, rather than translated to Zig, so the
samples are the same arithmetic as before.
wasm SIMD was measured and left off: with the simd128 feature, LLVM
vectorises enough of minimp3 to decode about 12% faster (some 405 ms
against 460 for 22,854 frames) with bit-identical samples, but the module
grows by 12.7 KB and would need SIMD of every engine. minimp3's own SIMD
is SSE and NEON only, which MINIMP3_NO_SIMD keeps off.
Where the module does not compile, prepareMp3() still resolves,
mp3Available() is false, and the player plays on: Sound.extract()
writes no samples for an MP3, as Flash does for a sound it cannot decode.
audio
SWF's other compressed sound, decoded synchronously in Zig alone
(src/audio/), in one module that imports nothing, compiled the first
time it is called and kept as compress's is:
decodeAdpcm(data, channels): ADPCM (adpcm.zig) as 16-bit samples, channels interleaved, each packet's header sample first, as adl gives it.NellymoserDecoder.decode(data): Nellymoser (nellymoser.zig, FFmpeg's decoder translated) as samples from -1 to 1, 256 for each whole 64-byte block; a decoder carries its stream's overlap and noise from one call to the next, its state copied in and out of the module with each call.
Each call copies its input into the module's memory, decodes there in an
arena reset first, and copies the samples out. Both give the samples the
TypeScript decoders they replaced gave, bit for bit: Nellymoser's
coefficients and samples are rounded to single precision, and its
transform done in double, where that decoder stored them. Decoding is
about 1.7 times as fast as that decoder for Nellymoser and 2.6 times for
ADPCM, where copying the samples out is most of the time. zig build test
runs each decoder's own test on the host.
tessellate
This compiles the small double-precision patch in vendor/libtess2.
build.zig compiles the vendored C and the arena/API adapter in
src/render/tessellate.zig together, into the render module, translating the C header with
b.addTranslateC, as for MP3 and compression. libtess2 remains under SGI
Free Software License B.
The player draws every fill and line through it. A RenderView makes a
Tessellator of its own, or takes one as its fillTessellator option
(its tessellate), which several views may share:
import { Tessellator } from "@swf2es/native/render";
import { RenderView } from "@swf2es/player/scene";
const tessellator = new Tessellator();
const view = new RenderView({ width, height, fillTessellator: tessellator.tessellate });A Tessellator compiles the module as it is made, and throws where the
host refuses it. The player keeps its paint and draw order, and passes
every contour of a fill together, using even-odd or non-zero winding, with
non-zero for masks; a fill the tessellator refuses is left out, resolved
once with the rest of the layer (scene/fills.ts, resolveFills), so
nothing retries it. Dynamic drawings and morph ratios construct new
results when their contents change. A fill alone, tessellate(contours,
nonZero), takes flattened polygons, for other hosts.
The player tessellates a shape layer's fills in one call,
tessellator.tessellate.layer(fills, nonZero), which takes each contour as
the shape's own path commands (PATH_MOVE, PATH_LINE, PATH_CURVE,
PATH_CUBIC, each followed by its coordinates), not as points: the wrapper
copies every fill's commands, the contours' ends, each fill's last contour
and its rule into one allocation, and src/render/flatten.zig flattens
each contour as the player's JS did, and the fuzzer's still does
(tests/fuzz/tessellate.ts):
chords within 0.02 px of the curve, at most 256 a curve, at the same
parametric points, repeated points dropped, a closing point that repeats the
first dropped, and contours of fewer than three points left out, all in
strict f64 arithmetic. So the player builds no point arrays for a layer.
The chords' length takes a plain square root where JS used Math.hypot,
which may differ in the last bit, so a curve whose bend falls within that
bit of a whole number of chords takes one chord more or fewer. Either is
within the flatness. Then layer runs libtess2 on each fill as
run would alone on those polygons, keeps each fill's output past its
scratch, which then goes, and gathers every fill's positions into one buffer
and its indices into another, counted from the layer's first vertex. The
wrapper copies those two out once into JS-owned typed arrays and gives each
fill views of its part, with indexOffset, its first vertex in the layer.
With layer(fills, nonZero, true) it copies nothing: the views are of the
module's memory, and the tessellator's next call overwrites them. The player
asks so, as it copies each fill into its own geometry at once, and the two
buffers cost a drawing made again every frame more than the fills did.
Positions remain doubles; indices use 16 bits through 65,536 vertices in the
layer and 32 bits above that. The module
checks every input coordinate and every output position and index, so the
player draws a layer's output unchecked; a fill alone (tessellate(contours,
nonZero)) is checked by its caller. Malformed commands and a fill whose
curves would flatten to more than a million points are refused; a fill
that ran out of memory, which may be the layer's, is tried as a layer of
its own, and a layer that unwinds or does not fit is tried a fill at a
time, so a layer gives every fill what a layer of its own would. No cached geometry aliases Wasm scratch. The
renderer copies each fill's triangles into a geometry of its own with its
paint's colours and texels (scene/shapes.ts), which its atlas holds
through context loss.
The absolute memory ceiling is 128 MiB, including static data, the C stack
and the arena. Instances above 8 MiB are discarded after the call. Options
can lower the limit or retained capacity. Coordinates that are not
finite, malformed contours, more than one million input vertices and
running out of memory return null. A fill of one convex contour, a
triangle above all, is a fan from its first point, its points as given,
with no sweep: convex as every turn goes one way and its edges go back
along each axis at most twice, which a contour winding round more than
once, as a pentagram, does not pass. A single simple concave contour of
at most 64 vertices uses ear clipping (src/render/earclip.zig), keeping
the input points too. One that goes once along an axis and once back, as a
crescent of two curves does, is first shown simple in a pass along that
axis (src/render/monotone.zig): each point strictly on its own side of
the other chain's edge beside it, so the chains meet only at their ends,
where ear clipping looks at every pair of edges. A thin one, its chains on
average no more than four of its points' steps apart, of at most 4,096
points, is then cut in a second pass into a strip of triangles between
the chains; a wide one goes to ear clipping, which skips its own check,
as a strip's triangles all reach across the contour and their long sides
cost a rasteriser more than ears' short ones.
Crossings, touches, overlapping edges and repeated
points, or an ear search that stalls, leave the fill to libtess2. The
fast paths stay within libtess2's coordinate range.
What libtess2 fails at, gives output
unfit to draw for, or cannot take (coordinates outside ±2^23), the module
fills by bands (src/render/bands.zig): the fill cut at every vertex's
height and every height two edges cross at, each span the rule fills a
trapezoid between two edges, the bands meeting along horizontal lines,
which the rasterizer splits without a crack. A fill that would make it
test more than 2^26 pairs of edges for a crossing is left out, as too slow
for a frame. A throwing failure import replaces libtess2's longjmp; that
instance is always discarded before another call, and the call is tried
again in a new one: a layer a fill at a time, and a fill that unwinds alone
by the bands, which never unwind. new Tessellator({ bands: true }) fills
by the bands alone, for tests. Arena reset alone
does not shrink Wasm memory. dispose() drops retained scratch without
affecting previous output.
The player references and context-loss checks draw with the native
tessellator, as everything does.
node tests/fuzz/tessellate.ts [cases] [seed]
checks both fill rules against independent ray crossings, by libtess2 and
again by the bands alone; the default test suite includes 2,000 fills and
24,000 coverage samples each way. It then flattens
curved layers, quadratics, cubics, curves of no length and NaN coordinates,
and checks each fill against a JS flattening tessellated alone: drawn or
refused alike, the same geometry bit for bit as JS with plain square roots
gives, and within the flatness of what Math.hypot gives. zig build
test in this folder runs flatten.zig's and bands.zig's own tests. Synthetic fixtures
also check coincident edges, holes and detail at large coordinates.
lines
tessellator.tessellate.lines, a LineBuilder, builds a shape layer's
lines in one call: the player packs the layer into input(n)
(scene/strokes.ts) and build(length) returns its positions, colours
and indices, copied out in one block. src/render/strokes.zig is the
player's only line builder. It began as a port of the player's TS, with
the same arithmetic in the same order, and keeps JS's semantics where they
show: Math.hypot is V8's algorithm (normalised to the larger value,
summed with Kahan's compensation), Math.sin and Math.cos are the host's
own, imported, since engines differ in their last bit, and atan2 and
acos are Zig's, which are fdlibm's, as V8's are. A line drawn opaque is
triangles along its path; any other is outlined and its outline filled
non-zero by the module's own libtess2, or its bands, as the Tessellator
fills it, with no call back to JS.
Where it cannot build a layer, build() returns undefined: an outline it
could not fill in its memory, a position that is NaN, or an instance that
unwound, after which the next fills the layer's outlines by the bands
alone; the player asks once more and otherwise draws the layer without
lines. The builder has an instance of its own, which no Tessellator call
shares, held to its Tessellator's memoryLimit and retainMemory, and
counted in its capacity; an instance grown past what is retained is let
go after its call. tests/unit/player/scene/strokes.test.ts checks the
lines it builds: their widths, caps, joins and miters by the area they
cover, that a wide line on a short curve leaves no hole, that an opaque
line's triangles cover what its outline does and meet corner to corner.
atf
Stage3D's ATF textures, which uploadCompressedTextureFromByteArray
takes: readAtfHeader(data, offset) reads the header, decodeAtf(data,
header) each face's levels, decoded to what Flash Player uploads on the
desktop. RGB888 and RGBA8888 hold a JPEG XR image a level and decode to
BGRA, alpha straight. The block compressed formats hold every GPU's
encoding, and decode to S3TC: Compressed (2) and its lossy variant (12) to
DXT1, CompressedAlpha (4, and 13) to DXT5, rebuilt from their LZMA'd
indices and the JPEG XR images of their endpoints; the raw formats (3, 5)
hold the blocks as they are. PVRTC, ETC1 and ETC2's blocks are skipped.
The layout is Adobe's "ATF file format" (version 3, 2015), and the old
header, which has no version, 24-bit lengths and no ETC2, as Adobe's MIT
dds2atf writes it; the endpoints'
images are a pixel a 4x4 block, the first endpoints above the second, the
indices 4 bytes a block (DXT5's alpha indices 6), as dds2atf encodes them.
Nothing is taken from dds2atf. A level rebuilt this way is the very bytes
png2atf's raw output holds for the same image (tests/unit/atf.test.ts).
Refusals are AIR's, as AIR 51 gives them for the same bytes: an
AtfError whose reason is size (#3669: less data than the header or
its length), decode (#3677: no signature, a format past 13, a size past
4096, a level count the size has not, a block the desktop reads cut short
by the data's end, a block that does not decode) or format (#3675:
the formats 6 to 11, which no texture takes). readAtfHeader checks only
what AIR checks before an asynchronous upload returns, the signature and
the length, and an offset that is a whole number within the data;
decodeAtf the rest. Past the length check, AIR reads the blocks as far
as the data goes, the length aside, and streams what it finds: data that
ends before a level's first block length, or within a block the desktop
skips (PVRTC's, ETC's), leaves that level and those after it absent, as
does a level whose blocks for the desktop are empty (png2atf's -n).
Nothing of the reserved bytes is read.
jxrlib's decoder, glue and encoder (vendor/jxrlib, https://github.com/swf2es/jxrlib,
a fork of 4creators/jxrlib, Microsoft's release, at tag v2019.10.9) are
compiled unchanged at -Os (the encoder without strenc_x86.c, SSE2's):
the module is about 154 KB, 101 KB of it the decoder's (150 KB at -O2
for 3% less decoding time), and 56 KB gzipped. src/atf/jxr.c decodes
an image in the pixel format its block must have, setting jxrlib's output
to the container's pixel format as jxrlib's own decoder does (the
codestream may name another, which jxrlib would write by into a buffer
sized for this one), and taking 24-bit RGB as png2atf writes it, named
24bppBGR. src/atf/include/ holds what jxrlib needs of libc beyond what
include/ declares, each header taking the package's with
#include_next, its file streams and diagnostics inert, and root.zig
its allocator over a bump arena that each call resets. The instance is
kept between images as compress's is (src/instance.ts, the same
MEMORY_KEPT).
jxrEncode(pixels, width, height, { alpha, quantization, subsampling,
trimFlexBits }) writes the JPEG XR file Flash's BitmapData.encode
writes for the same pixels, byte for byte (docs/architecture/bitmaps.md
has what Flash chooses). jxrlib's encoder writes the codestream, its rows
copied in 16 at a time; jxr.c then rewrites its headers as Flash's
(one quantizer index for all channels, the size always in 16 bits), pads
it as Flash does and wraps it in Flash's container of five tags. The
output grows in place at the top of the arena, so a file costs its own
size and the encoder's few rows of macroblocks. A 4800 by 2475 picture
encodes in about 150 ms at Flash's default quantization, 20, and 235 ms
lossless (jpegEncode takes 70 at quality 80); with alpha, 205 ms.
jxrlib is not memory safe on corrupt input: AddressSanitizer finds it
reading past its tables and writing through null pointers. In the module
these stay within its memory, whose stack comes first: a null pointer's
writes land at the bottom of the unused stack. An image refused or a
trap (#3677 either way) lets the instance go, and the next image starts
in a new one, so nothing a corrupt image did reaches another; one that
decodes keeps it.
node tests/fuzz/atf.ts [cases] [seed] mutates the fixtures, in both
headers, and checks that nothing traps or throws but AtfError and that
every level decoded is the size it should be; 450,000 cases traps none.
The 768 ATFs of a set of Alternativa3D demos, old-header Compressed up to
2048 pixels, decode in 3.6 s in node, 68 ms the largest.
