@apocaliss92/nodelink-js 0.4.34 → 0.4.36

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/dist/index.js CHANGED
@@ -67,7 +67,7 @@ import {
67
67
  setEmailPushCameraResolver,
68
68
  setGlobalLogger,
69
69
  xmlIndicatesFloodlight
70
- } from "./chunk-OJ5RWPGY.js";
70
+ } from "./chunk-6ILAHQF5.js";
71
71
  import {
72
72
  ReolinkCgiApi,
73
73
  ReolinkHttpClient,
@@ -8285,6 +8285,946 @@ function base64DecodeToBytes(b64) {
8285
8285
  return out.subarray(0, outIdx);
8286
8286
  }
8287
8287
 
8288
+ // src/reolink/baichuan/utils/imaAdpcm.ts
8289
+ var IMA_INDEX_TABLE = [
8290
+ -1,
8291
+ -1,
8292
+ -1,
8293
+ -1,
8294
+ 2,
8295
+ 4,
8296
+ 6,
8297
+ 8,
8298
+ -1,
8299
+ -1,
8300
+ -1,
8301
+ -1,
8302
+ 2,
8303
+ 4,
8304
+ 6,
8305
+ 8
8306
+ ];
8307
+ var IMA_STEP_TABLE = [
8308
+ 7,
8309
+ 8,
8310
+ 9,
8311
+ 10,
8312
+ 11,
8313
+ 12,
8314
+ 13,
8315
+ 14,
8316
+ 16,
8317
+ 17,
8318
+ 19,
8319
+ 21,
8320
+ 23,
8321
+ 25,
8322
+ 28,
8323
+ 31,
8324
+ 34,
8325
+ 37,
8326
+ 41,
8327
+ 45,
8328
+ 50,
8329
+ 55,
8330
+ 60,
8331
+ 66,
8332
+ 73,
8333
+ 80,
8334
+ 88,
8335
+ 97,
8336
+ 107,
8337
+ 118,
8338
+ 130,
8339
+ 143,
8340
+ 157,
8341
+ 173,
8342
+ 190,
8343
+ 209,
8344
+ 230,
8345
+ 253,
8346
+ 279,
8347
+ 307,
8348
+ 337,
8349
+ 371,
8350
+ 408,
8351
+ 449,
8352
+ 494,
8353
+ 544,
8354
+ 598,
8355
+ 658,
8356
+ 724,
8357
+ 796,
8358
+ 876,
8359
+ 963,
8360
+ 1060,
8361
+ 1166,
8362
+ 1282,
8363
+ 1411,
8364
+ 1552,
8365
+ 1707,
8366
+ 1878,
8367
+ 2066,
8368
+ 2272,
8369
+ 2499,
8370
+ 2749,
8371
+ 3024,
8372
+ 3327,
8373
+ 3660,
8374
+ 4026,
8375
+ 4428,
8376
+ 4871,
8377
+ 5358,
8378
+ 5894,
8379
+ 6484,
8380
+ 7132,
8381
+ 7845,
8382
+ 8630,
8383
+ 9493,
8384
+ 10442,
8385
+ 11487,
8386
+ 12635,
8387
+ 13899,
8388
+ 15289,
8389
+ 16818,
8390
+ 18500,
8391
+ 20350,
8392
+ 22385,
8393
+ 24623,
8394
+ 27086,
8395
+ 29794,
8396
+ 32767
8397
+ ];
8398
+ function clamp16(x) {
8399
+ if (x > 32767) return 32767;
8400
+ if (x < -32768) return -32768;
8401
+ return x | 0;
8402
+ }
8403
+ function encodeImaAdpcm(pcm, blockSizeBytes) {
8404
+ if (pcm.length === 0) return Buffer.alloc(0);
8405
+ if (!Number.isInteger(blockSizeBytes) || blockSizeBytes <= 0) {
8406
+ throw new RangeError(
8407
+ `encodeImaAdpcm: blockSizeBytes must be a positive integer, got ${blockSizeBytes}`
8408
+ );
8409
+ }
8410
+ const samplesPerBlock = blockSizeBytes * 2 + 1;
8411
+ const totalBlocks = Math.ceil(pcm.length / samplesPerBlock);
8412
+ const out = Buffer.alloc(totalBlocks * (4 + blockSizeBytes));
8413
+ let sampleIndex = 0;
8414
+ let outOffset = 0;
8415
+ for (let b = 0; b < totalBlocks; b++) {
8416
+ const blockStart = outOffset;
8417
+ const first = pcm[sampleIndex] ?? 0;
8418
+ let predictor = first;
8419
+ let index = 0;
8420
+ out.writeInt16LE(predictor, blockStart);
8421
+ out.writeUInt8(index, blockStart + 2);
8422
+ out.writeUInt8(0, blockStart + 3);
8423
+ sampleIndex++;
8424
+ const codes = new Uint8Array(blockSizeBytes * 2);
8425
+ for (let i = 0; i < codes.length; i++) {
8426
+ const sample = pcm[sampleIndex] ?? predictor;
8427
+ sampleIndex++;
8428
+ let diff = sample - predictor;
8429
+ let sign = 0;
8430
+ if (diff < 0) {
8431
+ sign = 8;
8432
+ diff = -diff;
8433
+ }
8434
+ let step = IMA_STEP_TABLE[index] ?? 7;
8435
+ let delta = 0;
8436
+ let vpdiff = step >> 3;
8437
+ if (diff >= step) {
8438
+ delta |= 4;
8439
+ diff -= step;
8440
+ vpdiff += step;
8441
+ }
8442
+ step >>= 1;
8443
+ if (diff >= step) {
8444
+ delta |= 2;
8445
+ diff -= step;
8446
+ vpdiff += step;
8447
+ }
8448
+ step >>= 1;
8449
+ if (diff >= step) {
8450
+ delta |= 1;
8451
+ vpdiff += step;
8452
+ }
8453
+ predictor = clamp16(sign ? predictor - vpdiff : predictor + vpdiff);
8454
+ index += IMA_INDEX_TABLE[delta] ?? 0;
8455
+ if (index < 0) index = 0;
8456
+ if (index > 88) index = 88;
8457
+ codes[i] = (delta | sign) & 15;
8458
+ }
8459
+ for (let i = 0; i < blockSizeBytes; i++) {
8460
+ const lo = codes[i * 2] ?? 0;
8461
+ const hi = codes[i * 2 + 1] ?? 0;
8462
+ out[blockStart + 4 + i] = lo & 15 | (hi & 15) << 4;
8463
+ }
8464
+ outOffset += 4 + blockSizeBytes;
8465
+ }
8466
+ return out;
8467
+ }
8468
+
8469
+ // src/reolink/baichuan/utils/audioMulaw.ts
8470
+ import { mulaw, alaw } from "alawmulaw";
8471
+ function mulawToPcm16(bytes) {
8472
+ if (bytes.length === 0) return new Int16Array(0);
8473
+ return mulaw.decode(bytes);
8474
+ }
8475
+ function alawToPcm16(bytes) {
8476
+ if (bytes.length === 0) return new Int16Array(0);
8477
+ return alaw.decode(bytes);
8478
+ }
8479
+
8480
+ // src/reolink/baichuan/utils/audioResample.ts
8481
+ function clamp162(x) {
8482
+ if (x > 32767) return 32767;
8483
+ if (x < -32768) return -32768;
8484
+ return x | 0;
8485
+ }
8486
+ function upsamplePcm16(src, factor) {
8487
+ if (!Number.isInteger(factor) || factor < 1) {
8488
+ throw new RangeError(
8489
+ `upsamplePcm16: factor must be a positive integer, got ${factor}`
8490
+ );
8491
+ }
8492
+ if (src.length === 0) return new Int16Array(0);
8493
+ if (factor === 1) return Int16Array.from(src);
8494
+ const out = new Int16Array(src.length * factor);
8495
+ const last = src.length - 1;
8496
+ for (let i = 0; i < last; i++) {
8497
+ const a = src[i];
8498
+ const b = src[i + 1];
8499
+ const base = i * factor;
8500
+ for (let k = 0; k < factor; k++) {
8501
+ const v = a + Math.round((b - a) * k / factor);
8502
+ out[base + k] = clamp162(v);
8503
+ }
8504
+ }
8505
+ const tail = src[last] | 0;
8506
+ for (let k = 0; k < factor; k++) {
8507
+ out[last * factor + k] = tail;
8508
+ }
8509
+ return out;
8510
+ }
8511
+
8512
+ // src/baichuan/stream/RtspBackchannel.ts
8513
+ var RTP_PT_PCMA = 8;
8514
+ var RTP_FIXED_HEADER_BYTES = 12;
8515
+ var G711_SOURCE_RATE_HZ = 8e3;
8516
+ var TALK_TARGET_RATE_HZ = 16e3;
8517
+ function parseRtpPacket(packet) {
8518
+ if (packet.length < RTP_FIXED_HEADER_BYTES) return null;
8519
+ const b0 = packet.readUInt8(0);
8520
+ const version = b0 >> 6;
8521
+ if (version !== 2) return null;
8522
+ const padding = (b0 & 32) !== 0;
8523
+ const extension = (b0 & 16) !== 0;
8524
+ const csrcCount = b0 & 15;
8525
+ const b1 = packet.readUInt8(1);
8526
+ const payloadType = b1 & 127;
8527
+ let offset = RTP_FIXED_HEADER_BYTES + csrcCount * 4;
8528
+ if (offset > packet.length) return null;
8529
+ if (extension) {
8530
+ if (offset + 4 > packet.length) return null;
8531
+ const extensionLengthWords = packet.readUInt16BE(offset + 2);
8532
+ offset += 4 + extensionLengthWords * 4;
8533
+ if (offset > packet.length) return null;
8534
+ }
8535
+ let end = packet.length;
8536
+ if (padding) {
8537
+ if (end - offset < 1) return null;
8538
+ const padLength = packet.readUInt8(end - 1);
8539
+ if (padLength < 1 || padLength > end - offset) return null;
8540
+ end -= padLength;
8541
+ }
8542
+ if (end <= offset) return null;
8543
+ return {
8544
+ payloadType,
8545
+ payload: packet.subarray(offset, end)
8546
+ };
8547
+ }
8548
+ var RtspBackchannel = class _RtspBackchannel {
8549
+ constructor(opts) {
8550
+ this.opts = opts;
8551
+ }
8552
+ session = void 0;
8553
+ pcmTail = new Int16Array(0);
8554
+ // residual samples below one full ADPCM block
8555
+ pcmBacklogBytes = 0;
8556
+ pumping = false;
8557
+ active = false;
8558
+ starting = void 0;
8559
+ stopping = void 0;
8560
+ lastBacklogClampLogMs = 0;
8561
+ rtpPacketsReceived = 0;
8562
+ rtpPacketsDropped = 0;
8563
+ adpcmBlocksSent = 0;
8564
+ /** Lazily-set on the first decoded RTP packet so we log the negotiated codec exactly once. */
8565
+ observedCodec = void 0;
8566
+ /** Sampled every `STATS_LOG_INTERVAL_MS` while audio flows. */
8567
+ lastStatsLogMs = 0;
8568
+ lastStatsAdpcmBlocks = 0;
8569
+ lastStatsRtpPackets = 0;
8570
+ startedAtMs = 0;
8571
+ static STATS_LOG_INTERVAL_MS = 5e3;
8572
+ get isActive() {
8573
+ return this.active;
8574
+ }
8575
+ get stats() {
8576
+ return {
8577
+ rtpPacketsReceived: this.rtpPacketsReceived,
8578
+ rtpPacketsDropped: this.rtpPacketsDropped,
8579
+ adpcmBlocksSent: this.adpcmBlocksSent
8580
+ };
8581
+ }
8582
+ /** Open the underlying TalkSession. Safe to call concurrently; resolves to the same session. */
8583
+ async start() {
8584
+ if (this.session) return this.session;
8585
+ if (!this.starting) {
8586
+ const openStart = Date.now();
8587
+ this.opts.logger?.log?.(
8588
+ `[RtspBackchannel] opening TalkSession on camera\u2026`
8589
+ );
8590
+ this.starting = (async () => {
8591
+ const s = await this.opts.openTalkSession();
8592
+ this.session = s;
8593
+ this.active = true;
8594
+ this.startedAtMs = Date.now();
8595
+ this.lastStatsLogMs = this.startedAtMs;
8596
+ this.opts.logger?.log?.(
8597
+ `[RtspBackchannel] TalkSession opened channel=${s.info.channel} block=${s.info.blockSize} fullBlock=${s.info.fullBlockSize} audioType=${s.info.audioConfig.audioType} sampleRate=${s.info.audioConfig.sampleRate} samplePrecision=${s.info.audioConfig.samplePrecision} soundTrack=${s.info.audioConfig.soundTrack} openMs=${Date.now() - openStart}`
8598
+ );
8599
+ return s;
8600
+ })().catch((e) => {
8601
+ this.starting = void 0;
8602
+ this.opts.logger?.log?.(
8603
+ `[RtspBackchannel] TalkSession open FAILED openMs=${Date.now() - openStart} error="${e.message}"`
8604
+ );
8605
+ throw e;
8606
+ });
8607
+ }
8608
+ return this.starting;
8609
+ }
8610
+ /**
8611
+ * Feed one inbound RTP packet (as carried in TCP-interleaved framing or UDP
8612
+ * datagram). Discards malformed packets and packets received before `start()`.
8613
+ * The actual audio dispatch to the TalkSession is awaited internally; callers
8614
+ * may fire-and-forget.
8615
+ */
8616
+ feedRtp(packet) {
8617
+ this.rtpPacketsReceived++;
8618
+ if (!this.active || !this.session) {
8619
+ this.rtpPacketsDropped++;
8620
+ if (this.rtpPacketsDropped === 1) {
8621
+ this.opts.logger?.log?.(
8622
+ `[RtspBackchannel] dropping RTP packets \u2014 session not active yet (received ${packet.length}B before start())`
8623
+ );
8624
+ }
8625
+ return;
8626
+ }
8627
+ const parsed = parseRtpPacket(packet);
8628
+ if (!parsed) {
8629
+ this.rtpPacketsDropped++;
8630
+ this.opts.logger?.log?.(
8631
+ `[RtspBackchannel] malformed RTP packet \u2014 dropping (len=${packet.length} firstByte=0x${packet.length ? (packet[0] ?? 0).toString(16) : "??"})`
8632
+ );
8633
+ return;
8634
+ }
8635
+ const codec = this.opts.forceCodec ?? (parsed.payloadType === RTP_PT_PCMA ? "pcma" : "pcmu");
8636
+ if (this.observedCodec === void 0) {
8637
+ this.observedCodec = codec;
8638
+ const firstPacketMs = Date.now() - this.startedAtMs;
8639
+ this.opts.logger?.log?.(
8640
+ `[RtspBackchannel] first RTP packet \u2014 codec=${codec} payloadType=${parsed.payloadType} payload=${parsed.payload.length}B firstByteMs=${firstPacketMs}` + (this.opts.forceCodec ? " (forced by config)" : "")
8641
+ );
8642
+ } else if (codec !== this.observedCodec) {
8643
+ this.opts.logger?.log?.(
8644
+ `[RtspBackchannel] codec switched mid-stream ${this.observedCodec} \u2192 ${codec} (payloadType=${parsed.payloadType})`
8645
+ );
8646
+ this.observedCodec = codec;
8647
+ }
8648
+ const decoded = codec === "pcma" ? alawToPcm16(parsed.payload) : mulawToPcm16(parsed.payload);
8649
+ if (decoded.length === 0) return;
8650
+ const upsampled = upsamplePcm16(decoded, TALK_TARGET_RATE_HZ / G711_SOURCE_RATE_HZ);
8651
+ this.enqueuePcm(upsampled);
8652
+ this.maybeLogStats();
8653
+ }
8654
+ /**
8655
+ * Throttled progress log (~every 5s while audio is flowing) so operators
8656
+ * can confirm the pipeline is making progress without per-packet noise.
8657
+ */
8658
+ maybeLogStats() {
8659
+ const now = Date.now();
8660
+ if (now - this.lastStatsLogMs < _RtspBackchannel.STATS_LOG_INTERVAL_MS) return;
8661
+ const elapsedSec = (now - this.lastStatsLogMs) / 1e3;
8662
+ const rtpDelta = this.rtpPacketsReceived - this.lastStatsRtpPackets;
8663
+ const adpcmDelta = this.adpcmBlocksSent - this.lastStatsAdpcmBlocks;
8664
+ this.lastStatsLogMs = now;
8665
+ this.lastStatsRtpPackets = this.rtpPacketsReceived;
8666
+ this.lastStatsAdpcmBlocks = this.adpcmBlocksSent;
8667
+ this.opts.logger?.log?.(
8668
+ `[RtspBackchannel] stats codec=${this.observedCodec ?? "?"} rtpRx=${this.rtpPacketsReceived} (+${rtpDelta} in ${elapsedSec.toFixed(1)}s) dropped=${this.rtpPacketsDropped} adpcmBlocks=${this.adpcmBlocksSent} (+${adpcmDelta}) pcmBacklog=${this.pcmBacklogBytes}B`
8669
+ );
8670
+ }
8671
+ /** Flush remaining audio and stop the talk session. Idempotent. */
8672
+ async stop() {
8673
+ if (this.stopping) return this.stopping;
8674
+ this.active = false;
8675
+ this.stopping = (async () => {
8676
+ const s = this.session;
8677
+ this.session = void 0;
8678
+ this.pcmTail = new Int16Array(0);
8679
+ this.pcmBacklogBytes = 0;
8680
+ const durationMs = this.startedAtMs ? Date.now() - this.startedAtMs : 0;
8681
+ this.opts.logger?.log?.(
8682
+ `[RtspBackchannel] closing TalkSession durationMs=${durationMs} rtpRx=${this.rtpPacketsReceived} rtpDropped=${this.rtpPacketsDropped} adpcmBlocks=${this.adpcmBlocksSent} pcmBacklogResidual=${this.pcmBacklogBytes}B codec=${this.observedCodec ?? "(none)"}`
8683
+ );
8684
+ if (s) {
8685
+ try {
8686
+ await s.stop();
8687
+ } catch (e) {
8688
+ this.opts.logger?.log?.(
8689
+ `[RtspBackchannel] TalkSession stop error: ${e.message}`
8690
+ );
8691
+ }
8692
+ }
8693
+ })();
8694
+ return this.stopping;
8695
+ }
8696
+ enqueuePcm(chunk) {
8697
+ if (chunk.length === 0) return;
8698
+ const tailLen = this.pcmTail.length;
8699
+ const merged = new Int16Array(tailLen + chunk.length);
8700
+ merged.set(this.pcmTail, 0);
8701
+ merged.set(chunk, tailLen);
8702
+ this.pcmBacklogBytes = merged.length * 2;
8703
+ const maxBytes = Math.max(2, this.opts.maxPcmBacklogBytes ?? 96e3);
8704
+ if (this.pcmBacklogBytes > maxBytes) {
8705
+ const keepSamples = Math.floor(maxBytes / 2);
8706
+ const dropSamples = merged.length - keepSamples;
8707
+ this.pcmTail = merged.subarray(merged.length - keepSamples);
8708
+ this.pcmBacklogBytes = this.pcmTail.length * 2;
8709
+ const now = Date.now();
8710
+ if (now - this.lastBacklogClampLogMs > 2e3) {
8711
+ this.lastBacklogClampLogMs = now;
8712
+ this.opts.logger?.log?.(
8713
+ `[RtspBackchannel] PCM backlog clamped \u2014 dropped ${dropSamples} samples, kept ${keepSamples}`
8714
+ );
8715
+ }
8716
+ } else {
8717
+ this.pcmTail = merged;
8718
+ }
8719
+ void this.pumpAdpcm();
8720
+ }
8721
+ async pumpAdpcm() {
8722
+ if (this.pumping) return;
8723
+ const session = this.session;
8724
+ if (!session) return;
8725
+ this.pumping = true;
8726
+ try {
8727
+ const samplesPerBlock = session.info.blockSize * 2 + 1;
8728
+ const blockSizeBytes = session.info.blockSize;
8729
+ while (this.active && this.pcmTail.length >= samplesPerBlock) {
8730
+ const consumeSamples = Math.floor(this.pcmTail.length / samplesPerBlock) * samplesPerBlock;
8731
+ const head = this.pcmTail.subarray(0, consumeSamples);
8732
+ const adpcm = encodeImaAdpcm(head, blockSizeBytes);
8733
+ const blocksInBatch = consumeSamples / samplesPerBlock;
8734
+ this.pcmTail = this.pcmTail.slice(consumeSamples);
8735
+ this.pcmBacklogBytes = this.pcmTail.length * 2;
8736
+ try {
8737
+ await session.sendAudio(adpcm);
8738
+ this.adpcmBlocksSent += blocksInBatch;
8739
+ } catch (e) {
8740
+ this.opts.logger?.log?.(
8741
+ `[RtspBackchannel] sendAudio FAILED \u2014 disabling pipeline blocksInBatch=${blocksInBatch} adpcmBytes=${adpcm.length} pcmBacklogBefore=${this.pcmBacklogBytes + adpcm.length}B error="${e.message}"`
8742
+ );
8743
+ this.pcmTail = new Int16Array(0);
8744
+ this.pcmBacklogBytes = 0;
8745
+ this.active = false;
8746
+ break;
8747
+ }
8748
+ }
8749
+ } finally {
8750
+ this.pumping = false;
8751
+ }
8752
+ }
8753
+ };
8754
+
8755
+ // src/baichuan/stream/BaichuanRtspBackchannelServer.ts
8756
+ import { EventEmitter as EventEmitter10 } from "events";
8757
+ import * as net3 from "net";
8758
+ import * as crypto2 from "crypto";
8759
+ var md5Hex = (s) => crypto2.createHash("md5").update(s).digest("hex");
8760
+ var BaichuanRtspBackchannelServer = class _BaichuanRtspBackchannelServer extends EventEmitter10 {
8761
+ api;
8762
+ channel;
8763
+ listenHost;
8764
+ listenPort;
8765
+ path;
8766
+ logger;
8767
+ authCredentials;
8768
+ requireAuth;
8769
+ authRealm;
8770
+ deviceId;
8771
+ server = void 0;
8772
+ /** Active backchannel sessions keyed by their per-client unique id. */
8773
+ sessionByClient = /* @__PURE__ */ new Map();
8774
+ nonces = /* @__PURE__ */ new Map();
8775
+ static NONCE_TTL_MS = 5 * 60 * 1e3;
8776
+ constructor(options) {
8777
+ super();
8778
+ this.api = options.api;
8779
+ this.channel = options.channel;
8780
+ this.listenHost = options.listenHost ?? "127.0.0.1";
8781
+ this.listenPort = options.listenPort ?? 8555;
8782
+ this.path = options.path ?? "/talk";
8783
+ this.logger = options.logger ?? console;
8784
+ this.authCredentials = (options.credentials ?? []).map((c) => ({
8785
+ username: c.username,
8786
+ ...c.password !== void 0 ? { password: c.password } : {},
8787
+ ...c.ha1 !== void 0 ? { ha1: c.ha1 } : {}
8788
+ }));
8789
+ this.requireAuth = options.requireAuth ?? this.authCredentials.length > 0;
8790
+ this.authRealm = options.authRealm ?? "BaichuanRtspBackchannelServer";
8791
+ this.deviceId = options.deviceId;
8792
+ }
8793
+ get listening() {
8794
+ return this.server !== void 0 && this.server.listening;
8795
+ }
8796
+ async start() {
8797
+ if (this.server) return;
8798
+ await new Promise((resolve, reject) => {
8799
+ const server = net3.createServer((socket) => this.handleConnection(socket));
8800
+ const onError = (err) => {
8801
+ server.removeListener("error", onError);
8802
+ reject(err);
8803
+ };
8804
+ server.once("error", onError);
8805
+ server.listen(this.listenPort, this.listenHost, () => {
8806
+ server.removeListener("error", onError);
8807
+ this.server = server;
8808
+ this.logger.info?.(
8809
+ `[BaichuanRtspBackchannelServer] listening on ${this.listenHost}:${this.listenPort} path=${this.path}`
8810
+ );
8811
+ resolve();
8812
+ });
8813
+ });
8814
+ }
8815
+ async stop() {
8816
+ const server = this.server;
8817
+ this.server = void 0;
8818
+ for (const session of this.sessionByClient.values()) {
8819
+ this.sessionByClient.delete(session.clientId);
8820
+ if (session.handler) {
8821
+ void session.handler.stop();
8822
+ }
8823
+ try {
8824
+ session.socket.destroy();
8825
+ } catch {
8826
+ }
8827
+ }
8828
+ if (!server) return;
8829
+ await new Promise((resolve) => {
8830
+ server.close(() => resolve());
8831
+ });
8832
+ }
8833
+ handleConnection(socket) {
8834
+ const clientId = `${socket.remoteAddress}:${socket.remotePort}`;
8835
+ const connectedAt = Date.now();
8836
+ let buffer = Buffer.alloc(0);
8837
+ this.logger.info?.(
8838
+ `[BaichuanRtspBackchannelServer] client connected client=${clientId} path=${this.path}`
8839
+ );
8840
+ this.emit("client", clientId);
8841
+ const cleanup = () => {
8842
+ const session = this.sessionByClient.get(clientId);
8843
+ const durationMs = Date.now() - connectedAt;
8844
+ if (session) {
8845
+ this.sessionByClient.delete(clientId);
8846
+ if (session.handler) {
8847
+ const stats = session.handler.stats;
8848
+ this.logger.info?.(
8849
+ `[BaichuanRtspBackchannelServer] client disconnected client=${clientId} session=${session.sessionId} duration=${durationMs}ms rtpRx=${stats.rtpPacketsReceived} rtpDropped=${stats.rtpPacketsDropped} adpcmBlocks=${stats.adpcmBlocksSent}`
8850
+ );
8851
+ void session.handler.stop();
8852
+ } else {
8853
+ this.logger.info?.(
8854
+ `[BaichuanRtspBackchannelServer] client disconnected client=${clientId} session=${session.sessionId} duration=${durationMs}ms (no RECORD)`
8855
+ );
8856
+ }
8857
+ } else {
8858
+ this.logger.info?.(
8859
+ `[BaichuanRtspBackchannelServer] client disconnected client=${clientId} duration=${durationMs}ms (no SETUP)`
8860
+ );
8861
+ }
8862
+ this.nonces.delete(clientId);
8863
+ this.emit("clientDisconnected", clientId);
8864
+ };
8865
+ socket.on("close", cleanup);
8866
+ socket.on("error", (err) => {
8867
+ this.logger.warn?.(
8868
+ `[BaichuanRtspBackchannelServer] socket error client=${clientId}: ${err.message}`
8869
+ );
8870
+ cleanup();
8871
+ });
8872
+ socket.on("data", (data) => {
8873
+ buffer = Buffer.concat([buffer, data]);
8874
+ this.drainBuffer(socket, clientId, (b) => {
8875
+ buffer = b;
8876
+ }, () => buffer);
8877
+ });
8878
+ }
8879
+ /**
8880
+ * Drain pending bytes from the per-client buffer. Each iteration first
8881
+ * peels off any TCP-interleaved `$` frames at the head (routing them to
8882
+ * the session's RtspBackchannel handler when their channel matches) and
8883
+ * then attempts to parse a complete RTSP request.
8884
+ *
8885
+ * Implemented as a thin loop so the parser can yield back to the event
8886
+ * loop when the buffer is partial — no async work between frames keeps
8887
+ * the data path tight.
8888
+ */
8889
+ drainBuffer(socket, clientId, setBuffer, getBuffer) {
8890
+ const tryDrainInterleaved = () => {
8891
+ let consumed = false;
8892
+ while (true) {
8893
+ const buf = getBuffer();
8894
+ if (buf.length === 0 || buf[0] !== 36) return consumed;
8895
+ if (buf.length < 4) return consumed;
8896
+ const channel = buf[1] ?? 0;
8897
+ const len = buf.readUInt16BE(2);
8898
+ if (buf.length < 4 + len) return consumed;
8899
+ const rtpPacket = buf.subarray(4, 4 + len);
8900
+ setBuffer(buf.subarray(4 + len));
8901
+ consumed = true;
8902
+ const session = this.sessionByClient.get(clientId);
8903
+ if (session && session.rtpChannel === channel && session.handler) {
8904
+ session.handler.feedRtp(Buffer.from(rtpPacket));
8905
+ }
8906
+ }
8907
+ };
8908
+ void (async () => {
8909
+ while (true) {
8910
+ tryDrainInterleaved();
8911
+ const buf = getBuffer();
8912
+ if (buf.length === 0) return;
8913
+ if (buf[0] === 36) return;
8914
+ const headerEnd = buf.indexOf("\r\n\r\n");
8915
+ if (headerEnd < 0) return;
8916
+ const requestText = buf.subarray(0, headerEnd).toString("utf8");
8917
+ setBuffer(buf.subarray(headerEnd + 4));
8918
+ try {
8919
+ await this.handleRequest(socket, clientId, requestText);
8920
+ } catch (e) {
8921
+ this.logger.warn?.(
8922
+ `[BaichuanRtspBackchannelServer] handleRequest failed for ${clientId}: ${e.message}`
8923
+ );
8924
+ try {
8925
+ socket.destroy();
8926
+ } catch {
8927
+ }
8928
+ return;
8929
+ }
8930
+ }
8931
+ })();
8932
+ }
8933
+ async handleRequest(socket, clientId, requestText) {
8934
+ const lines = requestText.split("\r\n");
8935
+ const head = lines[0]?.split(" ") ?? [];
8936
+ if (head.length < 3) {
8937
+ this.logger.warn?.(
8938
+ `[BaichuanRtspBackchannelServer] malformed request from ${clientId}: "${(lines[0] ?? "").slice(0, 120)}"`
8939
+ );
8940
+ return;
8941
+ }
8942
+ const method = head[0] ?? "";
8943
+ const url = head[1] ?? "";
8944
+ const protocol = head[2] ?? "RTSP/1.0";
8945
+ const cseqMatch = requestText.match(/CSeq:\s*(\d+)/i);
8946
+ const cseq = cseqMatch ? parseInt(cseqMatch[1] ?? "0", 10) : 0;
8947
+ const sessionMatch = requestText.match(/Session:\s*([^;\r\n]+)/i);
8948
+ let sessionId = sessionMatch?.[1]?.trim();
8949
+ const userAgent = requestText.match(/User-Agent:\s*([^\r\n]+)/i)?.[1]?.trim();
8950
+ this.logger.info?.(
8951
+ `[BaichuanRtspBackchannelServer] >> ${method} ${url} client=${clientId} cseq=${cseq}` + (sessionId ? ` session=${sessionId}` : "") + (userAgent ? ` ua="${userAgent}"` : "")
8952
+ );
8953
+ const send = (status, reason, headers = {}, body) => {
8954
+ let r = `${protocol} ${status} ${reason}\r
8955
+ CSeq: ${cseq}\r
8956
+ `;
8957
+ for (const [k, v] of Object.entries(headers)) {
8958
+ r += `${k}: ${v}\r
8959
+ `;
8960
+ }
8961
+ if (body) {
8962
+ const buf = Buffer.from(body, "utf8");
8963
+ r += `Content-Length: ${buf.length}\r
8964
+ \r
8965
+ `;
8966
+ socket.write(r);
8967
+ socket.write(buf);
8968
+ } else {
8969
+ r += "\r\n";
8970
+ socket.write(r);
8971
+ }
8972
+ const headerSummary = Object.entries(headers).map(([k, v]) => `${k}=${v}`).join(", ");
8973
+ this.logger.info?.(
8974
+ `[BaichuanRtspBackchannelServer] << ${status} ${reason} client=${clientId} cseq=${cseq}` + (headerSummary ? ` [${headerSummary}]` : "") + (body ? ` body=${body.length}B` : "")
8975
+ );
8976
+ };
8977
+ if (this.requireAuth && method !== "OPTIONS") {
8978
+ const authHeader = requestText.match(/Authorization:\s*([^\r\n]+)/i)?.[1] ?? "";
8979
+ if (!authHeader) {
8980
+ this.logger.info?.(
8981
+ `[BaichuanRtspBackchannelServer] auth challenge issued client=${clientId} method=${method}`
8982
+ );
8983
+ send(401, "Unauthorized", {
8984
+ "WWW-Authenticate": this.wwwAuthenticate(clientId)
8985
+ });
8986
+ return;
8987
+ }
8988
+ if (!this.validateDigest(authHeader, method, url, clientId)) {
8989
+ this.logger.warn?.(
8990
+ `[BaichuanRtspBackchannelServer] auth rejected client=${clientId} method=${method}`
8991
+ );
8992
+ this.nonces.delete(clientId);
8993
+ send(401, "Unauthorized", {
8994
+ "WWW-Authenticate": this.wwwAuthenticate(clientId)
8995
+ });
8996
+ return;
8997
+ }
8998
+ }
8999
+ switch (method) {
9000
+ case "OPTIONS":
9001
+ send(200, "OK", {
9002
+ Public: "OPTIONS, DESCRIBE, SETUP, RECORD, TEARDOWN"
9003
+ });
9004
+ return;
9005
+ case "DESCRIBE": {
9006
+ const sdp = this.buildSdp();
9007
+ this.logger.debug?.(
9008
+ `[BaichuanRtspBackchannelServer] DESCRIBE sdp for ${clientId}:
9009
+ ${sdp.trimEnd()}`
9010
+ );
9011
+ send(
9012
+ 200,
9013
+ "OK",
9014
+ {
9015
+ "Content-Type": "application/sdp",
9016
+ "Content-Base": `rtsp://${this.listenHost}:${this.listenPort}${this.path}/`
9017
+ },
9018
+ sdp
9019
+ );
9020
+ return;
9021
+ }
9022
+ case "SETUP": {
9023
+ if (!url.includes("audiobackchannel")) {
9024
+ this.logger.warn?.(
9025
+ `[BaichuanRtspBackchannelServer] SETUP rejected (unknown track) client=${clientId} url=${url}`
9026
+ );
9027
+ send(404, "Not Found");
9028
+ return;
9029
+ }
9030
+ const transportLine = requestText.match(/Transport:\s*([^\r\n]+)/i)?.[1] ?? "";
9031
+ this.logger.info?.(
9032
+ `[BaichuanRtspBackchannelServer] SETUP transport="${transportLine}" client=${clientId}`
9033
+ );
9034
+ if (!transportLine.toUpperCase().includes("RTP/AVP/TCP") && !transportLine.toLowerCase().includes("interleaved")) {
9035
+ this.logger.warn?.(
9036
+ `[BaichuanRtspBackchannelServer] SETUP rejected (non-TCP transport) client=${clientId}`
9037
+ );
9038
+ send(461, "Unsupported Transport");
9039
+ return;
9040
+ }
9041
+ const interleaved = parseInterleavedChannels(transportLine) ?? {
9042
+ rtp: 0,
9043
+ rtcp: 1
9044
+ };
9045
+ if (!sessionId) {
9046
+ sessionId = newSessionId();
9047
+ }
9048
+ this.sessionByClient.set(clientId, {
9049
+ sessionId,
9050
+ clientId,
9051
+ socket,
9052
+ rtpChannel: interleaved.rtp,
9053
+ rtcpChannel: interleaved.rtcp
9054
+ });
9055
+ this.logger.info?.(
9056
+ `[BaichuanRtspBackchannelServer] SETUP ok client=${clientId} session=${sessionId} interleaved=${interleaved.rtp}-${interleaved.rtcp}`
9057
+ );
9058
+ send(200, "OK", {
9059
+ Transport: `RTP/AVP/TCP;unicast;interleaved=${interleaved.rtp}-${interleaved.rtcp};mode=record`,
9060
+ Session: sessionId
9061
+ });
9062
+ return;
9063
+ }
9064
+ case "RECORD": {
9065
+ const session = sessionId ? Array.from(this.sessionByClient.values()).find(
9066
+ (s) => s.sessionId === sessionId
9067
+ ) : this.sessionByClient.get(clientId);
9068
+ if (!session) {
9069
+ this.logger.warn?.(
9070
+ `[BaichuanRtspBackchannelServer] RECORD without active session client=${clientId} requestedSession=${sessionId ?? "(none)"}`
9071
+ );
9072
+ send(454, "Session Not Found");
9073
+ return;
9074
+ }
9075
+ if (session.handler) {
9076
+ this.logger.info?.(
9077
+ `[BaichuanRtspBackchannelServer] RECORD idempotent (already recording) client=${clientId} session=${session.sessionId}`
9078
+ );
9079
+ send(200, "OK", { Session: session.sessionId });
9080
+ return;
9081
+ }
9082
+ const apiRef = this.api;
9083
+ const channelForCamera = this.channel;
9084
+ const loggerRef = this.logger;
9085
+ const deviceIdRef = this.deviceId ?? `rtsp-backchannel-${clientId}`;
9086
+ const handler = new RtspBackchannel({
9087
+ openTalkSession: () => apiRef.createDedicatedTalkSession(channelForCamera, {
9088
+ deviceId: deviceIdRef,
9089
+ logger: loggerRef
9090
+ }),
9091
+ logger: loggerRef
9092
+ });
9093
+ const recordStart = Date.now();
9094
+ this.logger.info?.(
9095
+ `[BaichuanRtspBackchannelServer] RECORD opening TalkSession client=${clientId} session=${session.sessionId} channel=${channelForCamera} deviceId="${deviceIdRef}"`
9096
+ );
9097
+ try {
9098
+ const talk = await handler.start();
9099
+ this.logger.info?.(
9100
+ `[BaichuanRtspBackchannelServer] RECORD talk session ready client=${clientId} session=${session.sessionId} blockSize=${talk.info.blockSize} fullBlockSize=${talk.info.fullBlockSize} sampleRate=${talk.info.audioConfig.sampleRate} audioType=${talk.info.audioConfig.audioType} duplex setupMs=${Date.now() - recordStart}`
9101
+ );
9102
+ } catch (e) {
9103
+ this.logger.warn?.(
9104
+ `[BaichuanRtspBackchannelServer] RECORD failed to open TalkSession client=${clientId} session=${session.sessionId} setupMs=${Date.now() - recordStart} error="${e.message}"`
9105
+ );
9106
+ send(503, "Service Unavailable");
9107
+ return;
9108
+ }
9109
+ session.handler = handler;
9110
+ send(200, "OK", { Session: session.sessionId });
9111
+ return;
9112
+ }
9113
+ case "TEARDOWN": {
9114
+ const session = this.sessionByClient.get(clientId);
9115
+ if (session) {
9116
+ this.sessionByClient.delete(clientId);
9117
+ if (session.handler) {
9118
+ const stats = session.handler.stats;
9119
+ this.logger.info?.(
9120
+ `[BaichuanRtspBackchannelServer] TEARDOWN client=${clientId} session=${session.sessionId} rtpRx=${stats.rtpPacketsReceived} rtpDropped=${stats.rtpPacketsDropped} adpcmBlocks=${stats.adpcmBlocksSent}`
9121
+ );
9122
+ void session.handler.stop();
9123
+ } else {
9124
+ this.logger.info?.(
9125
+ `[BaichuanRtspBackchannelServer] TEARDOWN client=${clientId} session=${session.sessionId} (no RECORD)`
9126
+ );
9127
+ }
9128
+ } else {
9129
+ this.logger.info?.(
9130
+ `[BaichuanRtspBackchannelServer] TEARDOWN client=${clientId} (no active session)`
9131
+ );
9132
+ }
9133
+ send(200, "OK", { Session: sessionId ?? "" });
9134
+ try {
9135
+ socket.end();
9136
+ } catch {
9137
+ }
9138
+ return;
9139
+ }
9140
+ default:
9141
+ this.logger.warn?.(
9142
+ `[BaichuanRtspBackchannelServer] unknown method ${method} from ${clientId} \u2014 replying 501`
9143
+ );
9144
+ send(501, "Not Implemented");
9145
+ }
9146
+ }
9147
+ buildSdp() {
9148
+ return `v=0\r
9149
+ o=- ${Date.now()} ${Date.now()} IN IP4 ${this.listenHost}\r
9150
+ s=Baichuan Backchannel\r
9151
+ c=IN IP4 ${this.listenHost}\r
9152
+ t=0 0\r
9153
+ a=control:*\r
9154
+ m=audio 0 RTP/AVP 0\r
9155
+ a=rtpmap:0 PCMU/8000\r
9156
+ a=sendonly\r
9157
+ a=control:audiobackchannel\r
9158
+ `;
9159
+ }
9160
+ // ─────────────────────────────────────────────────────────────────────
9161
+ // Digest auth helpers (mirror BaichuanRtspServer's behaviour so
9162
+ // operators can re-use the same credentials store across both servers).
9163
+ // ─────────────────────────────────────────────────────────────────────
9164
+ wwwAuthenticate(clientId) {
9165
+ const nonce = this.nonceFor(clientId);
9166
+ return `Digest realm="${this.authRealm}", nonce="${nonce}"`;
9167
+ }
9168
+ nonceFor(clientId) {
9169
+ const now = Date.now();
9170
+ const existing = this.nonces.get(clientId);
9171
+ if (existing && now - existing.ts < _BaichuanRtspBackchannelServer.NONCE_TTL_MS) {
9172
+ return existing.nonce;
9173
+ }
9174
+ const nonce = crypto2.randomBytes(16).toString("hex");
9175
+ this.nonces.set(clientId, { nonce, ts: now });
9176
+ return nonce;
9177
+ }
9178
+ validateDigest(header, method, uri, clientId) {
9179
+ const params = parseDigestHeader(header);
9180
+ if (!params) return false;
9181
+ if (params.realm && params.realm !== this.authRealm) return false;
9182
+ const nonce = this.nonces.get(clientId);
9183
+ if (!nonce || nonce.nonce !== params.nonce) return false;
9184
+ if (Date.now() - nonce.ts > _BaichuanRtspBackchannelServer.NONCE_TTL_MS)
9185
+ return false;
9186
+ const cred = this.authCredentials.find((c) => c.username === params.username);
9187
+ if (!cred) return false;
9188
+ const ha1 = cred.ha1 ?? (cred.password !== void 0 ? md5Hex(`${cred.username}:${this.authRealm}:${cred.password}`) : void 0);
9189
+ if (!ha1) return false;
9190
+ const ha2 = md5Hex(`${method}:${params.uri || uri}`);
9191
+ const expected = md5Hex(`${ha1}:${params.nonce}:${ha2}`);
9192
+ return expected === params.response;
9193
+ }
9194
+ };
9195
+ function newSessionId() {
9196
+ return `talk_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`;
9197
+ }
9198
+ function parseInterleavedChannels(transport) {
9199
+ const m = transport.match(/interleaved\s*=\s*(\d+)\s*-\s*(\d+)/i);
9200
+ if (!m) return void 0;
9201
+ const rtp = parseInt(m[1] ?? "", 10);
9202
+ const rtcp = parseInt(m[2] ?? "", 10);
9203
+ if (!Number.isFinite(rtp) || !Number.isFinite(rtcp)) return void 0;
9204
+ return { rtp, rtcp };
9205
+ }
9206
+ function parseDigestHeader(header) {
9207
+ if (!/^digest\s+/i.test(header)) return null;
9208
+ const params = {};
9209
+ const re = /(\w+)\s*=\s*("([^"]*)"|([^,\s]+))/g;
9210
+ let match;
9211
+ while ((match = re.exec(header)) !== null) {
9212
+ const key = (match[1] ?? "").toLowerCase();
9213
+ const value = match[3] ?? match[4] ?? "";
9214
+ params[key] = value;
9215
+ }
9216
+ if (!params.username || !params.nonce || !params.uri || !params.response) {
9217
+ return null;
9218
+ }
9219
+ return {
9220
+ username: params.username,
9221
+ realm: params.realm ?? "",
9222
+ nonce: params.nonce,
9223
+ uri: params.uri,
9224
+ response: params.response
9225
+ };
9226
+ }
9227
+
8288
9228
  // src/emailPush/server.ts
