Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ jobs:
- run: npm --prefix web run build:demo

voice:
name: Voice protocol check
name: Voice protocol and buffering checks
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
Expand Down
1 change: 1 addition & 0 deletions HOWTOSTART.md
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,7 @@ DATABASE_URL=sqlite:///./tsbot.db
- 界面图标和 TeamSpeak 机器人头像在 Web 设置页直接上传,固定保存在数据库目录旁的 `uploads/` 中;不再填写服务器图片路径。
- “保存配置”只将表单持久化到数据库;“应用配置”才会更新运行服务。应用 TeamSpeak 或 Voice 改动后,voice-service 会优雅断开并自动用新配置重启,Web 在新进程返回后提示“已重启成功”。
- “TeamSpeak 配置”包含连接、频道、身份和客户端简介;“Voice 服务”包含后端到 Voice 的连接与 Voice 运行参数。
- “高级设置 → 服务与日志”的 PCM 预缓冲上限默认 5 秒,支持整数 1–30 秒,直接限制有界读取通道;缓冲满时 FFmpeg 等待,不截断曲目。该值不包含解码器及进程自身开销。首次启动可由 `TSBOT_VOICE_PCM_BUFFER_SECONDS` 导入,已有数据库配置优先;独立 Voice 对无效值使用 5 秒默认值。保存后需应用,Voice 重启会中断播放。配置说明核验:2026-11-19(源码检查,不代表已更新在线部署)。
- 旧部署的 `TSBOT_TS3_*` 等变量会在数据库缺少对应值时导入一次,迁移后可从环境文件删除。
- QQ 音乐能力由后端内建提供,不需要额外部署独立的 QQ 音乐 API 服务。
- 网易云、QQ 音乐和 B 站授权统一位于“系统配置 → 音乐会员登录”;管理员 Cookie 写入数据库并使用 `TSBOT_COOKIE_KEY` 加密存储。
Expand Down
4 changes: 4 additions & 0 deletions README.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ Netease features require your own `NeteaseCloudMusicApi` service. QQ Music and B

For troubleshooting, run `docker compose -f docker-compose.prebuilt.yml logs --tail=100 backend voice-service`. See [source installation](#quick-start-recommended) and [Docker options](#docker-deployment) for more detail.

The **PCM prefetch limit (seconds)** setting is available under system settings → advanced → services and logs. It defaults to 5 seconds and accepts integers from 1 to 30. It bounds decoded audio held ahead of playback for every source; a full buffer makes the reader wait without discarding frames or limiting track duration. This limit controls the bounded reader channel itself, without an additional PCM queue; the decoder/process have their own overhead, so this is not a total process-memory limit.

Save stages the change; Apply restarts Voice and interrupts active playback, following the existing Voice settings flow. `TSBOT_VOICE_PCM_BUFFER_SECONDS` seeds a new database setting or configures standalone Voice; existing persisted settings take precedence. Missing, non-integer or out-of-range standalone values fall back to 5 seconds. Unlimited buffering is not supported.

## Help build TSBot

Deployment reports, reproducible bug reports, documentation, translations, and code are welcome. See the [contribution guide and starter tasks](CONTRIBUTING.md); you can work on one component at a time. Issues and pull requests in English or Chinese are welcome.
Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,10 @@ cp tsbot.env.example tsbot.env

设置页右上角的“保存配置”只把当前表单持久化到数据库,适合先分组检查配置;“应用配置”会合并所有已保存但尚未应用的改动,并更新运行中的服务。TeamSpeak 或 Voice 配置发生变化时,voice-service 会正常断开并自动使用新配置重启;Web 会等待新进程返回对应的配置版本后显示“已重启成功”,不需要给后端 Docker Socket 或 systemd 管理权限。

“系统配置 → 高级设置 → 服务与日志”中的 **PCM 预缓冲上限(秒)**控制 Voice 提前解码的音频量,默认 5 秒,可设为 1–30 秒。缓冲满后读取端等待播放消耗,长歌曲仍能完整播放,不会因超过缓冲长度而被截断或跳过。该限制适用于所有音乐来源,与歌曲总时长和压缩音质等级无关。该上限直接控制读取通道,不再维护额外 PCM 队列;进程和解码器本身也有内存开销,因此该值不是进程总内存限制。

此项沿用“保存配置 / 应用配置”的流程,应用时会重启 Voice,正在播放的内容会中断。`TSBOT_VOICE_PCM_BUFFER_SECONDS` 可用于首次导入或独立运行 Voice;已有数据库配置优先。独立 Voice 遇到缺失、非整数或超出 1–30 范围的环境值时使用安全默认值 5 秒,不提供无限缓冲选项。

“TeamSpeak 配置”同时包含连接、频道、身份和客户端简介;“Voice 服务”同时包含后端到 Voice 的连接与 Voice 运行参数,避免同一功能分散在重复菜单中。

界面图标和 TeamSpeak 机器人头像不再接受服务器文件路径。管理员可直接在 Web 设置页上传、更换或清除图片;文件固定保存在 SQLite 数据库所在目录的 `uploads/` 子目录中(Docker Compose 默认是 `data/uploads/`)。头像更换或清除后也会触发 voice-service 自动重启。
Expand Down
1 change: 1 addition & 0 deletions backend/runtime_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ class SettingDefinition:
SettingDefinition("voice.serverquery_sid", "serverquery", "虚拟服务器 SID", env="TSBOT_TS3_SERVERQUERY_SID", restart="voice"),
SettingDefinition("voice.serverquery_use_port", "serverquery", "语音端口映射", type="integer", env="TSBOT_TS3_SERVERQUERY_USE_PORT", default=9987, minimum=1, maximum=65535, restart="voice"),
SettingDefinition("voice.log_level", "backend", "Voice 日志等级", type="select", env="TSBOT_VOICE_LOG_LEVEL", default="INFO", options=("DEBUG", "INFO", "WARNING", "ERROR"), restart="voice"),
SettingDefinition("voice.pcm_buffer_seconds", "backend", "PCM 预缓冲上限(秒)", type="integer", env="TSBOT_VOICE_PCM_BUFFER_SECONDS", default=5, minimum=1, maximum=30, restart="voice", strict_integer=True, help="限制提前解码的音频量,不限制歌曲时长。缓冲满后等待播放消耗,不丢帧或跳歌;应用配置后 Voice 会重启。读取通道即为缓冲上限,解码器另有自身开销。"),
SettingDefinition("voice.state_file", "backend", "播放状态文件", env="TSBOT_VOICE_STATE_FILE", default="./logs/voice_state.json", restart="voice"),
)

