- 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>
159 lines
6.5 KiB
Python
159 lines
6.5 KiB
Python
"""APO(apo/vccore.h, C) 와 변환기(app/mic_bridge.py, 파이썬)가 같은 공유 메모리로 맞물려 도는지.
|
|
|
|
vccore.h 를 그대로 공유 라이브러리로 컴파일해서, audiodg 가 10ms 마다 부르는 것처럼 흉내 낸다.
|
|
gcc 가 없으면 건너뛴다.
|
|
"""
|
|
import ctypes
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
from pathlib import Path
|
|
|
|
import numpy as np
|
|
|
|
HERE = Path(__file__).resolve().parent.parent
|
|
sys.path.insert(0, str(HERE / "app"))
|
|
import mic_bridge as mb # noqa: E402
|
|
|
|
SHIM = r"""
|
|
#include "vccore.h"
|
|
#include <stdlib.h>
|
|
void *inst_new(uint32_t id, const vc_wchar *name) {
|
|
vc_inst *s = calloc(1, sizeof(vc_inst)); s->id = id;
|
|
for (unsigned i = 0; i < VC_NAME - 1 && name[i]; i++) s->name[i] = name[i];
|
|
return s;
|
|
}
|
|
void init_header(void *shm) { vc_init_header((vc_header *)shm); }
|
|
void process(void *st, void *shm, float *io, uint32_t frames, uint32_t ch, uint32_t rate, int64_t now) {
|
|
vc_process((vc_inst *)st, (vc_header *)shm, io, frames, ch, rate, now);
|
|
}
|
|
"""
|
|
|
|
MIC = "마이크(USB Audio Device)"
|
|
|
|
|
|
def build_core():
|
|
cc = shutil.which("gcc") or shutil.which("cc")
|
|
if not cc:
|
|
return None
|
|
d = Path(tempfile.mkdtemp())
|
|
(d / "shim.c").write_text(SHIM)
|
|
so = d / "core.so"
|
|
subprocess.run([cc, "-O2", "-shared", "-fPIC", f"-I{HERE / 'apo'}", "-o", str(so), str(d / "shim.c")], check=True)
|
|
lib = ctypes.CDLL(str(so))
|
|
lib.inst_new.restype = ctypes.c_void_p
|
|
lib.inst_new.argtypes = [ctypes.c_uint32, ctypes.c_void_p]
|
|
lib.init_header.argtypes = [ctypes.c_void_p]
|
|
lib.process.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_int64]
|
|
return lib
|
|
|
|
|
|
class Sim:
|
|
"""audiodg 흉내: 10ms 마다 APO 인스턴스를 부르고, 시계는 테스트가 돌린다."""
|
|
|
|
def __init__(self, lib, rate=48000, ch=2):
|
|
self.lib, self.rate, self.ch = lib, rate, ch
|
|
self.buf = (ctypes.c_char * mb.SIZE)()
|
|
lib.init_header(ctypes.addressof(self.buf))
|
|
self.now = 1000
|
|
self.bridge = mb.Bridge(self.buf, clock=lambda: self.now)
|
|
self.insts = {}
|
|
|
|
def inst(self, iid, name=MIC):
|
|
if iid not in self.insts:
|
|
arr = (ctypes.c_uint16 * mb.NAME_LEN)(*mb._utf16(name))
|
|
self.insts[iid] = (self.lib.inst_new(iid, arr), arr)
|
|
return self.insts[iid][0]
|
|
|
|
def call(self, iid, mic: np.ndarray, name=MIC) -> np.ndarray:
|
|
"""mic: 모노 원래 소리 (한 번 부를 분량). 돌려주는 값: 앱이 받는 첫 채널."""
|
|
io = np.repeat(mic.astype(np.float32), self.ch).copy()
|
|
self.lib.process(self.inst(iid, name), ctypes.addressof(self.buf), io.ctypes.data, len(mic), self.ch, self.rate, self.now)
|
|
return io[:: self.ch].copy()
|
|
|
|
|
|
@unittest.skipUnless(build_core(), "C 컴파일러 없음")
|
|
class MicBridgeTest(unittest.TestCase):
|
|
def setUp(self):
|
|
self.sim = Sim(build_core())
|
|
self.n = self.sim.rate // 100 # 10ms
|
|
|
|
def voice(self, i):
|
|
t = (np.arange(self.n) + i * self.n) / self.sim.rate
|
|
return 0.3 * np.cos(2 * np.pi * 150 * t)
|
|
|
|
def test_off_passes_real_voice(self):
|
|
out = self.sim.call(1, self.voice(0))
|
|
np.testing.assert_allclose(out, self.voice(0), atol=1e-6)
|
|
self.assertEqual(self.sim.bridge.endpoints(), [MIC])
|
|
|
|
def test_on_sends_converted_voice_and_never_leaks_real_voice(self):
|
|
s, b = self.sim, self.sim.bridge
|
|
b.start(MIC, prefill_ms=60)
|
|
block = s.rate // 4 # 앱은 0.25초씩 모아 바꾼다
|
|
got, pending = [], np.zeros(0, np.float32)
|
|
for i in range(300): # 3초
|
|
s.now += 10
|
|
out = s.call(1, self.voice(i))
|
|
got.append(out)
|
|
b.beat()
|
|
pending = np.concatenate([pending, b.read(s.rate)])
|
|
while len(pending) >= block: # "변환": 부호를 뒤집어 원래 소리와 구별되게
|
|
b.write(-pending[:block])
|
|
pending = pending[block:]
|
|
y = np.concatenate(got)
|
|
x = np.concatenate([self.voice(i) for i in range(300)])
|
|
start = np.argmax(np.abs(y) > 1e-6)
|
|
# 변환된 소리가 오기 전에는 무음 (원래 목소리가 새지 않음)
|
|
self.assertTrue(np.all(y[:start] == 0))
|
|
self.assertGreaterEqual(start, block)
|
|
# 그 뒤로는 끊김 없이 변환된 소리 = 원래 소리를 일정하게(D) 늦춘 것의 부호 반대
|
|
D = next(d for d in range(start + 1) if np.allclose(y[start:start + 1000], -x[start - d:start - d + 1000], atol=1e-6))
|
|
np.testing.assert_allclose(y[start:], -x[start - D: len(y) - D], atol=1e-6)
|
|
self.assertLess(D / s.rate, 0.25 + 0.01 + 0.06 + 0.02) # 블록 + 첫 10ms + 여유 + 시계 오차
|
|
self.assertEqual(s.bridge.h.underruns, 0)
|
|
self.assertEqual(b.rate, s.rate)
|
|
|
|
def test_only_target_mic_and_one_writer(self):
|
|
s, b = self.sim, self.sim.bridge
|
|
b.start(MIC)
|
|
for i in range(20):
|
|
s.now += 10
|
|
s.call(1, self.voice(i))
|
|
s.call(2, self.voice(i)) # 같은 마이크를 다른 앱(통신 모드 등)이 쓰는 두 번째 인스턴스
|
|
other = s.call(3, self.voice(i), name="마이크(Webcam)")
|
|
np.testing.assert_allclose(other, self.voice(i), atol=1e-6) # 다른 마이크는 그대로
|
|
b.beat()
|
|
self.assertEqual(int(b.h.in_w), 20 * self.n) # 입력은 한 인스턴스만 씀 (두 번 쓰면 40)
|
|
self.assertEqual(int(b.h.owner), 1)
|
|
|
|
def test_app_gone_returns_to_real_voice(self):
|
|
s, b = self.sim, self.sim.bridge
|
|
b.start(MIC)
|
|
s.now += 10
|
|
self.assertTrue(np.all(s.call(1, self.voice(0)) == 0))
|
|
s.now += 2000 # 변환기가 죽어서 신호가 끊김
|
|
np.testing.assert_allclose(s.call(1, self.voice(1)), self.voice(1), atol=1e-6)
|
|
self.assertEqual(int(b.h.owner), 0)
|
|
|
|
def test_underrun_is_silence_then_recovers(self):
|
|
s, b = self.sim, self.sim.bridge
|
|
b.start(MIC, prefill_ms=0)
|
|
s.now += 10
|
|
s.call(1, self.voice(0))
|
|
b.read(s.rate)
|
|
b.write(np.full(self.n // 2, 0.5, np.float32)) # 반 블록만 줌
|
|
s.now += 10
|
|
out = s.call(1, self.voice(1))
|
|
self.assertTrue(np.allclose(out[: self.n // 2], 0.5) and np.all(out[self.n // 2:] == 0))
|
|
self.assertEqual(int(b.h.underruns), 1)
|
|
b.write(np.full(self.n, 0.25, np.float32))
|
|
s.now += 10
|
|
self.assertTrue(np.allclose(s.call(1, self.voice(2)), 0.25))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|