"""마이크 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=" str: a = np.array(arr[:], dtype=" 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)