Expand Down
65 changes: 64 additions & 1 deletion tests/test_admin_configuration.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
import os
from pathlib import Path
import tempfile
import unittest
Expand All @@ -20,7 +21,7 @@
)
from backend.config import settings
from backend.db import Base
from backend.models import AdminCredential
from backend.models import AdminCredential, AppSetting
from backend import managed_assets
from backend.managed_assets import ASSET_BY_KEY, asset_path, delete_asset, save_asset, validate_image
from backend.runtime_config import (
Expand Down Expand Up @@ -148,6 +149,68 @@ def test_voice_change_writes_shared_configuration(self) -> None:
self.assertEqual("ts.example.test", written["TSBOT_TS3_HOST"])
self.assertTrue(written["TSBOT_VOICE_CONFIG_REVISION"])

def test_pcm_buffer_setting_has_safe_console_bounds_and_default(self) -> None:
field = next(item for item in settings_payload(self.session)["fields"] if item["key"] == "voice.pcm_buffer_seconds")
self.assertEqual((5, 1, 30, "integer", "backend", "voice"), (
field["value"], field["minimum"], field["maximum"], field["type"], field["group"], field["restart"],
))
written = json.loads(self.voice_file.read_text(encoding="utf-8"))
self.assertEqual("5", written["TSBOT_VOICE_PCM_BUFFER_SECONDS"])

def test_pcm_buffer_save_stages_until_apply_and_reset_restores_default(self) -> None:
before = self.voice_file.read_text(encoding="utf-8")
effects = update_settings(self.session, {"voice.pcm_buffer_seconds": 10}, apply=False)
self.assertIn("voice", effects)
self.assertEqual(before, self.voice_file.read_text(encoding="utf-8"))
self.assertTrue(settings_payload(self.session)["apply_pending"])
update_settings(self.session, {}, apply=True)
self.assertEqual("10", json.loads(self.voice_file.read_text(encoding="utf-8"))["TSBOT_VOICE_PCM_BUFFER_SECONDS"])
self.assertFalse(settings_payload(self.session)["apply_pending"])
update_settings(self.session, {"voice.pcm_buffer_seconds": None})
self.assertEqual("5", json.loads(self.voice_file.read_text(encoding="utf-8"))["TSBOT_VOICE_PCM_BUFFER_SECONDS"])

def test_pcm_buffer_rejects_invalid_values_without_partial_update(self) -> None:
definition = DEFINITION_BY_KEY["voice.pcm_buffer_seconds"]
name_definition = DEFINITION_BY_KEY["web.app_name"]
before_name = get_value(self.session, name_definition)
before_file = self.voice_file.read_text(encoding="utf-8")
for invalid in (0, -1, 31, True, 1.5, "1.5", "invalid", "0"):
with self.subTest(value=invalid), self.assertRaises(HTTPException) as raised:
update_settings(self.session, {"voice.pcm_buffer_seconds": invalid, "web.app_name": "must-not-persist"})
self.assertEqual(422, raised.exception.status_code)
self.assertEqual(5, get_value(self.session, definition))
self.assertEqual(before_name, get_value(self.session, name_definition))
self.assertEqual(before_file, self.voice_file.read_text(encoding="utf-8"))

def test_pcm_buffer_boundaries_are_written_to_voice_configuration(self) -> None:
for seconds in (1, 30):
with self.subTest(seconds=seconds):
effects = update_settings(self.session, {"voice.pcm_buffer_seconds": seconds})
self.assertIn("voice", effects)
self.assertEqual(str(seconds), json.loads(self.voice_file.read_text(encoding="utf-8"))["TSBOT_VOICE_PCM_BUFFER_SECONDS"])

def test_pcm_buffer_imports_environment_once_and_persists(self) -> None:
definition = DEFINITION_BY_KEY["voice.pcm_buffer_seconds"]
self.session.delete(self.session.get(AppSetting, definition.key))
self.session.commit()
with patch.dict(os.environ, {"TSBOT_VOICE_PCM_BUFFER_SECONDS": "12"}):
initialize_runtime_settings(self.session)
self.assertEqual(12, get_value(self.session, definition))
with patch.dict(os.environ, {"TSBOT_VOICE_PCM_BUFFER_SECONDS": "3"}):
initialize_runtime_settings(self.session)
self.assertEqual(12, get_value(self.session, definition))
self.assertEqual("12", json.loads(self.voice_file.read_text(encoding="utf-8"))["TSBOT_VOICE_PCM_BUFFER_SECONDS"])

def test_pcm_buffer_invalid_environment_uses_safe_default(self) -> None:
definition = DEFINITION_BY_KEY["voice.pcm_buffer_seconds"]
for invalid in ("0", "31", "-1", "invalid", "1.5", "0"):
self.session.delete(self.session.get(AppSetting, definition.key))
self.session.commit()
with self.subTest(value=invalid), patch.dict(os.environ, {"TSBOT_VOICE_PCM_BUFFER_SECONDS": invalid}):
initialize_runtime_settings(self.session)
self.assertEqual(5, get_value(self.session, definition))
self.assertEqual("5", json.loads(self.voice_file.read_text(encoding="utf-8"))["TSBOT_VOICE_PCM_BUFFER_SECONDS"])

def test_save_only_stages_voice_change_until_apply(self) -> None:
before = self.voice_file.read_text(encoding="utf-8")

Expand Down
5 changes: 5 additions & 0 deletions tsbot.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ export TSBOT_VOICE_GRPC_ADDR="127.0.0.1:50051"
# 两个进程必须能访问同一路径;仓库脚本与 Docker 默认共享 logs 目录。
export TSBOT_VOICE_CONFIG_FILE="./logs/voice-service.json"

# PCM 预缓冲上限:默认 5 秒,整数范围 1–30,不限制曲目时长。
# 首次启动导入后,请在“系统配置 → 高级设置 → 服务与日志”中维护。
# 独立 Voice 可直接使用此变量;无效值回退到 5 秒,不支持无限缓冲。
# export TSBOT_VOICE_PCM_BUFFER_SECONDS="5"

# =========================
# 管理员首次登录
# =========================
Expand Down
9 changes: 7 additions & 2 deletions voice-service/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,13 @@ use tracing::{error, info, warn};

mod logger;
mod playback;
#[cfg(test)]
mod pcm_playback_tests;

use playback::PlaybackRequest;
use voice_service::playback_status::SharedStatus;

use voice_service::pcm_buffer::{PcmBuffer, PcmFrame};
use voice_service::pcm_buffer::{max_frames_from_config, PcmBuffer, PcmFrame};

use tsclientlib::{Connection, DisconnectOptions, Identity, StreamItem, Version};
use tsproto_packets::packets::{AudioData, CodecType, Direction, Flags, OutAudio, OutCommand, OutPacket, PacketType};
Expand Down Expand Up @@ -1467,7 +1469,10 @@ async fn playback_loop(

// Encode/send loop must keep a stable 20ms cadence to prevent TS3 jitter buffer underruns.
// We decouple ffmpeg reads from the send cadence via a small PCM frame queue.
let (pcm_tx, mut pcm_buffer) = PcmBuffer::channel();
let max_frames = max_frames_from_config(
env::var("TSBOT_VOICE_PCM_BUFFER_SECONDS").ok().as_deref(),
);
let (pcm_tx, mut pcm_buffer) = PcmBuffer::channel(max_frames);

let encoder = Encoder::new(
audiopus::SampleRate::Hz48000,
Expand Down
20 changes: 17 additions & 3 deletions voice-service/src/pcm_buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,21 @@ use std::time::Duration;

use tokio::sync::mpsc;

pub const PCM_CHANNEL_CAPACITY: usize = if cfg!(windows) { 200 } else { 50 };
const FRAMES_PER_SECOND: usize = 50;
const DEFAULT_BUFFER_SECONDS: usize = 5;
const MIN_BUFFER_SECONDS: usize = 1;
const MAX_BUFFER_SECONDS: usize = 30;
pub const DEFAULT_BUFFERED_FRAMES: usize = DEFAULT_BUFFER_SECONDS * FRAMES_PER_SECOND;

pub fn max_frames_from_config(raw: Option<&str>) -> usize {
let seconds = raw
.map(str::trim)
.filter(|value| !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit()))
.and_then(|value| value.parse::<usize>().ok())
.filter(|seconds| (MIN_BUFFER_SECONDS..=MAX_BUFFER_SECONDS).contains(seconds))
.unwrap_or(DEFAULT_BUFFER_SECONDS);
seconds * FRAMES_PER_SECOND
}
const PREBUFFER_FRAMES: usize = if cfg!(windows) { 15 } else { 5 };
const LATE_FRAME_WAIT: Duration = Duration::from_millis(if cfg!(windows) { 8 } else { 3 });

Expand All @@ -20,8 +34,8 @@ pub struct PcmBuffer {
}

impl PcmBuffer {
pub fn channel() -> (mpsc::Sender<Vec<u8>>, Self) {
let (sender, receiver) = mpsc::channel(PCM_CHANNEL_CAPACITY);
pub fn channel(max_frames: usize) -> (mpsc::Sender<Vec<u8>>, Self) {
let (sender, receiver) = mpsc::channel(max_frames);
(
sender,
Self {
Expand Down
84 changes: 75 additions & 9 deletions voice-service/src/pcm_buffer/tests.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,82 @@
use super::*;

#[test]
fn configured_seconds_have_safe_bounds_and_default() {
for (value, frames) in [("1", 50), ("5", 250), ("30", 1500), (" 12 ", 600)] {
assert_eq!(max_frames_from_config(Some(value)), frames);
}
for value in [None, Some(""), Some("0"), Some("31"), Some("-1"),
Some("1.5"), Some("NaN"), Some("0"), Some("99999999999999999999999999999999")] {
assert_eq!(max_frames_from_config(value), DEFAULT_BUFFERED_FRAMES);
}
}

#[tokio::test]
async fn configured_capacity_blocks_and_resumes_without_losing_frames() {
for seconds in ["1", "30"] {
let capacity = max_frames_from_config(Some(seconds));
let (sender, mut buffer) = PcmBuffer::channel(capacity);
for index in 0..capacity {
sender.try_send(index.to_le_bytes().to_vec()).unwrap();
}
let producer = tokio::spawn(async move {
sender.send(capacity.to_le_bytes().to_vec()).await.unwrap();
});
tokio::task::yield_now().await;
assert!(!producer.is_finished());
assert!(matches!(buffer.next_frame().await, PcmFrame::Audio(frame) if frame == 0usize.to_le_bytes()));
producer.await.unwrap();
for index in 1..=capacity {
assert!(matches!(buffer.next_frame().await, PcmFrame::Audio(frame) if frame == index.to_le_bytes()));
}
assert!(matches!(buffer.next_frame().await, PcmFrame::Finished));
}
}

async fn drain_track(seconds: usize) {
let frame_count = seconds * FRAMES_PER_SECOND;
let (sender, mut buffer) = PcmBuffer::channel(max_frames_from_config(Some("1")));
let producer = tokio::spawn(async move {
for index in 0..frame_count {
sender.send(index.to_le_bytes().to_vec()).await.unwrap();
}
});
let mut consumed = 0usize;
loop {
match buffer.next_frame().await {
PcmFrame::Audio(frame) => {
assert_eq!(frame, consumed.to_le_bytes());
consumed += 1;
}
PcmFrame::Pending => tokio::task::yield_now().await,
PcmFrame::Finished => break,
}
}
producer.await.unwrap();
assert_eq!(consumed, frame_count);
}

#[tokio::test]
async fn ten_minute_track_delivers_every_frame_in_order() {
drain_track(600).await;
}

#[tokio::test]
async fn sixty_eight_minute_track_delivers_every_frame_in_order() {
drain_track(4105).await;
}

#[tokio::test]
async fn fast_producer_stays_bounded_and_preserves_order() {
let (sender, mut buffer) = PcmBuffer::channel();
for index in 0..PCM_CHANNEL_CAPACITY {
let (sender, mut buffer) = PcmBuffer::channel(DEFAULT_BUFFERED_FRAMES);
for index in 0..DEFAULT_BUFFERED_FRAMES {
sender.try_send(index.to_le_bytes().to_vec()).unwrap();
}
assert!(matches!(
sender.try_send(vec![]),
Err(mpsc::error::TrySendError::Full(_))
));
for expected in 0..PCM_CHANNEL_CAPACITY {
for expected in 0..DEFAULT_BUFFERED_FRAMES {
let PcmFrame::Audio(frame) = buffer.next_frame().await else {
panic!("lost frame")
};
Expand All @@ -21,7 +87,7 @@ async fn fast_producer_stays_bounded_and_preserves_order() {

#[tokio::test]
async fn waits_for_prebuffer_while_source_is_open() {
let (sender, mut buffer) = PcmBuffer::channel();
let (sender, mut buffer) = PcmBuffer::channel(DEFAULT_BUFFERED_FRAMES);
sender.send(vec![1]).await.unwrap();
assert!(buffer.has_audio());
assert!(matches!(buffer.next_frame().await, PcmFrame::Pending));
Expand All @@ -33,7 +99,7 @@ async fn waits_for_prebuffer_while_source_is_open() {

#[tokio::test]
async fn short_clip_drains_at_eof_without_waiting_for_prebuffer() {
let (sender, mut buffer) = PcmBuffer::channel();
let (sender, mut buffer) = PcmBuffer::channel(DEFAULT_BUFFERED_FRAMES);
sender.send(vec![1]).await.unwrap();
drop(sender);
assert!(matches!(buffer.next_frame().await, PcmFrame::Audio(frame) if frame == [1]));
Expand All @@ -42,15 +108,15 @@ async fn short_clip_drains_at_eof_without_waiting_for_prebuffer() {

#[tokio::test]
async fn empty_source_finishes_immediately() {
let (sender, mut buffer) = PcmBuffer::channel();
let (sender, mut buffer) = PcmBuffer::channel(DEFAULT_BUFFERED_FRAMES);
drop(sender);
assert!(!buffer.has_audio());
assert!(matches!(buffer.next_frame().await, PcmFrame::Finished));
}

#[tokio::test]
async fn temporary_underrun_does_not_end_stream() {
let (sender, mut buffer) = PcmBuffer::channel();
let (sender, mut buffer) = PcmBuffer::channel(DEFAULT_BUFFERED_FRAMES);
for _ in 0..PREBUFFER_FRAMES {
sender.send(vec![1]).await.unwrap();
}
Expand All @@ -64,8 +130,8 @@ async fn temporary_underrun_does_not_end_stream() {

#[tokio::test]
async fn dropping_playback_releases_a_backpressured_producer() {
let (sender, buffer) = PcmBuffer::channel();
for _ in 0..PCM_CHANNEL_CAPACITY {
let (sender, buffer) = PcmBuffer::channel(DEFAULT_BUFFERED_FRAMES);
for _ in 0..DEFAULT_BUFFERED_FRAMES {
sender.try_send(vec![1]).unwrap();
}
let producer = tokio::spawn(async move { sender.send(vec![2]).await });
Expand Down
Loading
Loading