@hexaversia/fovea-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +83 -0
  3. package/index.js +220 -0
  4. package/package.json +37 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Fovea Team
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,83 @@
1
+ # Fovea SDK
2
+
3
+ **Foveated Streaming Engine** for High-Performance Screen Sharing.
4
+
5
+ ![Fovea Banner](https://via.placeholder.com/800x200?text=Fovea+SDK)
6
+
7
+ ## Overview
8
+ Fovea uses **WebAssembly (Rust)** to perform "Foveated Rendering" on video streams entirely on the client side. It detects changes in the screen and only sends high-resolution updates for the active region (ROI), while blurring the static background. This results in **massive bandwidth savings (up to 90%)** for screen sharing applications.
9
+
10
+ ## Installation
11
+
12
+ ```bash
13
+ npm install fovea-sdk
14
+ ```
15
+
16
+ (Note: During private beta, install from local path or private registry)
17
+
18
+ ## Usage
19
+
20
+ ### 1. Electron (Node.js)
21
+
22
+ ```javascript
23
+ const FoveaEngine = require('fovea-sdk');
24
+ const path = require('path');
25
+
26
+ async function start() {
27
+ const engine = new FoveaEngine({ blurAmount: '12px' });
28
+
29
+ // Initialize with local WASM file
30
+ await engine.initialize({
31
+ wasmPath: path.join(__dirname, 'node_modules/fovea-sdk/fovea_rs/pkg/fovea_wasm_bg.wasm')
32
+ });
33
+
34
+ function loop() {
35
+ // Process video frame -> canvas
36
+ const result = engine.process(videoElement, outputCanvas);
37
+
38
+ if (result && result.type === 'foveated') {
39
+ console.log(`ROI: ${JSON.stringify(result.bbox)}`);
40
+ }
41
+ requestAnimationFrame(loop);
42
+ }
43
+ }
44
+ ```
45
+
46
+ ### 2. Browser (React/Vue/Vanilla)
47
+
48
+ Copy the `.wasm` file to your public assets folder first.
49
+
50
+ ```javascript
51
+ import FoveaEngine from 'fovea-sdk';
52
+
53
+ const engine = new FoveaEngine();
54
+
55
+ // Initialize by fetching WASM from public URL
56
+ await engine.initialize({
57
+ wasmPath: '/assets/fovea_wasm_bg.wasm'
58
+ });
59
+
60
+ // ... use engine.process() in your render loop
61
+ ```
62
+
63
+ ## API
64
+
65
+ ### `new FoveaEngine(config)`
66
+ - `config.blurAmount`: CSS blur string (default `'8px'`)
67
+ - `config.diffThreshold`: Sensitivity (0-255) for change detection (default `30`)
68
+
69
+ ### `async initialize(options)`
70
+ - `options.wasmPath`: Path (Node) or URL (Browser) to the `.wasm` binary.
71
+ - `options.wasmBuffer`: ArrayBuffer of the WASM binary (optional alternative).
72
+
73
+ ### `process(video, canvas)`
74
+ - `video`: Source HTMLVideoElement
75
+ - `canvas`: Target HTMLCanvasElement (where the foveated effect is drawn)
76
+ - Returns: `{ type, bbox, isKeyframe }`
77
+
78
+ ## 🤝 Contributing
79
+ Want to improve the engine? We welcome optimizations!
80
+ Since the core is written in Rust, please see our [Contribution Guide](CONTRIBUTING.md) for build instructions.
81
+
82
+ ## License
83
+ MIT
package/index.js ADDED
@@ -0,0 +1,220 @@
1
+ // Universal Import Strategy
2
+ let fs = null;
3
+ let path = null;
4
+
5
+ // Try to load Node modules if 'require' is available (Node.js or Electron)
6
+ if (typeof require !== 'undefined') {
7
+ try {
8
+ fs = require('fs');
9
+ path = require('path');
10
+ } catch (e) {
11
+ // Bundlers might define 'require' but fail to resolve 'fs'
12
+ console.warn("[Fovea SDK] 'require' present but failed to load fs/path:", e);
13
+ }
14
+ }
15
+
16
+ // Determine environment
17
+ const isNode = typeof process !== 'undefined' && process.versions && process.versions.node;
18
+
19
+
20
+ /**
21
+ * Fovea Engine SDK
22
+ *
23
+ * Usage:
24
+ * const engine = new FoveaEngine();
25
+ * await engine.initialize({ wasmPath: '/path/to/fovea.wasm' }); // Browser
26
+ * await engine.initialize({ wasmPath: __dirname + '/fovea.wasm' }); // Node
27
+ *
28
+ * const result = engine.process(videoElement, canvasElement);
29
+ */
30
+ class FoveaEngine {
31
+ constructor(config = {}) {
32
+ this.wasmInstance = null;
33
+ this.calculate_diff = null;
34
+ this.config = {
35
+ blurAmount: config.blurAmount || '8px',
36
+ diffThreshold: config.diffThreshold || 30,
37
+ debug: config.debug || false
38
+ };
39
+
40
+ // State
41
+ this.prevFrameData = null;
42
+ this.frameCount = 0;
43
+ this.keyframeInterval = 300;
44
+
45
+ // Internal scratch canvas
46
+ this.diffCanvas = null;
47
+ this.diffCtx = null;
48
+ }
49
+
50
+ async initialize(options = {}) {
51
+ if (this.wasmInstance) return;
52
+
53
+ console.log("[Fovea SDK] Initializing...");
54
+
55
+ let wasmBytes;
56
+
57
+ // 1. Try to load WASM based on Environment
58
+ if (isNode && options.wasmPath) {
59
+ // Node.js: Read from FS
60
+ try {
61
+ wasmBytes = fs.readFileSync(options.wasmPath);
62
+ } catch (e) {
63
+ throw new Error(`[Fovea SDK] Failed to read WASM file at ${options.wasmPath}: ${e.message}`);
64
+ }
65
+ } else if (!isNode && options.wasmPath) {
66
+ // Browser: Fetch URL
67
+ // Users should pass the URL where they host the .wasm file
68
+ // OR pass a pre-loaded ArrayBuffer/Response
69
+ if (typeof options.wasmPath === 'string') {
70
+ // It's a URL
71
+ const response = await fetch(options.wasmPath);
72
+ wasmBytes = await response.arrayBuffer();
73
+ } else {
74
+ // Assume it's already bytes/response
75
+ wasmBytes = options.wasmPath;
76
+ }
77
+ } else if (options.wasmBuffer) {
78
+ // Direct Buffer passed
79
+ wasmBytes = options.wasmBuffer;
80
+ } else {
81
+ throw new Error("[Fovea SDK] You must provide 'wasmPath' or 'wasmBuffer' to initialize.");
82
+ }
83
+
84
+ // 2. Instantiate WebAssembly
85
+ // We need the 'init' function from the pkg.
86
+ // Since we can't easily 'require' an ESM-only pkg in a generic CJS/UMD without a build step,
87
+ // We will assume the user environment supports dynamic import() OR
88
+ // strictly speaking, for this "raw" SDK, we might need to inline a lightweight loader.
89
+
90
+ // APPROACH: We will use the 'fovea_wasm.js' generated by wasm-pack
91
+ // but we need to locate it.
92
+ // For simplicity in this raw version, we'll try to dynamically import the relative file if possible,
93
+ // otherwise we expect the USER to pass the module exports?
94
+ // Let's try importing the local pkg file.
95
+
96
+ try {
97
+ // NOTE: This path depends on where this file is located relative to pkg
98
+ // If running in node, require works.
99
+ // If running in browser (via bundler), import works.
100
+ // This is the hardest part of "Universal" without a build step.
101
+
102
+ // Allow user to pass the init function if they imported it themselves
103
+ const initFunc = options.initFunction || (await import('./fovea_rs/pkg/fovea_wasm.js')).default;
104
+ const diffFunc = options.diffFunction || (await import('./fovea_rs/pkg/fovea_wasm.js')).calculate_diff;
105
+
106
+ await initFunc(wasmBytes);
107
+ this.calculate_diff = diffFunc;
108
+
109
+ console.log("[Fovea SDK] WASM Ready.");
110
+ this.wasmInstance = true;
111
+
112
+ } catch (e) {
113
+ console.error(e);
114
+ throw new Error("[Fovea SDK] Failed to instantiate WASM module. Ensure generated pkg is available.");
115
+ }
116
+ }
117
+
118
+ /**
119
+ * Main Processing Loop Step
120
+ * Call this on every animation frame.
121
+ * @param {HTMLVideoElement} video Source video
122
+ * @param {HTMLCanvasElement} outputCanvas Output canvas (visible)
123
+ * @returns {Object} { type: 'keyframe'|'foveated', dataUrl: string, stats: object }
124
+ */
125
+ process(video, outputCanvas) {
126
+ if (!this.wasmInstance) {
127
+ console.warn("[Fovea SDK] Not initialized.");
128
+ return null;
129
+ }
130
+ if (video.paused || video.ended) return null;
131
+
132
+ const w = outputCanvas.width;
133
+ const h = outputCanvas.height;
134
+ const ctx = outputCanvas.getContext('2d', { willReadFrequently: true });
135
+
136
+ this.frameCount++;
137
+ let isKeyframe = (this.frameCount === 1 || this.frameCount % this.keyframeInterval === 0);
138
+
139
+ // --- 1. Downscale for diffing ---
140
+ const diffScale = 0.1;
141
+ const dw = Math.floor(w * diffScale);
142
+ const dh = Math.floor(h * diffScale);
143
+
144
+ if (!this.diffCanvas) {
145
+ // Try OffscreenCanvas (Worker/Modern) or document (Browser)
146
+ if (typeof OffscreenCanvas !== 'undefined') {
147
+ this.diffCanvas = new OffscreenCanvas(dw, dh);
148
+ } else {
149
+ this.diffCanvas = document.createElement('canvas');
150
+ this.diffCanvas.width = dw;
151
+ this.diffCanvas.height = dh;
152
+ }
153
+ this.diffCtx = this.diffCanvas.getContext('2d', { willReadFrequently: true });
154
+ }
155
+
156
+ // Resize if needed
157
+ if (this.diffCanvas.width !== dw) this.diffCanvas.width = dw;
158
+ if (this.diffCanvas.height !== dh) this.diffCanvas.height = dh;
159
+
160
+ this.diffCtx.drawImage(video, 0, 0, dw, dh);
161
+
162
+ const currentFrameData = this.diffCtx.getImageData(0, 0, dw, dh);
163
+ const currentPixels = new Uint8Array(currentFrameData.data.buffer);
164
+
165
+ // --- 2. Calculate Diff (WASM) ---
166
+ let bbox = { min_x: 0, max_x: 0, min_y: 0, max_y: 0, changed: false };
167
+
168
+ if (this.prevFrameData && this.prevFrameData.length === currentPixels.length && !isKeyframe) {
169
+ try {
170
+ bbox = this.calculate_diff(currentPixels, this.prevFrameData, dw, dh, this.config.diffThreshold);
171
+ } catch (e) {
172
+ console.warn("[Fovea SDK] WASM Diff Error, forcing keyframe", e);
173
+ isKeyframe = true;
174
+ }
175
+ } else {
176
+ isKeyframe = true;
177
+ }
178
+
179
+ this.prevFrameData = new Uint8Array(currentPixels); // Cache
180
+
181
+ // --- 3. Render Output ---
182
+ if (isKeyframe) {
183
+ ctx.filter = 'none';
184
+ ctx.drawImage(video, 0, 0, w, h);
185
+ } else {
186
+ ctx.filter = `blur(${this.config.blurAmount})`;
187
+ ctx.drawImage(video, 0, 0, w, h); // Blurred Background
188
+
189
+ if (bbox.changed) {
190
+ ctx.filter = 'none';
191
+ const scale = 1 / diffScale;
192
+ const roiX = Math.max(0, (bbox.min_x * scale) - 20);
193
+ const roiY = Math.max(0, (bbox.min_y * scale) - 20);
194
+ const roiW = Math.min(w - roiX, (bbox.max_x - bbox.min_x) * scale + 40);
195
+ const roiH = Math.min(h - roiY, (bbox.max_y - bbox.min_y) * scale + 40);
196
+
197
+ ctx.save();
198
+ ctx.beginPath();
199
+ ctx.rect(roiX, roiY, roiW, roiH);
200
+ ctx.clip();
201
+ ctx.drawImage(video, 0, 0, w, h); // Sharp ROI
202
+ ctx.restore();
203
+ }
204
+ }
205
+
206
+ return {
207
+ type: isKeyframe ? 'keyframe' : 'foveated',
208
+ bbox: bbox,
209
+ isKeyframe: isKeyframe
210
+ };
211
+ }
212
+ }
213
+
214
+ // Export for CommonJS and ESM
215
+ if (typeof module !== 'undefined' && module.exports) {
216
+ module.exports = FoveaEngine;
217
+ } else {
218
+ // Browser Global
219
+ window.FoveaEngine = FoveaEngine;
220
+ }
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@hexaversia/fovea-sdk",
3
+ "version": "0.1.0",
4
+ "description": "Foveated Streaming Engine: High-performance, bandwidth-efficient screen sharing using WASM and Dynamic ROI.",
5
+ "main": "index.js",
6
+ "types": "index.d.ts",
7
+ "files": [
8
+ "index.js",
9
+ "fovea_rs/pkg"
10
+ ],
11
+ "scripts": {
12
+ "test": "echo \"Error: no test specified\" && exit 1"
13
+ },
14
+ "keywords": [
15
+ "foveated",
16
+ "streaming",
17
+ "wasm",
18
+ "screen-sharing",
19
+ "bandwidth-optimization",
20
+ "real-time",
21
+ "video-analysis",
22
+ "ai",
23
+ "computer-vision"
24
+ ],
25
+ "author": "Hexaversia Team",
26
+ "license": "MIT",
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/agentifyanchor/fovea-sdk.git"
30
+ },
31
+ "bugs": {
32
+ "url": "https://github.com/agentifyanchor/fovea-sdk/issues"
33
+ },
34
+ "homepage": "https://agentifyanchor.github.io/fovea-sdk",
35
+ "dependencies": {},
36
+ "devDependencies": {}
37
+ }