@rodit/hola-mfsk 0.0.0-stage → 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.
package/lib/mfsk.js ADDED
@@ -0,0 +1,596 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // src/mfsk.ts
20
+ var mfsk_exports = {};
21
+ __export(mfsk_exports, {
22
+ FSK_BAUD: () => FSK_BAUD,
23
+ FSK_BITS_PER_SYMBOL: () => FSK_BITS_PER_SYMBOL,
24
+ FSK_SAMPLE_RATE: () => FSK_SAMPLE_RATE,
25
+ FSK_TONES_HZ: () => FSK_TONES_HZ,
26
+ decodePcmToFramedText: () => decodePcmToFramedText,
27
+ decodePcmToHola: () => decodePcmToHola,
28
+ deframeFramedText: () => deframeFramedText,
29
+ deframeHolaBytes: () => deframeHolaBytes,
30
+ encodeHolaToPcm: () => encodeHolaToPcm,
31
+ estimateFskDurationMs: () => estimateFskDurationMs,
32
+ estimatePlaceholderChallenge: () => estimatePlaceholderChallenge,
33
+ estimatePlaceholderHola: () => estimatePlaceholderHola,
34
+ findEofOffset: () => findEofOffset,
35
+ findSofOffset: () => findSofOffset,
36
+ frameHolaBytes: () => frameHolaBytes,
37
+ isMfskBandBusy: () => isMfskBandBusy,
38
+ markerSampleCount: () => markerSampleCount,
39
+ maxDemodSamplesAfterPayload: () => maxDemodSamplesAfterPayload,
40
+ payloadStartAfterSof: () => payloadStartAfterSof,
41
+ scoreMfskBandBusy: () => scoreMfskBandBusy,
42
+ sofConfirmSamples: () => sofConfirmSamples
43
+ });
44
+ module.exports = __toCommonJS(mfsk_exports);
45
+
46
+ // src/hola-extract.ts
47
+ function extractHolaFromDecodedText(text) {
48
+ const source = String(text || "");
49
+ const match = source.match(
50
+ /hola\/[a-z0-9.:\-+=]+(?:\/[a-z0-9.:\-+=]+){5,}/i
51
+ );
52
+ return match ? match[0] : null;
53
+ }
54
+
55
+ // src/mfsk.ts
56
+ var FSK_SAMPLE_RATE = 16e3;
57
+ var FSK_TONES_HZ = [1800, 2100, 2400, 2700];
58
+ var FSK_BAUD = 100;
59
+ var FSK_BITS_PER_SYMBOL = 2;
60
+ var WARMUP_MS = 350;
61
+ var WARMUP_TONE_HZ = FSK_TONES_HZ[0];
62
+ var MARKER_MS = 120;
63
+ var SOF_TONE_PAIR = [0, 3];
64
+ var EOF_TONE_PAIR = [1, 2];
65
+ var PARTIAL_WEIGHTS = [1, 0.5, 0.25];
66
+ var MAX_PAYLOAD_BYTES = 65535;
67
+ function warmupSampleCount(sampleRate = FSK_SAMPLE_RATE) {
68
+ const sps = samplesPerSymbol(sampleRate);
69
+ return Math.max(sps, Math.round(WARMUP_MS / 1e3 * sampleRate / sps) * sps);
70
+ }
71
+ function markerSymbolCount(sampleRate = FSK_SAMPLE_RATE) {
72
+ const sps = samplesPerSymbol(sampleRate);
73
+ return Math.max(4, Math.round(MARKER_MS / 1e3 * sampleRate / sps));
74
+ }
75
+ function markerSampleCount(sampleRate = FSK_SAMPLE_RATE) {
76
+ return markerSymbolCount(sampleRate) * samplesPerSymbol(sampleRate);
77
+ }
78
+ function sofConfirmSamples(sampleRate = FSK_SAMPLE_RATE) {
79
+ return markerSampleCount(sampleRate) + Math.round(sampleRate * 0.75);
80
+ }
81
+ function markerTonePattern(pair, sampleRate) {
82
+ const n = markerSymbolCount(sampleRate);
83
+ const out = [];
84
+ for (let i = 0; i < n; i += 1) out.push(pair[i % 2]);
85
+ return out;
86
+ }
87
+ function samplesPerSymbol(sampleRate = FSK_SAMPLE_RATE) {
88
+ return Math.max(1, Math.round(sampleRate / FSK_BAUD));
89
+ }
90
+ function crc16Ccitt(bytes) {
91
+ let crc = 65535;
92
+ for (let i = 0; i < bytes.length; i += 1) {
93
+ crc ^= (bytes[i] & 255) << 8;
94
+ for (let bit = 0; bit < 8; bit += 1) {
95
+ crc = (crc & 32768) !== 0 ? (crc << 1 ^ 4129) & 65535 : crc << 1 & 65535;
96
+ }
97
+ }
98
+ return crc & 65535;
99
+ }
100
+ function cobsEncode(src) {
101
+ const out = new Uint8Array(src.length + 1 + Math.floor(src.length / 254));
102
+ let write = 1;
103
+ let codeIndex = 0;
104
+ let code = 1;
105
+ for (let i = 0; i < src.length; i += 1) {
106
+ if (src[i] === 0) {
107
+ out[codeIndex] = code;
108
+ codeIndex = write;
109
+ write += 1;
110
+ code = 1;
111
+ } else {
112
+ out[write] = src[i];
113
+ write += 1;
114
+ code += 1;
115
+ if (code === 255) {
116
+ out[codeIndex] = code;
117
+ codeIndex = write;
118
+ write += 1;
119
+ code = 1;
120
+ }
121
+ }
122
+ }
123
+ out[codeIndex] = code;
124
+ return out.subarray(0, write);
125
+ }
126
+ function cobsDecode(src) {
127
+ if (src.length === 0) return null;
128
+ for (let i = 0; i < src.length; i += 1) {
129
+ if (src[i] === 0) return null;
130
+ }
131
+ const out = new Uint8Array(src.length);
132
+ let write = 0;
133
+ let read = 0;
134
+ while (read < src.length) {
135
+ const code = src[read];
136
+ read += 1;
137
+ if (code === 0 || read + (code - 1) > src.length) return null;
138
+ for (let i = 1; i < code; i += 1) {
139
+ out[write] = src[read];
140
+ write += 1;
141
+ read += 1;
142
+ }
143
+ if (code !== 255 && read < src.length) {
144
+ out[write] = 0;
145
+ write += 1;
146
+ }
147
+ }
148
+ return out.subarray(0, write);
149
+ }
150
+ function tryDecodeCobsFrame(cobsBody) {
151
+ const decoded = cobsDecode(cobsBody);
152
+ if (!decoded || decoded.length < 3) return null;
153
+ const payload = decoded.subarray(0, decoded.length - 2);
154
+ const expect = (decoded[decoded.length - 2] & 255) << 8 | decoded[decoded.length - 1] & 255;
155
+ if (crc16Ccitt(payload) !== expect) return null;
156
+ return new TextDecoder("utf-8").decode(payload);
157
+ }
158
+ function bytesToBits(bytes) {
159
+ const bits = [];
160
+ for (let i = 0; i < bytes.length; i += 1) {
161
+ const b = bytes[i];
162
+ for (let bit = 7; bit >= 0; bit -= 1) {
163
+ bits.push(b >> bit & 1);
164
+ }
165
+ }
166
+ return bits;
167
+ }
168
+ function bitsToBytes(bits) {
169
+ const n = Math.floor(bits.length / 8);
170
+ const out = new Uint8Array(n);
171
+ for (let i = 0; i < n; i += 1) {
172
+ let b = 0;
173
+ for (let bit = 0; bit < 8; bit += 1) {
174
+ b = b << 1 | bits[i * 8 + bit] & 1;
175
+ }
176
+ out[i] = b;
177
+ }
178
+ return out;
179
+ }
180
+ function bitsToSymbols(bits) {
181
+ const symbols = [];
182
+ for (let i = 0; i < bits.length; i += FSK_BITS_PER_SYMBOL) {
183
+ const hi = bits[i] & 1;
184
+ const lo = i + 1 < bits.length ? bits[i + 1] & 1 : 0;
185
+ symbols.push(hi << 1 | lo);
186
+ }
187
+ return symbols;
188
+ }
189
+ function symbolsToBits(symbols) {
190
+ const bits = [];
191
+ for (let i = 0; i < symbols.length; i += 1) {
192
+ const s = symbols[i] & 3;
193
+ bits.push(s >> 1 & 1);
194
+ bits.push(s & 1);
195
+ }
196
+ return bits;
197
+ }
198
+ function frameHolaBytes(text) {
199
+ const payload = new TextEncoder().encode(String(text || ""));
200
+ if (payload.length === 0) {
201
+ throw new Error("HOLA payload empty");
202
+ }
203
+ if (payload.length > MAX_PAYLOAD_BYTES) {
204
+ throw new Error("HOLA payload too large for FSK frame");
205
+ }
206
+ const crc = crc16Ccitt(payload);
207
+ const body = new Uint8Array(payload.length + 2);
208
+ body.set(payload, 0);
209
+ body[payload.length] = crc >> 8 & 255;
210
+ body[payload.length + 1] = crc & 255;
211
+ const stuffed = cobsEncode(body);
212
+ const out = new Uint8Array(stuffed.length + 1);
213
+ out.set(stuffed, 0);
214
+ out[stuffed.length] = 0;
215
+ return out;
216
+ }
217
+ function deframeFramedText(bits) {
218
+ if (bits.length < 5 * 8) return null;
219
+ for (let bitOff = 0; bitOff < 8; bitOff += 1) {
220
+ const bytes = bitsToBytes(bitOff === 0 ? bits : bits.slice(bitOff));
221
+ for (let end = 0; end < bytes.length; end += 1) {
222
+ if (bytes[end] !== 0) continue;
223
+ for (let start = 0; start < end; start += 1) {
224
+ if (end - start < 4) continue;
225
+ const text = tryDecodeCobsFrame(bytes.subarray(start, end));
226
+ if (text != null) return text;
227
+ }
228
+ }
229
+ }
230
+ return null;
231
+ }
232
+ function deframeHolaBytes(bits) {
233
+ const text = deframeFramedText(bits);
234
+ if (!text) return null;
235
+ const hola = extractHolaFromDecodedText(text);
236
+ if (hola) return hola;
237
+ if (/^hola\//i.test(text.trim())) return text.trim();
238
+ return null;
239
+ }
240
+ function goertzelPower(frame, sampleRate, targetHz) {
241
+ const n = frame.length;
242
+ if (n < 8) return 0;
243
+ const nyquist = sampleRate / 2;
244
+ if (targetHz <= 0 || targetHz >= nyquist - 50) return 0;
245
+ const k = Math.round(n * targetHz / sampleRate);
246
+ if (k <= 0 || k >= n / 2) return 0;
247
+ const w = 2 * Math.PI * k / n;
248
+ const cosine = Math.cos(w);
249
+ const coeff = 2 * cosine;
250
+ let q0 = 0;
251
+ let q1 = 0;
252
+ let q2 = 0;
253
+ for (let i = 0; i < n; i += 1) {
254
+ q0 = coeff * q1 - q2 + frame[i];
255
+ q2 = q1;
256
+ q1 = q0;
257
+ }
258
+ const real = q1 - q2 * cosine;
259
+ const imag = q2 * Math.sin(w);
260
+ return real * real + imag * imag;
261
+ }
262
+ function toneScore(frame, sampleRate, baseHz) {
263
+ const fundamental = goertzelPower(frame, sampleRate, baseHz);
264
+ const second = goertzelPower(frame, sampleRate, baseHz * 2);
265
+ return fundamental + 0.35 * second;
266
+ }
267
+ function bandEnergy(frame, sampleRate) {
268
+ let sum = 0;
269
+ for (let t = 0; t < FSK_TONES_HZ.length; t += 1) {
270
+ sum += toneScore(frame, sampleRate, FSK_TONES_HZ[t]);
271
+ }
272
+ return sum;
273
+ }
274
+ var PHY_FRAME_MS = 20;
275
+ var PHY_MIN_ENERGY = 20;
276
+ var PHY_LOUD_ENERGY = 200;
277
+ var PHY_BUSY_RATIO = 6;
278
+ function scoreMfskBandBusy(pcm, sampleRate = FSK_SAMPLE_RATE) {
279
+ const samples = toFloat32(pcm);
280
+ const frameLen = Math.max(64, Math.round(sampleRate * PHY_FRAME_MS / 1e3));
281
+ const hop = Math.max(32, Math.floor(frameLen / 2));
282
+ if (samples.length < frameLen * 3) {
283
+ return { busy: false, recent: 0, noise: 0, ratio: 0 };
284
+ }
285
+ const energies = [];
286
+ for (let start = 0; start + frameLen <= samples.length; start += hop) {
287
+ energies.push(bandEnergy(samples.subarray(start, start + frameLen), sampleRate));
288
+ }
289
+ const sorted = [...energies].sort((a, b) => a - b);
290
+ const noise = sorted[Math.floor(sorted.length * 0.2)] ?? 0;
291
+ const recentCount = Math.min(4, energies.length);
292
+ let recent = 0;
293
+ for (let i = energies.length - recentCount; i < energies.length; i += 1) {
294
+ recent = Math.max(recent, energies[i]);
295
+ }
296
+ const ratio = noise > 1e-9 ? recent / noise : recent >= PHY_MIN_ENERGY ? Infinity : 0;
297
+ const busy = recent >= PHY_LOUD_ENERGY || recent >= PHY_MIN_ENERGY && ratio >= PHY_BUSY_RATIO;
298
+ return { busy, recent, noise, ratio };
299
+ }
300
+ function isMfskBandBusy(pcm, sampleRate = FSK_SAMPLE_RATE) {
301
+ return scoreMfskBandBusy(pcm, sampleRate).busy;
302
+ }
303
+ function toFloat32(pcm) {
304
+ if (pcm instanceof Float32Array) return pcm;
305
+ const out = new Float32Array(pcm.length);
306
+ for (let i = 0; i < pcm.length; i += 1) out[i] = pcm[i] / 32768;
307
+ return out;
308
+ }
309
+ function findToneOnset(samples, sampleRate) {
310
+ const sps = samplesPerSymbol(sampleRate);
311
+ const window = Math.max(16, Math.floor(sps * 0.75));
312
+ const hop = Math.max(8, Math.floor(window / 2));
313
+ const energies = [];
314
+ for (let start = 0; start + window <= samples.length; start += hop) {
315
+ const frame = samples.subarray(start, start + window);
316
+ energies.push(bandEnergy(frame, sampleRate));
317
+ }
318
+ if (energies.length < 4) return 0;
319
+ const sorted = [...energies].sort((a, b) => a - b);
320
+ const noise = sorted[Math.floor(sorted.length * 0.15)] ?? 0;
321
+ const peak = sorted[Math.floor(sorted.length * 0.9)] ?? 0;
322
+ const threshold = noise + (peak - noise) * 0.25;
323
+ for (let i = 0; i < energies.length; i += 1) {
324
+ if (energies[i] >= threshold) {
325
+ return Math.max(0, i * hop - Math.floor(sps / 4));
326
+ }
327
+ }
328
+ return 0;
329
+ }
330
+ function harmonicSample(phase, baseHz, sampleRate) {
331
+ const nyquist = sampleRate / 2 - 200;
332
+ let value = 0;
333
+ let weightSum = 0;
334
+ for (let p = 0; p < PARTIAL_WEIGHTS.length; p += 1) {
335
+ const freq = baseHz * (p + 1);
336
+ if (freq >= nyquist) break;
337
+ const w = PARTIAL_WEIGHTS[p];
338
+ value += Math.sin(phase * (p + 1)) * w;
339
+ weightSum += w;
340
+ }
341
+ return weightSum > 0 ? value / weightSum : 0;
342
+ }
343
+ function synthesizeWarmup(options) {
344
+ const sampleRate = options?.sampleRate ?? FSK_SAMPLE_RATE;
345
+ const total = warmupSampleCount(sampleRate);
346
+ const samples = new Int16Array(total);
347
+ const twoPiF = 2 * Math.PI * WARMUP_TONE_HZ / sampleRate;
348
+ const fade = Math.min(Math.floor(sampleRate * 0.01), Math.floor(total / 4));
349
+ let phase = 0;
350
+ for (let i = 0; i < total; i += 1) {
351
+ let env = 1;
352
+ if (i < fade) env = i / fade;
353
+ const value = harmonicSample(phase, WARMUP_TONE_HZ, sampleRate) * 0.55 * env;
354
+ samples[i] = Math.max(-32767, Math.min(32767, Math.round(value * 32767)));
355
+ phase += twoPiF;
356
+ }
357
+ return { samples, phase: phase % (2 * Math.PI) };
358
+ }
359
+ function synthesizeToneSymbols(toneIndices, options) {
360
+ const sampleRate = options?.sampleRate ?? FSK_SAMPLE_RATE;
361
+ const sps = samplesPerSymbol(sampleRate);
362
+ const total = toneIndices.length * sps;
363
+ const samples = new Int16Array(total);
364
+ let phase = options?.startPhase ?? 0;
365
+ const envSamples = Math.min(12, Math.floor(sps / 5));
366
+ for (let s = 0; s < toneIndices.length; s += 1) {
367
+ const baseHz = FSK_TONES_HZ[toneIndices[s] & 3];
368
+ const twoPiF = 2 * Math.PI * baseHz / sampleRate;
369
+ const offset = s * sps;
370
+ for (let i = 0; i < sps; i += 1) {
371
+ let env = 1;
372
+ if (i < envSamples) env = i / envSamples;
373
+ else if (i >= sps - envSamples) env = Math.max(0, (sps - i) / envSamples);
374
+ const value = harmonicSample(phase, baseHz, sampleRate) * 0.55 * env;
375
+ samples[offset + i] = Math.max(
376
+ -32767,
377
+ Math.min(32767, Math.round(value * 32767))
378
+ );
379
+ phase += twoPiF;
380
+ }
381
+ phase = phase % (2 * Math.PI);
382
+ }
383
+ return { samples, phase };
384
+ }
385
+ function symbolCore(frame, sps) {
386
+ const pad = Math.floor(sps * 0.15);
387
+ return pad * 2 < frame.length ? frame.subarray(pad, frame.length - pad) : frame;
388
+ }
389
+ function rankTones(core, sampleRate) {
390
+ let bestIdx = 0;
391
+ let bestPower = -Infinity;
392
+ let secondPower = -Infinity;
393
+ for (let t = 0; t < FSK_TONES_HZ.length; t += 1) {
394
+ const power = toneScore(core, sampleRate, FSK_TONES_HZ[t]);
395
+ if (power > bestPower) {
396
+ secondPower = bestPower;
397
+ bestPower = power;
398
+ bestIdx = t;
399
+ } else if (power > secondPower) {
400
+ secondPower = power;
401
+ }
402
+ }
403
+ return { bestIdx, bestPower, secondPower };
404
+ }
405
+ function scoreMarkerAt(samples, sampleRate, start, pattern) {
406
+ const sps = samplesPerSymbol(sampleRate);
407
+ if (start < 0 || start + pattern.length * sps > samples.length) return -Infinity;
408
+ let score = 0;
409
+ let matches = 0;
410
+ for (let s = 0; s < pattern.length; s += 1) {
411
+ const frame = samples.subarray(start + s * sps, start + (s + 1) * sps);
412
+ const core = symbolCore(frame, sps);
413
+ const expectedIdx = pattern[s] & 3;
414
+ const { bestIdx, bestPower, secondPower } = rankTones(core, sampleRate);
415
+ const expected = bestIdx === expectedIdx ? bestPower : toneScore(core, sampleRate, FSK_TONES_HZ[expectedIdx]);
416
+ const bestOther = bestIdx === expectedIdx ? secondPower : bestPower;
417
+ const margin = expected - Math.max(0, bestOther);
418
+ score += margin;
419
+ if (margin > 0) matches += 1;
420
+ }
421
+ if (matches < Math.ceil(pattern.length * 0.7)) return -Infinity;
422
+ return score;
423
+ }
424
+ function findMarkerOffset(pcm, sampleRate, pattern, fromOffset = 0, toOffset) {
425
+ const samples = toFloat32(pcm);
426
+ const sps = samplesPerSymbol(sampleRate);
427
+ const need = pattern.length * sps;
428
+ const end = Math.min(
429
+ samples.length,
430
+ toOffset != null ? Math.max(fromOffset, toOffset) : samples.length
431
+ );
432
+ if (end - fromOffset < need) return null;
433
+ const hop = Math.max(1, Math.floor(sps / 4));
434
+ let bestStart = -1;
435
+ let bestScore = 0;
436
+ const minScore = pattern.length * 5e-4;
437
+ for (let start = Math.max(0, fromOffset); start + need <= end; start += hop) {
438
+ const score = scoreMarkerAt(samples, sampleRate, start, pattern);
439
+ if (score > bestScore) {
440
+ bestScore = score;
441
+ bestStart = start;
442
+ }
443
+ }
444
+ if (bestStart < 0 || bestScore <= minScore) return null;
445
+ return bestStart;
446
+ }
447
+ function findSofOffset(pcm, sampleRate = FSK_SAMPLE_RATE, fromOffset = 0, toOffset) {
448
+ return findMarkerOffset(
449
+ pcm,
450
+ sampleRate,
451
+ markerTonePattern(SOF_TONE_PAIR, sampleRate),
452
+ fromOffset,
453
+ toOffset
454
+ );
455
+ }
456
+ function findEofOffset(pcm, sampleRate = FSK_SAMPLE_RATE, fromOffset = 0, toOffset) {
457
+ return findMarkerOffset(
458
+ pcm,
459
+ sampleRate,
460
+ markerTonePattern(EOF_TONE_PAIR, sampleRate),
461
+ fromOffset,
462
+ toOffset
463
+ );
464
+ }
465
+ function payloadStartAfterSof(sofOffset, sampleRate = FSK_SAMPLE_RATE) {
466
+ return sofOffset + markerSampleCount(sampleRate);
467
+ }
468
+ function demodulateAligned(samples, sampleRate, startOffset) {
469
+ const sps = samplesPerSymbol(sampleRate);
470
+ const symbols = [];
471
+ let score = 0;
472
+ for (let start = startOffset; start + sps <= samples.length; start += sps) {
473
+ const frame = samples.subarray(start, start + sps);
474
+ const { bestIdx, bestPower, secondPower } = rankTones(
475
+ symbolCore(frame, sps),
476
+ sampleRate
477
+ );
478
+ symbols.push(bestIdx);
479
+ score += bestPower - Math.max(0, secondPower);
480
+ }
481
+ return { bits: symbolsToBits(symbols), score };
482
+ }
483
+ function estimatePlaceholderHola(holaCharEstimate = 280) {
484
+ const body = Math.max(32, Math.floor(holaCharEstimate) - 80);
485
+ return "HOLA/MUNDO/abcdefghijkl/2026-01-01T00:00:00.000Z/" + "A".repeat(Math.min(64, body)) + "/API.IDENTYCLAW.COM/SIG/" + "B".repeat(Math.max(8, body - 64));
486
+ }
487
+ function estimatePlaceholderChallenge(charEstimate = 52) {
488
+ const n = Math.max(40, Math.floor(charEstimate));
489
+ const nonceLen = Math.min(32, Math.max(8, n - 20));
490
+ return "HEY/abcdefghijkl/" + "A".repeat(nonceLen) + "/X";
491
+ }
492
+ function maxDemodSamplesAfterPayload(sampleRate = FSK_SAMPLE_RATE) {
493
+ const symbols = bitsToSymbols(
494
+ bytesToBits(frameHolaBytes(estimatePlaceholderHola(280)))
495
+ ).length;
496
+ const sps = samplesPerSymbol(sampleRate);
497
+ return symbols * sps + markerSampleCount(sampleRate) + Math.round(sampleRate * 0.5);
498
+ }
499
+ function demodulateFsk(pcm, sampleRate = FSK_SAMPLE_RATE, options) {
500
+ const samples = toFloat32(pcm);
501
+ const sps = samplesPerSymbol(sampleRate);
502
+ if (samples.length < sps * 8) return [];
503
+ let sliced;
504
+ if (options?.startSample != null) {
505
+ sliced = samples.subarray(Math.max(0, options.startSample));
506
+ } else {
507
+ const sof = findSofOffset(samples, sampleRate);
508
+ if (sof != null) {
509
+ sliced = samples.subarray(payloadStartAfterSof(sof, sampleRate));
510
+ } else {
511
+ sliced = samples.subarray(findToneOnset(samples, sampleRate));
512
+ }
513
+ }
514
+ const cap = maxDemodSamplesAfterPayload(sampleRate);
515
+ if (sliced.length > cap) {
516
+ sliced = sliced.subarray(0, cap);
517
+ }
518
+ if (sliced.length < sps * 8) return [];
519
+ const maxOffset = sps;
520
+ const step = Math.max(1, Math.floor(sps / 10));
521
+ let bestBits = [];
522
+ let bestScore = -Infinity;
523
+ for (let offset = 0; offset < maxOffset; offset += step) {
524
+ const { bits, score } = demodulateAligned(sliced, sampleRate, offset);
525
+ if (deframeFramedText(bits)) {
526
+ return bits;
527
+ }
528
+ if (score > bestScore) {
529
+ bestScore = score;
530
+ bestBits = bits;
531
+ }
532
+ }
533
+ return bestBits;
534
+ }
535
+ function estimateFskDurationMs(text, sampleRate = FSK_SAMPLE_RATE) {
536
+ const symbols = bitsToSymbols(bytesToBits(frameHolaBytes(text))).length;
537
+ const sps = samplesPerSymbol(sampleRate);
538
+ const total = warmupSampleCount(sampleRate) + markerSampleCount(sampleRate) + symbols * sps + markerSampleCount(sampleRate);
539
+ return Math.ceil(total * 1e3 / sampleRate);
540
+ }
541
+ function encodeHolaToPcm(text, options) {
542
+ const sampleRate = options?.sampleRate ?? FSK_SAMPLE_RATE;
543
+ const warmup = synthesizeWarmup({ sampleRate });
544
+ const sof = synthesizeToneSymbols(
545
+ markerTonePattern(SOF_TONE_PAIR, sampleRate),
546
+ {
547
+ sampleRate,
548
+ startPhase: warmup.phase
549
+ }
550
+ );
551
+ const payload = synthesizeToneSymbols(
552
+ bitsToSymbols(bytesToBits(frameHolaBytes(text))),
553
+ { sampleRate, startPhase: sof.phase }
554
+ );
555
+ const eof = synthesizeToneSymbols(
556
+ markerTonePattern(EOF_TONE_PAIR, sampleRate),
557
+ {
558
+ sampleRate,
559
+ startPhase: payload.phase
560
+ }
561
+ );
562
+ const sofStart = warmup.samples.length;
563
+ const payloadStart = sofStart + sof.samples.length;
564
+ const eofStart = payloadStart + payload.samples.length;
565
+ const samples = new Int16Array(eofStart + eof.samples.length);
566
+ samples.set(warmup.samples, 0);
567
+ samples.set(sof.samples, sofStart);
568
+ samples.set(payload.samples, payloadStart);
569
+ samples.set(eof.samples, eofStart);
570
+ return {
571
+ samples,
572
+ sampleRate,
573
+ durationMs: Math.ceil(samples.length * 1e3 / sampleRate),
574
+ layout: {
575
+ warmupSamples: warmup.samples.length,
576
+ sofSamples: sof.samples.length,
577
+ payloadSamples: payload.samples.length,
578
+ eofSamples: eof.samples.length,
579
+ sofStart,
580
+ payloadStart,
581
+ eofStart
582
+ }
583
+ };
584
+ }
585
+ function bitsFromPcm(pcm, sampleRate, options) {
586
+ const sof = options?.sofOffset != null ? options.sofOffset : findSofOffset(pcm, sampleRate);
587
+ const startSample = sof != null ? payloadStartAfterSof(sof, sampleRate) : void 0;
588
+ return demodulateFsk(pcm, sampleRate, { startSample });
589
+ }
590
+ function decodePcmToFramedText(pcm, sampleRate = FSK_SAMPLE_RATE, options) {
591
+ return { text: deframeFramedText(bitsFromPcm(pcm, sampleRate, options)) };
592
+ }
593
+ function decodePcmToHola(pcm, sampleRate = FSK_SAMPLE_RATE, options) {
594
+ const hola = deframeHolaBytes(bitsFromPcm(pcm, sampleRate, options));
595
+ return { hola, text: hola || "" };
596
+ }
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "@rodit/hola-mfsk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Isomorphic 4-tone MFSK PHY for IdentyClaw HOLA over air (1800/2100/2400/2700 Hz, 100 baud)",
5
+ "license": "AGPL-3.0-only",
6
+ "type": "commonjs",
7
+ "main": "./index.js",
8
+ "types": "./index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./index.d.ts",
12
+ "default": "./index.js"
13
+ },
14
+ "./lib/mfsk": {
15
+ "types": "./index.d.ts",
16
+ "default": "./lib/mfsk.js"
17
+ },
18
+ "./lib/*": "./lib/*"
19
+ },
20
+ "engines": {
21
+ "node": ">=20"
22
+ },
23
+ "files": [
24
+ "index.js",
25
+ "index.d.ts",
26
+ "lib",
27
+ "README.md",
28
+ "CHANGELOG.md",
29
+ "LICENSE"
30
+ ],
31
+ "keywords": [
32
+ "identyclaw",
33
+ "hola",
34
+ "mfsk",
35
+ "fsk",
36
+ "acoustic",
37
+ "near",
38
+ "rodit",
39
+ "passport"
40
+ ],
41
+ "author": "Discernible IO",
42
+ "private": false,
43
+ "repository": {
44
+ "type": "git",
45
+ "url": "git+https://github.com/discernible-io/rodit-sdk.git",
46
+ "directory": "hola-mfsk"
47
+ },
48
+ "bugs": {
49
+ "url": "https://github.com/discernible-io/rodit-sdk/issues"
50
+ },
51
+ "homepage": "https://github.com/discernible-io/rodit-sdk/tree/main/hola-mfsk#readme",
52
+ "publishConfig": {
53
+ "access": "public"
54
+ },
55
+ "scripts": {
56
+ "build": "esbuild src/mfsk.ts --bundle --outfile=lib/mfsk.js --format=cjs --platform=neutral --target=es2020 --legal-comments=inline",
57
+ "test": "node --test test/*.test.js"
58
+ },
59
+ "devDependencies": {
60
+ "esbuild": "^0.25.0"
61
+ }
62
+ }