@hiroosy/baileys-lite 0.0.4 → 0.3.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.
- package/LICENSE +21 -0
- package/README.md +658 -10
- package/WAProto/index.js +2 -2558
- package/engine-requirements.js +3 -4
- package/package.json +8 -3
- package/src/binary/wa-binary.js +3 -25
- package/src/constants.js +7 -15
- package/src/defaults.js +2 -5
- package/src/foundation/ai-rich.js +530 -0
- package/src/foundation/audio-duration.js +43 -103
- package/src/foundation/audio-samples.js +19 -37
- package/src/foundation/boom.js +0 -7
- package/src/foundation/cache.js +4 -26
- package/src/foundation/concurrency.js +1 -19
- package/src/foundation/curve25519.js +7 -39
- package/src/foundation/link-preview.js +15 -57
- package/src/foundation/logger.js +0 -11
- package/src/foundation/long.js +4 -14
- package/src/foundation/protobuf-minimal.js +21 -53
- package/src/foundation/qrcode-terminal.js +273 -0
- package/src/foundation/sql-database.js +716 -0
- package/src/foundation/wa-crypto.js +2 -31
- package/src/foundation/zip.js +25 -41
- package/src/index.js +8 -18
- package/src/signal/libsignal.js +23 -78
- package/src/signal/signal-group.js +0 -35
- package/src/signal/signal-repository.js +10 -29
- package/src/socket/business-communities.js +12 -31
- package/src/socket/chats.js +5 -8
- package/src/socket/groups-newsletter.js +18 -17
- package/src/socket/messages-recv.js +81 -127
- package/src/socket/messages-send.js +372 -139
- package/src/socket/socket-core.js +227 -157
- package/src/socket/usync.js +2 -6
- package/src/socket-client/native-websocket.js +344 -0
- package/src/socket-client/websocket-client.js +84 -38
- package/src/utils/auth-state-core.js +14 -56
- package/src/utils/auth-state-storage.js +7 -42
- package/src/utils/chat-sync.js +4 -26
- package/src/utils/media.js +15 -71
- package/src/utils/message-compose.js +208 -85
- package/src/utils/message-processing.js +10 -65
- package/src/utils/username.js +19 -0
- package/src/utils/wa-protocol-core.js +71 -127
- package/src/vendor/jpeg-js/decoder.js +75 -136
- package/src/vendor/jpeg-js/encoder.js +179 -264
- package/src/vendor/pngjs/bitmapper.js +5 -27
- package/src/vendor/pngjs/bitpacker.js +4 -12
- package/src/vendor/pngjs/constants.js +3 -11
- package/src/vendor/pngjs/crc.js +0 -6
- package/src/vendor/pngjs/filter-pack.js +1 -7
- package/src/vendor/pngjs/filter-parse-sync.js +0 -6
- package/src/vendor/pngjs/filter-parse.js +1 -11
- package/src/vendor/pngjs/format-normaliser.js +5 -11
- package/src/vendor/pngjs/interlace.js +7 -24
- package/src/vendor/pngjs/packer-sync.js +0 -11
- package/src/vendor/pngjs/packer.js +7 -15
- package/src/vendor/pngjs/paeth-predictor.js +0 -6
- package/src/vendor/pngjs/parser-sync.js +0 -8
- package/src/vendor/pngjs/parser.js +5 -29
- package/src/vendor/pngjs/png-sync.js +0 -7
- package/src/vendor/pngjs/sync-inflate.js +7 -16
- package/src/vendor/pngjs/sync-reader.js +4 -11
- package/src/voip/WaVoipCoordinator.js +158 -0
- package/src/voip/app-data/WaAppDataStream.js +193 -0
- package/src/voip/app-data/protocol.js +172 -0
- package/src/voip/bytes.js +63 -0
- package/src/voip/call/WaCallManager.js +442 -0
- package/src/voip/call/WaCallMediaSession.js +1705 -0
- package/src/voip/call/call-state.js +203 -0
- package/src/voip/crypto/encryption.js +13 -0
- package/src/voip/crypto/primitives.js +21 -0
- package/src/voip/crypto/rtcp.js +66 -0
- package/src/voip/crypto/srtp.js +180 -0
- package/src/voip/crypto/ssrc.js +15 -0
- package/src/voip/index.js +628 -0
- package/src/voip/media/WaAudioEngine.js +486 -0
- package/src/voip/media/WaVideoEngine.js +275 -0
- package/src/voip/media/audio-codec.js +0 -0
- package/src/voip/media/audio-reorder.js +107 -0
- package/src/voip/media/h264.js +246 -0
- package/src/voip/media/mlow-codec.js +465 -0
- package/src/voip/media/rtcp.js +68 -0
- package/src/voip/media/rtp.js +242 -0
- package/src/voip/protobuf.js +30 -0
- package/src/voip/relay/WaManualRelay.js +609 -0
- package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
- package/src/voip/relay/dtls/aead.js +46 -0
- package/src/voip/relay/dtls/cert-builder.js +102 -0
- package/src/voip/relay/dtls/der.js +98 -0
- package/src/voip/relay/dtls/ecdhe.js +37 -0
- package/src/voip/relay/dtls/handshake-framing.js +100 -0
- package/src/voip/relay/dtls/handshake-messages.js +158 -0
- package/src/voip/relay/dtls/handshake.js +582 -0
- package/src/voip/relay/dtls/prf.js +39 -0
- package/src/voip/relay/dtls/record.js +56 -0
- package/src/voip/relay/relay-ack.js +141 -0
- package/src/voip/relay/sctp/association.js +434 -0
- package/src/voip/relay/sctp/crc32c.js +21 -0
- package/src/voip/relay/sctp/wire.js +226 -0
- package/src/voip/relay/stun.js +463 -0
- package/src/voip/shim/baileys-resolve.js +7 -0
- package/src/voip/shim/core.js +66 -0
- package/src/voip/shim/crypto.js +6 -0
- package/src/voip/shim/proto.js +10 -0
- package/src/voip/shim/protocol.js +130 -0
- package/src/voip/shim/transport.js +82 -0
- package/src/voip/shim/util.js +207 -0
- package/src/voip/signaling/bridge.js +102 -0
- package/src/voip/signaling/screen-share.js +60 -0
- package/src/voip/signaling/signaling.js +491 -0
- package/src/voip/types.js +69 -0
- package/src/voip/voip-deps.js +243 -0
- package/src/voip/voipClient.js +314 -0
- package/src/wam/wam-constants.js +0 -1
- package/src/wam/wam.js +2 -7
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
import { execFile, spawn } from 'node:child_process';
|
|
2
|
+
import { access } from 'node:fs/promises';
|
|
3
|
+
import { createNoopLogger } from '../shim/core.js';
|
|
4
|
+
import { toBytesView, toError } from '../shim/util.js';
|
|
5
|
+
import { TEXT_DECODER } from '../bytes.js';
|
|
6
|
+
import { DEFAULT_VIDEO_CONFIG } from '../types.js';
|
|
7
|
+
import { auHasIDR } from './h264.js';
|
|
8
|
+
const FFMPEG_BIN = 'ffmpeg';
|
|
9
|
+
const MAX_STDERR_CHARS = 16 * 1024;
|
|
10
|
+
|
|
11
|
+
const MAX_PENDING_BYTES = 8 * 1024 * 1024;
|
|
12
|
+
const ffmpegProbeCache = new Map();
|
|
13
|
+
function probeBinary(bin) {
|
|
14
|
+
return new Promise((resolve) => {
|
|
15
|
+
execFile(bin, ['-version'], { timeout: 5_000 }, (err) => resolve(!err));
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
async function hasFfmpeg(bin) {
|
|
19
|
+
let available = ffmpegProbeCache.get(bin);
|
|
20
|
+
if (available === undefined) {
|
|
21
|
+
available = await probeBinary(bin);
|
|
22
|
+
if (available)
|
|
23
|
+
ffmpegProbeCache.set(bin, available);
|
|
24
|
+
}
|
|
25
|
+
return available;
|
|
26
|
+
}
|
|
27
|
+
function startCodeLen(data, offset) {
|
|
28
|
+
if (offset + 3 < data.length &&
|
|
29
|
+
data[offset] === 0 && data[offset + 1] === 0 && data[offset + 2] === 0 && data[offset + 3] === 1) {
|
|
30
|
+
return 4;
|
|
31
|
+
}
|
|
32
|
+
if (offset + 2 < data.length && data[offset] === 0 && data[offset + 1] === 0 && data[offset + 2] === 1) {
|
|
33
|
+
return 3;
|
|
34
|
+
}
|
|
35
|
+
return 0;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function pickH264Level(width, height, frameRate) {
|
|
39
|
+
const mbs = Math.ceil(width / 16) * Math.ceil(height / 16);
|
|
40
|
+
const mbps = mbs * frameRate;
|
|
41
|
+
if (mbs <= 1620 && mbps <= 40500) return '3.0';
|
|
42
|
+
if (mbs <= 3600 && mbps <= 108000) return '3.1';
|
|
43
|
+
if (mbs <= 5120 && mbps <= 216000) return '3.2';
|
|
44
|
+
return '4.0';
|
|
45
|
+
}
|
|
46
|
+
const align16 = (n) => Math.max(16, Math.ceil(n / 16) * 16);
|
|
47
|
+
|
|
48
|
+
export class WaVideoEngine {
|
|
49
|
+
logger;
|
|
50
|
+
videoSender = null;
|
|
51
|
+
proc = null;
|
|
52
|
+
width;
|
|
53
|
+
height;
|
|
54
|
+
frameRate;
|
|
55
|
+
frameDurationMs;
|
|
56
|
+
running = false;
|
|
57
|
+
pending = new Uint8Array(0);
|
|
58
|
+
accessUnitsSent = 0;
|
|
59
|
+
videoPath = null;
|
|
60
|
+
waitingForKeyFrame = true;
|
|
61
|
+
|
|
62
|
+
sourceKind = null;
|
|
63
|
+
constructor(config = {}) {
|
|
64
|
+
const c = { ...DEFAULT_VIDEO_CONFIG, ...config };
|
|
65
|
+
this.logger = config.logger ?? createNoopLogger();
|
|
66
|
+
this.width = c.width;
|
|
67
|
+
this.height = c.height;
|
|
68
|
+
this.frameRate = c.frameRate;
|
|
69
|
+
this.frameDurationMs = 1000 / this.frameRate;
|
|
70
|
+
}
|
|
71
|
+
setVideoSender(sender) {
|
|
72
|
+
this.videoSender = sender;
|
|
73
|
+
}
|
|
74
|
+
isRunning() {
|
|
75
|
+
return this.running;
|
|
76
|
+
}
|
|
77
|
+
hasSource() {
|
|
78
|
+
return this.sourceKind !== null;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async loadVideoFile(videoPath) {
|
|
82
|
+
this.logger.debug('loading video file', { videoPath });
|
|
83
|
+
try {
|
|
84
|
+
await access(videoPath);
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
throw new Error(`File not found: ${videoPath}`);
|
|
88
|
+
}
|
|
89
|
+
if (!(await hasFfmpeg(FFMPEG_BIN))) {
|
|
90
|
+
throw new Error('ffmpeg not found on PATH (install ffmpeg to load video files)');
|
|
91
|
+
}
|
|
92
|
+
this.videoPath = videoPath;
|
|
93
|
+
this.sourceKind = 'file';
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async loadBlankSource() {
|
|
97
|
+
if (!(await hasFfmpeg(FFMPEG_BIN))) {
|
|
98
|
+
throw new Error('ffmpeg not found on PATH (install ffmpeg for the black-screen video fallback)');
|
|
99
|
+
}
|
|
100
|
+
this.sourceKind = 'blank';
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
start() {
|
|
104
|
+
if (!this.sourceKind || this.proc)
|
|
105
|
+
return;
|
|
106
|
+
const outW = align16(this.width);
|
|
107
|
+
const outH = align16(this.height);
|
|
108
|
+
const scaleFilter = `scale=${outW}:${outH}:force_original_aspect_ratio=decrease,pad=${outW}:${outH}:(ow-iw)/2:(oh-ih)/2,setsar=1`;
|
|
109
|
+
|
|
110
|
+
const keyframeIntervalFrames = Math.max(1, Math.round(this.frameRate));
|
|
111
|
+
const kbpsCap = 600;
|
|
112
|
+
const targetBitrateKbps = Math.max(200, Math.min(kbpsCap, Math.round((outW * outH * this.frameRate) / 1000 * 0.08)));
|
|
113
|
+
const bufsizeKbps = Math.max(60, Math.round(targetBitrateKbps * 0.25));
|
|
114
|
+
const level = pickH264Level(outW, outH, this.frameRate);
|
|
115
|
+
const inputArgs = this.sourceKind === 'blank'
|
|
116
|
+
|
|
117
|
+
? ['-f', 'lavfi', '-re', '-i', `color=c=black:s=${outW}x${outH}:r=${this.frameRate}`]
|
|
118
|
+
: ['-stream_loop', '-1', '-re', '-i', this.videoPath];
|
|
119
|
+
|
|
120
|
+
const args = [
|
|
121
|
+
'-hide_banner', '-loglevel', 'error',
|
|
122
|
+
...inputArgs,
|
|
123
|
+
'-an',
|
|
124
|
+
'-vf', scaleFilter,
|
|
125
|
+
'-r', String(this.frameRate),
|
|
126
|
+
'-c:v', 'libx264',
|
|
127
|
+
'-threads', '1',
|
|
128
|
+
'-profile:v', 'baseline',
|
|
129
|
+
'-level', level,
|
|
130
|
+
'-preset', 'veryfast',
|
|
131
|
+
'-tune', 'zerolatency',
|
|
132
|
+
'-pix_fmt', 'yuv420p',
|
|
133
|
+
'-bf', '0',
|
|
134
|
+
'-b:v', `${targetBitrateKbps}k`,
|
|
135
|
+
'-maxrate', `${targetBitrateKbps}k`,
|
|
136
|
+
'-bufsize', `${bufsizeKbps}k`,
|
|
137
|
+
'-x264-params', `aud=1:repeat-headers=1:keyint=${keyframeIntervalFrames}:min-keyint=${keyframeIntervalFrames}:scenecut=0:rc-lookahead=0:sync-lookahead=0:open-gop=0:ref=1`,
|
|
138
|
+
'-f', 'h264',
|
|
139
|
+
'pipe:1'
|
|
140
|
+
];
|
|
141
|
+
const proc = spawn(FFMPEG_BIN, args, { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
142
|
+
this.proc = proc;
|
|
143
|
+
this.pending = new Uint8Array(0);
|
|
144
|
+
this.accessUnitsSent = 0;
|
|
145
|
+
this.waitingForKeyFrame = true;
|
|
146
|
+
this.running = true;
|
|
147
|
+
this._deliberateStop = false;
|
|
148
|
+
this.logger.warn('[DIAG] ffmpeg video process started', {
|
|
149
|
+
pid: proc.pid, frameRate: this.frameRate, width: outW, height: outH, level, bitrateKbps: targetBitrateKbps
|
|
150
|
+
});
|
|
151
|
+
let stderr = '';
|
|
152
|
+
proc.stdout?.on('data', (chunk) => {
|
|
153
|
+
try {
|
|
154
|
+
this.onData(toBytesView(chunk));
|
|
155
|
+
}
|
|
156
|
+
catch (err) {
|
|
157
|
+
this.logger.error('video stream parse error', { message: toError(err).message });
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
proc.stderr?.on('data', (chunk) => {
|
|
161
|
+
stderr = (stderr + TEXT_DECODER.decode(chunk)).slice(-MAX_STDERR_CHARS);
|
|
162
|
+
});
|
|
163
|
+
proc.on('error', (err) => {
|
|
164
|
+
this.logger.error('ffmpeg video process error', { message: err.message });
|
|
165
|
+
this.running = false;
|
|
166
|
+
});
|
|
167
|
+
proc.on('close', (code) => {
|
|
168
|
+
if (this.proc === proc)
|
|
169
|
+
this.proc = null;
|
|
170
|
+
this.running = false;
|
|
171
|
+
if (code !== 0 && code !== null) {
|
|
172
|
+
this.logger.error('ffmpeg video process exited unexpectedly', { code, stderr: stderr.trim() });
|
|
173
|
+
}
|
|
174
|
+
if (!this._deliberateStop && this.sourceKind) {
|
|
175
|
+
const now = Date.now();
|
|
176
|
+
if (!this._restartWindowStartedAt || now - this._restartWindowStartedAt > 60_000) {
|
|
177
|
+
this._restartWindowStartedAt = now;
|
|
178
|
+
this._restartCount = 0;
|
|
179
|
+
}
|
|
180
|
+
this._restartCount = (this._restartCount ?? 0) + 1;
|
|
181
|
+
if (this._restartCount > 5) {
|
|
182
|
+
this.logger.error('video encoder crash-looped, giving up on auto-restart', {
|
|
183
|
+
source: this.sourceKind, videoPath: this.videoPath, restartCount: this._restartCount
|
|
184
|
+
});
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
this.logger.error('restarting video encoder after unexpected exit', {
|
|
188
|
+
source: this.sourceKind, videoPath: this.videoPath, restartCount: this._restartCount
|
|
189
|
+
});
|
|
190
|
+
this.start();
|
|
191
|
+
}
|
|
192
|
+
});
|
|
193
|
+
this.logger.media('video source starting', {
|
|
194
|
+
source: this.sourceKind, videoPath: this.videoPath, width: this.width, height: this.height, fps: this.frameRate
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
onData(chunk) {
|
|
199
|
+
const merged = new Uint8Array(this.pending.length + chunk.length);
|
|
200
|
+
merged.set(this.pending, 0);
|
|
201
|
+
merged.set(chunk, this.pending.length);
|
|
202
|
+
this.pending = merged;
|
|
203
|
+
if (this.pending.length > MAX_PENDING_BYTES) {
|
|
204
|
+
this.logger.debug('video pending buffer exceeded cap without a second AUD, dropping', {
|
|
205
|
+
bytes: this.pending.length
|
|
206
|
+
});
|
|
207
|
+
this.pending = new Uint8Array(0);
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
const audPositions = [];
|
|
211
|
+
let i = 0;
|
|
212
|
+
const data = this.pending;
|
|
213
|
+
while (i < data.length) {
|
|
214
|
+
const sc = startCodeLen(data, i);
|
|
215
|
+
if (sc > 0) {
|
|
216
|
+
const naluStart = i + sc;
|
|
217
|
+
if (naluStart < data.length && (data[naluStart] & 0x1f) === 9) {
|
|
218
|
+
audPositions.push(i);
|
|
219
|
+
}
|
|
220
|
+
i += sc;
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
223
|
+
i++;
|
|
224
|
+
}
|
|
225
|
+
if (audPositions.length < 2)
|
|
226
|
+
return;
|
|
227
|
+
for (let k = 0; k < audPositions.length - 1; k++) {
|
|
228
|
+
const au = data.subarray(audPositions[k], audPositions[k + 1]);
|
|
229
|
+
this.emitAccessUnit(au);
|
|
230
|
+
}
|
|
231
|
+
this.pending = data.slice(audPositions[audPositions.length - 1]);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
emitAccessUnit(au) {
|
|
235
|
+
if (this.waitingForKeyFrame) {
|
|
236
|
+
if (!auHasIDR(au))
|
|
237
|
+
return;
|
|
238
|
+
this.waitingForKeyFrame = false;
|
|
239
|
+
}
|
|
240
|
+
this.accessUnitsSent++;
|
|
241
|
+
if (this.videoSender) {
|
|
242
|
+
try {
|
|
243
|
+
this.videoSender.sendCapturedVideoAU(au, this.frameDurationMs);
|
|
244
|
+
}
|
|
245
|
+
catch (err) {
|
|
246
|
+
this.logger.trace('captured video send failed', { message: toError(err).message });
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
if (this.accessUnitsSent === 1 || this.accessUnitsSent % 300 === 0) {
|
|
250
|
+
this.logger.trace('video access unit emitted', {
|
|
251
|
+
count: this.accessUnitsSent, bytes: au.length
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
stop({ keepSource = false } = {}) {
|
|
257
|
+
this._deliberateStop = true;
|
|
258
|
+
this.running = false;
|
|
259
|
+
if (this.proc) {
|
|
260
|
+
this.logger.warn('[DIAG] ffmpeg video process stopping', { pid: this.proc.pid });
|
|
261
|
+
try {
|
|
262
|
+
this.proc.kill('SIGKILL');
|
|
263
|
+
}
|
|
264
|
+
catch (err) {
|
|
265
|
+
this.logger.trace('ffmpeg video kill failed', { message: toError(err).message });
|
|
266
|
+
}
|
|
267
|
+
this.proc = null;
|
|
268
|
+
}
|
|
269
|
+
this.pending = new Uint8Array(0);
|
|
270
|
+
if (!keepSource) {
|
|
271
|
+
this.videoPath = null;
|
|
272
|
+
this.sourceKind = null;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
Binary file
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
const SEQ_MOD = 0x10000;
|
|
2
|
+
const HALF = 0x8000;
|
|
3
|
+
|
|
4
|
+
function seqDelta(a, b) {
|
|
5
|
+
const d = (b - a) & 0xffff;
|
|
6
|
+
return d >= HALF ? d - SEQ_MOD : d;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export class AudioReorderBuffer {
|
|
10
|
+
#next = -1;
|
|
11
|
+
#pending = new Map();
|
|
12
|
+
#window;
|
|
13
|
+
#maxConcealRun;
|
|
14
|
+
#resyncDistance;
|
|
15
|
+
stats = { duplicates: 0, late: 0, concealed: 0, resyncs: 0, delivered: 0 };
|
|
16
|
+
|
|
17
|
+
constructor({ window = 3, maxConcealRun = 5, resyncDistance = 250 } = {}) {
|
|
18
|
+
this.#window = window;
|
|
19
|
+
this.#maxConcealRun = maxConcealRun;
|
|
20
|
+
this.#resyncDistance = resyncDistance;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
reset() {
|
|
24
|
+
this.#next = -1;
|
|
25
|
+
this.#pending.clear();
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
push(seq, payload) {
|
|
29
|
+
const out = [];
|
|
30
|
+
if (this.#next < 0) {
|
|
31
|
+
this.#next = seq;
|
|
32
|
+
}
|
|
33
|
+
const d = seqDelta(this.#next, seq);
|
|
34
|
+
if (d < 0) {
|
|
35
|
+
if (d < -this.#resyncDistance) {
|
|
36
|
+
this.#resync(seq);
|
|
37
|
+
} else {
|
|
38
|
+
this.stats.late++;
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
} else if (d > this.#resyncDistance) {
|
|
42
|
+
this.#resync(seq);
|
|
43
|
+
}
|
|
44
|
+
if (this.#pending.has(seq)) {
|
|
45
|
+
this.stats.duplicates++;
|
|
46
|
+
return out;
|
|
47
|
+
}
|
|
48
|
+
this.#pending.set(seq, payload);
|
|
49
|
+
this.#drain(out, false);
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
flush() {
|
|
54
|
+
const out = [];
|
|
55
|
+
this.#drain(out, true);
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
#resync(seq) {
|
|
60
|
+
this.stats.resyncs++;
|
|
61
|
+
this.#pending.clear();
|
|
62
|
+
this.#next = seq;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
#drain(out, force) {
|
|
66
|
+
for (;;) {
|
|
67
|
+
if (this.#pending.has(this.#next)) {
|
|
68
|
+
out.push(this.#pending.get(this.#next));
|
|
69
|
+
this.#pending.delete(this.#next);
|
|
70
|
+
this.#next = (this.#next + 1) & 0xffff;
|
|
71
|
+
this.stats.delivered++;
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
if (this.#pending.size === 0) {
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
const farthest = this.#farthestAhead();
|
|
78
|
+
if (!force && farthest < this.#window) {
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
const hole = Math.min(this.#maxConcealRun, this.#holeLength());
|
|
82
|
+
for (let i = 0; i < hole; i++) {
|
|
83
|
+
out.push(null);
|
|
84
|
+
this.stats.concealed++;
|
|
85
|
+
}
|
|
86
|
+
this.#next = (this.#next + this.#holeLength()) & 0xffff;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
#farthestAhead() {
|
|
91
|
+
let max = 0;
|
|
92
|
+
for (const s of this.#pending.keys()) {
|
|
93
|
+
const d = seqDelta(this.#next, s);
|
|
94
|
+
if (d > max) max = d;
|
|
95
|
+
}
|
|
96
|
+
return max;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
#holeLength() {
|
|
100
|
+
let min = Infinity;
|
|
101
|
+
for (const s of this.#pending.keys()) {
|
|
102
|
+
const d = seqDelta(this.#next, s);
|
|
103
|
+
if (d >= 0 && d < min) min = d;
|
|
104
|
+
}
|
|
105
|
+
return min === Infinity ? 0 : min;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
const H264_STAP_A_TYPE = 24;
|
|
2
|
+
const H264_FUA_TYPE = 28;
|
|
3
|
+
const MTU_PAYLOAD_MAX = 800;
|
|
4
|
+
|
|
5
|
+
export function auHasIDR(au) {
|
|
6
|
+
for (const nalu of splitAnnexB(au)) {
|
|
7
|
+
if (nalu.length > 0 && (nalu[0] & 0x1f) === 5) return true;
|
|
8
|
+
}
|
|
9
|
+
return false;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function packageH264NALU(nalu) {
|
|
13
|
+
if (!nalu || nalu.length === 0) return [];
|
|
14
|
+
if (nalu.length <= MTU_PAYLOAD_MAX) {
|
|
15
|
+
return [nalu.slice()];
|
|
16
|
+
}
|
|
17
|
+
const naluHeader = nalu[0];
|
|
18
|
+
const fbitAndNri = naluHeader & 0xe0;
|
|
19
|
+
const originalType = naluHeader & 0x1f;
|
|
20
|
+
const fuIndicator = fbitAndNri | H264_FUA_TYPE;
|
|
21
|
+
|
|
22
|
+
const body = nalu.subarray(1);
|
|
23
|
+
const fragSize = MTU_PAYLOAD_MAX - 2;
|
|
24
|
+
|
|
25
|
+
const out = [];
|
|
26
|
+
let offset = 0;
|
|
27
|
+
while (offset < body.length) {
|
|
28
|
+
const end = Math.min(offset + fragSize, body.length);
|
|
29
|
+
const chunk = body.subarray(offset, end);
|
|
30
|
+
|
|
31
|
+
let fuHeader = originalType;
|
|
32
|
+
if (offset === 0) fuHeader |= 0x80;
|
|
33
|
+
if (end === body.length) fuHeader |= 0x40;
|
|
34
|
+
|
|
35
|
+
const pkt = new Uint8Array(2 + chunk.length);
|
|
36
|
+
pkt[0] = fuIndicator;
|
|
37
|
+
pkt[1] = fuHeader;
|
|
38
|
+
pkt.set(chunk, 2);
|
|
39
|
+
out.push(pkt);
|
|
40
|
+
|
|
41
|
+
offset = end;
|
|
42
|
+
}
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function annexBStartCodeLen(data, offset) {
|
|
47
|
+
if (
|
|
48
|
+
offset + 3 < data.length &&
|
|
49
|
+
data[offset] === 0 &&
|
|
50
|
+
data[offset + 1] === 0 &&
|
|
51
|
+
data[offset + 2] === 0 &&
|
|
52
|
+
data[offset + 3] === 1
|
|
53
|
+
) {
|
|
54
|
+
return 4;
|
|
55
|
+
}
|
|
56
|
+
if (offset + 2 < data.length && data[offset] === 0 && data[offset + 1] === 0 && data[offset + 2] === 1) {
|
|
57
|
+
return 3;
|
|
58
|
+
}
|
|
59
|
+
return 0;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function splitAnnexB(data) {
|
|
63
|
+
const nalus = [];
|
|
64
|
+
let start = -1;
|
|
65
|
+
let i = 0;
|
|
66
|
+
while (i < data.length) {
|
|
67
|
+
const sc = annexBStartCodeLen(data, i);
|
|
68
|
+
if (sc > 0) {
|
|
69
|
+
if (start >= 0) {
|
|
70
|
+
let end = i;
|
|
71
|
+
while (end > start && data[end - 1] === 0) end--;
|
|
72
|
+
if (end > start) nalus.push(data.subarray(start, end));
|
|
73
|
+
}
|
|
74
|
+
i += sc;
|
|
75
|
+
start = i;
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
i++;
|
|
79
|
+
}
|
|
80
|
+
if (start >= 0 && start < data.length) nalus.push(data.subarray(start));
|
|
81
|
+
return nalus;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export const DROP_NAL_TYPES = new Set([6, 9, 10, 11, 12]);
|
|
85
|
+
|
|
86
|
+
export function buildAccessUnitPayload(au) {
|
|
87
|
+
const nalus = splitAnnexB(au);
|
|
88
|
+
const parts = [];
|
|
89
|
+
for (const n of nalus) {
|
|
90
|
+
if (n.length === 0 || DROP_NAL_TYPES.has(n[0] & 0x1f)) continue;
|
|
91
|
+
if (parts.length > 0) parts.push(Uint8Array.of(0, 0, 0, 1));
|
|
92
|
+
parts.push(n);
|
|
93
|
+
}
|
|
94
|
+
if (parts.length === 0) return null;
|
|
95
|
+
let total = 0;
|
|
96
|
+
for (const p of parts) total += p.length;
|
|
97
|
+
const out = new Uint8Array(total);
|
|
98
|
+
let off = 0;
|
|
99
|
+
for (const p of parts) {
|
|
100
|
+
out.set(p, off);
|
|
101
|
+
off += p.length;
|
|
102
|
+
}
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const MAX_FU_REASSEMBLY_BYTES = 4 << 20;
|
|
107
|
+
const MAX_ACCESS_UNIT_BYTES = 8 << 20;
|
|
108
|
+
|
|
109
|
+
export class H264Depacketizer {
|
|
110
|
+
fuBuf = new Uint8Array(0);
|
|
111
|
+
fuActive = false;
|
|
112
|
+
overflow = false;
|
|
113
|
+
|
|
114
|
+
depacketize(payload) {
|
|
115
|
+
if (!payload || payload.length < 1) return [];
|
|
116
|
+
const naluType = payload[0] & 0x1f;
|
|
117
|
+
const fbitAndNri = payload[0] & 0xe0;
|
|
118
|
+
|
|
119
|
+
if (naluType >= 1 && naluType <= 23) {
|
|
120
|
+
this.fuActive = false;
|
|
121
|
+
return [payload.slice()];
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (naluType === H264_STAP_A_TYPE) {
|
|
125
|
+
this.fuActive = false;
|
|
126
|
+
let body = payload.subarray(1);
|
|
127
|
+
const out = [];
|
|
128
|
+
while (body.length >= 2) {
|
|
129
|
+
const size = (body[0] << 8) | body[1];
|
|
130
|
+
body = body.subarray(2);
|
|
131
|
+
if (size <= 0 || size > body.length) return out;
|
|
132
|
+
out.push(body.slice(0, size));
|
|
133
|
+
body = body.subarray(size);
|
|
134
|
+
}
|
|
135
|
+
return out;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
if (naluType === H264_FUA_TYPE) {
|
|
139
|
+
if (payload.length < 2) {
|
|
140
|
+
this.fuActive = false;
|
|
141
|
+
return [];
|
|
142
|
+
}
|
|
143
|
+
const fuHeader = payload[1];
|
|
144
|
+
const startBit = fuHeader & 0x80;
|
|
145
|
+
const endBit = fuHeader & 0x40;
|
|
146
|
+
const origType = fuHeader & 0x1f;
|
|
147
|
+
const body = payload.subarray(2);
|
|
148
|
+
|
|
149
|
+
if (startBit !== 0) {
|
|
150
|
+
if (1 + body.length > MAX_FU_REASSEMBLY_BYTES) {
|
|
151
|
+
this.fuActive = false;
|
|
152
|
+
this.fuBuf = new Uint8Array(0);
|
|
153
|
+
this.overflow = true;
|
|
154
|
+
return [];
|
|
155
|
+
}
|
|
156
|
+
this.fuActive = true;
|
|
157
|
+
this.fuBuf = new Uint8Array(1 + body.length);
|
|
158
|
+
this.fuBuf[0] = fbitAndNri | origType;
|
|
159
|
+
this.fuBuf.set(body, 1);
|
|
160
|
+
} else if (this.fuActive) {
|
|
161
|
+
if (this.fuBuf.length + body.length > MAX_FU_REASSEMBLY_BYTES) {
|
|
162
|
+
this.fuActive = false;
|
|
163
|
+
this.fuBuf = new Uint8Array(0);
|
|
164
|
+
this.overflow = true;
|
|
165
|
+
return [];
|
|
166
|
+
}
|
|
167
|
+
const merged = new Uint8Array(this.fuBuf.length + body.length);
|
|
168
|
+
merged.set(this.fuBuf, 0);
|
|
169
|
+
merged.set(body, this.fuBuf.length);
|
|
170
|
+
this.fuBuf = merged;
|
|
171
|
+
} else {
|
|
172
|
+
return [];
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
if (endBit !== 0 && this.fuActive) {
|
|
176
|
+
this.fuActive = false;
|
|
177
|
+
const out = this.fuBuf;
|
|
178
|
+
this.fuBuf = new Uint8Array(0);
|
|
179
|
+
return [out];
|
|
180
|
+
}
|
|
181
|
+
return [];
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
this.fuActive = false;
|
|
185
|
+
return [];
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export class H264AccessUnitAssembler {
|
|
190
|
+
depacketizer = new H264Depacketizer();
|
|
191
|
+
accessUnit = new Uint8Array(0);
|
|
192
|
+
expectedSeq = 0;
|
|
193
|
+
hasSequence = false;
|
|
194
|
+
keyframeNeeded = false;
|
|
195
|
+
|
|
196
|
+
reset() {
|
|
197
|
+
this.depacketizer = new H264Depacketizer();
|
|
198
|
+
this.accessUnit = new Uint8Array(0);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
push(sequence, marker, payload) {
|
|
202
|
+
let recoveryNeeded = false;
|
|
203
|
+
if (this.hasSequence && sequence !== this.expectedSeq) {
|
|
204
|
+
recoveryNeeded = !this.keyframeNeeded;
|
|
205
|
+
this.reset();
|
|
206
|
+
this.keyframeNeeded = true;
|
|
207
|
+
}
|
|
208
|
+
this.hasSequence = true;
|
|
209
|
+
this.expectedSeq = (sequence + 1) & 0xffff;
|
|
210
|
+
|
|
211
|
+
for (const nalu of this.depacketizer.depacketize(payload)) {
|
|
212
|
+
if (this.accessUnit.length + 4 + nalu.length > MAX_ACCESS_UNIT_BYTES) {
|
|
213
|
+
recoveryNeeded = recoveryNeeded || !this.keyframeNeeded;
|
|
214
|
+
this.reset();
|
|
215
|
+
this.keyframeNeeded = true;
|
|
216
|
+
break;
|
|
217
|
+
}
|
|
218
|
+
const merged = new Uint8Array(this.accessUnit.length + 4 + nalu.length);
|
|
219
|
+
merged.set(this.accessUnit, 0);
|
|
220
|
+
merged.set([0, 0, 0, 1], this.accessUnit.length);
|
|
221
|
+
merged.set(nalu, this.accessUnit.length + 4);
|
|
222
|
+
this.accessUnit = merged;
|
|
223
|
+
}
|
|
224
|
+
if (this.depacketizer.overflow) {
|
|
225
|
+
recoveryNeeded = recoveryNeeded || !this.keyframeNeeded;
|
|
226
|
+
this.reset();
|
|
227
|
+
this.keyframeNeeded = true;
|
|
228
|
+
}
|
|
229
|
+
if (!marker) {
|
|
230
|
+
return [null, false, recoveryNeeded];
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const accessUnit = this.accessUnit;
|
|
234
|
+
this.reset();
|
|
235
|
+
if (accessUnit.length === 0) {
|
|
236
|
+
return [null, false, recoveryNeeded];
|
|
237
|
+
}
|
|
238
|
+
if (this.keyframeNeeded) {
|
|
239
|
+
if (!auHasIDR(accessUnit)) {
|
|
240
|
+
return [null, false, recoveryNeeded];
|
|
241
|
+
}
|
|
242
|
+
this.keyframeNeeded = false;
|
|
243
|
+
}
|
|
244
|
+
return [accessUnit, true, recoveryNeeded];
|
|
245
|
+
}
|
|
246
|
+
}
|