8289
9229
  import { format as utilFormat } from "util";
8290
9230
  import { SMTPServer } from "smtp-server";
@@ -8747,6 +9687,7 @@ export {
8747
9687
  BaichuanHlsServer,
8748
9688
  BaichuanHttpStreamServer,
8749
9689
  BaichuanMjpegServer,
9690
+ BaichuanRtspBackchannelServer,
8750
9691
  BaichuanRtspServer,
8751
9692
  BaichuanVideoStream,
8752
9693
  BaichuanWebRTCServer,
@@ -8772,10 +9713,12 @@ export {
8772
9713
  ReolinkCgiApi,
8773
9714
  ReolinkHttpClient,
8774
9715
  Rfc4571Muxer,
9716
+ RtspBackchannel,
8775
9717
  _resetEmailPushBusForTests,
8776
9718
  abilitiesHasAny,
8777
9719
  aesDecrypt,
8778
9720
  aesEncrypt,
9721
+ alawToPcm16,
8779
9722
  applyStreamPatch,
8780
9723
  applyXmlTagPatch,
8781
9724
  asLogger,
@@ -8848,6 +9791,7 @@ export {
8848
9791
  discoverViaUdpDirect,
8849
9792
  emitEmailPushEvent,
8850
9793
  encodeHeader,
9794
+ encodeImaAdpcm,
8851
9795
  encodeMotionScopeBitmap,
8852
9796
  encodeMotionSensitivityListXml,
8853
9797
  encodeShelterCoord,
@@ -8890,6 +9834,7 @@ export {
8890
9834
  maskUid,
8891
9835
  md5HexUpper,
8892
9836
  md5StrModern,
9837
+ mulawToPcm16,
8893
9838
  normalizeDayNightMode,
8894
9839
  normalizeOpenClose,
8895
9840
  normalizeUid,
@@ -8901,6 +9846,7 @@ export {
8901
9846
  parseAdtsHeader,
8902
9847
  parseBcMedia,
8903
9848
  parseRecordingFileName,
9849
+ parseRtpPacket,
8904
9850
  parseSupportXml,
8905
9851
  patchAiDetectCfgXml,
8906
9852
  patchMotionSensitivityListXml,
@@ -8918,6 +9864,7 @@ export {
8918
9864
  splitAnnexBToNals,
8919
9865
  splitAnnexBToNalPayloads2 as splitH265AnnexBToNalPayloads,
8920
9866
  testChannelStreams,
9867
+ upsamplePcm16,
8921
9868
  upsertXmlTag,
8922
9869
  xmlEscape,
8923
9870
  xmlIndicatesFloodlight,