Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ jobs:
- name: Install Pages runtime dependencies
shell: bash
run: |
npm install --prefix .pages-runtime --no-save --no-package-lock --ignore-scripts three@0.186.1
npm install --prefix .pages-runtime --no-save --no-package-lock --ignore-scripts three@0.186.1 zstddec@0.3.1

- name: Validate example JavaScript
shell: bash
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/pages.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ jobs:
- name: Install Pages runtime dependencies
shell: bash
run: |
npm install --prefix .pages-runtime --no-save --no-package-lock --ignore-scripts three@0.186.1
npm install --prefix .pages-runtime --no-save --no-package-lock --ignore-scripts three@0.186.1 zstddec@0.3.1

- name: Validate example JavaScript
shell: bash
Expand Down
60 changes: 60 additions & 0 deletions THIRD_PARTY_LICENSES
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,63 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

4. zstddec 0.3.1
-----------------

Project: https://github.com/donmccurdy/zstddec-wasm
License: MIT AND BSD-3-Clause

The MIT License (MIT)

Copyright (c) 2020 Don McCurdy

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

BSD License

For Zstandard software

Copyright (c) 2016-present, Yann Collet, Facebook, Inc. All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

* Neither the name Facebook nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

3 changes: 2 additions & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@
"imports": {
"three": "https://cdn.jsdelivr.net/npm/three@0.186.1/build/three.module.js",
"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.186.1/examples/jsm/",
"augmenta-client-sdk": "./vendor/AugmentaClientSDK-JS/dist/esm/index.js"
"augmenta-client-sdk": "./vendor/AugmentaClientSDK-JS/dist/esm/index.js",
"zstddec": "https://cdn.jsdelivr.net/npm/zstddec@0.3.1/+esm"
}
}
</script>
Expand Down
32 changes: 32 additions & 0 deletions scripts/assemble-site.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ const root = process.cwd();
const out = join(root, '_site');
const rev = (process.env.GITHUB_SHA || 'local').slice(0, 12);
const threeRoot = join(root, '.pages-runtime', 'node_modules', 'three');
const zstdRoot = join(root, '.pages-runtime', 'node_modules', 'zstddec');
const sdkOut = join(out, 'vendor', 'AugmentaClientSDK-JS', rev, 'dist', 'esm');
const zstdOut = join(out, 'vendor', 'zstddec', rev);

