Files
voice_copy/voice-changer/app/mic_bridge.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

161 lines
5.7 KiB
Python

"""마이크 APO(apo/vcapo.cpp)와 주고받는 공유 메모리. 규약은 apo/vccore.h 와 같다.
APO 가 실제 마이크 소리를 in 링에 쓰면, 변환기가 읽어서 바꾼 소리를 out 링에 쓴다.
APO 는 그 소리를 마이크 소리 대신 디스코드 · 게임에 보낸다.
"""
import ctypes
import sys
import time
import numpy as np
NAME = "Global\\VoiceChangerAPO"
MAGIC = 0x31414356
VERSION = 1
RING = 262144
HEADER = 4096
SLOTS = 8
NAME_LEN = 128
SIZE = HEADER + 2 * RING * 4
class Slot(ctypes.Structure):
_fields_ = [("name", ctypes.c_uint16 * NAME_LEN), ("beat", ctypes.c_int64)]
class Header(ctypes.Structure):
_fields_ = [
("magic", ctypes.c_uint32),
("version", ctypes.c_uint32),
("app_beat", ctypes.c_int64),
("apo_beat", ctypes.c_int64),
("in_w", ctypes.c_int64),
("out_w", ctypes.c_int64),
("owner", ctypes.c_uint32),
("rate", ctypes.c_uint32),
("active", ctypes.c_uint32),
("prefill_ms", ctypes.c_uint32),
("underruns", ctypes.c_uint32),
("reserved", ctypes.c_uint32),
("target", ctypes.c_uint16 * NAME_LEN),
("slots", Slot * SLOTS),
]
assert ctypes.sizeof(Header) <= HEADER and Header.target.offset == 64 and Header.slots.offset == 320
def tick_ms() -> int:
"""APO 와 같은 시계 (GetTickCount64)."""
if sys.platform == "win32":
f = ctypes.windll.kernel32.GetTickCount64
f.restype = ctypes.c_uint64
return int(f())
return int(time.monotonic() * 1000)
def _utf16(s: str) -> list:
b = s.encode("utf-16-le")[: (NAME_LEN - 1) * 2]
return list(np.frombuffer(b, dtype="<u2")) + [0]
def _from_utf16(arr) -> str:
a = np.array(arr[:], dtype="<u2")
n = int(np.argmin(a)) if (a == 0).any() else len(a)
return a[:n].tobytes().decode("utf-16-le", "replace")
class NotConnected(RuntimeError):
pass
class Bridge:
def __init__(self, buf, clock=tick_ms, keep=None):
self._keep = keep # 매핑 핸들 등 (buf 보다 먼저 사라지면 안 됨)
self.clock = clock
self.h = Header.from_buffer(buf)
self.inr = np.frombuffer(buf, np.float32, RING, offset=HEADER)
self.outr = np.frombuffer(buf, np.float32, RING, offset=HEADER + RING * 4)
self.cursor = None
@classmethod
def open(cls):
"""APO 가 만든 공유 메모리를 연다. 아직 마이크를 쓰는 앱이 없으면 NotConnected."""
if sys.platform != "win32":
raise NotConnected("Windows 에서만 됩니다")
k32 = ctypes.WinDLL("kernel32", use_last_error=True)
k32.OpenFileMappingW.restype = ctypes.c_void_p
k32.OpenFileMappingW.argtypes = [ctypes.c_uint32, ctypes.c_int, ctypes.c_wchar_p]
k32.MapViewOfFile.restype = ctypes.c_void_p
k32.MapViewOfFile.argtypes = [ctypes.c_void_p, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_size_t]
h = k32.OpenFileMappingW(0x0006, 0, NAME) # FILE_MAP_READ | FILE_MAP_WRITE
if not h:
raise NotConnected(f"마이크 변환 모듈이 아직 열리지 않았습니다 (오류 {ctypes.get_last_error()})")
p = k32.MapViewOfFile(h, 0x0006, 0, 0, SIZE)
if not p:
k32.CloseHandle(ctypes.c_void_p(h))
raise NotConnected(f"공유 메모리를 열지 못했습니다 (오류 {ctypes.get_last_error()})")
buf = (ctypes.c_char * SIZE).from_address(p)
b = cls(buf, keep=(k32, h, p))
if b.h.magic != MAGIC or b.h.version != VERSION:
raise NotConnected("마이크 변환 모듈 버전이 맞지 않습니다. 설치를 다시 해 주세요")
return b
def close(self):
if self._keep and sys.platform == "win32":
k32, h, p = self._keep
self.h = self.inr = self.outr = None
k32.UnmapViewOfFile(ctypes.c_void_p(p))
k32.CloseHandle(ctypes.c_void_p(h))
self._keep = None
# ---- 상태 ----
def endpoints(self, within_ms=2000) -> list:
"""최근에 APO 가 돈 마이크 이름들."""
now = self.clock()
return [_from_utf16(s.name) for s in self.h.slots if s.beat and now - s.beat < within_ms and s.name[0]]
def owner_alive(self, within_ms=500) -> bool:
return self.h.owner != 0 and self.clock() - self.h.apo_beat < within_ms
@property
def rate(self) -> int:
return int(self.h.rate)
def start(self, target: str, prefill_ms: int = 60):
h = self.h
h.target[:] = (_utf16(target) + [0] * NAME_LEN)[:NAME_LEN]
h.prefill_ms = prefill_ms
h.app_beat = self.clock()
self.cursor = None
h.active = 1
def beat(self):
self.h.app_beat = self.clock()
def stop(self):
if self.h is not None:
self.h.active = 0
# ---- 소리 ----
def read(self, max_lag: int) -> np.ndarray:
"""APO 가 새로 쓴 마이크 소리 (모노 float32). 너무 밀렸으면 최근 max_lag 프레임만."""
w = int(self.h.in_w)
if self.cursor is None or w - self.cursor > min(max_lag, RING) or w < self.cursor:
self.cursor = max(w - max_lag, 0) if self.cursor is not None else w
n = w - self.cursor
if n <= 0:
return np.zeros(0, np.float32)
i = np.arange(self.cursor, w) % RING
self.cursor = w
return self.inr[i].copy()
def write(self, x: np.ndarray):
"""변환된 소리를 out 링에 이어 쓴다. 쓴 뒤에 위치를 올려야 APO 가 덜 쓴 소리를 읽지 않는다."""
x = np.asarray(x, np.float32).reshape(-1)
if len(x) == 0:
return
w = int(self.h.out_w)
self.outr[np.arange(w, w + len(x)) % RING] = x
self.h.out_w = w + len(x)