Files
voice_copy/voice-changer/tests/test_converter_pump.py
EJClaw 21b4278b77 voice-changer: one-click installer, mic APO instead of virtual cable, keep all files in install folder
- apo/: VoiceChangerAPO.dll (SFX APO on the real mic, built with mingw). When the app converts,
  the mic's own stream carries the converted voice; otherwise it passes the real voice through.
  Shared-memory protocol in vccore.h, Python side app/mic_bridge.py
- scripts/mic-apo.ps1: register/unregister on every capture endpoint with admin value rights only
  (no ACL changes unless FxProperties is missing), originals backed up and restored
- app: mic is the conversion target (WASAPI names), no output device, '마이크 다시 연결' button,
  44.1k<->48k streaming resample, caches/temp redirected into <install>/cache
- installer/VoiceChanger.iss (Inno Setup): choose install folder, register APO, download engine
  into that folder, uninstall restores mic settings and asks before deleting models
- install.ps1: uv python --no-bin --no-registry, temp/caches inside the folder, uv cache clean
- tests: C core compiled with gcc against the Python bridge; converter pump 44.1k round trip

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 16:33:15 +09:00

89 lines
3.3 KiB
Python

"""변환기(voice_changer.Converter._pump)가 마이크 모듈과 실제로 맞물려 도는지.
APO 는 vccore.h 를 그대로 컴파일한 것(test_mic_bridge.Sim)이고 마이크는 44.1kHz 스테레오다.
엔진 자리에는 부호만 뒤집는 가짜 엔진을 넣어서, 44.1kHz → 48kHz → 엔진 → 44.1kHz 로 바꿔 마이크로
돌려보낸 소리가 끊김 없이 이어지는지(원래 목소리는 새지 않는지) 본다. Applio 엔진 자체는 따로 검증함.
"""
import os
import sys
import tempfile
import threading
import time
import types
import unittest
from pathlib import Path
import numpy as np
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
sys.path.insert(0, str(HERE.parent / "app"))
os.environ.setdefault("VC_ROOT", tempfile.mkdtemp())
try:
import soxr # noqa: F401
import tkinter # noqa: F401
except ImportError:
soxr = None
from test_mic_bridge import Sim, build_core # noqa: E402
LIB = build_core()
def fake_engine():
"""rvc.realtime.audio.queue_latest 와 AudioCallbacks.audio 자리."""
mod = types.ModuleType("rvc.realtime.audio")
mod.queue_latest = lambda q, x: None
for name in ("rvc", "rvc.realtime"):
sys.modules.setdefault(name, types.ModuleType(name))
sys.modules["rvc.realtime.audio"] = mod
audio = types.SimpleNamespace(
output_audio_gain=1.0, use_monitor=False, mon_queue=None,
process_data_with_time=lambda x: -x[:, 0], # (N, 1) → (N,), Applio 와 같은 모양
)
return types.SimpleNamespace(audio=audio)
@unittest.skipUnless(LIB and soxr, "C 컴파일러 · soxr · tkinter 필요")
class PumpTest(unittest.TestCase):
def test_44k_mic_roundtrip_through_48k_engine(self):
from voice_changer import Converter
sim = Sim(LIB, rate=44100, ch=2)
b = sim.bridge
b.start("마이크(USB Audio Device)", prefill_ms=60)
conv = Converter()
cb = fake_engine()
t = threading.Thread(target=conv._pump, args=(b, cb, 12000, 48000), daemon=True) # 0.25초 블록
n = 441 # 10ms
xs, ys = [], []
t.start()
try:
for i in range(300): # 3초, 실제 시간으로 흘린다
sim.now += 10
x = 0.3 * np.sin(2 * np.pi * 300 * (np.arange(n) + i * n) / 44100)
xs.append(x)
ys.append(sim.call(1, x, name="마이크(USB Audio Device)"))
time.sleep(0.01)
finally:
conv.halt.set()
t.join(2)
self.assertIsNone(conv.error)
x, y = np.concatenate(xs), np.concatenate(ys)
start = int(np.argmax(np.abs(y) > 1e-4))
self.assertTrue(np.all(np.abs(y[:start]) <= 1e-4), "변환된 소리가 오기 전에 원래 목소리가 샘")
self.assertLess(start / 44100, 0.6)
seg = y[start + 2000:]
# 지연 D 를 찾아 y[t] ≈ -x[t-D] 인지 (리샘플 두 번의 오차만 남아야 함)
best = max(range(0, start + 2000), key=lambda d: -np.abs(seg[:4000] + x[start + 2000 - d:start + 6000 - d]).mean())
ref = -x[start + 2000 - best: start + 2000 - best + len(seg)]
err = np.abs(seg - ref)
self.assertLess(float(err.mean()), 0.01)
self.assertEqual(int(b.h.underruns), 0, "중간에 끊김")
self.assertEqual(b.rate, 44100)
if __name__ == "__main__":
unittest.main()