fix(playback): resume interrupted finite music streams

This commit is contained in:
TIANYAO ZHANG committed 2026-11-18 18:31:46 +08:00
1 parent d130652279
commit 135ff0ae0e
7 files changed
+151 -19

No files matched your search

+72
View File
@@ -3,6 +3,7 @@ import { EventEmitter } from "node:events";
import { BotInstance } from "./instance.js";
import { AudioPlayer } from "../audio/player.js";
import { PlayQueue } from "../audio/queue.js";
import type { Platform } from "../music/provider.js";
import { BiliBiliProvider } from "../music/bilibili.js";
import { ManagedVoiceClientRegistry } from "./managed-voice-clients.js";
@@ -80,9 +81,80 @@ function cancel(bot: any, action: string) {
} else { bot.player.sessionId++; bot.player.state = "idle"; }
}
function makeMusicBot(platform: Platform = "netease") {
const bot = makeBot();
bot.queue.clear();
bot.queue.add({
id: "music", name: "Music", artist: "A", album: "", coverUrl: "",
platform, duration: 240, url: "https://cdn.test/old.wav",
});
bot.queue.playAt(0);
bot.player.elapsed = 60.28;
bot.effectiveDuration = 240;
bot.provider.getSongUrl.mockResolvedValue({ url: "https://cdn.test/new.wav" });
return bot;
}
beforeEach(() => vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }));
afterEach(() => { vi.clearAllTimers(); vi.useRealTimers(); });
describe("finite music CDN recovery", () => {
it.each(["netease", "qq", "kugou"] as const)("resumes %s at the real playback position", async platform => {
const bot = makeMusicBot(platform);
bot.player.emit("trackEnd");
await flush();
expect(bot.player.play).toHaveBeenCalledWith("https://cdn.test/new.wav", 60.28, 240);
expect(bot.playNext).not.toHaveBeenCalled();
});
it.each(["preview", "zero progress", "infinite duration", "local URL"])("does not recover %s streams", async condition => {
const bot = makeMusicBot();
if (condition === "preview") bot.currentStreamIsTrial = true;
if (condition === "zero progress") bot.player.elapsed = 0;
if (condition === "infinite duration") bot.effectiveDuration = Infinity;
if (condition === "local URL") bot.queue.current().url = "file:///example.wav";
bot.player.emit("trackEnd");
await flush();
expect(bot.provider.getSongUrl).not.toHaveBeenCalled();
expect(bot.playNext).toHaveBeenCalledTimes(1);
});
it("does not resume a full track into a preview URL", async () => {
const bot = makeMusicBot("qq");
bot.provider.getSongUrl.mockResolvedValue({ url: "https://cdn.test/preview.wav", trialDuration: 30 });
bot.player.emit("trackEnd");
await flush();
expect(bot.provider.getSongUrl).toHaveBeenCalledTimes(1);
expect(bot.player.play).not.toHaveBeenCalled();
expect(bot.playNext).toHaveBeenCalledTimes(1);
});
it("advances after exhausting the resume budget at the same position", async () => {
const bot = makeMusicBot("qq");
for (let i = 0; i < 4; i++) {
bot.player.state = "idle";
bot.player.emit("trackEnd");
await flush();
}
expect(bot.player.play).toHaveBeenCalledTimes(3);
expect(bot.playNext).toHaveBeenCalledTimes(1);
});
it.each(["stop", "disconnect"])("does not use a fresh URL after %s", async action => {
const bot = makeMusicBot("kugou");
const lookup = deferred<{ url: string }>();
bot.provider.getSongUrl.mockReturnValueOnce(lookup.promise);
bot.player.emit("trackEnd");
await flush();
expect(bot.provider.getSongUrl).toHaveBeenCalledTimes(1);
cancel(bot, action);
lookup.resolve({ url: "https://cdn.test/stale.wav" });
await flush();
expect(bot.player.play).not.toHaveBeenCalled();
expect(bot.playNext).not.toHaveBeenCalled();
});
});
describe("Bilibili recovery retries transient URL failures", () => {
it("rotates to untried CDN hosts after a long stream ends repeatedly at the same point", async () => {
const bot = makeBot();
+29 -15
View File
@@ -233,6 +233,7 @@ export class BotInstance extends EventEmitter {
private playbackRequest?: symbol;
/** 当前曲实际播放时长(试听片段秒数或完整 duration);resolveAndPlay 赋值。 */
private effectiveDuration: number | undefined;
private currentStreamIsTrial = false;
/** Resume attempts for the current song's stream (#161); see resumeInterruptedStream. */
private streamRecovery: {
song: QueuedSong;
@@ -1257,6 +1258,7 @@ export class BotInstance extends EventEmitter {
this.player.play(result.url, 0, this.effectiveDuration);
}
song.url = result.url;
this.currentStreamIsTrial = result.trialDuration !== undefined;
} catch (err) {
if (isCancelled()) return false;
this.logger.error({ err, songId: song.id }, "Failed to resolve URL");
@@ -1294,19 +1296,15 @@ export class BotInstance extends EventEmitter {
return true;
}
/** Platforms whose CDN stream can die mid-file on long content (#89, #161). */
private static readonly RESUMABLE_PLATFORMS: ReadonlySet<Platform> = new Set(["bilibili"]);
private static readonly RESUMABLE_PLATFORMS: ReadonlySet<Platform> = new Set(["bilibili", "netease", "qq", "kugou"]);
/** A track that ends within this many seconds of its duration ended normally. */
private static readonly STREAM_END_TOLERANCE_S = 30;
private static readonly MAX_STREAM_RESUMES = 3;
private static readonly MAX_STREAM_URL_LOOKUPS = 3;
/**
* Called when the player reports a track end. If a B站 stream ended long
* before its known duration, the CDN dropped it (#161): fetch a fresh URL
* and continue from where it stopped instead of skipping the rest of a
* 2-3 hour video. Gives up after MAX_STREAM_RESUMES attempts that make no
* real progress, so a truly broken stream still advances the queue.
* Renew an interrupted finite CDN stream and seek to the audio clock at EOF.
* The existing recovery budget bounds restarts that make no progress.
*
* Returns true when it handled the end (resumed, or a newer track has
* already taken over), false when the caller should advance the queue.
@@ -1316,12 +1314,19 @@ export class BotInstance extends EventEmitter {
if (!song || !this.connected || !BotInstance.RESUMABLE_PLATFORMS.has(song.platform)) {
return false;
}
const bilibili = song.platform === "bilibili";
const source = song.url ? URL.parse(song.url) : null;
const duration = this.effectiveDuration ?? song.duration;
const position = Math.floor(this.player.getElapsed());
const elapsed = this.player.getElapsed();
const position = bilibili ? Math.floor(elapsed) : elapsed;
const endedSession = this.player.getPlaybackSessionId();
if (!(duration > 0) || duration - position <= BotInstance.STREAM_END_TOLERANCE_S) {
if (!Number.isFinite(duration) || duration <= 0 || !Number.isFinite(position) || position < 0 ||
duration - position <= BotInstance.STREAM_END_TOLERANCE_S) {
return false;
}
// Music previews can start at a different offset than the full song.
if (!bilibili && (this.currentStreamIsTrial || position <= 0 ||
(source?.protocol !== "http:" && source?.protocol !== "https:"))) return false;
if (this.player.getState() !== "idle") return true;
const generation = this.lifecycleGeneration;
@@ -1349,11 +1354,11 @@ export class BotInstance extends EventEmitter {
return false;
}
state.position = position;
const failedHost = song.url ? URL.parse(song.url)?.hostname.replace(/\.$/, "") : undefined;
if (failedHost) state.failedHosts.add(failedHost);
const failedHost = source?.hostname.replace(/\.$/, "");
if (bilibili && failedHost) state.failedHosts.add(failedHost);
this.logger.warn(
{ songId: song.id, position, duration, attempt: state.attempts + 1 },
{ platform: song.platform, songId: song.id, position, duration, attempt: state.attempts + 1 },
"Stream ended before the track did — resuming with a fresh URL",
);
state.inFlight = true;
@@ -1375,14 +1380,23 @@ export class BotInstance extends EventEmitter {
let reason = "no-url";
try {
result = await this.getProviderFor(song.platform).getSongUrl(
song.id, undefined, { avoidHosts: state.failedHosts },
song.id, undefined, bilibili ? { avoidHosts: state.failedHosts } : { refresh: true },
);
} catch {
} catch (err) {
if (!isCurrent()) return cancelled();
if (blocksProviderForAdvance(toPlayFailure(song.platform, song.id, err).code)) return false;
reason = "lookup-error";
}
// Skip, stop, reconnect, or a new playback session supersedes the lookup.
if (!isCurrent()) return cancelled();
if (result?.url) {
if (!bilibili) {
const stream = URL.parse(result.url);
if (result.trialDuration !== undefined || (stream?.protocol !== "http:" && stream?.protocol !== "https:")) {
this.logger.warn({ platform: song.platform, songId: song.id }, "Fresh URL cannot resume the full track");
return false;
}
}
// Lookup retries do not consume the actual decoder resume budget.
state.attempts++;
song.url = result.url;
@@ -1393,7 +1407,7 @@ export class BotInstance extends EventEmitter {
return true;
}
this.logger.warn(
{ platform: "bilibili", sessionId: endedSession, position, duration, lookupAttempt: lookup + 1, reason },
{ platform: song.platform, sessionId: endedSession, position, duration, lookupAttempt: lookup + 1, reason },
"Fresh stream URL lookup failed",
);
}
+11
View File
@@ -480,6 +480,17 @@ describe("NetEase risk control (-460)", () => {
expect(r?.url).toBe("http://cdn.example/x.mp3");
expect(r?.trialDuration).toBe(60);
});
it("requests a new sidecar cache key for interruption recovery", async () => {
const get = vi.fn(async (_url: string, _config: unknown) => ({
data: { data: [{ url: "http://cdn.example/track.mp3" }] },
}));
const provider = providerWithApi(get);
await provider.getSongUrl("1");
await provider.getSongUrl("1", undefined, { refresh: true });
expect(get.mock.calls[0][1]).not.toHaveProperty("params.timestamp");
expect(get.mock.calls[1][1]).toMatchObject({ params: { id: "1", timestamp: expect.any(Number) } });
});
});
// ---------------------------------------------------------------------------
+7 -2
View File
@@ -6,6 +6,7 @@ import type {
MusicProvider,
Song,
SongUrlResult,
SongUrlRequestOptions,
Playlist,
PlaylistDetail,
LyricLine,
@@ -299,12 +300,16 @@ export class NeteaseProvider implements MusicProvider {
return { songs, playlists, albums, artists };
}
async getSongUrl(songId: string, quality?: string): Promise<SongUrlResult | null> {
async getSongUrl(songId: string, quality?: string, options?: SongUrlRequestOptions): Promise<SongUrlResult | null> {
const level = quality ?? this.quality;
let res;
try {
res = await this.api.get("/song/url/v1", {
params: { id: songId, level, ua: getPlaybackUserAgent(this.cookie), ...this.cookieParams },
params: {
id: songId, level, ua: getPlaybackUserAgent(this.cookie), ...this.cookieParams,
// The embedded sidecar caches successful responses for two minutes.
...(options?.refresh && { timestamp: Date.now() }),
},
});
} catch (err) {
// -460 arrives as HTTP 400, and left as-is it looks like "this track is
+2
View File
@@ -217,6 +217,8 @@ export interface AuthStatus {
export interface SongUrlRequestOptions {
/** CDN hosts that already failed around this playback position (where supported). */
avoidHosts?: ReadonlySet<string>;
/** Resolve after an interruption without reusing a cached playback URL. */
refresh?: boolean;
}
export interface MusicProvider {
+21
View File
@@ -99,4 +99,25 @@ describe("playback request timing", () => {
expect(store.timings.a?.serverElapsed).toBe(58);
expect(store.timings.b?.serverElapsed).toBe(10);
});
it("freezes steady elapsed samples and interpolates again when audio advances", async () => {
const store = usePlayerStore();
store.activeBotId = "a";
store.bots = [{
id: "a", name: "bot", connected: true, playing: true, paused: false, currentSong: track,
queueSize: 1, volume: 50, playMode: "sequential",
}];
const poll = vi.spyOn(axios, "get").mockResolvedValue({ data: { elapsed: 60 } });
vi.setSystemTime(10000);
await store.syncElapsed();
vi.setSystemTime(13000);
await store.syncElapsed();
vi.setSystemTime(14000);
expect(store.liveElapsed()).toBe(60);
poll.mockResolvedValue({ data: { elapsed: 61 } });
await store.syncElapsed();
vi.setSystemTime(15000);
expect(store.liveElapsed()).toBe(62);
});
});
+9 -2
View File
@@ -82,6 +82,7 @@ export interface TimingState {
serverElapsed: number;
serverSyncTime: number;
wasPlaying: boolean;
lastPolledElapsed?: number;
}
const HOME_CACHE_TTL = 5 * 60 * 1000;
@@ -312,6 +313,7 @@ export const usePlayerStore = defineStore('player', {
serverElapsed: status.elapsed,
serverSyncTime: Date.now(),
wasPlaying: status.playing && !status.paused,
lastPolledElapsed: undefined,
});
}
@@ -321,6 +323,7 @@ export const usePlayerStore = defineStore('player', {
serverElapsed: status.elapsed ?? 0,
serverSyncTime: Date.now(),
wasPlaying: status.playing && !status.paused,
lastPolledElapsed: undefined,
});
}
},
@@ -396,6 +399,7 @@ export const usePlayerStore = defineStore('player', {
serverElapsed: bot.elapsed,
serverSyncTime: Date.now(),
wasPlaying: bot.playing && !bot.paused,
lastPolledElapsed: undefined,
});
}
}
@@ -410,10 +414,13 @@ export const usePlayerStore = defineStore('player', {
const res = await axios.get(`/api/player/${botId}/elapsed`);
// A newer WebSocket update or poll supersedes this result.
if (this.timings[botId] !== timing) return;
const elapsed = res.data.elapsed;
if (!Number.isFinite(elapsed)) return;
this._setTiming(botId, {
serverElapsed: res.data.elapsed,
serverElapsed: elapsed,
serverSyncTime: Date.now(),
wasPlaying: true,
wasPlaying: timing?.lastPolledElapsed !== elapsed,
lastPolledElapsed: elapsed,
});
} catch {
// ignore