Compare commits

...
5 changed files with 158 additions and 22 deletions

No files matched your search

+101 -17
View File
@@ -206,6 +206,14 @@ export class AudioPlayer extends EventEmitter {
private duckingRampStartedAt = 0; private duckingRampStartedAt = 0;
private duckingRampDurationMs = 0; private duckingRampDurationMs = 0;
private pcmBuffer: Buffer = Buffer.alloc(0); private pcmBuffer: Buffer = Buffer.alloc(0);
private transitionSilence = false;
private pauseFrames = 0;
private resumeSilenceFrames = 0;
private stopAfterPauseTail = false;
private transportRampStart: number | null = null;
private transportRampEnd: number | null = null;
private transportRampFrom = 1;
private transportRampTo = 1;
private logger: Logger; private logger: Logger;
private frameLoopRunning = false; private frameLoopRunning = false;
private nextFrameTime = 0; private nextFrameTime = 0;
@@ -256,7 +264,7 @@ export class AudioPlayer extends EventEmitter {
play(url: string, seekSeconds = 0, songDuration = 0): void { play(url: string, seekSeconds = 0, songDuration = 0): void {
// 1. 停止当前所有播放,自增 sessionId 屏蔽旧回调 ( // 1. 停止当前所有播放,自增 sessionId 屏蔽旧回调 (
this.stop(); this.stop(true);
const currentSessionId = this.sessionId; const currentSessionId = this.sessionId;
this.currentUrl = url; this.currentUrl = url;
@@ -270,7 +278,7 @@ export class AudioPlayer extends EventEmitter {
if (this.consecutiveFailures >= AudioPlayer.MAX_CONSECUTIVE_FAILURES) { if (this.consecutiveFailures >= AudioPlayer.MAX_CONSECUTIVE_FAILURES) {
this.logger.error({ failures: this.consecutiveFailures }, "FFmpeg failures limit reached"); this.logger.error({ failures: this.consecutiveFailures }, "FFmpeg failures limit reached");
this.state = "idle"; this.stop();
this.emit("error", new Error("ffmpeg unavailable")); this.emit("error", new Error("ffmpeg unavailable"));
return; return;
} }
@@ -497,7 +505,7 @@ export class AudioPlayer extends EventEmitter {
playPcmStream(readable: Readable, opts: { onExternalEnd?: () => void } = {}): void { playPcmStream(readable: Readable, opts: { onExternalEnd?: () => void } = {}): void {
// 1. Fence current playback: stop() bumps sessionId, clears pcmBuffer, kills // 1. Fence current playback: stop() bumps sessionId, clears pcmBuffer, kills
// any ffmpeg, and DETACHES (never destroys) any prior external stream. // any ffmpeg, and DETACHES (never destroys) any prior external stream.
this.stop(); this.stop(true);
const currentSessionId = this.sessionId; const currentSessionId = this.sessionId;
this.externalMode = true; this.externalMode = true;
@@ -587,7 +595,26 @@ export class AudioPlayer extends EventEmitter {
this.onExternalEnd = null; this.onExternalEnd = null;
} }
stop(): void { stopWithFade(): void {
if (this.externalMode || this.state === "idle") {
this.stop();
return;
}
this.stopAfterPauseTail = true;
if (this.state === "playing") {
this.pauseFrames = 9;
this.setTransportRamp(0, 0, 5);
this.state = "paused";
} else if (this.pauseFrames === 0) {
this.stop();
}
}
stop(keepAlive = false): void {
const wasRunning = this.frameLoopRunning;
const deadline = this.nextFrameTime;
this.transitionSilence = keepAlive;
this.stopAfterPauseTail = false;
// 3. 递增 ID 是最有效的逻辑“隔离墙” // 3. 递增 ID 是最有效的逻辑“隔离墙”
this.sessionId++; this.sessionId++;
this.frameLoopRunning = false; this.frameLoopRunning = false;
@@ -630,6 +657,17 @@ export class AudioPlayer extends EventEmitter {
this.seekOffset = 0; this.seekOffset = 0;
this.framesPlayed = 0; this.framesPlayed = 0;
this.healthyFrames = 0; this.healthyFrames = 0;
this.pauseFrames = 0;
this.resumeSilenceFrames = 0;
this.transportRampStart = null;
this.transportRampEnd = null;
this.transportRampFrom = 1;
this.transportRampTo = 1;
if (keepAlive) {
this.frameLoopRunning = true;
this.nextFrameTime = wasRunning ? Math.max(performance.now(), deadline - FRAME_DURATION_MS) : performance.now();
this.scheduleNextFrame();
}
} }
private forceCleanup(proc: ChildProcess, pid: number): void { private forceCleanup(proc: ChildProcess, pid: number): void {
@@ -675,8 +713,25 @@ export class AudioPlayer extends EventEmitter {
if (loopSessionId !== this.sessionId || !this.frameLoopRunning) return; if (loopSessionId !== this.sessionId || !this.frameLoopRunning) return;
const framesBeforeTick = this.framesPlayed; const framesBeforeTick = this.framesPlayed;
if (this.state === "playing") this.sendNextFrame(); if (this.state === "paused") {
else if (this.state === "paused") this.nextFrameTime = performance.now(); if (this.pauseFrames > 0) {
this.pauseFrames--;
if (this.pauseFrames > 3) this.sendNextFrame();
else this.emitSilenceFrame(false);
} else {
this.nextFrameTime = performance.now();
if (this.stopAfterPauseTail) {
this.stop();
return;
}
}
}
else if (this.state === "idle" && this.transitionSilence) this.emitSilenceFrame(false);
else if (this.state === "playing" && this.resumeSilenceFrames > 0) {
this.resumeSilenceFrames--;
this.emitSilenceFrame(false);
}
else if (this.state === "playing") this.sendNextFrame();
const frameSent = this.framesPlayed > framesBeforeTick; const frameSent = this.framesPlayed > framesBeforeTick;
// 检测pcmBuffer不足PCM_FRAME_BYTES导致连续循环卡死: // 检测pcmBuffer不足PCM_FRAME_BYTES导致连续循环卡死:
@@ -748,7 +803,7 @@ export class AudioPlayer extends EventEmitter {
// R3-4: likewise gated on state==="playing" — a drained/EOF'd stream must // R3-4: likewise gated on state==="playing" — a drained/EOF'd stream must
// not emit trackEnd while paused; end-detection resumes on resume(). // not emit trackEnd while paused; end-detection resumes on resume().
if (this.state === "playing" && !this.externalMode && !this.ffmpeg && this.pcmBuffer.length < PCM_FRAME_BYTES) { if (this.state === "playing" && !this.externalMode && !this.ffmpeg && !this.downloader && this.pcmBuffer.length < PCM_FRAME_BYTES) {
this.frameLoopRunning = false; this.frameLoopRunning = false;
// Outer gate guarantees state==="playing"; end directly (no !=="idle" guard). // Outer gate guarantees state==="playing"; end directly (no !=="idle" guard).
this.state = "idle"; this.state = "idle";
@@ -764,12 +819,12 @@ export class AudioPlayer extends EventEmitter {
private sendNextFrame(): void { private sendNextFrame(): void {
if (this.pcmBuffer.length < PCM_FRAME_BYTES) { if (this.pcmBuffer.length < PCM_FRAME_BYTES) {
// External mode: the sidecar PCM stream is long-lived and must NOT end on // Keep the voice timeline continuous while the source is preparing/stalled.
// a transient underrun. Emit an encoded silence frame so the 20ms voice // URL silence must not advance elapsed time or hide the stall watchdog.
// timeline stays continuous instead of returning (which would desync TS). if (this.externalMode || this.ffmpeg || this.downloader || this.transitionSilence) this.emitSilenceFrame(this.externalMode);
if (this.externalMode) this.emitSilenceFrame();
return; return;
} }
this.transitionSilence = false;
const pcmFrame = this.pcmBuffer.subarray(0, PCM_FRAME_BYTES); const pcmFrame = this.pcmBuffer.subarray(0, PCM_FRAME_BYTES);
this.pcmBuffer = this.pcmBuffer.subarray(PCM_FRAME_BYTES); this.pcmBuffer = this.pcmBuffer.subarray(PCM_FRAME_BYTES);
@@ -798,11 +853,11 @@ export class AudioPlayer extends EventEmitter {
} }
} }
private emitSilenceFrame(): void { private emitSilenceFrame(advanceTimeline = true): void {
try { try {
const opusFrame = this.encoder.encode(Buffer.alloc(PCM_FRAME_BYTES)); const opusFrame = this.encoder.encode(Buffer.alloc(PCM_FRAME_BYTES));
this.emit("frame", opusFrame); this.emit("frame", opusFrame);
this.framesPlayed++; if (advanceTimeline) this.framesPlayed++;
} catch (err) { } catch (err) {
this.emit("error", err as Error); this.emit("error", err as Error);
} }
@@ -813,8 +868,10 @@ export class AudioPlayer extends EventEmitter {
const now = performance.now(); const now = performance.now();
const startDuckingGain = this.duckingGainAt(now); const startDuckingGain = this.duckingGainAt(now);
const endDuckingGain = this.duckingGainAt(now + FRAME_DURATION_MS); const endDuckingGain = this.duckingGainAt(now + FRAME_DURATION_MS);
const startFactor = baseFactor * startDuckingGain; const startTransportGain = this.transportGainAt(now);
const endFactor = baseFactor * endDuckingGain; const endTransportGain = this.transportGainAt(now + FRAME_DURATION_MS);
const startFactor = baseFactor * startDuckingGain * startTransportGain;
const endFactor = baseFactor * endDuckingGain * endTransportGain;
if (startFactor >= 1 && endFactor >= 1) { if (startFactor >= 1 && endFactor >= 1) {
return Buffer.from(pcm); return Buffer.from(pcm);
@@ -844,6 +901,25 @@ export class AudioPlayer extends EventEmitter {
return out; return out;
} }
private setTransportRamp(target: number, delayFrames = 0, durationFrames = 3): void {
const now = performance.now();
const from = this.transportGainAt(now);
this.transportRampStart = now + FRAME_DURATION_MS * delayFrames;
this.transportRampEnd = this.transportRampStart + FRAME_DURATION_MS * durationFrames;
this.transportRampFrom = from;
this.transportRampTo = target;
}
private transportGainAt(at: number): number {
if (this.transportRampStart === null || this.transportRampEnd === null) return this.transportRampTo;
const progress = Math.max(0, Math.min(1, (at - this.transportRampStart) / (this.transportRampEnd - this.transportRampStart)));
if (progress >= 1) {
this.transportRampStart = null;
this.transportRampEnd = null;
}
return this.transportRampFrom + (this.transportRampTo - this.transportRampFrom) * progress;
}
private duckingGainAt(at: number): number { private duckingGainAt(at: number): number {
if (this.duckingRampDurationMs <= 0) return this.duckingTargetGain; if (this.duckingRampDurationMs <= 0) return this.duckingTargetGain;
@@ -868,11 +944,19 @@ export class AudioPlayer extends EventEmitter {
// transport is delegated to the SpotifyController by the caller (Task 7). // transport is delegated to the SpotifyController by the caller (Task 7).
if (this.externalMode) return; if (this.externalMode) return;
if (this.currentUrl && Number.isFinite(seconds) && seconds >= 0) { if (this.currentUrl && Number.isFinite(seconds) && seconds >= 0) {
const paused = this.state === "paused";
this.play(this.currentUrl, seconds, this.currentSongDuration); this.play(this.currentUrl, seconds, this.currentSongDuration);
if (paused && this.state === "playing") this.pause();
} }
} }
pause(): void { if (this.state === "playing") this.state = "paused"; } pause(): void {
resume(): void { if (this.state === "paused") { this.state = "playing"; this.nextFrameTime = performance.now(); } } if (this.state === "playing") {
this.pauseFrames = 9;
this.setTransportRamp(0, 0, 5);
this.state = "paused";
}
}
resume(): void { if (this.state === "paused") { this.pauseFrames = 0; this.resumeSilenceFrames = 3; this.setTransportRamp(1, 3, 5); this.state = "playing"; } }
resetFailures(): void { this.consecutiveFailures = 0; } resetFailures(): void { this.consecutiveFailures = 0; }
setVolume(vol: number): void { this.volume = Math.max(0, Math.min(100, vol)); } setVolume(vol: number): void { this.volume = Math.max(0, Math.min(100, vol)); }
getVolume(): number { return this.volume; } getVolume(): number { return this.volume; }
+5 -2
View File
@@ -1547,11 +1547,13 @@ export class BotInstance extends EventEmitter {
private cmdStop(): string { private cmdStop(): string {
// Read the current song BEFORE queue.clear() so we can tell whether the // Read the current song BEFORE queue.clear() so we can tell whether the
// sidecar needs stopping. // sidecar needs stopping.
if (this.queue.current()?.platform === "spotify") { const isSpotify = this.queue.current()?.platform === "spotify";
if (isSpotify) {
this.spotifyController.stop(); this.spotifyController.stop();
} }
this.currentSourceIsSpotify = false; this.currentSourceIsSpotify = false;
this.player.stop(); if (isSpotify) this.player.stop();
else this.player.stopWithFade();
this.jellyfinReporter?.onStop(); this.jellyfinReporter?.onStop();
this.autoPaused = false; this.autoPaused = false;
this.queue.clear(); this.queue.clear();
@@ -2103,6 +2105,7 @@ export class BotInstance extends EventEmitter {
this.isAdvancing = true; this.isAdvancing = true;
let started = false; let started = false;
try { try {
if (this.player.getState() !== "idle") this.player.stop(true);
this.voteSkipUsers.clear(); this.voteSkipUsers.clear();
const next = this.queue.next(); const next = this.queue.next();
if (next) { if (next) {
+30
View File
@@ -0,0 +1,30 @@
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
describe("application log errors", () => {
it("preserves HTTP diagnostics while omitting Axios request and response data", () => {
const child = spawnSync(process.execPath, [
"--import", "tsx", "--input-type=module", "--eval", `
import { AxiosError } from "axios";
import { createLogger } from "./src/logger.ts";
const config = { params: { cookie: "sample-request-cookie" } };
const response = { status: 400, data: { code: -460, cookie: "sample-response-cookie" } };
const err = new AxiosError("sample-sensitive-url", "ERR_BAD_REQUEST", config, undefined, response);
const log = createLogger().child({ component: "test" });
log.warn({ err }, "Provider failed");
log.error({ reason: err }, "Unhandled rejection");
log.error(new Error("ordinary error"));
`,
], { cwd: fileURLToPath(new URL("..", import.meta.url)), encoding: "utf8" });
expect(child.status, child.stderr).toBe(0);
const [provider, rejection, ordinary] = child.stdout.trim().split("\n").map(line => JSON.parse(line));
const expected = { type: "AxiosError", code: "ERR_BAD_REQUEST", status: 400, upstreamCode: -460 };
expect(provider.err).toMatchObject(expected);
expect(rejection.reason).toMatchObject(expected);
expect(child.stdout).not.toContain("sample-");
expect(ordinary.err.message).toBe("ordinary error");
});
});
+20 -2
View File
@@ -1,12 +1,30 @@
import pino from "pino"; import pino from "pino";
import { isAxiosError } from "axios";
import { mkdirSync } from "node:fs"; import { mkdirSync } from "node:fs";
import { join } from "node:path"; import { join } from "node:path";
export type Logger = pino.Logger; export type Logger = pino.Logger;
function serializeHttpError(error: unknown): unknown {
if (!isAxiosError<{ code?: unknown }>(error)) {
return error instanceof Error ? pino.stdSerializers.err(error) : error;
}
const upstreamCode = error.response?.data?.code;
return {
type: "AxiosError",
code: error.code,
status: error.response?.status ?? error.status,
upstreamCode: typeof upstreamCode === "number" ? upstreamCode : undefined,
};
}
// Axios errors include the original request configuration and may contain
// session cookies, authorization headers or secrets in the request URL.
const serializers = { err: serializeHttpError, reason: serializeHttpError };
export function createLogger(logDir?: string): Logger { export function createLogger(logDir?: string): Logger {
if (!logDir) { if (!logDir) {
return pino({ level: "info" }); return pino({ level: "info", serializers });
} }
mkdirSync(logDir, { recursive: true }); mkdirSync(logDir, { recursive: true });
@@ -32,5 +50,5 @@ export function createLogger(logDir?: string): Logger {
console.error("Logger transport error:", err); console.error("Logger transport error:", err);
}); });
return pino({ level: "debug" }, transport); return pino({ level: "debug", serializers }, transport);
} }
+2 -1
View File
@@ -285,7 +285,7 @@ export function createPlayerRouter(
if (index >= queue.size()) { if (index >= queue.size()) {
return { status: 400 as const, body: { error: "Invalid queue index" } }; return { status: 400 as const, body: { error: "Invalid queue index" } };
} }
bot.getPlayer().stop(); bot.getPlayer().stop(true);
bot.getPlayer().resetFailures(); bot.getPlayer().resetFailures();
const song = queue.playAt(index); const song = queue.playAt(index);
if (!song) { if (!song) {
@@ -293,6 +293,7 @@ export function createPlayerRouter(
} }
const ok = await bot.resolveAndPlay(song); const ok = await bot.resolveAndPlay(song);
if (!ok) { if (!ok) {
bot.getPlayer().stop();
return { body: { message: `Cannot play: ${song.name}` } }; return { body: { message: `Cannot play: ${song.name}` } };
} }
return { body: { message: `Now playing: ${song.name} - ${song.artist}` } }; return { body: { message: `Now playing: ${song.name} - ${song.artist}` } };