Files
voiceScript/pc-voice/main.cpp
T

379 lines
15 KiB
C++
Raw Normal View History

// pc-voice:PC 变声麦(男变女实时变声 → 虚拟声卡 → 微信/QQ 电脑版)
//
// 链路:物理麦克风 →[采集]→ DSP(PSOLA 变调+共振峰搬移)→[输出]→ VB-Cable Input
// 微信/QQ 电脑版把「CABLE Output (VB-Audio Virtual Cable)」选作麦克风即生效
//
// 用法:
// pc-voice.exe 交互模式(列设备→选择→运行)
// pc-voice.exe --list 仅列音频设备
// pc-voice.exe --line-out 线路输出模式(3.5mm 音频线连手机,方案一)
// pc-voice.exe --in 名字片段 --out 名子片段 --config 配置路径
//
// 运行中快捷键:1 少女 / 2 御姐 / 3 萝莉 / 4 中性女 / B 旁路开关 / ESC 退出
#include <windows.h>
#include <atomic>
#include <cstdarg>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#define MINIAUDIO_IMPLEMENTATION
#include "lib/miniaudio.h"
#include "config.h"
#include "dsp_pipeline.h"
// 控制台输出统一入口:
// 控制台 → WriteConsoleW 宽字符直写(免受代码页/GBK 影响,双击运行不乱码)
// 重定向 → 保持 UTF-8 字节输出(便于日志与脚本采集)
static void cprintf(const char* fmt, ...) {
char buf[1024];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD mode = 0;
if (h != INVALID_HANDLE_VALUE && GetConsoleMode(h, &mode)) {
wchar_t wbuf[1024];
int wlen = MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, 1024);
if (wlen > 0) {
DWORD written = 0;
WriteConsoleW(h, wbuf, (DWORD)(wlen - 1), &written, NULL);
}
} else {
fputs(buf, stdout);
fflush(stdout);
}
}
// ---------- 共享状态(采集线程 → 播放线程,SPSC 环) ----------
static DspPipeline g_pipeline;
static std::vector<float> g_ring;
static std::atomic<long> g_w{0}, g_r{0};
static std::atomic<int> g_underruns{0}, g_drops{0}, g_frames{0};
static long g_ringCap = 8192;
static long g_maxDepth = 960; // 环深上限 ≈ 20ms @48k
static void captureCallback(ma_device* dev, void* output, const void* input, ma_uint32 frameCount) {
(void)dev;
(void)output;
if (frameCount > 4096) frameCount = 4096;
float tmp[4096];
g_pipeline.process((const float*)input, tmp, (int)frameCount);
long w = g_w.load(std::memory_order_relaxed);
long r = g_r.load(std::memory_order_acquire);
for (ma_uint32 i = 0; i < frameCount; ++i) {
if (w - r >= g_ringCap) break;
g_ring[(size_t)(w & (g_ringCap - 1))] = tmp[i];
++w;
}
g_w.store(w, std::memory_order_release);
g_frames.fetch_add(1, std::memory_order_relaxed);
}
static void playbackCallback(ma_device* dev, void* output, const void* input, ma_uint32 frameCount) {
(void)dev;
(void)input;
float* dst = (float*)output;
const ma_uint32 totalFrames = frameCount;
if (frameCount > 4096) frameCount = 4096;
long w = g_w.load(std::memory_order_acquire);
long r = g_r.load(std::memory_order_relaxed);
// 延迟控制器:积压超限丢最旧
if (w - r > g_maxDepth) {
r = w - g_maxDepth;
g_drops.fetch_add(1, std::memory_order_relaxed);
}
ma_uint32 got = 0;
while (got < frameCount && r < w) {
dst[got++] = g_ring[(size_t)(r & (g_ringCap - 1))];
++r;
}
g_r.store(r, std::memory_order_release);
for (ma_uint32 i = got; i < frameCount; ++i) dst[i] = 0.f;
if (got < frameCount) g_underruns.fetch_add(1, std::memory_order_relaxed);
// 防御路径:帧数超界时清零尾部
if (totalFrames > 4096) {
memset((char*)output + 4096 * sizeof(float), 0, (size_t)(totalFrames - 4096) * sizeof(float));
}
}
// ---------- 参数下发 ----------
static VoiceCfg g_cfg;
static void applyParams() {
g_pipeline.setParams(g_cfg.pitchSemitones, g_cfg.formantRatio, g_cfg.strength,
g_cfg.eqFreqHz, g_cfg.eqGainDb, g_cfg.gateThreshold,
g_cfg.f0MinHz, g_cfg.f0MaxHz, g_cfg.smoothing, g_cfg.bypass);
g_pipeline.setOutputGain(g_cfg.outputGain);
g_pipeline.setTargetMode(g_cfg.targetMode, g_cfg.targetF0Hz);
}
static void applyPreset(int idx) {
g_cfg.pitchSemitones = g_cfg.presets[idx][0];
g_cfg.formantRatio = g_cfg.presets[idx][1];
applyParams();
cprintf("预设 → %s(+%.0f 半音, 共振峰 ×%.2f)\n",
idx == 0 ? "少女" : idx == 1 ? "御姐" : idx == 2 ? "萝莉" : "中性女",
(double)g_cfg.pitchSemitones, (double)g_cfg.formantRatio);
}
// ---------- 设备工具 ----------
struct DevicePick {
std::string inName, outName, configPath;
bool listOnly = false;
bool allowSpeakers = false;
};
static bool containsNoCase(const std::string& hay, const std::string& needle) {
auto lower = [](std::string s) {
for (auto& c : s) c = (char)tolower((unsigned char)c);
return s;
};
return lower(hay).find(lower(needle)) != std::string::npos;
}
static void printDevices(ma_context* ctx) {
ma_device_info* pCapture = NULL;
ma_uint32 nCapture = 0;
ma_device_info* pPlayback = NULL;
ma_uint32 nPlayback = 0;
if (ma_context_get_devices(ctx, &pPlayback, &nPlayback, &pCapture, &nCapture) != MA_SUCCESS) {
cprintf("设备枚举失败\n");
return;
}
cprintf("==== 录音设备(--in)====\n");
for (ma_uint32 i = 0; i < nCapture; ++i) {
cprintf(" [%u] %s%s\n", i, pCapture[i].name,
pCapture[i].isDefault ? " (默认)" : "");
}
cprintf("==== 播放设备(--out)====\n");
for (ma_uint32 i = 0; i < nPlayback; ++i) {
cprintf(" [%u] %s%s\n", i, pPlayback[i].name,
pPlayback[i].isDefault ? " (默认)" : "");
}
}
static bool pickDevice(ma_context* ctx, ma_device_type type, const std::string& namePat,
ma_device_id* outId, std::string& outName) {
ma_device_info* pCapture = NULL;
ma_uint32 nCapture = 0;
ma_device_info* pPlayback = NULL;
ma_uint32 nPlayback = 0;
if (ma_context_get_devices(ctx, &pPlayback, &nPlayback, &pCapture, &nCapture) != MA_SUCCESS) {
return false;
}
ma_device_info* list = (type == ma_device_type_capture) ? pCapture : pPlayback;
ma_uint32 n = (type == ma_device_type_capture) ? nCapture : nPlayback;
// 采集端防自环:CABLE 是我们自己的输出回环;立体声混音收的是系统播放声,
// 两者都不能当麦克风(否则 f0 恒 0 / 正反馈)
auto isLoopback = [](const char* name) {
return containsNoCase(name, "CABLE") || containsNoCase(name, "Mix") ||
containsNoCase(name, "混音");
};
auto looksLikeMic = [](const char* name) {
return containsNoCase(name, "Mic") || containsNoCase(name, "麦克风") ||
containsNoCase(name, "Array") || containsNoCase(name, "Headset") ||
containsNoCase(name, "耳麦");
};
// 1) 名字模糊匹配
if (!namePat.empty()) {
for (ma_uint32 i = 0; i < n; ++i) {
if (containsNoCase(list[i].name, namePat)) {
*outId = list[i].id;
outName = list[i].name;
return true;
}
}
cprintf("警告:未找到包含「%s」的设备,改用默认设备\n", namePat.c_str());
}
// 2) 默认设备(采集端跳过回环设备)
for (ma_uint32 i = 0; i < n; ++i) {
if (list[i].isDefault) {
if (type == ma_device_type_capture && isLoopback(list[i].name)) {
cprintf("提示:跳过回环设备「%s」\n", list[i].name);
continue;
}
*outId = list[i].id;
outName = list[i].name;
return true;
}
}
// 3) 兜底一:优先选长得像麦克风的
for (ma_uint32 i = 0; i < n; ++i) {
if (type == ma_device_type_capture &&
(isLoopback(list[i].name) || !looksLikeMic(list[i].name))) continue;
*outId = list[i].id;
outName = list[i].name;
return true;
}
// 4) 兜底二:任意非回环设备
for (ma_uint32 i = 0; i < n; ++i) {
if (type == ma_device_type_capture && isLoopback(list[i].name)) continue;
*outId = list[i].id;
outName = list[i].name;
return true;
}
return n > 0;
}
// ---------- main ----------
int main(int argc, char** argv) {
cprintf("==== pc-voice 变声麦 v0.1(男变女实时变声)====\n");
DevicePick pick;
for (int i = 1; i < argc; ++i) {
if (!strcmp(argv[i], "--list")) pick.listOnly = true;
else if (!strcmp(argv[i], "--line-out") || !strcmp(argv[i], "--allow-speakers")) pick.allowSpeakers = true;
else if (!strcmp(argv[i], "--in") && i + 1 < argc) pick.inName = argv[++i];
else if (!strcmp(argv[i], "--out") && i + 1 < argc) pick.outName = argv[++i];
else if (!strcmp(argv[i], "--config") && i + 1 < argc) pick.configPath = argv[++i];
}
if (pick.configPath.empty()) pick.configPath = "voice_config.json";
if (pick.outName.empty()) pick.outName = "CABLE Input"; // VB-Cable 默认输出端名
ma_context context;
if (ma_context_init(NULL, 0, NULL, &context) != MA_SUCCESS) {
cprintf("音频子系统初始化失败\n");
return 1;
}
if (pick.listOnly) {
printDevices(&context);
ma_context_uninit(&context);
return 0;
}
ma_device_id inId, outId;
std::string inName, outName;
if (!pickDevice(&context, ma_device_type_capture, pick.inName, &inId, inName) ||
!pickDevice(&context, ma_device_type_playback, pick.outName, &outId, outName)) {
cprintf("设备选择失败\n");
ma_context_uninit(&context);
return 1;
}
cprintf("输入: %s\n输出: %s\n", inName.c_str(), outName.c_str());
// 强校验:输出默认必须是虚拟声卡——直连扬声器会形成声反馈啸叫;
// --line-out 明示"线已插到手机里"(方案一),此时物理输出不会回授
if (!containsNoCase(outName, "CABLE") && !pick.allowSpeakers) {
cprintf("\n错误:输出设备「%s」是扬声器,直连会啸叫。\n", outName.c_str());
cprintf("方案一(音频线连手机):加 --line-out 启动(确认线已插入手机耳机孔)。\n");
cprintf("方案二(微信/QQ 电脑版):安装 VB-Cable 后选「CABLE Input」(README 有步骤)。\n");
ma_context_uninit(&context);
return 1;
}
// 配置加载(缺失则用默认值,运行中每 2 秒热加载)
bool hasCfg = loadConfig(pick.configPath, g_cfg);
cprintf("配置: %s (%s)\n", pick.configPath.c_str(), hasCfg ? "已加载" : "缺失,用默认值");
g_ring.assign((size_t)g_ringCap, 0.f); // 环形缓冲分配(音频回调前提)
g_pipeline.setup(48000.f);
applyParams();
// 设备配置:48kHz 单声道浮点,10ms 周期,低延迟档
ma_device_config cfgIn = ma_device_config_init(ma_device_type_capture);
cfgIn.capture.format = ma_format_f32;
cfgIn.capture.channels = 1;
cfgIn.capture.pDeviceID = &inId;
cfgIn.sampleRate = 48000;
cfgIn.periodSizeInMilliseconds = 10;
cfgIn.performanceProfile = ma_performance_profile_low_latency;
cfgIn.dataCallback = captureCallback;
ma_device_config cfgOut = ma_device_config_init(ma_device_type_playback);
cfgOut.playback.format = ma_format_f32;
cfgOut.playback.channels = 1;
cfgOut.playback.pDeviceID = &outId;
cfgOut.sampleRate = 48000;
cfgOut.periodSizeInMilliseconds = 10;
cfgOut.performanceProfile = ma_performance_profile_low_latency;
cfgOut.dataCallback = playbackCallback;
ma_device devIn, devOut;
if (ma_device_init(&context, &cfgIn, &devIn) != MA_SUCCESS ||
ma_device_init(&context, &cfgOut, &devOut) != MA_SUCCESS) {
cprintf("音频设备初始化失败(确认已安装 VB-Cable 且未被独占)\n");
ma_context_uninit(&context);
return 1;
}
if (ma_device_start(&devIn) != MA_SUCCESS || ma_device_start(&devOut) != MA_SUCCESS) {
cprintf("音频设备启动失败\n");
ma_context_uninit(&context);
return 1;
}
if (pick.allowSpeakers) {
cprintf("运行中!方案一(线连手机):确认音频线已插入手机耳机孔,手机戴耳机通话。\n");
} else {
cprintf("运行中!方案二(电脑版):微信/QQ 把「CABLE Output (VB-Audio Virtual Cable)」选作麦克风。\n");
}
cprintf("快捷键:1 少女 / 2 御姐 / 3 萝莉 / 4 中性女 / B 旁路 / ESC 退出\n\n");
// 主循环:快捷键 + 统计 + 配置热加载
long cfgMtime = 0;
{
WIN32_FILE_ATTRIBUTE_DATA fad;
if (GetFileAttributesExA(pick.configPath.c_str(), GetFileExInfoStandard, &fad))
cfgMtime = (long)fad.ftLastWriteTime.dwLowDateTime;
}
int tick = 0;
for (;;) {
Sleep(250);
// 快捷键(低 bit = 自上次调用以来按下过)
if (GetAsyncKeyState('1') & 1) applyPreset(0);
if (GetAsyncKeyState('2') & 1) applyPreset(1);
if (GetAsyncKeyState('3') & 1) applyPreset(2);
if (GetAsyncKeyState('4') & 1) applyPreset(3);
if (GetAsyncKeyState('B') & 1) {
g_cfg.bypass = !g_cfg.bypass;
applyParams();
cprintf("旁路 → %s\n", g_cfg.bypass ? "开(干声)" : "关(变声)");
}
if (GetAsyncKeyState(VK_ESCAPE) & 1) break;
// 配置热加载(每 2 秒)
if ((++tick % 8) == 0) {
WIN32_FILE_ATTRIBUTE_DATA fad;
if (GetFileAttributesExA(pick.configPath.c_str(), GetFileExInfoStandard, &fad) &&
(long)fad.ftLastWriteTime.dwLowDateTime != cfgMtime) {
cfgMtime = (long)fad.ftLastWriteTime.dwLowDateTime;
if (loadConfig(pick.configPath, g_cfg)) {
applyParams();
cprintf("配置已热更新\n");
}
}
}
// 统计(每秒)
if ((tick % 4) == 0) {
long depth = g_w.load() - g_r.load();
cprintf("f0=%.1fHz | 处理=%.2fms/帧 | 环深=%ld | 欠载=%d | 裁剪=%d | 端到端≈%.1fms | %s\n",
(double)g_pipeline.currentF0(), (double)g_pipeline.avgProcMs(),
depth, g_underruns.load(), g_drops.load(),
(double)(depth + Psola::kLatencySamples + 2048) * 1000.0 / 48000.0,
g_cfg.bypass ? "旁路" : "变声中");
fflush(stdout);
}
}
ma_device_uninit(&devIn);
ma_device_uninit(&devOut);
ma_context_uninit(&context);
cprintf("已退出。\n");
return 0;
}