@hiroosy/baileys-lite 0.4.3 → 0.4.5
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/README.md +8 -17
- package/WAProto/index.d.ts +4 -0
- package/WAProto/parts/Message.part +42 -0
- package/package.json +1 -1
- package/src/ffmpeg/LICENSE +502 -0
- package/src/ffmpeg/index.js +64 -0
- package/src/ffmpeg/lib/bits.js +150 -0
- package/src/ffmpeg/lib/bsf.js +242 -0
- package/src/ffmpeg/lib/codec/flac.js +801 -0
- package/src/ffmpeg/lib/codec/index.js +108 -0
- package/src/ffmpeg/lib/codec/mp3.js +768 -0
- package/src/ffmpeg/lib/codec/mpa.js +65 -0
- package/src/ffmpeg/lib/codec/mpa_tables.js +27 -0
- package/src/ffmpeg/lib/codec/opus.js +140 -0
- package/src/ffmpeg/lib/codec/pcm.js +198 -0
- package/src/ffmpeg/lib/compat.js +42 -0
- package/src/ffmpeg/lib/crc.js +60 -0
- package/src/ffmpeg/lib/demux/adts.js +151 -0
- package/src/ffmpeg/lib/demux/flac.js +150 -0
- package/src/ffmpeg/lib/demux/image.js +47 -0
- package/src/ffmpeg/lib/demux/index.js +60 -0
- package/src/ffmpeg/lib/demux/matroska.js +525 -0
- package/src/ffmpeg/lib/demux/merge.js +106 -0
- package/src/ffmpeg/lib/demux/mp3.js +199 -0
- package/src/ffmpeg/lib/demux/mp4.js +622 -0
- package/src/ffmpeg/lib/demux/ogg.js +250 -0
- package/src/ffmpeg/lib/demux/ts.js +354 -0
- package/src/ffmpeg/lib/demux/wav.js +156 -0
- package/src/ffmpeg/lib/errors.js +27 -0
- package/src/ffmpeg/lib/filter/gain.js +69 -0
- package/src/ffmpeg/lib/filter/mix.js +95 -0
- package/src/ffmpeg/lib/filter/resample.js +187 -0
- package/src/ffmpeg/lib/filter/video.js +575 -0
- package/src/ffmpeg/lib/image/bmp.js +123 -0
- package/src/ffmpeg/lib/image/frame.js +216 -0
- package/src/ffmpeg/lib/image/gif.js +215 -0
- package/src/ffmpeg/lib/image/index.js +70 -0
- package/src/ffmpeg/lib/image/jpeg.js +964 -0
- package/src/ffmpeg/lib/image/png.js +256 -0
- package/src/ffmpeg/lib/image/run.js +67 -0
- package/src/ffmpeg/lib/io.js +298 -0
- package/src/ffmpeg/lib/mux/adts.js +75 -0
- package/src/ffmpeg/lib/mux/flac.js +79 -0
- package/src/ffmpeg/lib/mux/mp3.js +85 -0
- package/src/ffmpeg/lib/mux/mp4.js +450 -0
- package/src/ffmpeg/lib/mux/ogg.js +146 -0
- package/src/ffmpeg/lib/mux/wav.js +94 -0
- package/src/ffmpeg/lib/net.js +270 -0
- package/src/ffmpeg/lib/pipeline.js +579 -0
- package/src/ffmpeg/lib/probe.js +45 -0
- package/src/ffmpeg/lib/tags.js +307 -0
- package/src/ffmpeg/lib/util.js +104 -0
- package/src/foundation/image-thumb.js +4 -56
- package/src/socket/messages-recv.js +5 -6
- package/src/socket/socket-core.js +3 -3
- package/src/utils/media.js +8 -85
- package/src/utils/message-compose.js +19 -11
- package/src/utils/wa-protocol-core.js +5 -5
- package/src/voip/index.js +16 -50
- package/src/voip/media/WaAudioEngine.js +8 -216
- package/src/voip/media/WaVideoEngine.js +8 -237
|
@@ -1468,24 +1468,24 @@ export const generateWAMessageFromContent = (jid, message, options) => {
|
|
|
1468
1468
|
const isNewsletter = isJidNewsletter(jid)
|
|
1469
1469
|
const { quoted, userJid } = options
|
|
1470
1470
|
|
|
1471
|
+
const mergeContextInfo = patch => {
|
|
1472
|
+
message = mapInnerContent(message, inner => ({ ...inner, [key]: { ...inner[key], contextInfo: { ...inner[key]?.contextInfo, ...patch } } }))
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1471
1475
|
if (quoted) {
|
|
1472
1476
|
const participant = quoted.key.fromMe ? userJid : quoted.participant || quoted.key.participant || quoted.key.remoteJid
|
|
1473
1477
|
let quotedMsg = normalizeMessageContent(quoted.message)
|
|
1474
1478
|
const msgType = getContentType(quotedMsg)
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
const
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
contextInfo.quotedMessage = quotedMsg
|
|
1482
|
-
|
|
1483
|
-
if (!isNewsletter && jid !== quoted.key.remoteJid) contextInfo.remoteJid = quoted.key.remoteJid
|
|
1484
|
-
if (contextInfo && innerMessage[key]) innerMessage[key].contextInfo = contextInfo
|
|
1479
|
+
const quotedContent = { ...quotedMsg[msgType] }
|
|
1480
|
+
delete quotedContent.contextInfo
|
|
1481
|
+
quotedMsg = proto.Message.create({ [msgType]: quotedContent })
|
|
1482
|
+
const patch = { participant: jidNormalizedUser(participant), stanzaId: quoted.key.id, quotedMessage: quotedMsg }
|
|
1483
|
+
if (!isNewsletter && jid !== quoted.key.remoteJid) patch.remoteJid = quoted.key.remoteJid
|
|
1484
|
+
mergeContextInfo(patch)
|
|
1485
1485
|
}
|
|
1486
1486
|
|
|
1487
1487
|
if (!!options?.ephemeralExpiration && key !== 'protocolMessage' && key !== 'ephemeralMessage' && !isNewsletter) {
|
|
1488
|
-
|
|
1488
|
+
mergeContextInfo({ expiration: options.ephemeralExpiration || WA_DEFAULT_EPHEMERAL })
|
|
1489
1489
|
}
|
|
1490
1490
|
|
|
1491
1491
|
message = WAProto.Message.create(message)
|
|
@@ -1514,8 +1514,16 @@ export const getContentType = content => {
|
|
|
1514
1514
|
}
|
|
1515
1515
|
}
|
|
1516
1516
|
|
|
1517
|
+
const mapInnerContent = (msg, transform) => {
|
|
1518
|
+
const wrapper = getFutureProofMessage(msg)
|
|
1519
|
+
if (!wrapper) return transform(msg)
|
|
1520
|
+
const envelopeKey = Object.keys(msg).find(k => msg[k] === wrapper)
|
|
1521
|
+
return { ...msg, [envelopeKey]: { ...wrapper, message: mapInnerContent(wrapper.message, transform) } }
|
|
1522
|
+
}
|
|
1523
|
+
|
|
1517
1524
|
const getFutureProofMessage = message =>
|
|
1518
1525
|
message?.associatedChildMessage ||
|
|
1526
|
+
message?.audioStickerMessage ||
|
|
1519
1527
|
message?.botForwardedMessage ||
|
|
1520
1528
|
message?.botInvokeMessage ||
|
|
1521
1529
|
message?.botTaskMessage ||
|
|
@@ -484,6 +484,8 @@ export const getCompanionWebClientType = ([os, browserName]) => {
|
|
|
484
484
|
|
|
485
485
|
export const getCompanionPlatformId = browser => getCompanionWebClientType(browser).toString()
|
|
486
486
|
|
|
487
|
+
export const getPairingCodePlatformId = browser => (browser[1].toLocaleLowerCase().includes('android') ? 'e' : getCompanionPlatformId(browser))
|
|
488
|
+
|
|
487
489
|
export const buildPairingQRData = (ref, noiseKeyB64, identityKeyB64, advB64, browser) =>
|
|
488
490
|
'https://wa.me/settings/linked_devices#' + [ref, noiseKeyB64, identityKeyB64, advB64, getCompanionPlatformId(browser)].join(',')
|
|
489
491
|
|
|
@@ -890,9 +892,7 @@ const WA_ADV_HOSTED_ACCOUNT_SIG_PREFIX = Buffer.from([6, 5])
|
|
|
890
892
|
|
|
891
893
|
const getUserAgent = config => ({
|
|
892
894
|
appVersion: { primary: config.version[0], secondary: config.version[1], tertiary: config.version[2] },
|
|
893
|
-
platform:
|
|
894
|
-
? proto.ClientPayload.UserAgent.Platform.ANDROID
|
|
895
|
-
: proto.ClientPayload.UserAgent.Platform.WEB,
|
|
895
|
+
platform: proto.ClientPayload.UserAgent.Platform.WEB,
|
|
896
896
|
releaseChannel: proto.ClientPayload.UserAgent.ReleaseChannel.RELEASE,
|
|
897
897
|
osVersion: '0.1',
|
|
898
898
|
device: 'Desktop',
|
|
@@ -920,9 +920,9 @@ const getClientPayload = config => {
|
|
|
920
920
|
const payload = {
|
|
921
921
|
connectType: proto.ClientPayload.ConnectType.WIFI_UNKNOWN,
|
|
922
922
|
connectReason: proto.ClientPayload.ConnectReason.USER_ACTIVATED,
|
|
923
|
-
userAgent: getUserAgent(config)
|
|
923
|
+
userAgent: getUserAgent(config),
|
|
924
|
+
webInfo: getWebInfo(config)
|
|
924
925
|
}
|
|
925
|
-
if (!config.browser[1].toLocaleLowerCase().includes('android')) payload.webInfo = getWebInfo(config)
|
|
926
926
|
if (config.pushName) payload.pushName = config.pushName
|
|
927
927
|
return payload
|
|
928
928
|
}
|
package/src/voip/index.js
CHANGED
|
@@ -2,6 +2,7 @@ import fs from 'node:fs';
|
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { EventEmitter } from 'node:events';
|
|
4
4
|
import { VoipClient } from './voipClient.js';
|
|
5
|
+
import { probeNative } from '../ffmpeg/index.js';
|
|
5
6
|
import { CallDirection, CallMediaType } from './types.js';
|
|
6
7
|
|
|
7
8
|
const RESOLUTION_PRESETS = {
|
|
@@ -82,46 +83,18 @@ async function downloadToTemp(url, extHint, maxBytes, tmpDirOverride) {
|
|
|
82
83
|
return filePath;
|
|
83
84
|
}
|
|
84
85
|
|
|
85
|
-
async function probeMedia(filePath
|
|
86
|
+
async function probeMedia(filePath) {
|
|
86
87
|
try {
|
|
87
|
-
const
|
|
88
|
-
const
|
|
89
|
-
|
|
90
|
-
const { stdout } = await execFileAsync(ffprobePath, [
|
|
91
|
-
'-v', 'error', '-print_format', 'json', '-show_format', '-show_streams', filePath
|
|
92
|
-
]);
|
|
93
|
-
const parsed = JSON.parse(stdout);
|
|
94
|
-
const duration = parsed?.format?.duration;
|
|
95
|
-
const durationMs = (!duration || isNaN(duration)) ? null : Math.ceil(parseFloat(duration) * 1000);
|
|
96
|
-
const videoStream = parsed?.streams?.find((s) => s.codec_type === 'video');
|
|
97
|
-
let width = videoStream?.width || null;
|
|
98
|
-
let height = videoStream?.height || null;
|
|
99
|
-
const rotation = getEffectiveRotation(videoStream);
|
|
100
|
-
if (width && height && Math.abs(rotation) % 180 === 90) {
|
|
101
|
-
[width, height] = [height, width];
|
|
102
|
-
}
|
|
103
|
-
return { durationMs, width, height };
|
|
88
|
+
const native = await probeNative(filePath);
|
|
89
|
+
const duration = native?.format.duration;
|
|
90
|
+
return duration > 0 ? Math.ceil(duration * 1000) : null;
|
|
104
91
|
}
|
|
105
92
|
catch {
|
|
106
|
-
return
|
|
93
|
+
return null;
|
|
107
94
|
}
|
|
108
95
|
}
|
|
109
96
|
|
|
110
|
-
function
|
|
111
|
-
const tagRotate = videoStream?.tags?.rotate;
|
|
112
|
-
if (tagRotate !== undefined) {
|
|
113
|
-
const n = parseInt(tagRotate, 10);
|
|
114
|
-
if (!isNaN(n)) return ((n % 360) + 360) % 360;
|
|
115
|
-
}
|
|
116
|
-
const matrixSideData = videoStream?.side_data_list?.find((sd) => sd.rotation !== undefined);
|
|
117
|
-
if (matrixSideData) {
|
|
118
|
-
const n = Math.round(matrixSideData.rotation);
|
|
119
|
-
if (!isNaN(n)) return ((n % 360) + 360) % 360;
|
|
120
|
-
}
|
|
121
|
-
return 0;
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
async function normalizeItem(item, ffprobePath, tmpDir) {
|
|
97
|
+
async function normalizeItem(item, tmpDir) {
|
|
125
98
|
let kind;
|
|
126
99
|
let rawSource;
|
|
127
100
|
let autoAdvance = false;
|
|
@@ -146,26 +119,21 @@ async function normalizeItem(item, ffprobePath, tmpDir) {
|
|
|
146
119
|
else {
|
|
147
120
|
throw new Error('Playlist item must be a string or an object.');
|
|
148
121
|
}
|
|
122
|
+
if (kind === 'video') {
|
|
123
|
+
throw new Error('Video is not supported by the built-in media engine.');
|
|
124
|
+
}
|
|
149
125
|
let source = rawSource;
|
|
150
126
|
let isTemp = false;
|
|
151
|
-
if (isUrl(rawSource) && kind === 'audio') {
|
|
152
|
-
return { kind, source: rawSource, isTemp: false, durationMs: undefined, autoAdvance };
|
|
153
|
-
}
|
|
154
127
|
if (isUrl(rawSource)) {
|
|
155
|
-
|
|
128
|
+
const extHint = path.extname(new URL(rawSource).pathname) || '.bin';
|
|
129
|
+
source = await downloadToTemp(rawSource, extHint, 50 * 1024 * 1024, tmpDir);
|
|
156
130
|
isTemp = true;
|
|
157
131
|
}
|
|
158
132
|
else if (!fs.existsSync(rawSource)) {
|
|
159
133
|
throw new Error(`Media file not found: ${rawSource}`);
|
|
160
134
|
}
|
|
161
|
-
const
|
|
162
|
-
|
|
163
|
-
const result = { kind, source, isTemp, durationMs, autoAdvance };
|
|
164
|
-
if (kind === 'video' && probed.width && probed.height) {
|
|
165
|
-
result.sourceWidth = probed.width;
|
|
166
|
-
result.sourceHeight = probed.height;
|
|
167
|
-
}
|
|
168
|
-
return result;
|
|
135
|
+
const durationMs = (await probeMedia(source)) ?? undefined;
|
|
136
|
+
return { kind, source, isTemp, durationMs, autoAdvance };
|
|
169
137
|
}
|
|
170
138
|
|
|
171
139
|
class VoipCall extends EventEmitter {
|
|
@@ -517,12 +485,10 @@ export class Voip {
|
|
|
517
485
|
#calls = new Set();
|
|
518
486
|
#pending = 0;
|
|
519
487
|
#maxConcurrentCalls;
|
|
520
|
-
#ffprobePath;
|
|
521
488
|
#tmpDir;
|
|
522
489
|
#voipLogLevel;
|
|
523
490
|
constructor(conn, opts = {}) {
|
|
524
491
|
this.#conn = conn;
|
|
525
|
-
this.#ffprobePath = opts.ffprobePath || 'ffprobe';
|
|
526
492
|
this.#voipLogLevel = opts.voipLogLevel ?? opts.level ?? 'warn';
|
|
527
493
|
this.#maxConcurrentCalls = opts.maxConcurrentCalls ?? Number.MAX_SAFE_INTEGER;
|
|
528
494
|
if (!Number.isSafeInteger(this.#maxConcurrentCalls) || this.#maxConcurrentCalls < 1)
|
|
@@ -633,7 +599,7 @@ export class Voip {
|
|
|
633
599
|
items.push({ kind: 'audio', source: 'silence', isTemp: false });
|
|
634
600
|
continue;
|
|
635
601
|
}
|
|
636
|
-
items.push(await normalizeItem(raw, this.#
|
|
602
|
+
items.push(await normalizeItem(raw, this.#tmpDir));
|
|
637
603
|
}
|
|
638
604
|
const first = items[0];
|
|
639
605
|
const videoConfig = resolveVideoConfig(resolution, { width: first.sourceWidth, height: first.sourceHeight });
|
|
@@ -661,7 +627,7 @@ export class Voip {
|
|
|
661
627
|
startVideoOnFirst: options.startVideoOnFirst,
|
|
662
628
|
target: targetJid,
|
|
663
629
|
onItemAdvance: rescheduleSafetyForItem,
|
|
664
|
-
normalize: raw => normalizeItem(raw, this.#
|
|
630
|
+
normalize: raw => normalizeItem(raw, this.#tmpDir),
|
|
665
631
|
});
|
|
666
632
|
this.#calls.add(call);
|
|
667
633
|
releaseReservation();
|
|
@@ -1,27 +1,8 @@
|
|
|
1
|
-
import { execFile, spawn } from 'node:child_process';
|
|
2
1
|
import { access } from 'node:fs/promises';
|
|
2
|
+
import { decodePcm16 } from '../../ffmpeg/index.js';
|
|
3
3
|
import { createNoopLogger } from '../shim/core.js';
|
|
4
|
-
import { TEXT_DECODER } from '../bytes.js';
|
|
5
4
|
import { DEFAULT_AUDIO_CONFIG } from '../types.js';
|
|
6
|
-
const FFMPEG_BIN = 'ffmpeg';
|
|
7
5
|
const MAX_DECODE_BYTES = 128 * 1024 * 1024;
|
|
8
|
-
const MAX_STDERR_CHARS = 16 * 1024;
|
|
9
|
-
const ffmpegProbeCache = new Map();
|
|
10
|
-
function probeBinary(bin) {
|
|
11
|
-
return new Promise((resolve) => {
|
|
12
|
-
execFile(bin, ['-version'], { timeout: 5_000 }, (err) => resolve(!err));
|
|
13
|
-
});
|
|
14
|
-
}
|
|
15
|
-
async function hasFfmpeg(bin) {
|
|
16
|
-
let available = ffmpegProbeCache.get(bin);
|
|
17
|
-
if (available === undefined) {
|
|
18
|
-
available = await probeBinary(bin);
|
|
19
|
-
if (available) {
|
|
20
|
-
ffmpegProbeCache.set(bin, available);
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
return available;
|
|
24
|
-
}
|
|
25
6
|
function createSelfCorrectingInterval(callback, intervalMs) {
|
|
26
7
|
let expected = performance.now() + intervalMs;
|
|
27
8
|
let timer = null;
|
|
@@ -71,18 +52,9 @@ export class WaAudioEngine {
|
|
|
71
52
|
extTargetBuffer;
|
|
72
53
|
extHighWater;
|
|
73
54
|
extMaxBuffer;
|
|
74
|
-
streamPreBufferSize;
|
|
75
|
-
streamHighWater;
|
|
76
55
|
captureChunkBuffer;
|
|
77
56
|
silenceChunkBuffer;
|
|
78
57
|
playbackOutputBuffer;
|
|
79
|
-
streamProc = null;
|
|
80
|
-
streamMode = false;
|
|
81
|
-
streamEnded = false;
|
|
82
|
-
streamPaused = false;
|
|
83
|
-
streamToken = 0;
|
|
84
|
-
streamQueue = [];
|
|
85
|
-
streamCarry = Buffer.alloc(0);
|
|
86
58
|
constructor(config = {}) {
|
|
87
59
|
const c = { ...DEFAULT_AUDIO_CONFIG, ...config };
|
|
88
60
|
this.logger = config.logger ?? createNoopLogger();
|
|
@@ -99,9 +71,6 @@ export class WaAudioEngine {
|
|
|
99
71
|
this.extTargetBuffer = Math.floor(this.sampleRate * 0.06);
|
|
100
72
|
this.extHighWater = Math.floor(this.sampleRate * 0.2);
|
|
101
73
|
this.extMaxBuffer = Math.floor(this.sampleRate);
|
|
102
|
-
this.streamPreBufferSize = Math.floor(this.sampleRate * 0.3);
|
|
103
|
-
this.streamHighWater = Math.floor(this.sampleRate * 0.6);
|
|
104
|
-
this.streamMaxBacklog = Math.floor(this.sampleRate * 1);
|
|
105
74
|
}
|
|
106
75
|
setAudioSender(sender) {
|
|
107
76
|
this.audioSender = sender;
|
|
@@ -113,7 +82,6 @@ export class WaAudioEngine {
|
|
|
113
82
|
this.onAudioFinished = callback;
|
|
114
83
|
}
|
|
115
84
|
setExternalMode(enabled) {
|
|
116
|
-
this.stopStream();
|
|
117
85
|
this.externalMode = enabled;
|
|
118
86
|
this.extStarted = false;
|
|
119
87
|
if (enabled) {
|
|
@@ -169,15 +137,8 @@ export class WaAudioEngine {
|
|
|
169
137
|
return this.audioFinished;
|
|
170
138
|
}
|
|
171
139
|
async loadSource(source) {
|
|
172
|
-
if (WaAudioEngine.isRemoteSource(source)) {
|
|
173
|
-
this.startStream(source);
|
|
174
|
-
return;
|
|
175
|
-
}
|
|
176
140
|
await this.loadAudioFile(source);
|
|
177
141
|
}
|
|
178
|
-
static isRemoteSource(source) {
|
|
179
|
-
return /^https?:\/\//i.test(String(source));
|
|
180
|
-
}
|
|
181
142
|
async loadAudioFile(audioPath) {
|
|
182
143
|
this.setExternalMode(false);
|
|
183
144
|
try {
|
|
@@ -186,71 +147,15 @@ export class WaAudioEngine {
|
|
|
186
147
|
catch {
|
|
187
148
|
throw new Error(`File not found: ${audioPath}`);
|
|
188
149
|
}
|
|
189
|
-
if (!(await hasFfmpeg(FFMPEG_BIN))) {
|
|
190
|
-
throw new Error('ffmpeg not found on PATH (install ffmpeg to load audio files)');
|
|
191
|
-
}
|
|
192
150
|
this.audioBuffer = null;
|
|
193
|
-
this.audioBuffer = await this.
|
|
151
|
+
this.audioBuffer = await decodePcm16(audioPath, { sampleRate: this.sampleRate, channels: 1, maxBytes: MAX_DECODE_BYTES });
|
|
152
|
+
if (!this.audioBuffer) {
|
|
153
|
+
throw new Error(`Could not decode audio: ${audioPath}`);
|
|
154
|
+
}
|
|
194
155
|
this.audioScale = 1 / 32768;
|
|
195
156
|
this.audioPosition = 0;
|
|
196
157
|
this.audioFinished = false;
|
|
197
158
|
}
|
|
198
|
-
async decodeWithFFmpeg(inputPath) {
|
|
199
|
-
return new Promise((resolve, reject) => {
|
|
200
|
-
const proc = spawn(FFMPEG_BIN, [
|
|
201
|
-
'-hide_banner',
|
|
202
|
-
'-loglevel',
|
|
203
|
-
'error',
|
|
204
|
-
'-i',
|
|
205
|
-
inputPath,
|
|
206
|
-
'-ac',
|
|
207
|
-
'1',
|
|
208
|
-
'-ar',
|
|
209
|
-
String(this.sampleRate),
|
|
210
|
-
'-acodec',
|
|
211
|
-
'pcm_s16le',
|
|
212
|
-
'-f',
|
|
213
|
-
's16le',
|
|
214
|
-
'pipe:1'
|
|
215
|
-
], { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
216
|
-
let pcm = Buffer.allocUnsafeSlow(1 << 20);
|
|
217
|
-
let decodedBytes = 0;
|
|
218
|
-
let stderr = '';
|
|
219
|
-
let aborted = false;
|
|
220
|
-
proc.stdout?.on('data', (chunk) => {
|
|
221
|
-
if (aborted)
|
|
222
|
-
return;
|
|
223
|
-
decodedBytes += chunk.length;
|
|
224
|
-
if (decodedBytes > MAX_DECODE_BYTES) {
|
|
225
|
-
aborted = true;
|
|
226
|
-
proc.kill('SIGKILL');
|
|
227
|
-
reject(new Error(`ffmpeg output exceeded ${MAX_DECODE_BYTES} bytes: ${inputPath}`));
|
|
228
|
-
return;
|
|
229
|
-
}
|
|
230
|
-
if (decodedBytes > pcm.length) {
|
|
231
|
-
const grown = Buffer.allocUnsafeSlow(Math.max(pcm.length * 2, decodedBytes));
|
|
232
|
-
pcm.copy(grown, 0, 0, decodedBytes - chunk.length);
|
|
233
|
-
pcm = grown;
|
|
234
|
-
}
|
|
235
|
-
chunk.copy(pcm, decodedBytes - chunk.length);
|
|
236
|
-
});
|
|
237
|
-
proc.stderr?.on('data', (chunk) => {
|
|
238
|
-
stderr = (stderr + TEXT_DECODER.decode(chunk)).slice(0, MAX_STDERR_CHARS);
|
|
239
|
-
});
|
|
240
|
-
proc.on('error', (err) => reject(new Error(`ffmpeg not available (install ffmpeg on PATH): ${err.message}`)));
|
|
241
|
-
proc.on('close', (code) => {
|
|
242
|
-
if (aborted)
|
|
243
|
-
return;
|
|
244
|
-
if (code !== 0) {
|
|
245
|
-
reject(new Error(`ffmpeg exited with code ${code}: ${stderr.trim()}`));
|
|
246
|
-
return;
|
|
247
|
-
}
|
|
248
|
-
const exact = pcm.length - decodedBytes > 1048576 ? Buffer.from(pcm.subarray(0, decodedBytes - (decodedBytes % 2))) : pcm;
|
|
249
|
-
resolve(new Int16Array(exact.buffer, exact.byteOffset, (exact === pcm ? decodedBytes : exact.length) >> 1));
|
|
250
|
-
pcm = null;
|
|
251
|
-
});
|
|
252
|
-
});
|
|
253
|
-
}
|
|
254
159
|
generateTestTone(frequency = 440, duration = 3, amplitude = 0.3) {
|
|
255
160
|
const samples = this.sampleRate * duration;
|
|
256
161
|
this.audioBuffer = new Float32Array(samples);
|
|
@@ -262,102 +167,6 @@ export class WaAudioEngine {
|
|
|
262
167
|
this.audioBuffer[i] = Math.sin(2 * Math.PI * frequency * t) * amplitude;
|
|
263
168
|
}
|
|
264
169
|
}
|
|
265
|
-
startStream(source) {
|
|
266
|
-
this.setExternalMode(true);
|
|
267
|
-
this.streamMode = true;
|
|
268
|
-
const token = this.streamToken;
|
|
269
|
-
const args = ['-hide_banner', '-loglevel', 'error', '-nostdin'];
|
|
270
|
-
if (WaAudioEngine.isRemoteSource(source)) {
|
|
271
|
-
args.push('-user_agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:152.0) Gecko/20100101 Firefox/152.0', '-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5');
|
|
272
|
-
}
|
|
273
|
-
if (/\.m3u8/i.test(source))
|
|
274
|
-
args.push('-live_start_index', '-1');
|
|
275
|
-
args.push('-i', source, '-vn', '-map', '0:a:0', '-ac', '1', '-ar', String(this.sampleRate), '-acodec', 'pcm_s16le', '-f', 's16le', 'pipe:1');
|
|
276
|
-
const proc = spawn(FFMPEG_BIN, args, { stdio: ['ignore', 'pipe', 'ignore'] });
|
|
277
|
-
this.streamProc = proc;
|
|
278
|
-
const markEnded = () => {
|
|
279
|
-
if (token === this.streamToken) {
|
|
280
|
-
this.streamEnded = true;
|
|
281
|
-
}
|
|
282
|
-
};
|
|
283
|
-
proc.stdout.on('data', (chunk) => {
|
|
284
|
-
if (token !== this.streamToken) {
|
|
285
|
-
return;
|
|
286
|
-
}
|
|
287
|
-
this.streamQueue.push(this.toStreamSamples(chunk));
|
|
288
|
-
this.pumpStream();
|
|
289
|
-
});
|
|
290
|
-
proc.on('error', markEnded);
|
|
291
|
-
proc.on('close', markEnded);
|
|
292
|
-
}
|
|
293
|
-
stopStream() {
|
|
294
|
-
this.streamToken++;
|
|
295
|
-
if (this.streamProc) {
|
|
296
|
-
this.streamProc.kill('SIGKILL');
|
|
297
|
-
this.streamProc = null;
|
|
298
|
-
}
|
|
299
|
-
this.streamMode = false;
|
|
300
|
-
this.streamEnded = false;
|
|
301
|
-
this.streamPaused = false;
|
|
302
|
-
this.streamQueue = [];
|
|
303
|
-
this.streamCarry = Buffer.alloc(0);
|
|
304
|
-
}
|
|
305
|
-
toStreamSamples(chunk) {
|
|
306
|
-
const bytes = this.streamCarry.length > 0 ? Buffer.concat([this.streamCarry, chunk]) : chunk;
|
|
307
|
-
const usable = bytes.length - (bytes.length % 2);
|
|
308
|
-
const samples = new Float32Array(usable / 2);
|
|
309
|
-
for (let i = 0; i < samples.length; i++) {
|
|
310
|
-
samples[i] = bytes.readInt16LE(i * 2) / 32768;
|
|
311
|
-
}
|
|
312
|
-
this.streamCarry = Buffer.from(bytes.subarray(usable));
|
|
313
|
-
return samples;
|
|
314
|
-
}
|
|
315
|
-
pumpStream() {
|
|
316
|
-
const proc = this.streamProc;
|
|
317
|
-
if (!proc) {
|
|
318
|
-
return;
|
|
319
|
-
}
|
|
320
|
-
while (this.streamQueue.length > 0) {
|
|
321
|
-
const room = this.streamHighWater - (this.liveWritePos - this.audioPosition);
|
|
322
|
-
if (room <= 0) {
|
|
323
|
-
break;
|
|
324
|
-
}
|
|
325
|
-
const head = this.streamQueue[0];
|
|
326
|
-
const take = Math.min(head.length, room);
|
|
327
|
-
this.feedExternalAudio(head.subarray(0, take));
|
|
328
|
-
if (take < head.length) {
|
|
329
|
-
this.streamQueue[0] = head.subarray(take);
|
|
330
|
-
}
|
|
331
|
-
else {
|
|
332
|
-
this.streamQueue.shift();
|
|
333
|
-
}
|
|
334
|
-
}
|
|
335
|
-
let queued = 0;
|
|
336
|
-
for (const chunk of this.streamQueue)
|
|
337
|
-
queued += chunk.length;
|
|
338
|
-
if (queued > this.streamMaxBacklog) {
|
|
339
|
-
proc.stdout?.pause();
|
|
340
|
-
}
|
|
341
|
-
else {
|
|
342
|
-
proc.stdout?.resume();
|
|
343
|
-
}
|
|
344
|
-
}
|
|
345
|
-
isStreamFinished() {
|
|
346
|
-
if (this.audioFinished) {
|
|
347
|
-
return true;
|
|
348
|
-
}
|
|
349
|
-
if (!this.streamEnded || this.streamQueue.length > 0 || this.audioPosition < this.liveWritePos) {
|
|
350
|
-
return false;
|
|
351
|
-
}
|
|
352
|
-
this.audioFinished = true;
|
|
353
|
-
const token = this.streamToken;
|
|
354
|
-
setTimeout(() => {
|
|
355
|
-
if (token === this.streamToken && this.onAudioFinished) {
|
|
356
|
-
this.onAudioFinished();
|
|
357
|
-
}
|
|
358
|
-
}, 0);
|
|
359
|
-
return true;
|
|
360
|
-
}
|
|
361
170
|
startPlayback() {
|
|
362
171
|
if (this.playbackInterval) {
|
|
363
172
|
return;
|
|
@@ -399,10 +208,7 @@ export class WaAudioEngine {
|
|
|
399
208
|
return;
|
|
400
209
|
}
|
|
401
210
|
this.silenceMode = false;
|
|
402
|
-
if (this.
|
|
403
|
-
this.extStarted = this.liveWritePos - this.audioPosition >= this.streamPreBufferSize;
|
|
404
|
-
}
|
|
405
|
-
else if (this.externalMode) {
|
|
211
|
+
if (this.externalMode) {
|
|
406
212
|
this.audioPosition = Math.max(0, this.liveWritePos - this.extPreBufferSize);
|
|
407
213
|
const available = this.liveWritePos - this.audioPosition;
|
|
408
214
|
this.extStarted = available >= this.extPreBufferSize;
|
|
@@ -429,7 +235,6 @@ export class WaAudioEngine {
|
|
|
429
235
|
stop() {
|
|
430
236
|
this.stopPlayback();
|
|
431
237
|
this.stopCapture();
|
|
432
|
-
this.stopStream();
|
|
433
238
|
}
|
|
434
239
|
release() {
|
|
435
240
|
this.stop();
|
|
@@ -468,32 +273,19 @@ export class WaAudioEngine {
|
|
|
468
273
|
if (!this.audioBuffer) {
|
|
469
274
|
return this.silenceChunkBuffer;
|
|
470
275
|
}
|
|
471
|
-
if (this.streamMode) {
|
|
472
|
-
this.pumpStream();
|
|
473
|
-
if (this.isStreamFinished()) {
|
|
474
|
-
return this.silenceChunkBuffer;
|
|
475
|
-
}
|
|
476
|
-
}
|
|
477
276
|
const endPos = this.externalMode ? this.liveWritePos : this.audioBuffer.length;
|
|
478
277
|
if (endPos === 0 || (this.audioFinished && !this.externalMode)) {
|
|
479
278
|
return this.silenceChunkBuffer;
|
|
480
279
|
}
|
|
481
280
|
if (this.externalMode) {
|
|
482
281
|
const available = endPos - this.audioPosition;
|
|
483
|
-
const preBuffer = this.streamMode ? this.streamPreBufferSize : this.extPreBufferSize;
|
|
484
282
|
if (!this.extStarted) {
|
|
485
|
-
if (available <
|
|
283
|
+
if (available < this.extPreBufferSize) {
|
|
486
284
|
return this.silenceChunkBuffer;
|
|
487
285
|
}
|
|
488
286
|
this.extStarted = true;
|
|
489
287
|
}
|
|
490
|
-
if (this.
|
|
491
|
-
if (available < this.captureChunkSize && !this.streamEnded) {
|
|
492
|
-
this.extStarted = false;
|
|
493
|
-
return this.silenceChunkBuffer;
|
|
494
|
-
}
|
|
495
|
-
}
|
|
496
|
-
else if (available > this.extHighWater) {
|
|
288
|
+
if (available > this.extHighWater) {
|
|
497
289
|
this.audioPosition = endPos - this.extTargetBuffer;
|
|
498
290
|
}
|
|
499
291
|
if (this.audioPosition >= endPos) {
|