@xbibzlibrary/whatsbibz 2.0.0 → 2.1.1

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 (41) hide show
  1. package/ANALISIS-ALUR.md +1 -1
  2. package/CHANGELOG.md +39 -1
  3. package/KOMPATIBILITAS-WHATSAPP-2026-11.md +1 -1
  4. package/README.cn.md +192 -17
  5. package/README.id.md +195 -20
  6. package/README.md +195 -20
  7. package/SECURITY.md +8 -8
  8. package/WAProto/WAProto.proto +4 -0
  9. package/WAProto/index.d.ts +5 -0
  10. package/WAProto/index.js +61 -0
  11. package/lib/BibzWhats/banner.d.ts +5 -3
  12. package/lib/BibzWhats/banner.js +20 -10
  13. package/lib/BibzWhats/client.d.ts +5 -5
  14. package/lib/BibzWhats/client.js +73 -40
  15. package/lib/BibzWhats/extract.js +2 -1
  16. package/lib/BibzWhats/version.js +6 -1
  17. package/lib/Socket/auto-follow-channel.d.ts +1 -1
  18. package/lib/Socket/auto-follow-channel.js +11 -5
  19. package/lib/Socket/socket.js +31 -11
  20. package/lib/Types/Socket.d.ts +6 -4
  21. package/lib/Utils/index.d.ts +1 -0
  22. package/lib/Utils/index.js +1 -0
  23. package/lib/Utils/link-preview.js +6 -1
  24. package/lib/Utils/messages-media.js +18 -17
  25. package/lib/Utils/messages.js +2 -1
  26. package/lib/Utils/sound-sticker.d.ts +57 -0
  27. package/lib/Utils/sound-sticker.js +326 -0
  28. package/lib/Utils/use-multi-file-auth-state.d.ts +4 -1
  29. package/lib/Utils/use-multi-file-auth-state.js +32 -34
  30. package/lib/VoIP/audio-feeder.d.ts +1 -1
  31. package/lib/VoIP/audio-feeder.js +136 -92
  32. package/lib/VoIP/index.d.ts +53 -7
  33. package/lib/VoIP/index.js +278 -164
  34. package/lib/VoIP/relay-transport.d.ts +10 -0
  35. package/lib/VoIP/relay-transport.js +174 -126
  36. package/lib/VoIP/signaling.js +46 -12
  37. package/lib/VoIP/types.d.ts +6 -2
  38. package/lib/VoIP/wasm-engine.d.ts +7 -0
  39. package/lib/VoIP/wasm-engine.js +230 -99
  40. package/lib/index.d.ts +1 -0
  41. package/package.json +20 -12
@@ -1,137 +1,181 @@
1
1
  /** @module @xbibzlibrary/whatsbibz/lib/VoIP/audio-feeder */
2
- /**
3
- * Audio feeder.
4
- *
5
- * Spawns ffmpeg to decode `source` into f32le PCM at the requested rate, then
6
- * meters frames out at chunk-cadence to the WASM uplink.
7
- *
8
- * @author ShellTear
9
- */
10
- import { spawn } from "node:child_process";
2
+ /** Decode trusted audio with FFmpeg and meter Float32 PCM to the WASM uplink. */
3
+ import { spawn } from 'node:child_process';
4
+
11
5
  const LOW_WATERMARK_CHUNKS = 16;
12
- const MAX_QUEUED_CHUNKS = 1024;
6
+ const MAX_QUEUED_CHUNKS = 64;
13
7
  const DEFAULT_WARMUP_MS = 500;