function requirePath(path, label) {
if (!existsSync(path)) {
Expand All @@ -32,10 +34,31 @@ function replaceRequired(source, search, replacement) {
requirePath(join(root, 'vendor', 'AugmentaClientSDK-JS', 'dist', 'esm'), 'built Augmenta SDK');
requirePath(join(root, 'vendor', 'qrcode-generator', 'qrcode.js'), 'vendored QR generator');
requirePath(join(threeRoot, 'build', 'three.module.js'), 'Three.js runtime');
requirePath(join(zstdRoot, 'package.json'), 'Zstd decoder package');

const zstdPackage = JSON.parse(readFileSync(join(zstdRoot, 'package.json'), 'utf8'));
const zstdExports = zstdPackage.exports;
const zstdEntrypoint = (
typeof zstdExports === 'string'
? zstdExports
: zstdExports?.['.']?.browser
?? zstdExports?.['.']?.default
?? zstdExports?.browser
?? zstdExports?.default
?? zstdPackage.browser
?? zstdPackage.module
?? zstdPackage.main
);
if (typeof zstdEntrypoint !== 'string' || !zstdEntrypoint) {
throw new Error('Could not resolve the zstddec browser entrypoint.');
}
const zstdEntrypointRelative = zstdEntrypoint.replace(/^\.\//, '');
requirePath(join(zstdRoot, zstdEntrypointRelative), 'Zstd browser decoder entrypoint');

rmSync(out, { recursive: true, force: true });
mkdirSync(join(out, 'src'), { recursive: true });
mkdirSync(sdkOut, { recursive: true });
mkdirSync(zstdOut, { recursive: true });
mkdirSync(join(out, 'vendor', 'qrcode-generator'), { recursive: true });

copyFileSync(join(root, 'index.html'), join(out, 'index.html'));
Expand All @@ -54,6 +77,10 @@ cpSync(
sdkOut,
{ recursive: true }
);
// zstddec embeds the WebAssembly decoder in its browser package, so copying the
// package keeps compressed Augmenta streams self-contained on GitHub Pages with
// no runtime CDN dependency.
cpSync(zstdRoot, zstdOut, { recursive: true });
copyFileSync(
join(root, 'vendor', 'qrcode-generator', 'qrcode.js'),
join(out, 'vendor', 'qrcode-generator', 'qrcode.js')
Expand Down Expand Up @@ -98,6 +125,11 @@ html = replaceRequired(
'./vendor/AugmentaClientSDK-JS/dist/esm/index.js',
`./vendor/AugmentaClientSDK-JS/${rev}/dist/esm/index.js`
);
html = replaceRequired(
html,
'https://cdn.jsdelivr.net/npm/zstddec@0.3.1/+esm',
`./vendor/zstddec/${rev}/${zstdEntrypointRelative}`
);
html = replaceRequired(html, './src/styles.css', `./src/styles.css?v=${rev}`);
html = replaceRequired(html, './src/qr.js', `./src/qr.js?v=${rev}`);
html = replaceRequired(html, './src/main.js', `./src/main.js?v=${rev}`);
Expand Down
56 changes: 49 additions & 7 deletions src/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,26 @@ import { APP_VERSION } from './app-info.js';
const RECONNECT_DELAY_MS = 1000;
const CONNECTION_ATTEMPT_TIMEOUT_MS = 2500;

let zstdDecompressorPromise;

async function getZstdDecompressor() {
if (!zstdDecompressorPromise) {
zstdDecompressorPromise = import('zstddec')
.then(async ({ ZSTDDecoder }) => {
const decoder = new ZSTDDecoder();
await decoder.init();
return (data) => decoder.decode(data);
})
.catch((error) => {
// Allow a later reconnect attempt to retry initialization if loading the
// local decoder failed transiently.
zstdDecompressorPromise = undefined;
throw error;
});
}
return zstdDecompressorPromise;
}

// Three.js is Y-up, right-handed and metre-based. Ask Augmenta/Pleiades to
// deliver tracking and setup data directly in that convention.
const THREE_JS_AXIS_TRANSFORM = Object.freeze({
Expand Down Expand Up @@ -38,6 +58,7 @@ export function createConnectionController({
let targetIndex = 0;
let targetKey = '';
let attemptTimer;
let connectionAttemptGeneration = 0;

function getState() {
return { wantsConnection, socketOpen, retrying, activeVersion, phase, note };
Expand Down Expand Up @@ -70,6 +91,7 @@ export function createConnectionController({
}

function stopTransport(reason = 'User disconnect') {
connectionAttemptGeneration += 1;
clearReconnectTimer();
clearAttemptTimer();
socketOpen = false;
Expand Down Expand Up @@ -107,7 +129,7 @@ export function createConnectionController({

reconnectTimer = window.setTimeout(() => {
reconnectTimer = undefined;
attemptConnection();
void attemptConnection();
}, delay);
}

Expand All @@ -119,14 +141,15 @@ export function createConnectionController({
publish('connecting', `Server uses protocol V${version}. Reconnecting with the matching parser…`);
reconnectTimer = window.setTimeout(() => {
reconnectTimer = undefined;
attemptConnection();
void attemptConnection();
}, 0);
}

function attemptConnection() {
async function attemptConnection() {
if (!wantsConnection) return;

clearReconnectTimer();
const attemptGeneration = ++connectionAttemptGeneration;

let target;
let protocol;
Expand Down Expand Up @@ -160,18 +183,37 @@ export function createConnectionController({
publish('connecting', `Connecting to ${target.label} with protocol V${version}…`);
}

let decompressor;
try {
decompressor = await getZstdDecompressor();
} catch (error) {
if (attemptGeneration !== connectionAttemptGeneration || !wantsConnection) return;
wantsConnection = false;
retrying = false;
const message = error instanceof Error ? error.message : String(error);
publish('error', `Could not initialize Zstd decompression: ${message}`);
return;
}

if (attemptGeneration !== connectionAttemptGeneration || !wantsConnection) return;

const connection = new AugmentaWebSocketClient(target.url, {
clientName: 'Augmenta Three.js Debug Viewer',
applicationName: 'Augmenta ThreeJS Example',
applicationVersion: APP_VERSION,
decompressor,
options: {
version,
downSample,
streamClouds,
streamClusters,
streamClusterPoints,
streamZonePoints: true,
useCompression: false,
// Keep the realtime stream compressed by default, matching the Unity,
// TouchDesigner and VVVV clients. This cuts WebSocket bandwidth and
// backlog pressure; zstddec is initialized before the connection and
// the JS SDK invokes it synchronously before parsing each binary frame.
useCompression: true,
displayPointIntensity: true,
// Quaternions preserve Pleiades' exact OBB orientation. The viewer
// performs the left-handed -> right-handed basis reflection explicitly.
Expand All @@ -196,7 +238,7 @@ export function createConnectionController({
socketOpen = true;
publish(
'connected',
`Connected to ${target.label}. Protocol V${activeVersion}; uncompressed debug stream.`
`Connected to ${target.label}. Protocol V${activeVersion}; Zstd-compressed debug stream.`
);
});

Expand Down Expand Up @@ -274,7 +316,7 @@ export function createConnectionController({
autoNegotiatedVersion = undefined;
wantsConnection = true;
retrying = false;
attemptConnection();
void attemptConnection();
}

function stop() {
Expand All @@ -290,7 +332,7 @@ export function createConnectionController({
retrying = false;
autoNegotiatedVersion = undefined;
stopTransport(reason);
attemptConnection();
void attemptConnection();
}

return { getState, start, stop, restart };
Expand Down
50 changes: 50 additions & 0 deletions tests/websocket-compression.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import test from 'node:test';

const compressedFixture = Uint8Array.from([
40, 181, 47, 253, 36, 30, 241, 0, 0, 65, 117, 103, 109, 101, 110, 116,
97, 32, 90, 115, 116, 100, 32, 105, 110, 116, 101, 103, 114, 97, 116, 105,
111, 110, 32, 116, 101, 115, 116, 185, 49, 3, 224
]);

test('bundled zstd decoder can decode Augmenta binary payloads synchronously after init', async () => {
const zstdRoot = new URL('../.pages-runtime/node_modules/zstddec/', import.meta.url);
const packageJson = JSON.parse(readFileSync(new URL('package.json', zstdRoot), 'utf8'));
const packageExports = packageJson.exports;
const entrypoint = (
typeof packageExports === 'string'
? packageExports
: packageExports?.['.']?.default
?? packageExports?.default
?? packageJson.module
?? packageJson.main
);
assert.equal(typeof entrypoint, 'string');

const { ZSTDDecoder } = await import(new URL(entrypoint, zstdRoot).href);
const decoder = new ZSTDDecoder();
await decoder.init();

const decoded = decoder.decode(compressedFixture);
assert.equal(new TextDecoder().decode(decoded), 'Augmenta Zstd integration test');

// The SDK requires a synchronous decompressor once the transport is running.
const decompressor = (data) => decoder.decode(data);
assert.equal(
new TextDecoder().decode(decompressor(compressedFixture)),
'Augmenta Zstd integration test'
);
});

test('Three.js runtime requests compression and ships the decoder in the Pages artifact', () => {
const connection = readFileSync(new URL('../src/connection.js', import.meta.url), 'utf8');
const index = readFileSync(new URL('../index.html', import.meta.url), 'utf8');
const assemble = readFileSync(new URL('../scripts/assemble-site.mjs', import.meta.url), 'utf8');

assert.match(connection, /useCompression:\s*true/);
assert.match(connection, /decompressor,/);
assert.match(connection, /import\('zstddec'\)/);
assert.match(index, /zstddec@0\.3\.1\/\+esm/);
assert.match(assemble, /zstdEntrypointRelative/);
});
Loading