shared-memory-image 0.0.0-stage → 1.0.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.
@@ -0,0 +1,556 @@
1
+ /*
2
+ (c) 2025-2026
3
+
4
+ https://github.com/true-goniss/shared-memory-image
5
+
6
+ Windows shared-memory RGBA frame exchange.
7
+ N-API (node-addon-api, NAPI_VERSION 8, no C++ exceptions).
8
+ Concurrency: shared header + seqlock + named auto-reset event.
9
+ */
10
+
11
+ #include <napi.h>
12
+ #include <Windows.h>
13
+ #include <cstdint>
14
+ #include <cmath>
15
+ #include <cstring>
16
+ #include <string>
17
+ #include <emmintrin.h> // _mm_pause()
18
+
19
+ #define SHARED_MAGIC 0x5348444D
20
+
21
+ // helper: portable 64-bit atomic increment
22
+ static inline uint64_t AtomicIncrement64(volatile LONG64* p) {
23
+ #if defined(_WIN64)
24
+ return InterlockedIncrement64(p);
25
+ #else
26
+ // 32-bit: implement via CAS loop using InterlockedCompareExchange64
27
+ LONG64 oldval, newval;
28
+ do {
29
+ oldval = *p;
30
+ newval = oldval + 1;
31
+ } while (InterlockedCompareExchange64(p, newval, oldval) != oldval);
32
+ return static_cast<uint64_t>(newval);
33
+ #endif
34
+ }
35
+
36
+ // args come from JS and can be anything; As<Napi::Number>() is an unchecked
37
+ // cast, so coerce first like V8 ToNumber did ("42" -> 42, undefined -> 0)
38
+ static inline double CoerceNumber(const Napi::Value& v) {
39
+ napi_env env = v.Env();
40
+ if (v.IsNumber()) return v.As<Napi::Number>().DoubleValue();
41
+ napi_value num = nullptr;
42
+ if (napi_coerce_to_number(env, v, &num) != napi_ok) {
43
+ // Symbol/BigInt throw under V8 too; clear the pending exception, NaN
44
+ napi_value pending = nullptr;
45
+ napi_get_and_clear_last_exception(env, &pending);
46
+ return NAN;
47
+ }
48
+ double d = 0.0;
49
+ if (napi_get_value_double(env, num, &d) != napi_ok) return 0.0;
50
+ return d;
51
+ }
52
+
53
+ static inline int64_t ToInt64(const Napi::Value& v) {
54
+ double d = CoerceNumber(v);
55
+ if (std::isnan(d) || d <= 0.0) return 0;
56
+ if (d >= 9.007199254740991e15) return (int64_t)9.007199254740991e15;
57
+ return (int64_t)d;
58
+ }
59
+
60
+ // Shared header layout (wire contract: do not change)
61
+ #pragma pack(push,1)
62
+ struct SharedHeader {
63
+ uint32_t magic; // 0x5348444D 'SHDM'
64
+ uint32_t version; // 1
65
+ volatile LONG seq; // sequence counter (seqlock)
66
+ uint32_t width;
67
+ uint32_t height;
68
+ uint32_t channels;
69
+ uint32_t frame_size; // bytes of current frame
70
+ uint64_t frame_index; // ever increasing frame counter
71
+ uint64_t mapping_size; // total mapping size
72
+ uint8_t reserved[48];
73
+ };
74
+ #pragma pack(pop)
75
+
76
+ static const size_t HEADER_SIZE = ((sizeof(SharedHeader) + 63) / 64) * 64;
77
+
78
+ // external Buffers handed to JS point into this mapping; real UnmapViewOfFile
79
+ // waits until the owner retires it and the last Buffer is finalized, so stale
80
+ // Buffer writes land in mapped memory instead of crashing
81
+ struct MappingRef {
82
+ void* base = nullptr;
83
+ HANDLE hMap = nullptr;
84
+ size_t mapSize = 0;
85
+ volatile LONG bufCount = 0;
86
+ bool retired = false;
87
+ };
88
+
89
+ static void MappingRefRelease(MappingRef* ref) {
90
+ if (!ref) return;
91
+ if (InterlockedDecrement(&ref->bufCount) == 0 && ref->retired) {
92
+ // owner is gone and this was the last live Buffer: safe to unmap now
93
+ if (ref->base) UnmapViewOfFile(ref->base);
94
+ if (ref->hMap) CloseHandle(ref->hMap);
95
+ delete ref;
96
+ }
97
+ }
98
+
99
+ // mapping owns the memory, the finalizer only drops its refcount
100
+ static void BufferFinalize(napi_env /*env*/, void* /*data*/, void* hint) {
101
+ MappingRefRelease(static_cast<MappingRef*>(hint));
102
+ }
103
+
104
+ class SharedMemory : public Napi::ObjectWrap<SharedMemory> {
105
+ public:
106
+ static Napi::Object Init(Napi::Env env, Napi::Object exports);
107
+ explicit SharedMemory(const Napi::CallbackInfo& info);
108
+ ~SharedMemory();
109
+
110
+ private:
111
+ // Methods mapped to JS
112
+ Napi::Value Create(const Napi::CallbackInfo& info);
113
+ Napi::Value SetFormat(const Napi::CallbackInfo& info);
114
+ Napi::Value GetFrameBuffer(const Napi::CallbackInfo& info);
115
+ Napi::Value GetCapacity(const Napi::CallbackInfo& info);
116
+ Napi::Value PublishFrame(const Napi::CallbackInfo& info);
117
+ Napi::Value PublishRaw(const Napi::CallbackInfo& info);
118
+ Napi::Value ReadFrame(const Napi::CallbackInfo& info);
119
+ Napi::Value ReadFrameInto(const Napi::CallbackInfo& info);
120
+ Napi::Value Close(const Napi::CallbackInfo& info);
121
+ Napi::Value GetMetadata(const Napi::CallbackInfo& info);
122
+
123
+ // Internal helpers
124
+ SharedHeader* headerPtr() { return reinterpret_cast<SharedHeader*>((uint8_t*)base_); }
125
+ void* dataPtr() { return (uint8_t*)base_ + HEADER_SIZE; }
126
+ size_t dataCapacity() { return ref_ && ref_->mapSize > HEADER_SIZE ? ref_->mapSize - HEADER_SIZE : 0; }
127
+ void RetireMapping();
128
+
129
+ // Member variables
130
+ MappingRef* ref_ = nullptr; // owns the mapping, may outlive this instance
131
+ void* base_ = nullptr; // == ref_->base, null after close()
132
+ HANDLE hEvent_ = nullptr;
133
+ std::string eventName_;
134
+
135
+ // same JS object per mapping: getFrameBuffer sits on the compositor hot path
136
+ // (every frame), a fresh Buffer + finalizer per call would spam the GC
137
+ napi_env env_ = nullptr;
138
+ napi_ref bufRef_ = nullptr;
139
+ };
140
+
141
+ // --- Implementation ---
142
+
143
+ SharedMemory::SharedMemory(const Napi::CallbackInfo& info)
144
+ : Napi::ObjectWrap<SharedMemory>(info) {
145
+ env_ = info.Env();
146
+ }
147
+
148
+ SharedMemory::~SharedMemory() {
149
+ RetireMapping();
150
+ if (hEvent_) CloseHandle(hEvent_);
151
+ }
152
+
153
+ void SharedMemory::RetireMapping() {
154
+ // drop our strong ref; its finalizer releases bufCount when GC collects it
155
+ if (bufRef_ && env_) { napi_delete_reference(env_, bufRef_); bufRef_ = nullptr; }
156
+ MappingRef* ref = ref_;
157
+ ref_ = nullptr;
158
+ base_ = nullptr;
159
+ if (!ref) return;
160
+ ref->retired = true;
161
+ // no live Buffers left: free right here, otherwise the last finalizer will
162
+ if (ref->bufCount == 0) {
163
+ if (ref->base) UnmapViewOfFile(ref->base);
164
+ if (ref->hMap) CloseHandle(ref->hMap);
165
+ delete ref;
166
+ }
167
+ }
168
+
169
+ Napi::Object SharedMemory::Init(Napi::Env env, Napi::Object exports) {
170
+ Napi::Function func = DefineClass(env, "SharedMemory", {
171
+ InstanceMethod("create", &SharedMemory::Create),
172
+ InstanceMethod("setFormat", &SharedMemory::SetFormat),
173
+ InstanceMethod("getFrameBuffer", &SharedMemory::GetFrameBuffer),
174
+ InstanceMethod("getCapacity", &SharedMemory::GetCapacity),
175
+ InstanceMethod("publishFrame", &SharedMemory::PublishFrame),
176
+ InstanceMethod("publishRaw", &SharedMemory::PublishRaw),
177
+ InstanceMethod("readFrame", &SharedMemory::ReadFrame),
178
+ InstanceMethod("readFrameInto", &SharedMemory::ReadFrameInto),
179
+ InstanceMethod("close", &SharedMemory::Close),
180
+ InstanceMethod("getMetadata", &SharedMemory::GetMetadata),
181
+ });
182
+
183
+ exports.Set("SharedMemory", func);
184
+ return exports;
185
+ }
186
+
187
+ // --- Method Implementations ---
188
+
189
+ Napi::Value SharedMemory::Create(const Napi::CallbackInfo& info) {
190
+ Napi::Env env = info.Env();
191
+
192
+ if (info.Length() < 2 || !info[0].IsString() || !info[1].IsNumber()) {
193
+ Napi::TypeError::New(env, "Args: name, size").ThrowAsJavaScriptException();
194
+ return env.Undefined();
195
+ }
196
+
197
+ // cleanup if already opened (unmap may be deferred, see MappingRef)
198
+ RetireMapping();
199
+
200
+ std::string mapName = info[0].As<Napi::String>().Utf8Value();
201
+ uint64_t requestedSize = (uint64_t)ToInt64(info[1]);
202
+
203
+ uint32_t width = 0, height = 0, channels = 0;
204
+ if (info.Length() >= 5) {
205
+ width = (uint32_t)ToInt64(info[2]);
206
+ height = (uint32_t)ToInt64(info[3]);
207
+ channels = (uint32_t)ToInt64(info[4]);
208
+ }
209
+
210
+ HANDLE hMap = OpenFileMappingA(FILE_MAP_ALL_ACCESS, FALSE, mapName.c_str());
211
+ bool isCreator = false;
212
+
213
+ if (!hMap) {
214
+ DWORD sizeLow = static_cast<DWORD>(requestedSize & 0xFFFFFFFF);
215
+ DWORD sizeHigh = static_cast<DWORD>((requestedSize >> 32) & 0xFFFFFFFF);
216
+ hMap = CreateFileMappingA(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, sizeHigh, sizeLow, mapName.c_str());
217
+ if (!hMap) {
218
+ Napi::Error::New(env, "CreateFileMapping failed").ThrowAsJavaScriptException();
219
+ return env.Undefined();
220
+ }
221
+ isCreator = true;
222
+ }
223
+
224
+ void* base = MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);
225
+ if (!base) {
226
+ CloseHandle(hMap);
227
+ Napi::Error::New(env, "MapViewOfFile failed").ThrowAsJavaScriptException();
228
+ return env.Undefined();
229
+ }
230
+
231
+ MEMORY_BASIC_INFORMATION mbi;
232
+ VirtualQuery(base, &mbi, sizeof(mbi));
233
+
234
+ MappingRef* ref = new MappingRef();
235
+ ref->base = base;
236
+ ref->hMap = hMap;
237
+ ref->mapSize = mbi.RegionSize;
238
+ ref_ = ref;
239
+ base_ = base;
240
+
241
+ // Event setup
242
+ eventName_ = "Global\\SHM_EV_" + mapName;
243
+ hEvent_ = OpenEventA(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, eventName_.c_str());
244
+ if (!hEvent_) {
245
+ eventName_ = "Local\\SHM_EV_" + mapName;
246
+ hEvent_ = CreateEventA(nullptr, FALSE, FALSE, eventName_.c_str());
247
+ }
248
+
249
+ if (isCreator) {
250
+ // Initialize header
251
+ SharedHeader* hdr = headerPtr();
252
+ ZeroMemory(hdr, sizeof(SharedHeader));
253
+ hdr->magic = SHARED_MAGIC;
254
+ hdr->version = 1;
255
+ hdr->width = width;
256
+ hdr->height = height;
257
+ hdr->channels = channels;
258
+ hdr->mapping_size = ref->mapSize;
259
+ }
260
+
261
+ return Napi::String::New(env, "ok");
262
+ }
263
+
264
+ Napi::Value SharedMemory::SetFormat(const Napi::CallbackInfo& info) {
265
+ Napi::Env env = info.Env();
266
+ if (!base_) return env.Undefined();
267
+
268
+ uint32_t w = (uint32_t)ToInt64(info[0]);
269
+ uint32_t h = (uint32_t)ToInt64(info[1]);
270
+ uint32_t c = (uint32_t)ToInt64(info[2]);
271
+
272
+ SharedHeader* hdr = headerPtr();
273
+ InterlockedIncrement(&hdr->seq);
274
+ MemoryBarrier();
275
+ hdr->width = w; hdr->height = h; hdr->channels = c;
276
+ MemoryBarrier();
277
+ InterlockedIncrement(&hdr->seq);
278
+
279
+ if (hEvent_) SetEvent(hEvent_);
280
+ return Napi::Boolean::New(env, true);
281
+ }
282
+
283
+ Napi::Value SharedMemory::GetFrameBuffer(const Napi::CallbackInfo& info) {
284
+ Napi::Env env = info.Env();
285
+
286
+ if (!ref_ || !base_ || dataCapacity() == 0) {
287
+ return env.Null();
288
+ }
289
+
290
+ // hot path: same JS object until the mapping retires
291
+ napi_value cached = nullptr;
292
+ if (bufRef_ && napi_get_reference_value(env, bufRef_, &cached) == napi_ok && cached) {
293
+ return Napi::Value(env, cached);
294
+ }
295
+
296
+ // zero-copy view; the Buffer keeps the mapping alive through bufCount
297
+ InterlockedIncrement(&ref_->bufCount);
298
+ napi_value result = nullptr;
299
+ napi_status status = napi_create_external_buffer(
300
+ env, dataCapacity(), dataPtr(), BufferFinalize, ref_, &result);
301
+ if (status != napi_ok || !result) {
302
+ MappingRefRelease(ref_);
303
+ return env.Null();
304
+ }
305
+ if (napi_create_reference(env, result, 1, &bufRef_) != napi_ok) {
306
+ bufRef_ = nullptr; // cache is an optimization, running without it is fine
307
+ }
308
+ return Napi::Value(env, result);
309
+ }
310
+
311
+ Napi::Value SharedMemory::GetCapacity(const Napi::CallbackInfo& info) {
312
+ return Napi::Number::New(info.Env(), (double)dataCapacity());
313
+ }
314
+
315
+ Napi::Value SharedMemory::PublishFrame(const Napi::CallbackInfo& info) {
316
+ Napi::Env env = info.Env();
317
+ if (!base_) return env.Undefined();
318
+
319
+ uint32_t frameBytes = (uint32_t)ToInt64(info[0]);
320
+ if (frameBytes > dataCapacity()) return env.Undefined();
321
+
322
+ SharedHeader* hdr = headerPtr();
323
+ InterlockedIncrement(&hdr->seq); // Start write
324
+ MemoryBarrier();
325
+
326
+ hdr->frame_size = frameBytes;
327
+ AtomicIncrement64((volatile LONG64*)&hdr->frame_index);
328
+
329
+ MemoryBarrier();
330
+ InterlockedIncrement(&hdr->seq); // End write
331
+
332
+ if (hEvent_) SetEvent(hEvent_);
333
+ return Napi::Boolean::New(env, true);
334
+ }
335
+
336
+ // payload copy must sit INSIDE the seqlock section: with plain publishFrame
337
+ // the data lands in shm outside it, and a reader deep-copying the frame
338
+ // mid-rewrite gets a torn frame
339
+ Napi::Value SharedMemory::PublishRaw(const Napi::CallbackInfo& info) {
340
+ Napi::Env env = info.Env();
341
+ if (!ref_ || !base_) return env.Undefined();
342
+
343
+ size_t capacity = dataCapacity();
344
+ if (capacity == 0) return env.Undefined();
345
+
346
+ napi_value src = info[0];
347
+ bool isTyped = false;
348
+ if (src == nullptr || napi_is_typedarray(env, src, &isTyped) != napi_ok || !isTyped)
349
+ return env.Undefined();
350
+ size_t srcLen = 0; void* srcData = nullptr;
351
+ if (napi_get_typedarray_info(env, src, nullptr, &srcLen, &srcData, nullptr, nullptr) != napi_ok)
352
+ return env.Undefined();
353
+ uint8_t* srcPtr = static_cast<uint8_t*>(srcData); // view start, byte_offset already applied
354
+
355
+ uint64_t want = (uint64_t)ToInt64(info[1]);
356
+ size_t frameBytes = want == 0 ? srcLen : (size_t)want;
357
+ if (frameBytes > srcLen) frameBytes = srcLen;
358
+ if (frameBytes > capacity) frameBytes = capacity;
359
+
360
+ SharedHeader* hdr = headerPtr();
361
+ InterlockedIncrement(&hdr->seq); // Start write
362
+ MemoryBarrier();
363
+
364
+ memcpy(dataPtr(), srcPtr, frameBytes);
365
+ hdr->frame_size = (uint32_t)frameBytes;
366
+ AtomicIncrement64((volatile LONG64*)&hdr->frame_index);
367
+
368
+ MemoryBarrier();
369
+ InterlockedIncrement(&hdr->seq); // End write
370
+
371
+ if (hEvent_) SetEvent(hEvent_);
372
+ return Napi::Boolean::New(env, true);
373
+ }
374
+
375
+ Napi::Value SharedMemory::ReadFrame(const Napi::CallbackInfo& info) {
376
+ Napi::Env env = info.Env();
377
+
378
+ if (!base_) {
379
+ Napi::Error::New(env, "Not connected").ThrowAsJavaScriptException();
380
+ return env.Undefined();
381
+ }
382
+
383
+ DWORD timeout = INFINITE;
384
+ if (info.Length() > 0 && info[0].IsNumber()) {
385
+ timeout = (DWORD)info[0].As<Napi::Number>().Int64Value();
386
+ }
387
+
388
+ // Wait for event (sleeping wait)
389
+ if (hEvent_) {
390
+ if (WaitForSingleObject(hEvent_, timeout) == WAIT_TIMEOUT) {
391
+ return env.Null();
392
+ }
393
+ }
394
+
395
+ SharedHeader* hdr = headerPtr();
396
+ uint32_t startSeq, endSeq;
397
+ uint32_t frameBytes;
398
+ const int MAX_RETRIES = 10;
399
+ int retries = 0;
400
+
401
+ // Seqlock read loop with spin-wait
402
+ int spinCount = 0;
403
+ const int SPIN_LIMIT = 2000; // Cycles to spin before yielding
404
+
405
+ do {
406
+ if (retries++ > MAX_RETRIES) {
407
+ Napi::Error::New(env, "ReadFrame contention").ThrowAsJavaScriptException();
408
+ return env.Undefined();
409
+ }
410
+
411
+ startSeq = hdr->seq;
412
+
413
+ // if seq number is odd, then write is in progress, waiting...
414
+ if (startSeq & 1) {
415
+ if (spinCount < SPIN_LIMIT) {
416
+ spinCount++;
417
+ _mm_pause();
418
+ continue;
419
+ } else {
420
+ Sleep(0); // if waited too long
421
+ spinCount = 0;
422
+ continue;
423
+ }
424
+ }
425
+
426
+ MemoryBarrier();
427
+ frameBytes = hdr->frame_size;
428
+ if (frameBytes > dataCapacity()) frameBytes = 0;
429
+
430
+ // Copying data (deep copy)
431
+ napi_value outBuf = nullptr;
432
+ napi_status status;
433
+ if (frameBytes > 0) {
434
+ status = napi_create_buffer_copy(env, frameBytes, dataPtr(), nullptr, &outBuf);
435
+ } else {
436
+ status = napi_create_buffer(env, 0, nullptr, &outBuf);
437
+ }
438
+ if (status != napi_ok || !outBuf) {
439
+ return env.Null();
440
+ }
441
+
442
+ MemoryBarrier();
443
+ endSeq = hdr->seq;
444
+
445
+ if (startSeq == endSeq) {
446
+ // Read successfully
447
+ return Napi::Value(env, outBuf);
448
+ }
449
+
450
+ // if seq was changed when reading, then image tearing happened, trying again
451
+ // Reset spin count to try eagerly again
452
+ spinCount = 0;
453
+
454
+ } while (true);
455
+ }
456
+
457
+ // zero-alloc readFrame for consumers that keep one reusable buffer: readFrame
458
+ // allocates a 2MB Buffer per call and per retry. Returns the byte count,
459
+ // null on timeout, throws the same errors as readFrame.
460
+ Napi::Value SharedMemory::ReadFrameInto(const Napi::CallbackInfo& info) {
461
+ Napi::Env env = info.Env();
462
+
463
+ if (!base_) {
464
+ Napi::Error::New(env, "Not connected").ThrowAsJavaScriptException();
465
+ return env.Undefined();
466
+ }
467
+
468
+ napi_value dst = info[0];
469
+ bool isTyped = false;
470
+ if (dst == nullptr || napi_is_typedarray(env, dst, &isTyped) != napi_ok || !isTyped) {
471
+ Napi::TypeError::New(env, "Args: dstTypedArray, [timeout]").ThrowAsJavaScriptException();
472
+ return env.Undefined();
473
+ }
474
+ size_t dstLen = 0; void* dstData = nullptr;
475
+ if (napi_get_typedarray_info(env, dst, nullptr, &dstLen, &dstData, nullptr, nullptr) != napi_ok) {
476
+ return env.Null();
477
+ }
478
+ uint8_t* dstPtr = static_cast<uint8_t*>(dstData); // view start, byte_offset already applied
479
+
480
+ DWORD timeout = INFINITE;
481
+ if (info.Length() > 1 && info[1].IsNumber()) {
482
+ timeout = (DWORD)info[1].As<Napi::Number>().Int64Value();
483
+ }
484
+
485
+ if (hEvent_) {
486
+ if (WaitForSingleObject(hEvent_, timeout) == WAIT_TIMEOUT) {
487
+ return env.Null();
488
+ }
489
+ }
490
+
491
+ SharedHeader* hdr = headerPtr();
492
+ uint32_t startSeq, endSeq;
493
+ size_t frameBytes;
494
+ const int MAX_RETRIES = 10;
495
+ int retries = 0;
496
+ int spinCount = 0;
497
+ const int SPIN_LIMIT = 2000;
498
+
499
+ do {
500
+ if (retries++ > MAX_RETRIES) {
501
+ Napi::Error::New(env, "ReadFrame contention").ThrowAsJavaScriptException();
502
+ return env.Undefined();
503
+ }
504
+
505
+ startSeq = hdr->seq;
506
+ if (startSeq & 1) {
507
+ if (spinCount < SPIN_LIMIT) { spinCount++; _mm_pause(); continue; }
508
+ else { Sleep(0); spinCount = 0; continue; }
509
+ }
510
+
511
+ MemoryBarrier();
512
+ frameBytes = hdr->frame_size;
513
+ if (frameBytes > dataCapacity()) frameBytes = 0;
514
+ if (frameBytes > dstLen) frameBytes = dstLen;
515
+
516
+ if (frameBytes > 0) memcpy(dstPtr, dataPtr(), frameBytes);
517
+
518
+ MemoryBarrier();
519
+ endSeq = hdr->seq;
520
+
521
+ if (startSeq == endSeq) {
522
+ return Napi::Number::New(env, (double)frameBytes);
523
+ }
524
+
525
+ spinCount = 0;
526
+
527
+ } while (true);
528
+ }
529
+
530
+ Napi::Value SharedMemory::Close(const Napi::CallbackInfo& info) {
531
+ Napi::Env env = info.Env();
532
+ RetireMapping();
533
+ if (hEvent_) { CloseHandle(hEvent_); hEvent_ = nullptr; }
534
+ return Napi::Boolean::New(env, true);
535
+ }
536
+
537
+ Napi::Value SharedMemory::GetMetadata(const Napi::CallbackInfo& info) {
538
+ Napi::Env env = info.Env();
539
+ if (!base_) return env.Undefined();
540
+
541
+ SharedHeader* hdr = headerPtr();
542
+ Napi::Object ret = Napi::Object::New(env);
543
+
544
+ ret.Set("width", hdr->width);
545
+ ret.Set("height", hdr->height);
546
+ ret.Set("channels", hdr->channels);
547
+ ret.Set("frame_index", Napi::Number::New(env, (double)hdr->frame_index)); // JS Number (lossy > 2^53)
548
+
549
+ return ret;
550
+ }
551
+
552
+ Napi::Object InitModule(Napi::Env env, Napi::Object exports) {
553
+ return SharedMemory::Init(env, exports);
554
+ }
555
+
556
+ NODE_API_MODULE(NODE_GYP_MODULE_NAME, InitModule)
package/test/bench.js ADDED
@@ -0,0 +1,103 @@
1
+ // Micro benchmark for the addon. Usage: node test/bench.js [e2e]
2
+ // Paths: publishRaw (sealed payload copy), publishFrame (header only),
3
+ // the legacy JS-copy combo, getFrameBuffer (cached external Buffer),
4
+ // readFrame / readFrameInto, setFormat, getMetadata.
5
+ // "e2e": writer + reader in separate processes, max fps.
6
+ 'use strict';
7
+ const { fork } = require('child_process');
8
+
9
+ const M = require('..');
10
+
11
+ const W = 960, H = 540, CH = 4, FRAME = W * H * CH; // a real-size 2 MB frame
12
+ const NAME = 'BenchSHM';
13
+
14
+ function bench(label, iters, fn, setup) {
15
+ for (let i = 0; i < Math.max(50, iters / 20) | 0; i++) { if (setup) setup(); fn(i); } // warmup
16
+ const t0 = process.hrtime.bigint();
17
+ for (let i = 0; i < iters; i++) fn(i);
18
+ const ns = Number(process.hrtime.bigint() - t0) / iters;
19
+ const us = ns / 1000;
20
+ const mbps = FRAME / (ns / 1000) / 1024 / 1024; // only meaningful for whole-frame ops
21
+ console.log(`${label.padEnd(46)} ${us.toFixed(2).padStart(9)} us/op${/publish|read|copy/.test(label) ? ' ' + mbps.toFixed(0).padStart(5) + ' MB/s' : ''}`);
22
+ return us;
23
+ }
24
+
25
+ // ---------- e2e writer (forked; skips the solo part) ----------
26
+ if (process.env.ROLE === 'e2e-writer') {
27
+ const smw = new M.SharedMemory();
28
+ smw.create(NAME, FRAME + 65536, W, H, CH);
29
+ const buf = Buffer.alloc(FRAME, 0xCD);
30
+ const cadence = +(process.env.E2E_CADENCE || 0); // 0 = no pauses, 60 = a realistic 16ms gap
31
+ const period = cadence > 0 ? 1000 / cadence : 0;
32
+ const t0 = Date.now(); let n = 0; let next = t0;
33
+ while (Date.now() - t0 < 10000) {
34
+ smw.publishRaw(buf, FRAME); n++;
35
+ if (period) { next += period; const d = next - Date.now(); if (d > 0) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, d); }
36
+ }
37
+ if (process.send) process.send({ e2eWriterFps: +(n / 10).toFixed(0) });
38
+ process.exit(0);
39
+ }
40
+
41
+ // ---------- solo mode ----------
42
+ if (process.argv[2] !== 'e2e') {
43
+ const sm = new M.SharedMemory();
44
+ sm.create(NAME, FRAME + 65536, W, H, CH);
45
+ const local = Buffer.alloc(FRAME, 0xAB);
46
+ const fb = sm.getFrameBuffer();
47
+
48
+ console.log(`frame ${W}x${H}x${CH} = ${(FRAME / 1048576).toFixed(1)} MB, node ${process.version}\n`);
49
+
50
+ bench('publishRaw (2MB memcpy inside seqlock)', 2000, () => sm.publishRaw(local, FRAME));
51
+ bench('publishFrame (header + event only)', 50000, () => sm.publishFrame(FRAME));
52
+ bench('legacy: fb.set (JS copy) + publishFrame', 2000, () => { fb.set(local); sm.publishFrame(FRAME); });
53
+ bench('getFrameBuffer (cached external Buffer)', 100000, () => sm.getFrameBuffer());
54
+ bench('getCapacity', 100000, () => sm.getCapacity());
55
+ bench('setFormat', 50000, () => sm.setFormat(W, H, CH));
56
+ bench('getMetadata', 50000, () => sm.getMetadata());
57
+ bench('readFrame (2MB deep copy, event + check)', 2000, () => { sm.publishFrame(FRAME); sm.readFrame(100); });
58
+ {
59
+ const dst = Buffer.alloc(FRAME);
60
+ bench('readFrameInto (reused buffer)', 2000, () => { sm.publishFrame(FRAME); sm.readFrameInto(dst, 100); });
61
+ }
62
+
63
+ // GC pressure of getFrameBuffer: 200k calls, time + heap delta, no GC in the loop
64
+ if (global.gc) {
65
+ global.gc();
66
+ const before = process.memoryUsage().heapUsed;
67
+ const t0 = process.hrtime.bigint();
68
+ for (let i = 0; i < 200000; i++) sm.getFrameBuffer();
69
+ const dt = Number(process.hrtime.bigint() - t0) / 1e6;
70
+ const churn = (process.memoryUsage().heapUsed - before) / 1048576;
71
+ console.log(`getFrameBuffer x200k: ${dt.toFixed(0)} ms, heap delta ${churn.toFixed(1)} MB (no GC in the loop)`);
72
+ }
73
+ sm.close();
74
+ console.log('\nSOLO OK');
75
+ process.exit(0);
76
+ }
77
+
78
+ // ---------- e2e: forked writer vs a reader here ----------
79
+ async function e2eRun(cadence, label) {
80
+ let writerFps = '?';
81
+ const w = fork(__filename, [], { env: { ...process.env, ROLE: 'e2e-writer', E2E_CADENCE: String(cadence) }, stdio: ['ignore', 'inherit', 'inherit', 'ipc'] });
82
+ w.on('message', m => { if (m && m.e2eWriterFps) writerFps = m.e2eWriterFps; });
83
+ const smr = new M.SharedMemory();
84
+ smr.create(NAME, FRAME + 65536, W, H, CH);
85
+ const t0 = Date.now(); let frames = 0, contended = 0;
86
+ while (Date.now() - t0 < 10000) {
87
+ try {
88
+ const f = smr.readFrame(100);
89
+ if (f) frames++;
90
+ } catch (e) { if (/conten/i.test(String(e))) contended++; }
91
+ }
92
+ await new Promise(r => { w.on('exit', r); setTimeout(() => { w.kill(); setTimeout(r, 500); }, 2000); });
93
+ console.log(`e2e ${label}: writer ~${writerFps} fps, reader ${Math.round(frames / 10)} fps (${contended} contention refusals)`);
94
+ smr.close();
95
+ }
96
+
97
+ if (process.argv[2] === 'e2e') {
98
+ (async () => {
99
+ await e2eRun(0, 'writer at full speed (saturation)');
100
+ await e2eRun(60, 'writer at 60 Hz (16ms gaps)');
101
+ process.exit(0);
102
+ })();
103
+ }