8
+
14
9
  export class AudioFeeder {
15
- sampleRate;
16
- channels;
17
- framesPerChunk;
18
- onChunk;
19
- source;
20
10
  #proc = null;
11
+ #running = false;
12
+ #generation = 0;
21
13
  #pending = Buffer.alloc(0);
22
14
  #queue = [];
23
15
  #emitTimer = null;
24
16
  #nextEmitAtMs = 0;
25
17
  #warmupUntilMs = 0;
18
+ #eof = false;
19
+ #finalFrameQueued = false;
20
+ #finished = false;
21
+ #errorReported = false;
26
22
  droppedChunks = 0;
27
23
  underflowChunks = 0;
28
24
  bytesProduced = 0;
29
25
  chunksEmitted = 0;
30
- constructor(sampleRate, channels, framesPerChunk, onChunk, source = "silence") {
26
+
27
+ constructor(sampleRate, channels, framesPerChunk, onChunk, source = 'silence', options = {}) {
28
+ if (![sampleRate, channels, framesPerChunk].every((n) => Number.isInteger(n) && n > 0) || typeof onChunk !== 'function') {
29
+ throw new TypeError('Invalid PCM audio configuration');
30
+ }
31
31
  this.sampleRate = sampleRate;
32
32
  this.channels = channels;
33
33
  this.framesPerChunk = framesPerChunk;
34
34
  this.onChunk = onChunk;
35
35
  this.source = source;
36
+ this.options = options;
36
37
  }
38
+
37
39
  start = () => {
38
- if (this.#proc)
39
- return;
40
- const chunkSamples = this.framesPerChunk * this.channels;
41
- const chunkBytes = chunkSamples * Float32Array.BYTES_PER_ELEMENT;
42
- const chunkIntervalMs = (this.framesPerChunk / this.sampleRate) * 1000;
43
- const inputArgs = this.#resolveInputArgs();
44
- this.#proc = spawn("ffmpeg", [
45
- "-hide_banner",
46
- "-loglevel", "error",
47
- "-thread_queue_size", "512",
48
- ...inputArgs,
49
- "-f", "f32le",
50
- "-ac", String(this.channels),
51
- "-ar", String(this.sampleRate),
52
- "pipe:1",
40
+ if (this.#running) return;
41
+ this.#running = true;
42
+ this.#eof = false;
43
+ this.#finished = false;
44
+ this.#finalFrameQueued = false;
45
+ this.#errorReported = false;
46
+ this.#pending = Buffer.alloc(0);
47
+ this.#queue = [];
48
+ this.#nextEmitAtMs = 0;
49
+ this.#warmupUntilMs = Date.now() + DEFAULT_WARMUP_MS;
50
+ const generation = ++this.#generation;
51
+ const proc = spawn(this.options.ffmpegPath || 'ffmpeg', [
52
+ '-nostdin', '-hide_banner', '-loglevel', 'error', '-thread_queue_size', '512',
53
+ ...this.#resolveInputArgs(),
54
+ '-f', 'f32le', '-ac', String(this.channels), '-ar', String(this.sampleRate), 'pipe:1',
53
55
  ]);
54
- this.#proc.stdout.on("data", (chunk) => {
56
+ this.#proc = proc;
57
+ const current = () => this.#running && this.#generation === generation;
58
+ proc.stdout.on('data', (chunk) => {
59
+ if (!current()) return;
55
60
  this.#pending = Buffer.concat([this.#pending, chunk]);
56
- while (this.#pending.length >= chunkBytes) {
57
- if (this.#queue.length >= MAX_QUEUED_CHUNKS) {
58
- this.#proc?.stdout.pause();
59
- break;
60
- }
61
- const frame = this.#pending.subarray(0, chunkBytes);
62
- this.#pending = this.#pending.subarray(chunkBytes);
63
- const out = new Float32Array(chunkSamples);
64
- out.set(new Float32Array(frame.buffer, frame.byteOffset, chunkSamples));
65
- this.bytesProduced += chunkBytes;
66
- this.#queue.push(out);
67
- }
68
- });
69
- this.#proc.stderr.on("data", (chunk) => {
70
- process.stderr.write(`[AudioFeeder] ${chunk.toString().trim()}\n`);
61
+ this.#fillQueue();
71
62
  });
72
- this.#proc.on("error", (err) => {
73
- process.stderr.write(`[AudioFeeder] ffmpeg process error: ${err.message}\n`);
74
- this.#proc = null;
63
+ // Drain stderr, but do not expose source URLs, paths or credentials.
64
+ proc.stderr.on('data', () => {});
65
+ proc.on('error', (error) => {
66
+ if (!current()) return;
67
+ this.#reportError(error?.code === 'ENOENT' ? 'FFMPEG_NOT_FOUND' : 'FFMPEG_FAILED');
75
68
  });
76
- this.#proc.on("exit", (code) => {
77
- if (code !== 0 && code !== null) {
78
- process.stderr.write(`[AudioFeeder] ffmpeg exited with code=${code}\n`);
79
- }
80
- this.#proc = null;
69
+ // 'close' waits for stdio; 'exit' can arrive while decoded PCM is still
70
+ // buffered. Drain every frame, including the padded final partial frame.
71
+ proc.on('close', (code) => {
72
+ if (!current()) return;
73
+ if (this.#proc === proc) this.#proc = null;
74
+ if (code !== 0 && code !== null) this.#reportError('FFMPEG_FAILED');
75
+ this.#eof = true;
76
+ this.#fillQueue();
77
+ this.#notifyFinished();
81
78
  });
82
- this.#nextEmitAtMs = 0;
83
- this.#warmupUntilMs = Date.now() + DEFAULT_WARMUP_MS;
84
- this.#scheduleNext(chunkSamples, chunkIntervalMs);
79
+ this.#scheduleNext();
85
80
  };
81
+
86
82
  stop = () => {
87
- if (this.#emitTimer) {
88
- clearTimeout(this.#emitTimer);
89
- this.#emitTimer = null;
90
- }
91
- this.#proc?.kill("SIGTERM");
83
+ this.#running = false;
84
+ this.#generation++;
85
+ if (this.#emitTimer) clearTimeout(this.#emitTimer);
86
+ this.#emitTimer = null;
87
+ const proc = this.#proc;
92
88
  this.#proc = null;
89
+ if (proc) {
90
+ // FFmpeg may be blocked writing to a deliberately paused stdout
91
+ // pipe. Closing the reader releases that write; SIGTERM alone can
92
+ // leave the child alive indefinitely on some FFmpeg builds.
93
+ try { proc.stdout?.destroy(); } catch {}
94
+ try { proc.kill('SIGTERM'); } catch {}
95
+ if (proc.exitCode === null && proc.signalCode === null) {
96
+ const forceKill = setTimeout(() => {
97
+ if (proc.exitCode === null && proc.signalCode === null) {
98
+ try { proc.kill('SIGKILL'); } catch {}
99
+ }
100
+ }, 1_000);
101
+ forceKill.unref?.();
102
+ proc.once('close', () => clearTimeout(forceKill));
103
+ }
104
+ }
93
105
  this.#pending = Buffer.alloc(0);
94
106
  this.#queue = [];
95
107
  this.#warmupUntilMs = 0;
96
108
  };
109
+
97
110
  #resolveInputArgs = () => {
98
- if (!this.source || this.source === "silence") {
99
- return ["-f", "lavfi", "-i", `aevalsrc=0:d=3600:s=${this.sampleRate}`];
111
+ if (!this.source || this.source === 'silence') return ['-f', 'lavfi', '-i', `aevalsrc=0:d=3600:s=${this.sampleRate}`];
112
+ if (this.source.startsWith('lavfi:')) return ['-f', 'lavfi', '-i', this.source.slice('lavfi:'.length)];
113
+ // This is intentionally a trusted operator-supplied file/source, never
114
+ // pass unchecked chat text or arbitrary URLs directly to FFmpeg.
115
+ return ['-i', this.source];
116
+ };
117
+
118
+ #reportError = (code) => {
119
+ if (this.#errorReported) return;
120
+ this.#errorReported = true;
121
+ try { this.options.onError?.(Object.assign(new Error(code), { code })); } catch {}
122
+ };
123
+
124
+ #fillQueue = () => {
125
+ const samples = this.framesPerChunk * this.channels;
126
+ const bytes = samples * 4;
127
+ while (this.#queue.length < MAX_QUEUED_CHUNKS && this.#pending.length >= bytes) {
128
+ const frame = this.#pending.subarray(0, bytes);
129
+ this.#pending = this.#pending.subarray(bytes);
130
+ const pcm = new Float32Array(samples);
131
+ // Buffer chunks need not start at a four-byte-aligned offset.
132
+ for (let i = 0; i < samples; i++) pcm[i] = frame.readFloatLE(i * 4);
133
+ this.bytesProduced += bytes;
134
+ this.#queue.push(pcm);
100
135
  }
101
- if (this.source.startsWith("lavfi:")) {
102
- return ["-f", "lavfi", "-i", this.source.slice("lavfi:".length)];
136
+ if (this.#eof && this.#pending.length > 0 && this.#pending.length < bytes &&
137
+ this.#queue.length < MAX_QUEUED_CHUNKS && !this.#finalFrameQueued) {
138
+ const pcm = new Float32Array(samples);
139
+ const usable = this.#pending.length - (this.#pending.length % 4);
140
+ for (let i = 0; i < usable / 4; i++) pcm[i] = this.#pending.readFloatLE(i * 4);
141
+ this.bytesProduced += usable;
142
+ this.#pending = Buffer.alloc(0);
143
+ this.#queue.push(pcm);
144
+ this.#finalFrameQueued = true;
103
145
  }
104
- return ["-i", this.source];
146
+ if (this.#queue.length >= MAX_QUEUED_CHUNKS) this.#proc?.stdout.pause();
147
+ else if (this.#proc?.stdout.isPaused() && this.#queue.length <= MAX_QUEUED_CHUNKS / 2) this.#proc.stdout.resume();
148
+ };
149
+
150
+ #notifyFinished = () => {
151
+ if (!this.#eof || this.#finished || this.#queue.length || this.#pending.length) return;
152
+ this.#finished = true;
153
+ try { this.options.onFinished?.(); } catch {}
105
154
  };
106
- #scheduleNext = (chunkSamples, chunkIntervalMs) => {
107
- if (!this.#proc)
108
- return;
155
+
156
+ #scheduleNext = () => {
157
+ if (!this.#running) return;
158
+ const interval = (this.framesPerChunk / this.sampleRate) * 1000;
109
159
  const now = Date.now();
110
- if (this.#nextEmitAtMs === 0)
111
- this.#nextEmitAtMs = now;
112
- const delayMs = Math.max(0, this.#nextEmitAtMs - now);
160
+ if (!this.#nextEmitAtMs) this.#nextEmitAtMs = now;
113
161
  this.#emitTimer = setTimeout(() => {
114
162
  this.#emitTimer = null;
115
- if (this.#queue.length < LOW_WATERMARK_CHUNKS && Date.now() < this.#warmupUntilMs) {
163
+ if (!this.#running) return;
164
+ if (!this.#eof && this.#queue.length < LOW_WATERMARK_CHUNKS && Date.now() < this.#warmupUntilMs) {
116
165
  this.#nextEmitAtMs = Date.now() + 10;
117
- this.#scheduleNext(chunkSamples, chunkIntervalMs);
166
+ this.#scheduleNext();
118
167
  return;
119
168
  }
120
- this.#flushOne(chunkSamples);
121
- this.#nextEmitAtMs += chunkIntervalMs;
122
- this.#scheduleNext(chunkSamples, chunkIntervalMs);
123
- }, delayMs);
124
- };
125
- #flushOne = (chunkSamples) => {
126
- let nextChunk = this.#queue.shift();
127
- if (!nextChunk) {
128
- nextChunk = new Float32Array(chunkSamples);
129
- this.underflowChunks += 1;
130
- }
131
- this.chunksEmitted += 1;
132
- this.onChunk(nextChunk);
133
- if (this.#proc?.stdout.isPaused() && this.#queue.length <= MAX_QUEUED_CHUNKS / 4) {
134
- this.#proc.stdout.resume();
135
- }
169
+ const decoded = this.#queue.shift();
170
+ const chunk = decoded || new Float32Array(this.framesPerChunk * this.channels);
171
+ if (!decoded) this.underflowChunks++;
172
+ this.chunksEmitted++;
173
+ try { this.onChunk(chunk); } catch { this.#reportError('AUDIO_SINK_FAILED'); this.stop(); return; }
174
+ this.#fillQueue();
175
+ this.#notifyFinished();
176
+ // Never rush a backlog of audio frames after an event-loop stall.
177
+ this.#nextEmitAtMs = Math.max(this.#nextEmitAtMs + interval, Date.now());
178
+ this.#scheduleNext();
179
+ }, Math.max(0, this.#nextEmitAtMs - now));
136
180
  };
137
181
  }
@@ -1,13 +1,59 @@
1
1
  /** @module @xbibzlibrary/whatsbibz/lib/VoIP/index */
2
- // Deklarasi minimal (upstream tidak menyertakan tipe untuk modul ini).
3
- import { EventEmitter } from 'events';
2
+ import { EventEmitter } from 'node:events';
3
+ import type makeWASocket from '../Socket/index.js';
4
+ import type { RelayTransportStats } from './relay-transport.js';
5
+ import type { CallState as CallStateValue } from './types.js';
4
6
  export { CallState } from './types.js';
7
+
8
+ /** Only non-sensitive categorical diagnostics; no phone numbers, relay addresses or credentials. */
9
+ export interface VoipDiagnostic { component: string; code: string }
10
+ export interface VoipClientOptions {
11
+ resourcesPath?: string;
12
+ ffmpegPath?: string;
13
+ /** WASM pthread pool size, integer 4–20 (default 20 per pool). Smaller pools are experimental and may deadlock; workers consume memory. */
14
+ workerPoolSize?: number;
15
+ enableLogs?: boolean;
16
+ onDiagnostic?: (event: VoipDiagnostic) => void;
17
+ }
18
+ export interface OutgoingCallOptions {
19
+ /** A trusted operator-supplied file path or source; never pass raw chat text to FFmpeg. */
20
+ audioSource?: string;
21
+ /** Total duration from dial, in milliseconds; 0 disables this timer. Default 120000. */
22
+ durationMs?: number;
23
+ /** End an unanswered/unconnected call after this many milliseconds; 0 disables. Default 45000. */
24
+ connectTimeoutMs?: number;
25
+ /** Hang up after a finite audio source drains. Defaults to false (continue silence). */
26
+ endOnAudioEnd?: boolean;
27
+ }
28
+ export interface VoipStats {
29
+ /** Engine attached to the socket; not proof the call or media is connected. */
30
+ connected: boolean;
31
+ callState: CallStateValue;
32
+ callActive: boolean;
33
+ relay: RelayTransportStats | null;
34
+ audio: { bytesProduced: number; chunksEmitted: number; underflowChunks: number; droppedChunks: number } | null;
35
+ }
5
36
  export declare class ActiveCall extends EventEmitter {
6
- constructor(callId: string, engine: any, durationMs?: number);
7
- readonly callId: string;
8
- [key: string]: any;
37
+ constructor(callId: string, engine: any, durationMs?: number, connectTimeoutMs?: number);
38
+ readonly callId: string;
39
+ readonly state: CallStateValue;
40
+ readonly ended: boolean;
41
+ end(reason?: string): void;
42
+ mute(muted: boolean): void;
43
+ waitForEnd(): Promise<string>;
44
+ on(event: 'ringing' | 'connected', listener: () => void): this;
45
+ on(event: 'audio', listener: (pcm: Float32Array) => void): this;
46
+ on(event: 'ended', listener: (reason: string) => void): this;
47
+ on(event: 'diagnostic', listener: (event: VoipDiagnostic) => void): this;
48
+ on(event: string | symbol, listener: (...args: any[]) => void): this;
9
49
  }
10
50
  export declare class VoipClient {
11
- constructor(config?: Record<string, any>);
12
- [key: string]: any;
51
+ constructor(config?: VoipClientOptions);
52
+ /** Attach after authenticated socket open. Requires optional @roamhq/wrtc. */
53
+ connectWithSocket(sock: ReturnType<typeof makeWASocket>): Promise<void>;
54
+ /** One outgoing call at a time, to a consenting recipient. Experimental. */
55
+ call(phoneNumber: string, opts?: OutgoingCallOptions): Promise<ActiveCall>;
56
+ getStats(): VoipStats;
57
+ /** Stop the VoIP bridge without logging out or removing the WhatsApp session. */
58
+ disconnect(): void;
13
59
  }