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>
This commit is contained in:
@@ -8,24 +8,48 @@
|
||||
- torch 2.11 + CUDA 12.8 (RTX 50 시리즈 지원). NVIDIA 드라이버 580 이상
|
||||
- 디스크: 설치 약 8GB(Python · torch · 엔진 기본 모델) + 모델마다 약 80MB + 학습 중간 파일. 예시 모델까지 만들면 15GB 정도 여유를 두세요
|
||||
|
||||
## 설치
|
||||
## 설치 — `VoiceChangerSetup.exe` 하나만
|
||||
|
||||
1. 이 폴더를 원하는 곳에 풉니다 (경로에 한글이 없어도, 있어도 됩니다).
|
||||
2. `install.bat` 을 더블클릭합니다. uv, Python 3.12, 엔진, torch(CUDA 12.8), 엔진 기본 모델(rmvpe · contentvec · 사전학습 가중치 · ffmpeg)을 이 폴더 안에만 받습니다. 처음에는 10~20분 걸립니다.
|
||||
3. 마지막 줄에 `GPU 확인: NVIDIA GeForce RTX 5070 Ti (sm_120)` 가 나오면 끝입니다.
|
||||
4. 디스코드에서 쓰려면 가상 오디오 케이블 [VB-CABLE](https://vb-audio.com/Cable/) 을 설치합니다 (무료).
|
||||
1. `VoiceChangerSetup.exe` 를 실행합니다 (관리자 권한 확인 창이 뜹니다).
|
||||
2. **설치할 폴더**를 고릅니다. 기본값은 `C:\VoiceChanger` 이고, 다른 드라이브(`D:\...`)나 한글 · 띄어쓰기가 들어간 경로도 됩니다.
|
||||
Python · 엔진 · torch · 목소리 모델 · 설정 · 학습 파일 · 캐시 · 임시 파일이 **모두 이 폴더 안에만** 저장됩니다.
|
||||
설치하면서 약 8GB 를 내려받고 모델을 만들수록 늘어나므로 15GB 이상 비어 있는 드라이브를 고르세요.
|
||||
3. 설치 프로그램이 마이크마다 변환 모듈을 붙이고(윈도우 소리가 1~2초 끊김), 검은 창에서 Python 3.12 · 엔진(Applio) ·
|
||||
torch(CUDA 12.8) · 엔진 기본 모델(rmvpe · contentvec · 사전학습 가중치 · ffmpeg)을 그 폴더로 내려받습니다. 10~20분 걸립니다.
|
||||
마지막에 `GPU 확인: NVIDIA GeForce RTX 5070 Ti (sm_120)` 가 나오면 정상입니다.
|
||||
4. 시작 메뉴의 **음성 변환기**로 실행합니다.
|
||||
|
||||
## 변환하기 — `VoiceChanger.exe`
|
||||
가상 오디오 장치(VB-CABLE 등)는 필요 없습니다. 변환기가 내 마이크에서 나가는 소리를 직접 바꿔 주므로,
|
||||
디스코드 · 게임의 입력 장치는 **평소 쓰던 마이크 그대로** 두면 됩니다.
|
||||
|
||||
- 내려받다가 끊기면 설치 폴더의 `install.bat` 을 실행합니다. 받은 곳부터 이어서 받습니다.
|
||||
- 폴더 밖에 남는 것은 윈도우가 관리하는 항목뿐입니다: 시작 메뉴 바로 가기, 프로그램 제거 목록, 마이크 모듈 등록(레지스트리).
|
||||
사용자 폴더(`%APPDATA%` · `%LOCALAPPDATA%` · `%TEMP%` · `.cache`)에는 아무것도 쓰지 않습니다.
|
||||
- 제거: 설정 → 앱 → 음성 변환기 → 제거. 마이크 설정을 원래대로 되돌리고, 만든 모델 · 녹음 · 설정까지 지울지 묻습니다.
|
||||
|
||||
### 마이크 모듈은 어떻게 동작하나
|
||||
|
||||
윈도우는 마이크 소리를 앱에 넘기기 전에 오디오 처리 모듈(APO, Equalizer APO 와 같은 방식)을 거칩니다.
|
||||
설치 프로그램이 `apo\VoiceChangerAPO.dll` 을 각 마이크의 처리 단계에 붙입니다 (`scripts\mic-apo.ps1`, 바꾼 값의 원래 값은 `config\mic-apo-backup.json`).
|
||||
|
||||
- 변환기가 꺼져 있으면 아무것도 하지 않습니다. 원래 목소리가 그대로 나갑니다
|
||||
- 변환을 켜면 고른 마이크의 소리를 변환기로 넘기고, 바뀐 목소리를 대신 내보냅니다. 바뀐 소리가 아직 없을 때는 무음이라 원래 목소리가 새지 않습니다
|
||||
- 변환기가 꺼지거나 멈추면 1.5초 안에 원래 목소리로 돌아갑니다
|
||||
- 그 마이크를 쓰는 모든 앱(디스코드 · 게임 · 녹음기)에 바뀐 목소리가 갑니다
|
||||
- 윈도우 소리 설정에서 마이크의 **오디오 향상**을 끄면 모듈이 빠집니다. 설치할 때 켜 두지만, 직접 끄면 변환이 안 됩니다
|
||||
- 새로 꽂은 마이크나 드라이버를 업데이트한 마이크는 변환기 화면의 **마이크 다시 연결**을 누릅니다
|
||||
|
||||
## 변환하기 — 음성 변환기
|
||||
|
||||
1. 목소리 모델을 고릅니다. 직접 학습한 모델이 위에, 예시 모델이 아래에 나옵니다.
|
||||
2. **내 목소리 성별**을 고르면 성별이 다른 모델은 음높이를 ±12반음(한 옥타브)으로 자동으로 맞춥니다. 슬라이더로 더 맞출 수 있고, 켜 둔 채로 바꿔도 바로 적용됩니다.
|
||||
3. **마이크**에 내 마이크, **출력**에 `CABLE Input (VB-Audio Virtual Cable)` 을 고릅니다. 디스코드 음성 설정의 입력 장치를 `CABLE Output` 으로 바꿉니다.
|
||||
3. **마이크**에서 내 마이크를 고릅니다. 디스코드 입력 장치도 같은 마이크로 둡니다.
|
||||
4. 내 귀로 확인하려면 **내 귀로 듣기**를 켜고 헤드셋을 고릅니다.
|
||||
5. **▶ 변환 시작**. 처음에는 모델을 불러오느라 몇 초 걸립니다. 아래에 처리 시간(ms)이 나옵니다.
|
||||
|
||||
- 지연: 보통(0.25초)이 기본입니다. RTX 5070 Ti 는 낮음(0.13초)도 됩니다. 소리가 끊기면 한 단계 올리세요.
|
||||
- 잡음 무시: 이 크기(dB)보다 작은 소리는 변환하지 않습니다. 키보드 소리가 들어가면 올리세요.
|
||||
- 설정은 `config/settings.json` 에 저장돼 다음에 그대로 열립니다.
|
||||
- 설정은 `config\settings.json` 에 저장돼 다음에 그대로 열립니다.
|
||||
|
||||
## 목소리 모델 학습 — `train.bat`
|
||||
|
||||
@@ -67,16 +91,33 @@ train.bat D:\dataset_지원 "지원" female --epochs 300
|
||||
|
||||
```
|
||||
VoiceChanger.exe 실행기 (env\Scripts\pythonw.exe app\voice_changer.py 를 띄움, 소스 launcher\launcher.c)
|
||||
install.bat 설치 (scripts\install.ps1)
|
||||
install.bat 엔진 내려받기 · 이어 받기 (scripts\install.ps1, 설치 프로그램도 이것을 실행)
|
||||
train.bat 학습 (app\train.py)
|
||||
examples.bat 예시 모델 (app\examples.py)
|
||||
app\ 화면 · 학습 · 모델 목록 코드
|
||||
app\ 화면 · 학습 · 모델 목록 · 마이크 모듈 연결(mic_bridge.py) 코드
|
||||
apo\ 마이크 모듈 VoiceChangerAPO.dll 과 소스 (vcapo.cpp, 주고받는 규약 vccore.h)
|
||||
scripts\mic-apo.ps1 마이크 모듈 붙이기 · 떼기 (관리자)
|
||||
models\<아이디>\ model.pth · model.index · info.json(이름 · 성별 · 출처 · 라이선스)
|
||||
engine\ env\ tools\ 설치하면 생기는 폴더 (엔진 · Python · uv)
|
||||
config\ 설정 · 마이크 모듈 백업
|
||||
cache\ 임시 파일 · torch · huggingface · matplotlib 등 라이브러리 캐시 (지워도 됨)
|
||||
engine\ env\ tools\ 설치하면 생기는 폴더 (엔진 · Python · uv)
|
||||
uninstall\ 제거 프로그램
|
||||
```
|
||||
|
||||
## 배포 파일 만들기 (리눅스)
|
||||
## 배포 파일 만들기
|
||||
|
||||
```bash
|
||||
voice-changer/scripts/build-release.sh # mingw 로 VoiceChanger.exe 를 빌드하고 dist/voice-changer-win.zip 을 만듦
|
||||
voice-changer/scripts/build-release.sh # 리눅스 mingw: VoiceChanger.exe · VoiceChangerAPO.dll 빌드 → dist/payload, dist/voice-changer-win.zip
|
||||
```
|
||||
|
||||
```powershell
|
||||
powershell -ExecutionPolicy Bypass -File installer\build.ps1 # Windows + Inno Setup 6: dist\payload → dist\VoiceChangerSetup.exe
|
||||
```
|
||||
|
||||
Inno Setup 은 리눅스 wine 에서 돌지 않아(32비트 프로그램이 wine wow64 에서 죽음) Windows 에서 빌드합니다.
|
||||
|
||||
## 테스트
|
||||
|
||||
```bash
|
||||
python -m unittest discover -s voice-changer/tests # 마이크 모듈 C 코드를 gcc 로 컴파일해 파이썬 쪽과 맞물려 봄 (soxr · numpy 필요)
|
||||
```
|
||||
|
||||
457
voice-changer/apo/vcapo.cpp
Normal file
457
voice-changer/apo/vcapo.cpp
Normal file
@@ -0,0 +1,457 @@
|
||||
/* VoiceChangerAPO.dll: 실제 마이크에 붙는 Windows 오디오 처리 모듈(SFX APO).
|
||||
* 음성 변환기가 켜져 있으면 마이크 소리를 변환된 목소리로 바꿔 디스코드 · 게임에 보낸다.
|
||||
* 가상 오디오 드라이버(VB-CABLE 등) 없이 쓰기 위한 것. 처리 내용은 vccore.h.
|
||||
*
|
||||
* 빌드 (리눅스): scripts/build-release.sh 가 아래처럼 빌드한다
|
||||
* x86_64-w64-mingw32-g++ -O2 -shared -static -fno-exceptions -fno-rtti -o VoiceChangerAPO.dll \
|
||||
* apo/vcapo.cpp apo/vcapo.def -lole32 -luuid -ladvapi32
|
||||
* 등록 · 해제는 scripts/mic-apo.ps1 (설치 프로그램이 관리자 권한으로 실행). */
|
||||
#include <windows.h>
|
||||
#include <objbase.h>
|
||||
#include <mmreg.h>
|
||||
#include <propsys.h>
|
||||
#include <sddl.h>
|
||||
#include <new>
|
||||
#include "vccore.h"
|
||||
|
||||
/* ---- audioenginebaseapo.h / audiomediatype.h 의 필요한 부분 (mingw 에 없음) ---- */
|
||||
typedef LONGLONG HNSTIME;
|
||||
enum { BUFFER_INVALID = 0, BUFFER_VALID = 1, BUFFER_SILENT = 2 };
|
||||
/* FRAMESPERSECOND_MUST_MATCH | BITSPERSAMPLE_MUST_MATCH | INPLACE (Equalizer APO 와 같음) */
|
||||
#define VC_APO_FLAGS 0x0000000d
|
||||
#define APOERR_NOT_INITIALIZED ((HRESULT)0x887D0002L)
|
||||
#define APOERR_FORMAT_NOT_SUPPORTED ((HRESULT)0x887D0003L)
|
||||
#define APOERR_ALREADY_UNLOCKED ((HRESULT)0x887D0006L)
|
||||
#define APOERR_NUM_CONNECTIONS_INVALID ((HRESULT)0x887D0007L)
|
||||
#define APOERR_APO_LOCKED ((HRESULT)0x887D000AL)
|
||||
|
||||
struct UNCOMPRESSEDAUDIOFORMAT {
|
||||
GUID guidFormatType;
|
||||
DWORD dwSamplesPerFrame;
|
||||
DWORD dwBytesPerSampleContainer;
|
||||
DWORD dwValidBitsPerSample;
|
||||
FLOAT fFramesPerSecond;
|
||||
DWORD dwChannelMask;
|
||||
};
|
||||
|
||||
struct IAudioMediaType : public IUnknown {
|
||||
virtual HRESULT STDMETHODCALLTYPE IsCompressedFormat(BOOL *) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE IsEqual(IAudioMediaType *, DWORD *) = 0;
|
||||
virtual const WAVEFORMATEX *STDMETHODCALLTYPE GetAudioFormat() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE GetUncompressedAudioFormat(UNCOMPRESSEDAUDIOFORMAT *) = 0;
|
||||
};
|
||||
|
||||
struct APO_CONNECTION_DESCRIPTOR {
|
||||
UINT32 Type;
|
||||
UINT_PTR pBuffer;
|
||||
UINT32 u32MaxFrameCount;
|
||||
IAudioMediaType *pFormat;
|
||||
UINT32 u32Signature;
|
||||
};
|
||||
|
||||
struct APO_CONNECTION_PROPERTY {
|
||||
UINT_PTR pBuffer;
|
||||
UINT32 u32ValidFrameCount;
|
||||
UINT32 u32BufferFlags;
|
||||
UINT32 u32Signature;
|
||||
};
|
||||
|
||||
struct APO_REG_PROPERTIES {
|
||||
CLSID clsid;
|
||||
UINT32 Flags;
|
||||
WCHAR szFriendlyName[256];
|
||||
WCHAR szCopyrightInfo[256];
|
||||
UINT32 u32MajorVersion;
|
||||
UINT32 u32MinorVersion;
|
||||
UINT32 u32MinInputConnections;
|
||||
UINT32 u32MaxInputConnections;
|
||||
UINT32 u32MinOutputConnections;
|
||||
UINT32 u32MaxOutputConnections;
|
||||
UINT32 u32MaxInstances;
|
||||
UINT32 u32NumAPOInterfaces;
|
||||
IID iidAPOInterfaceList[1];
|
||||
};
|
||||
|
||||
struct APOInitBaseStruct {
|
||||
UINT32 cbSize;
|
||||
CLSID clsid;
|
||||
};
|
||||
|
||||
struct APOInitSystemEffects {
|
||||
APOInitBaseStruct APOInit;
|
||||
IPropertyStore *pAPOEndpointProperties;
|
||||
IPropertyStore *pAPOSystemEffectsProperties;
|
||||
void *pReserved;
|
||||
IUnknown *pDeviceCollection;
|
||||
};
|
||||
|
||||
struct APOInitSystemEffects2 {
|
||||
APOInitBaseStruct APOInit;
|
||||
IPropertyStore *pAPOEndpointProperties;
|
||||
IPropertyStore *pAPOSystemEffectsProperties;
|
||||
void *pReserved;
|
||||
IUnknown *pDeviceCollection;
|
||||
UINT nSoftwareIoDeviceInCollection;
|
||||
UINT nSoftwareIoConnectorIndex;
|
||||
GUID AudioProcessingMode;
|
||||
BOOL InitializeForDiscoveryOnly;
|
||||
};
|
||||
|
||||
struct IAudioProcessingObject : public IUnknown {
|
||||
virtual HRESULT STDMETHODCALLTYPE Reset() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE GetLatency(HNSTIME *) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE GetRegistrationProperties(APO_REG_PROPERTIES **) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE Initialize(UINT32, BYTE *) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE IsInputFormatSupported(IAudioMediaType *, IAudioMediaType *, IAudioMediaType **) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE IsOutputFormatSupported(IAudioMediaType *, IAudioMediaType *, IAudioMediaType **) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE GetInputChannelCount(UINT32 *) = 0;
|
||||
};
|
||||
|
||||
struct IAudioProcessingObjectRT : public IUnknown {
|
||||
virtual void STDMETHODCALLTYPE APOProcess(UINT32, APO_CONNECTION_PROPERTY **, UINT32, APO_CONNECTION_PROPERTY **) = 0;
|
||||
virtual UINT32 STDMETHODCALLTYPE CalcInputFrames(UINT32) = 0;
|
||||
virtual UINT32 STDMETHODCALLTYPE CalcOutputFrames(UINT32) = 0;
|
||||
};
|
||||
|
||||
struct IAudioProcessingObjectConfiguration : public IUnknown {
|
||||
virtual HRESULT STDMETHODCALLTYPE LockForProcess(UINT32, APO_CONNECTION_DESCRIPTOR **, UINT32, APO_CONNECTION_DESCRIPTOR **) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE UnlockForProcess() = 0;
|
||||
};
|
||||
|
||||
struct IAudioSystemEffects2 : public IUnknown {
|
||||
virtual HRESULT STDMETHODCALLTYPE GetEffectsList(LPGUID *, UINT *, HANDLE) = 0;
|
||||
};
|
||||
|
||||
static const IID IID_IAudioProcessingObject_ = {0xFD7F2B29, 0x24D0, 0x4b5c, {0xB1, 0x77, 0x59, 0x2C, 0x39, 0xF9, 0xCA, 0x10}};
|
||||
static const IID IID_IAudioProcessingObjectRT_ = {0x9E1D6A6D, 0xDDBC, 0x4E95, {0xA4, 0xC7, 0xAD, 0x64, 0xBA, 0x37, 0x84, 0x6C}};
|
||||
static const IID IID_IAudioProcessingObjectConfiguration_ = {0x0E5ED805, 0xABA6, 0x49c3, {0x8F, 0x9A, 0x2B, 0x8C, 0x88, 0x9C, 0x4F, 0xA8}};
|
||||
static const IID IID_IAudioSystemEffects_ = {0x5FA00F27, 0xADD6, 0x499a, {0x8A, 0x9D, 0x6B, 0x98, 0x52, 0x1F, 0xA7, 0x5B}};
|
||||
static const IID IID_IAudioSystemEffects2_ = {0xBAFE99D2, 0x7436, 0x44CE, {0x9E, 0x0E, 0x4D, 0x89, 0xAF, 0xBF, 0xFF, 0x56}};
|
||||
static const GUID SUBTYPE_IEEE_FLOAT = {0x00000003, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}};
|
||||
static const PROPERTYKEY PKEY_FriendlyName_ = {{0xa45c254e, 0xdf1c, 0x4efd, {0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0}}, 14};
|
||||
|
||||
/* 이 APO 의 CLSID. scripts/mic-apo.ps1 의 $Clsid 와 같아야 한다. */
|
||||
static const CLSID CLSID_VoiceChangerAPO = {0x6f1c5e2a, 0x3b7d, 0x4c41, {0x9a, 0x0e, 0x5d, 0x2b, 0x8f, 0x61, 0xc4, 0x37}};
|
||||
static const wchar_t SHM_NAME[] = L"Global\\VoiceChangerAPO";
|
||||
|
||||
static LONG g_objects = 0, g_locks = 0;
|
||||
|
||||
#ifdef VC_DEBUG /* 진단용 빌드: audiodg 의 임시 폴더(LocalService)에 vcapo.log 를 남긴다 */
|
||||
#include <stdio.h>
|
||||
static void dlog(const char *fmt, ...) {
|
||||
wchar_t dir[MAX_PATH], path[MAX_PATH];
|
||||
if (!GetTempPathW(MAX_PATH, dir)) return;
|
||||
_snwprintf(path, MAX_PATH, L"%lsvcapo.log", dir);
|
||||
FILE *f = _wfopen(path, L"a");
|
||||
if (!f) return;
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
fprintf(f, "%llu pid=%lu ", (unsigned long long)GetTickCount64(), GetCurrentProcessId());
|
||||
vfprintf(f, fmt, ap);
|
||||
fputc('\n', f);
|
||||
va_end(ap);
|
||||
fclose(f);
|
||||
}
|
||||
#else
|
||||
#define dlog(...) ((void)0)
|
||||
#endif
|
||||
static volatile LONG g_next_id = 0;
|
||||
|
||||
static bool is_float32(IAudioMediaType *t, UNCOMPRESSEDAUDIOFORMAT *f) {
|
||||
if (!t) return false;
|
||||
BOOL compressed = TRUE;
|
||||
if (FAILED(t->IsCompressedFormat(&compressed)) || compressed) return false;
|
||||
if (FAILED(t->GetUncompressedAudioFormat(f))) return false;
|
||||
return IsEqualGUID(f->guidFormatType, SUBTYPE_IEEE_FLOAT) && f->dwBytesPerSampleContainer == 4 &&
|
||||
f->dwSamplesPerFrame > 0;
|
||||
}
|
||||
|
||||
static bool same_shape(IAudioMediaType *a, IAudioMediaType *b) {
|
||||
UNCOMPRESSEDAUDIOFORMAT fa, fb;
|
||||
if (!is_float32(a, &fa) || !is_float32(b, &fb)) return false;
|
||||
return fa.dwSamplesPerFrame == fb.dwSamplesPerFrame && fa.fFramesPerSecond == fb.fFramesPerSecond;
|
||||
}
|
||||
|
||||
struct INonDelegatingUnknown {
|
||||
virtual HRESULT STDMETHODCALLTYPE NDQueryInterface(REFIID, void **) = 0;
|
||||
virtual ULONG STDMETHODCALLTYPE NDAddRef() = 0;
|
||||
virtual ULONG STDMETHODCALLTYPE NDRelease() = 0;
|
||||
};
|
||||
|
||||
class VoiceChangerAPO : public INonDelegatingUnknown,
|
||||
public IAudioProcessingObject,
|
||||
public IAudioProcessingObjectRT,
|
||||
public IAudioProcessingObjectConfiguration,
|
||||
public IAudioSystemEffects2 {
|
||||
LONG ref_ = 1;
|
||||
IUnknown *outer_;
|
||||
bool init_ = false, locked_ = false, discovery_ = false;
|
||||
UINT32 ch_ = 0, rate_ = 0;
|
||||
HANDLE map_ = NULL;
|
||||
vc_header *shm_ = NULL;
|
||||
vc_inst st_;
|
||||
|
||||
void open_shm() {
|
||||
if (shm_) return;
|
||||
/* audiodg(LocalService) 가 만들고, 일반 권한의 음성 변환기가 연다 */
|
||||
SECURITY_ATTRIBUTES sa = {sizeof(sa), NULL, FALSE};
|
||||
PSECURITY_DESCRIPTOR sd = NULL;
|
||||
if (ConvertStringSecurityDescriptorToSecurityDescriptorW(
|
||||
L"D:(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;LS)(A;;GA;;;IU)(A;;GA;;;AU)S:(ML;;NW;;;LW)", SDDL_REVISION_1, &sd,
|
||||
NULL))
|
||||
sa.lpSecurityDescriptor = sd;
|
||||
map_ = CreateFileMappingW(INVALID_HANDLE_VALUE, &sa, PAGE_READWRITE, 0, VC_SIZE, SHM_NAME);
|
||||
dlog("open_shm map=%p err=%lu sd=%p", map_, GetLastError(), sd);
|
||||
if (sd) LocalFree(sd);
|
||||
if (!map_) return;
|
||||
shm_ = (vc_header *)MapViewOfFile(map_, FILE_MAP_ALL_ACCESS, 0, 0, VC_SIZE);
|
||||
if (!shm_) {
|
||||
CloseHandle(map_);
|
||||
map_ = NULL;
|
||||
return;
|
||||
}
|
||||
vc_init_header(shm_);
|
||||
}
|
||||
|
||||
void close_shm() {
|
||||
if (shm_) UnmapViewOfFile(shm_);
|
||||
if (map_) CloseHandle(map_);
|
||||
shm_ = NULL;
|
||||
map_ = NULL;
|
||||
}
|
||||
|
||||
public:
|
||||
explicit VoiceChangerAPO(IUnknown *outer) {
|
||||
outer_ = outer ? outer : reinterpret_cast<IUnknown *>(static_cast<INonDelegatingUnknown *>(this));
|
||||
InterlockedIncrement(&g_objects);
|
||||
memset(&st_, 0, sizeof(st_));
|
||||
st_.id = (uint32_t)InterlockedIncrement(&g_next_id) | ((GetCurrentProcessId() & 0xffff) << 16);
|
||||
if (st_.id == 0) st_.id = 1;
|
||||
}
|
||||
virtual ~VoiceChangerAPO() {
|
||||
close_shm();
|
||||
InterlockedDecrement(&g_objects);
|
||||
}
|
||||
|
||||
/* 오디오 엔진은 APO 를 COM 집합(aggregation)으로 만든다. 바깥 객체가 있으면 IUnknown 호출은 그쪽으로 넘기고,
|
||||
자기 수명은 INonDelegatingUnknown 으로 따로 센다 (Windows SDK 의 CBaseAudioProcessingObject 와 같은 방식). */
|
||||
STDMETHODIMP NDQueryInterface(REFIID riid, void **ppv) override {
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = NULL;
|
||||
if (IsEqualIID(riid, IID_IUnknown)) {
|
||||
*ppv = static_cast<INonDelegatingUnknown *>(this);
|
||||
NDAddRef();
|
||||
return S_OK;
|
||||
}
|
||||
if (IsEqualIID(riid, IID_IAudioProcessingObject_))
|
||||
*ppv = static_cast<IAudioProcessingObject *>(this);
|
||||
else if (IsEqualIID(riid, IID_IAudioProcessingObjectRT_))
|
||||
*ppv = static_cast<IAudioProcessingObjectRT *>(this);
|
||||
else if (IsEqualIID(riid, IID_IAudioProcessingObjectConfiguration_))
|
||||
*ppv = static_cast<IAudioProcessingObjectConfiguration *>(this);
|
||||
else if (IsEqualIID(riid, IID_IAudioSystemEffects_) || IsEqualIID(riid, IID_IAudioSystemEffects2_))
|
||||
*ppv = static_cast<IAudioSystemEffects2 *>(this);
|
||||
else {
|
||||
dlog("QI miss %08lx", riid.Data1);
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
reinterpret_cast<IUnknown *>(*ppv)->AddRef();
|
||||
return S_OK;
|
||||
}
|
||||
STDMETHODIMP_(ULONG) NDAddRef() override { return (ULONG)InterlockedIncrement(&ref_); }
|
||||
STDMETHODIMP_(ULONG) NDRelease() override {
|
||||
LONG r = InterlockedDecrement(&ref_);
|
||||
if (r == 0) delete this;
|
||||
return (ULONG)r;
|
||||
}
|
||||
STDMETHODIMP QueryInterface(REFIID riid, void **ppv) override { return outer_->QueryInterface(riid, ppv); }
|
||||
STDMETHODIMP_(ULONG) AddRef() override { return outer_->AddRef(); }
|
||||
STDMETHODIMP_(ULONG) Release() override { return outer_->Release(); }
|
||||
|
||||
/* IAudioProcessingObject */
|
||||
STDMETHODIMP Reset() override {
|
||||
st_.primed = 0;
|
||||
st_.first_seen = 0;
|
||||
st_.was_alive = 0;
|
||||
return S_OK;
|
||||
}
|
||||
STDMETHODIMP GetLatency(HNSTIME *t) override {
|
||||
if (!t) return E_POINTER;
|
||||
*t = 0;
|
||||
return S_OK;
|
||||
}
|
||||
STDMETHODIMP GetRegistrationProperties(APO_REG_PROPERTIES **pp) override {
|
||||
if (!pp) return E_POINTER;
|
||||
APO_REG_PROPERTIES *p = (APO_REG_PROPERTIES *)CoTaskMemAlloc(sizeof(APO_REG_PROPERTIES));
|
||||
if (!p) return E_OUTOFMEMORY;
|
||||
memset(p, 0, sizeof(*p));
|
||||
p->clsid = CLSID_VoiceChangerAPO;
|
||||
p->Flags = VC_APO_FLAGS;
|
||||
lstrcpynW(p->szFriendlyName, L"Voice Changer", 256);
|
||||
lstrcpynW(p->szCopyrightInfo, L"voice_copy (MIT)", 256);
|
||||
p->u32MajorVersion = 1;
|
||||
p->u32MinorVersion = 0;
|
||||
p->u32MinInputConnections = p->u32MaxInputConnections = 1;
|
||||
p->u32MinOutputConnections = p->u32MaxOutputConnections = 1;
|
||||
p->u32MaxInstances = 0xffffffff;
|
||||
p->u32NumAPOInterfaces = 1;
|
||||
p->iidAPOInterfaceList[0] = IID_IAudioProcessingObject_;
|
||||
*pp = p;
|
||||
return S_OK;
|
||||
}
|
||||
STDMETHODIMP Initialize(UINT32 cb, BYTE *data) override {
|
||||
if (init_) return S_OK;
|
||||
if (data && cb >= sizeof(APOInitSystemEffects)) {
|
||||
APOInitSystemEffects *ini = (APOInitSystemEffects *)data;
|
||||
if (cb >= sizeof(APOInitSystemEffects2)) discovery_ = ((APOInitSystemEffects2 *)data)->InitializeForDiscoveryOnly != FALSE;
|
||||
if (ini->pAPOEndpointProperties) {
|
||||
PROPVARIANT v;
|
||||
PropVariantInit(&v);
|
||||
if (SUCCEEDED(ini->pAPOEndpointProperties->GetValue(PKEY_FriendlyName_, &v)) && v.vt == VT_LPWSTR && v.pwszVal) {
|
||||
unsigned i = 0;
|
||||
for (; i + 1 < VC_NAME && v.pwszVal[i]; i++) st_.name[i] = (vc_wchar)v.pwszVal[i];
|
||||
st_.name[i] = 0;
|
||||
}
|
||||
PropVariantClear(&v);
|
||||
}
|
||||
}
|
||||
init_ = true;
|
||||
dlog("Initialize cb=%u discovery=%d name0=%04x", cb, (int)discovery_, st_.name[0]);
|
||||
return S_OK;
|
||||
}
|
||||
STDMETHODIMP IsInputFormatSupported(IAudioMediaType *opposite, IAudioMediaType *req, IAudioMediaType **out) override {
|
||||
return check_format(opposite, req, out);
|
||||
}
|
||||
STDMETHODIMP IsOutputFormatSupported(IAudioMediaType *opposite, IAudioMediaType *req, IAudioMediaType **out) override {
|
||||
return check_format(opposite, req, out);
|
||||
}
|
||||
HRESULT check_format(IAudioMediaType *opposite, IAudioMediaType *req, IAudioMediaType **out) {
|
||||
if (!req || !out) return E_POINTER;
|
||||
*out = NULL;
|
||||
UNCOMPRESSEDAUDIOFORMAT f;
|
||||
{
|
||||
UNCOMPRESSEDAUDIOFORMAT r = {};
|
||||
BOOL c = 0;
|
||||
req->IsCompressedFormat(&c);
|
||||
req->GetUncompressedAudioFormat(&r);
|
||||
dlog("check_format opp=%p comp=%d bytes=%lu bits=%lu ch=%lu rate=%.0f type=%08lx", opposite, c, r.dwBytesPerSampleContainer,
|
||||
r.dwValidBitsPerSample, r.dwSamplesPerFrame, r.fFramesPerSecond, r.guidFormatType.Data1);
|
||||
}
|
||||
if (is_float32(req, &f) && (!opposite || same_shape(opposite, req))) {
|
||||
req->AddRef();
|
||||
*out = req;
|
||||
return S_OK;
|
||||
}
|
||||
if (opposite && is_float32(opposite, &f)) { /* 반대쪽과 같은 형식을 제안 */
|
||||
opposite->AddRef();
|
||||
*out = opposite;
|
||||
return S_FALSE;
|
||||
}
|
||||
return APOERR_FORMAT_NOT_SUPPORTED;
|
||||
}
|
||||
STDMETHODIMP GetInputChannelCount(UINT32 *n) override {
|
||||
if (!n) return E_POINTER;
|
||||
if (!locked_) return APOERR_NOT_INITIALIZED;
|
||||
*n = ch_;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
/* IAudioProcessingObjectConfiguration */
|
||||
STDMETHODIMP LockForProcess(UINT32 nin, APO_CONNECTION_DESCRIPTOR **in, UINT32 nout, APO_CONNECTION_DESCRIPTOR **out) override {
|
||||
dlog("LockForProcess nin=%u nout=%u", nin, nout);
|
||||
if (locked_) return APOERR_APO_LOCKED;
|
||||
if (nin != 1 || nout != 1 || !in || !out || !in[0] || !out[0]) return APOERR_NUM_CONNECTIONS_INVALID;
|
||||
UNCOMPRESSEDAUDIOFORMAT fi, fo;
|
||||
if (!is_float32(in[0]->pFormat, &fi) || !is_float32(out[0]->pFormat, &fo) ||
|
||||
fi.dwSamplesPerFrame != fo.dwSamplesPerFrame || fi.fFramesPerSecond != fo.fFramesPerSecond)
|
||||
return APOERR_FORMAT_NOT_SUPPORTED;
|
||||
dlog("format ch=%lu rate=%.0f", fi.dwSamplesPerFrame, fi.fFramesPerSecond);
|
||||
ch_ = fi.dwSamplesPerFrame;
|
||||
rate_ = (UINT32)(fi.fFramesPerSecond + 0.5f);
|
||||
if (!discovery_) open_shm();
|
||||
Reset();
|
||||
locked_ = true;
|
||||
return S_OK;
|
||||
}
|
||||
STDMETHODIMP UnlockForProcess() override {
|
||||
if (!locked_) return APOERR_ALREADY_UNLOCKED;
|
||||
if (shm_ && shm_->owner == st_.id) VC_CAS(&shm_->owner, 0u, st_.id);
|
||||
close_shm();
|
||||
locked_ = false;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
/* IAudioProcessingObjectRT: 실시간 스레드. 메모리 할당 · 잠금 금지 */
|
||||
STDMETHODIMP_(void) APOProcess(UINT32 nin, APO_CONNECTION_PROPERTY **in, UINT32 nout, APO_CONNECTION_PROPERTY **out) override {
|
||||
if (nin < 1 || nout < 1) return;
|
||||
#ifdef VC_DEBUG
|
||||
static volatile LONG calls = 0;
|
||||
if (InterlockedIncrement(&calls) % 500 == 1) dlog("APOProcess frames=%u flags=%u shm=%p", in[0]->u32ValidFrameCount, in[0]->u32BufferFlags, shm_);
|
||||
#endif
|
||||
APO_CONNECTION_PROPERTY *i = in[0], *o = out[0];
|
||||
UINT32 frames = i->u32ValidFrameCount;
|
||||
float *dst = (float *)o->pBuffer;
|
||||
const float *src = (const float *)i->pBuffer;
|
||||
size_t bytes = (size_t)frames * ch_ * 4;
|
||||
if (i->u32BufferFlags == BUFFER_SILENT)
|
||||
memset(dst, 0, bytes);
|
||||
else if (dst != src)
|
||||
memcpy(dst, src, bytes);
|
||||
vc_process(&st_, shm_, dst, frames, ch_, rate_, (int64_t)GetTickCount64());
|
||||
o->u32ValidFrameCount = frames;
|
||||
o->u32BufferFlags = BUFFER_VALID;
|
||||
}
|
||||
STDMETHODIMP_(UINT32) CalcInputFrames(UINT32 n) override { return n; }
|
||||
STDMETHODIMP_(UINT32) CalcOutputFrames(UINT32 n) override { return n; }
|
||||
|
||||
/* IAudioSystemEffects2: 윈도우 설정 화면에 보여 줄 효과 목록은 없음 */
|
||||
STDMETHODIMP GetEffectsList(LPGUID *ids, UINT *count, HANDLE) override {
|
||||
if (!ids || !count) return E_POINTER;
|
||||
*ids = NULL;
|
||||
*count = 0;
|
||||
return S_OK;
|
||||
}
|
||||
};
|
||||
|
||||
class Factory : public IClassFactory {
|
||||
public:
|
||||
STDMETHODIMP QueryInterface(REFIID riid, void **ppv) override {
|
||||
if (!ppv) return E_POINTER;
|
||||
if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IClassFactory)) {
|
||||
*ppv = static_cast<IClassFactory *>(this);
|
||||
return S_OK;
|
||||
}
|
||||
*ppv = NULL;
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
STDMETHODIMP_(ULONG) AddRef() override { return 2; }
|
||||
STDMETHODIMP_(ULONG) Release() override { return 1; }
|
||||
STDMETHODIMP CreateInstance(IUnknown *outer, REFIID riid, void **ppv) override {
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = NULL;
|
||||
dlog("CreateInstance outer=%p riid=%08lx", outer, riid.Data1);
|
||||
if (outer && !IsEqualIID(riid, IID_IUnknown)) return CLASS_E_NOAGGREGATION;
|
||||
VoiceChangerAPO *a = new (std::nothrow) VoiceChangerAPO(outer);
|
||||
if (!a) return E_OUTOFMEMORY;
|
||||
HRESULT hr = a->NDQueryInterface(riid, ppv);
|
||||
a->NDRelease();
|
||||
return hr;
|
||||
}
|
||||
STDMETHODIMP LockServer(BOOL lock) override {
|
||||
if (lock)
|
||||
InterlockedIncrement(&g_locks);
|
||||
else
|
||||
InterlockedDecrement(&g_locks);
|
||||
return S_OK;
|
||||
}
|
||||
};
|
||||
|
||||
static Factory g_factory;
|
||||
|
||||
extern "C" HRESULT STDAPICALLTYPE DllGetClassObject(REFCLSID clsid, REFIID riid, void **ppv) {
|
||||
dlog("DllGetClassObject clsid=%08lx", clsid.Data1);
|
||||
if (!IsEqualCLSID(clsid, CLSID_VoiceChangerAPO)) return CLASS_E_CLASSNOTAVAILABLE;
|
||||
return g_factory.QueryInterface(riid, ppv);
|
||||
}
|
||||
|
||||
extern "C" HRESULT STDAPICALLTYPE DllCanUnloadNow() { return (g_objects == 0 && g_locks == 0) ? S_OK : S_FALSE; }
|
||||
4
voice-changer/apo/vcapo.def
Normal file
4
voice-changer/apo/vcapo.def
Normal file
@@ -0,0 +1,4 @@
|
||||
LIBRARY VoiceChangerAPO
|
||||
EXPORTS
|
||||
DllGetClassObject PRIVATE
|
||||
DllCanUnloadNow PRIVATE
|
||||
165
voice-changer/apo/vccore.h
Normal file
165
voice-changer/apo/vccore.h
Normal file
@@ -0,0 +1,165 @@
|
||||
/* 마이크 APO 와 음성 변환기(app/mic_bridge.py)가 함께 쓰는 공유 메모리 규약과 APO 쪽 처리.
|
||||
*
|
||||
* APO 는 실제 마이크의 소리 처리 단계(audiodg.exe 안)에서 10ms 마다 불린다.
|
||||
* - 변환기가 꺼져 있으면 아무것도 하지 않는다 (원래 목소리가 그대로 나감)
|
||||
* - 변환기가 켜져 있고 이 마이크를 고르면: 원래 소리를 in 링에 쓰고, 변환기가 out 링에 써 준
|
||||
* 변환된 소리를 내보낸다. 변환된 소리가 아직 없으면 무음 (원래 목소리가 새지 않게)
|
||||
* 리눅스 테스트(tests/test_mic_bridge.py)가 이 파일을 그대로 컴파일해 파이썬 쪽과 맞춰 본다.
|
||||
* 레이아웃을 바꾸면 VC_VERSION 과 mic_bridge.py 의 Header 를 같이 바꿀 것. */
|
||||
#ifndef VCCORE_H
|
||||
#define VCCORE_H
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
#define VC_MAGIC 0x31414356u /* "VCA1" */
|
||||
#define VC_VERSION 1u
|
||||
#define VC_RING 262144u /* 프레임 (48kHz 에서 5.4초) */
|
||||
#define VC_HEADER 4096u
|
||||
#define VC_SLOTS 8u
|
||||
#define VC_NAME 128u
|
||||
#define VC_SIZE (VC_HEADER + 2u * VC_RING * 4u)
|
||||
|
||||
typedef uint16_t vc_wchar; /* UTF-16 (Windows wchar_t) */
|
||||
|
||||
typedef struct {
|
||||
vc_wchar name[VC_NAME];
|
||||
volatile int64_t beat; /* 이 마이크의 APO 가 마지막으로 돈 시각 (ms) */
|
||||
} vc_slot;
|
||||
|
||||
typedef struct {
|
||||
uint32_t magic, version; /* 0 */
|
||||
volatile int64_t app_beat; /* 8: 변환기가 살아 있다는 표시 (ms, GetTickCount64) */
|
||||
volatile int64_t apo_beat; /* 16: 입력을 쓰는 APO 의 마지막 시각 */
|
||||
volatile int64_t in_w; /* 24: in 링에 쓴 프레임 수 (누적) */
|
||||
volatile int64_t out_w; /* 32: out 링에 쓴 프레임 수 (누적, 변환기가 씀) */
|
||||
volatile uint32_t owner; /* 40: 입력을 쓰는 APO 인스턴스 (0 = 없음) */
|
||||
volatile uint32_t rate; /* 44: 입력 샘플레이트 */
|
||||
volatile uint32_t active; /* 48: 변환기가 켜져 있음 */
|
||||
volatile uint32_t prefill_ms; /* 52: 변환된 소리를 이만큼 모은 뒤 내보냄 (끊김 방지 여유) */
|
||||
volatile uint32_t underruns; /* 56: 변환된 소리가 모자랐던 횟수 */
|
||||
uint32_t reserved; /* 60 */
|
||||
vc_wchar target[VC_NAME]; /* 64: 변환할 마이크 이름 (변환기가 씀) */
|
||||
vc_slot slots[VC_SLOTS]; /* 320: 지금 APO 가 붙어 도는 마이크들 (진단용) */
|
||||
} vc_header;
|
||||
|
||||
typedef struct {
|
||||
uint32_t id;
|
||||
int primed; /* 변환된 소리를 내보내는 중 */
|
||||
int64_t cursor; /* out 링에서 다음에 읽을 위치 */
|
||||
int64_t first_seen; /* 다시 모으기 시작한 시각 (0 = 아직 소리 없음) */
|
||||
int64_t slot_beat;
|
||||
int was_alive;
|
||||
vc_wchar name[VC_NAME];
|
||||
} vc_inst;
|
||||
|
||||
#if defined(_MSC_VER) || defined(_WIN32)
|
||||
#include <windows.h>
|
||||
#define VC_CAS(p, n, o) ((uint32_t)InterlockedCompareExchange((volatile LONG *)(p), (LONG)(n), (LONG)(o)))
|
||||
#define VC_FENCE() MemoryBarrier()
|
||||
#else
|
||||
#define VC_CAS(p, n, o) __sync_val_compare_and_swap((p), (o), (n))
|
||||
#define VC_FENCE() __sync_synchronize()
|
||||
#endif
|
||||
|
||||
static inline int vc_name_eq(const vc_wchar *a, const vc_wchar *b) {
|
||||
for (unsigned i = 0; i < VC_NAME; i++) {
|
||||
if (a[i] != b[i]) return 0;
|
||||
if (a[i] == 0) return 1;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static inline float *vc_in_ring(vc_header *s) { return (float *)((uint8_t *)s + VC_HEADER); }
|
||||
static inline float *vc_out_ring(vc_header *s) { return (float *)((uint8_t *)s + VC_HEADER + VC_RING * 4u); }
|
||||
|
||||
static inline void vc_init_header(vc_header *s) {
|
||||
if (s->magic != VC_MAGIC) {
|
||||
s->version = VC_VERSION;
|
||||
s->prefill_ms = 60;
|
||||
VC_FENCE();
|
||||
s->magic = VC_MAGIC;
|
||||
}
|
||||
}
|
||||
|
||||
static inline void vc_mark_slot(vc_inst *st, vc_header *s, int64_t now) {
|
||||
if (now - st->slot_beat < 500) return;
|
||||
st->slot_beat = now;
|
||||
unsigned pick = VC_SLOTS;
|
||||
for (unsigned i = 0; i < VC_SLOTS; i++)
|
||||
if (vc_name_eq(s->slots[i].name, st->name)) { pick = i; break; }
|
||||
if (pick == VC_SLOTS) {
|
||||
int64_t oldest = INT64_MAX;
|
||||
for (unsigned i = 0; i < VC_SLOTS; i++)
|
||||
if (s->slots[i].beat < oldest) { oldest = s->slots[i].beat; pick = i; }
|
||||
memcpy(s->slots[pick].name, st->name, sizeof(st->name));
|
||||
}
|
||||
s->slots[pick].beat = now;
|
||||
}
|
||||
|
||||
/* io: 인터리브 float32 (frames × ch). 들어올 때 원래 마이크 소리, 나갈 때 내보낼 소리. */
|
||||
static inline void vc_process(vc_inst *st, vc_header *s, float *io, uint32_t frames, uint32_t ch,
|
||||
uint32_t rate, int64_t now) {
|
||||
if (!s || s->magic != VC_MAGIC || s->version != VC_VERSION || ch == 0) return;
|
||||
vc_mark_slot(st, s, now);
|
||||
int alive = s->active && now - s->app_beat < 1500 && vc_name_eq(s->target, st->name);
|
||||
if (!alive) {
|
||||
if (s->owner == st->id) VC_CAS(&s->owner, 0u, st->id);
|
||||
st->was_alive = 0;
|
||||
return; /* 그대로 내보냄 */
|
||||
}
|
||||
if (!st->was_alive) { /* 막 켜짐: 지금 쓰인 곳부터 읽는다 */
|
||||
st->was_alive = 1;
|
||||
st->primed = 0;
|
||||
st->first_seen = 0;
|
||||
st->cursor = s->out_w;
|
||||
}
|
||||
|
||||
uint32_t o = s->owner;
|
||||
if (o == 0 || (o != st->id && now - s->apo_beat > 300)) VC_CAS(&s->owner, st->id, o);
|
||||
if (s->owner == st->id) {
|
||||
float *in = vc_in_ring(s);
|
||||
int64_t w = s->in_w;
|
||||
for (uint32_t i = 0; i < frames; i++) {
|
||||
float m = 0;
|
||||
for (uint32_t c = 0; c < ch; c++) m += io[i * ch + c];
|
||||
in[(uint64_t)(w + i) % VC_RING] = m / (float)ch;
|
||||
}
|
||||
s->rate = rate;
|
||||
VC_FENCE();
|
||||
s->in_w = w + frames;
|
||||
s->apo_beat = now;
|
||||
}
|
||||
|
||||
if (s->rate != rate) { memset(io, 0, (size_t)frames * ch * 4); return; }
|
||||
int64_t ow = s->out_w;
|
||||
VC_FENCE();
|
||||
int64_t avail = ow - st->cursor;
|
||||
if (avail < 0 || avail > (int64_t)(VC_RING / 2)) { /* 너무 뒤처짐: 최신으로 */
|
||||
st->cursor = ow;
|
||||
st->primed = 0;
|
||||
st->first_seen = 0;
|
||||
avail = 0;
|
||||
}
|
||||
if (!st->primed) {
|
||||
if (avail > 0 && st->first_seen == 0) st->first_seen = now;
|
||||
if (st->first_seen == 0 || now - st->first_seen < (int64_t)s->prefill_ms) {
|
||||
memset(io, 0, (size_t)frames * ch * 4);
|
||||
return;
|
||||
}
|
||||
st->primed = 1;
|
||||
}
|
||||
const float *out = vc_out_ring(s);
|
||||
uint32_t n = avail < (int64_t)frames ? (uint32_t)avail : frames;
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
float v = out[(uint64_t)(st->cursor + i) % VC_RING];
|
||||
for (uint32_t c = 0; c < ch; c++) io[i * ch + c] = v;
|
||||
}
|
||||
if (n < frames) {
|
||||
memset(io + (size_t)n * ch, 0, (size_t)(frames - n) * ch * 4);
|
||||
st->primed = 0;
|
||||
st->first_seen = 0;
|
||||
s->underruns++;
|
||||
}
|
||||
st->cursor += n;
|
||||
}
|
||||
#endif
|
||||
@@ -12,6 +12,29 @@ TRAINING = ROOT / "training"
|
||||
DATASETS = ROOT / "datasets"
|
||||
CONFIG = ROOT / "config"
|
||||
SETTINGS = CONFIG / "settings.json"
|
||||
CACHE = ROOT / "cache"
|
||||
|
||||
|
||||
def keep_files_in_root():
|
||||
"""라이브러리가 사용자 폴더(%TEMP% · %USERPROFILE%\\.cache · %APPDATA%)에 쓰는 캐시와 임시 파일을
|
||||
모두 설치 폴더 안 cache\\ 로 돌린다. 다른 import 보다 먼저 돌아야 해서 이 모듈을 불러올 때 바로 한다."""
|
||||
dirs = {
|
||||
"TEMP": "temp", "TMP": "temp", "TMPDIR": "temp",
|
||||
"TORCH_HOME": "torch", "TORCHINDUCTOR_CACHE_DIR": "torch/inductor", "CUDA_CACHE_PATH": "cuda",
|
||||
"HF_HOME": "huggingface", "XDG_CACHE_HOME": "xdg", "MPLCONFIGDIR": "matplotlib",
|
||||
"NUMBA_CACHE_DIR": "numba", "PIP_CACHE_DIR": "pip", "UV_CACHE_DIR": "uv",
|
||||
}
|
||||
for var, sub in dirs.items():
|
||||
p = CACHE / sub
|
||||
p.mkdir(parents=True, exist_ok=True)
|
||||
os.environ[var] = str(p)
|
||||
os.environ["PYTHONNOUSERSITE"] = "1" # %APPDATA%\Python 의 패키지를 읽지도 쓰지도 않게
|
||||
import tempfile
|
||||
|
||||
tempfile.tempdir = None # 위 TEMP 를 다시 읽게
|
||||
|
||||
|
||||
keep_files_in_root()
|
||||
|
||||
|
||||
def use_engine():
|
||||
|
||||
160
voice-changer/app/mic_bridge.py
Normal file
160
voice-changer/app/mic_bridge.py
Normal file
@@ -0,0 +1,160 @@
|
||||
"""마이크 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)
|
||||
@@ -1,56 +1,83 @@
|
||||
"""실시간 음성 변환기 (Windows 게임PC 용 화면).
|
||||
|
||||
마이크로 들어온 내 말소리를 고른 목소리 모델로 바꿔서 출력 장치로 내보낸다.
|
||||
디스코드 · 게임에 쓰려면 출력을 가상 케이블(VB-CABLE 의 "CABLE Input")로 두고,
|
||||
디스코드 입력 장치를 "CABLE Output" 으로 고른다.
|
||||
마이크로 들어온 내 말소리를 고른 목소리 모델로 바꿔서, 그 마이크에서 나가는 소리를 바꿔치기한다.
|
||||
마이크에 붙인 오디오 처리 모듈(apo/VoiceChangerAPO.dll)이 소리를 주고받으므로 가상 케이블이 필요 없다.
|
||||
디스코드 · 게임의 입력 장치는 평소 마이크 그대로 두면 된다.
|
||||
"""
|
||||
import json
|
||||
import multiprocessing as mp
|
||||
import queue
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import tkinter as tk
|
||||
from tkinter import messagebox, ttk
|
||||
|
||||
from common import SETTINGS, load_json, save_json, use_engine
|
||||
from common import CONFIG, ROOT, SETTINGS, load_json, save_json, use_engine
|
||||
from models import GENDERS, auto_pitch, list_models
|
||||
|
||||
LATENCY = {"낮음 (약 0.15초, GPU 여유 필요)": 128, "보통 (약 0.25초)": 250, "안정 (약 0.4초)": 400}
|
||||
|
||||
|
||||
def list_devices():
|
||||
"""(입력 이름→번호, 출력 이름→번호). 가상 케이블을 출력 맨 앞에 둔다."""
|
||||
"""(마이크 이름→번호, 출력 이름→번호). 마이크는 WASAPI 항목만 쓴다 (이름이 윈도우 장치 이름과 같아서
|
||||
마이크 모듈이 자기 마이크인지 알아볼 수 있음)."""
|
||||
from rvc.realtime.audio import list_audio_device
|
||||
|
||||
ins, outs = list_audio_device()
|
||||
|
||||
def is_virtual(d):
|
||||
n = d.name.lower()
|
||||
return "cable" in n or "virtual" in n or "vb-audio" in n
|
||||
|
||||
outs = sorted(outs, key=lambda d: not is_virtual(d))
|
||||
ins = sorted(ins, key=is_virtual) # 마이크를 앞에, 가상 케이블은 뒤에
|
||||
mics = {d.name: d.index for d in ins if "WASAPI" in d.host_api and "loopback" not in d.name.lower()}
|
||||
fmt = lambda d: f"{d.name} ({d.host_api})"
|
||||
return {fmt(d): d.index for d in ins}, {fmt(d): d.index for d in outs}
|
||||
return mics, {fmt(d): d.index for d in outs}
|
||||
|
||||
|
||||
def hooked_mics() -> list:
|
||||
"""설치할 때 마이크 모듈을 붙인 마이크들 (scripts/mic-apo.ps1 이 남긴 목록)."""
|
||||
try:
|
||||
items = json.loads((CONFIG / "mic-apo.json").read_text(encoding="utf-8-sig"))
|
||||
except (OSError, ValueError):
|
||||
return []
|
||||
items = items if isinstance(items, list) else [items]
|
||||
return [(i.get("desc") or "", i.get("iface") or "") for i in items if isinstance(i, dict)]
|
||||
|
||||
|
||||
def is_hooked(name: str, hooked: list) -> bool:
|
||||
return any(d and d in name and (not f or f in name) for d, f in hooked)
|
||||
|
||||
|
||||
def reconnect_mics() -> int:
|
||||
"""관리자 권한으로 마이크 모듈을 다시 붙인다 (UAC 확인 창이 뜸). 종료 코드를 돌려준다."""
|
||||
script = ROOT / "scripts" / "mic-apo.ps1"
|
||||
inner = f"-NoProfile -ExecutionPolicy Bypass -File '{script}' -Install -Root '{ROOT}'"
|
||||
cmd = ["powershell", "-NoProfile", "-Command",
|
||||
f"$p = Start-Process powershell -Verb RunAs -Wait -PassThru -WindowStyle Hidden -ArgumentList \"{inner}\"; exit $p.ExitCode"]
|
||||
return subprocess.run(cmd, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0)).returncode
|
||||
|
||||
|
||||
class Converter:
|
||||
"""Applio 실시간 엔진(AudioCallbacks) 하나를 켜고 끈다."""
|
||||
"""Applio 실시간 엔진 하나를 켜고, 마이크 모듈과 소리를 주고받는다."""
|
||||
|
||||
def __init__(self):
|
||||
self.callbacks = None
|
||||
self.bridge = None
|
||||
self.streams = []
|
||||
self.halt = threading.Event()
|
||||
self.worker = None
|
||||
self.error = None
|
||||
|
||||
@property
|
||||
def running(self):
|
||||
return self.callbacks is not None
|
||||
|
||||
def start(self, model, pitch, in_id, out_id, monitor_id, chunk_ms, threshold, index_rate, on_status):
|
||||
def start(self, model, pitch, mic_name, mic_id, monitor_id, chunk_ms, threshold, index_rate, on_status):
|
||||
import numpy as np
|
||||
import sounddevice as sd
|
||||
from mic_bridge import Bridge, NotConnected
|
||||
from rvc.realtime.callbacks import AudioCallbacks
|
||||
from rvc.realtime.core import AUDIO_SAMPLE_RATE
|
||||
|
||||
# 엔진은 받은 소리를 항상 48kHz 로 보고 분석·합성한다. 장치 기본값(44.1kHz 등)으로 열면
|
||||
# 음높이와 처리 시간이 어긋나므로 스트림을 늘 48kHz 로 연다. MME · DirectSound 는 OS 가,
|
||||
# WASAPI 는 Applio 가 켜는 auto_convert 가 장치 샘플레이트로 바꿔 준다.
|
||||
# 엔진은 받은 소리를 항상 48kHz 로 보고 분석·합성한다. 마이크 소리는 장치 샘플레이트로 오므로
|
||||
# 48kHz 로 바꿔서 넣고, 나온 소리를 다시 장치 샘플레이트로 바꿔 마이크로 돌려보낸다.
|
||||
sr = AUDIO_SAMPLE_RATE
|
||||
block = int(chunk_ms * sr / 1000)
|
||||
cb = AudioCallbacks(
|
||||
@@ -70,23 +97,8 @@ class Converter:
|
||||
audio_sample_rate=sr,
|
||||
)
|
||||
self.callbacks = cb
|
||||
try:
|
||||
cb.audio.start(
|
||||
input_device_id=in_id,
|
||||
output_device_id=out_id,
|
||||
output_monitor_id=monitor_id,
|
||||
block_frame=block,
|
||||
audio_sample_rate=sr,
|
||||
asio_input_channel=-1,
|
||||
asio_output_channel=-1,
|
||||
asio_output_monitor_channel=-1,
|
||||
)
|
||||
except Exception as e:
|
||||
self.stop()
|
||||
raise RuntimeError(
|
||||
f"오디오 장치를 {sr // 1000}kHz 로 열지 못했습니다: {e}\n"
|
||||
"같은 장치의 (MME) 또는 (Windows WASAPI) 항목을 골라 보세요."
|
||||
) from e
|
||||
self.halt.clear()
|
||||
self.error = None
|
||||
t0 = time.time()
|
||||
while not cb.vc.ready:
|
||||
if self.callbacks is not cb:
|
||||
@@ -101,6 +113,91 @@ class Converter:
|
||||
on_status(f"모델 불러오는 중... {int(time.time() - t0)}초")
|
||||
time.sleep(0.5)
|
||||
|
||||
try:
|
||||
on_status("마이크에 연결하는 중...")
|
||||
# 마이크를 쓰는 앱이 하나라도 있어야 윈도우가 마이크 모듈을 돌린다. 디스코드가 꺼져 있어도
|
||||
# 변환이 돌도록 이 앱도 마이크를 연다 (받은 소리는 쓰지 않음).
|
||||
keep = sd.InputStream(device=mic_id, channels=1, dtype="float32", callback=lambda *a: None,
|
||||
extra_settings=sd.WasapiSettings(auto_convert=True))
|
||||
keep.start()
|
||||
self.streams.append(keep)
|
||||
b, err = None, None
|
||||
for _ in range(50):
|
||||
try:
|
||||
b = Bridge.open()
|
||||
break
|
||||
except NotConnected as e:
|
||||
err = e
|
||||
time.sleep(0.1)
|
||||
if b is None:
|
||||
raise RuntimeError(f"{err}\n'마이크 다시 연결' 을 눌러 주세요.")
|
||||
self.bridge = b
|
||||
b.start(mic_name, prefill_ms=60)
|
||||
for _ in range(30):
|
||||
if b.owner_alive() and b.rate:
|
||||
break
|
||||
b.beat()
|
||||
time.sleep(0.1)
|
||||
else:
|
||||
seen = ", ".join(b.endpoints()) or "없음"
|
||||
raise RuntimeError(
|
||||
f"'{mic_name}' 에 마이크 모듈이 붙어 있지 않습니다 (모듈이 붙은 마이크: {seen}).\n"
|
||||
"'마이크 다시 연결' 을 누르고, 윈도우 소리 설정에서 이 마이크의 '오디오 향상' 이 켜져 있는지 확인해 주세요."
|
||||
)
|
||||
if monitor_id is not None:
|
||||
from rvc.realtime.audio import queue_latest # noqa: F401 (엔진과 같은 모니터 큐)
|
||||
|
||||
dev = sd.query_devices(monitor_id)
|
||||
api = sd.query_hostapis(dev["hostapi"])["name"]
|
||||
mon = sd.OutputStream(
|
||||
callback=lambda outdata, frames, times, status: cb.audio.audio_queue(cb.audio.mon_queue, outdata, cb.audio.monitor_audio_gain),
|
||||
latency="low", dtype=np.float32, device=monitor_id, blocksize=block, samplerate=sr,
|
||||
channels=min(2, dev["max_output_channels"]),
|
||||
extra_settings=sd.WasapiSettings(auto_convert=True) if "WASAPI" in api else None,
|
||||
)
|
||||
cb.audio.running = True
|
||||
mon.start()
|
||||
self.streams.append(mon)
|
||||
except Exception as e:
|
||||
self.stop()
|
||||
if isinstance(e, RuntimeError):
|
||||
raise
|
||||
raise RuntimeError(f"마이크를 열지 못했습니다: {e}") from e
|
||||
self.worker = threading.Thread(target=self._pump, args=(b, cb, block, sr), daemon=True)
|
||||
self.worker.start()
|
||||
|
||||
def _pump(self, b, cb, block, sr):
|
||||
"""마이크 모듈 ↔ 엔진. 장치 샘플레이트 ↔ 48kHz 는 끊김 없이 이어지는 리샘플러로 바꾼다."""
|
||||
import numpy as np
|
||||
import soxr
|
||||
from rvc.realtime.audio import queue_latest
|
||||
|
||||
rate, rs_in, rs_out = None, None, None
|
||||
pending = np.zeros(0, np.float32)
|
||||
try:
|
||||
while not self.halt.is_set():
|
||||
b.beat()
|
||||
if not b.rate: # 마이크 모듈이 아직 소리를 쓰기 전
|
||||
time.sleep(0.005)
|
||||
continue
|
||||
if b.rate != rate:
|
||||
rate = b.rate
|
||||
rs_in = soxr.ResampleStream(rate, sr, 1, dtype="float32") if rate != sr else None
|
||||
rs_out = soxr.ResampleStream(sr, rate, 1, dtype="float32") if rate != sr else None
|
||||
pending = np.zeros(0, np.float32)
|
||||
x = b.read(max_lag=rate) # 1초 넘게 밀렸으면 버리고 따라잡는다
|
||||
if len(x):
|
||||
pending = np.concatenate([pending, rs_in.resample_chunk(x) if rs_in else x])
|
||||
while len(pending) >= block and not self.halt.is_set():
|
||||
blk, pending = pending[:block], pending[block:]
|
||||
out = np.asarray(cb.audio.process_data_with_time(blk[:, None]), np.float32) * cb.audio.output_audio_gain
|
||||
if cb.audio.use_monitor:
|
||||
queue_latest(cb.audio.mon_queue, out)
|
||||
b.write(rs_out.resample_chunk(out) if rs_out else out)
|
||||
time.sleep(0.005)
|
||||
except Exception as e: # 화면이 알 수 있게 남긴다
|
||||
self.error = e
|
||||
|
||||
def set_pitch(self, pitch: int):
|
||||
if self.callbacks is not None:
|
||||
self.callbacks.audio.f0_up_key = pitch
|
||||
@@ -108,13 +205,28 @@ class Converter:
|
||||
def latency_ms(self) -> float:
|
||||
return float(getattr(self.callbacks.audio, "latency", 0) or 0) if self.callbacks else 0.0
|
||||
|
||||
def mic_ok(self) -> bool:
|
||||
return self.bridge is not None and self.bridge.owner_alive(1000)
|
||||
|
||||
def stop(self):
|
||||
cb, self.callbacks = self.callbacks, None
|
||||
if cb is None:
|
||||
return
|
||||
try:
|
||||
cb.audio.stop()
|
||||
finally:
|
||||
self.halt.set()
|
||||
if self.worker is not None:
|
||||
self.worker.join(timeout=3)
|
||||
self.worker = None
|
||||
if self.bridge is not None:
|
||||
self.bridge.stop() # 마이크 모듈이 바로 원래 목소리로 돌아감
|
||||
self.bridge.close()
|
||||
self.bridge = None
|
||||
for s in self.streams:
|
||||
try:
|
||||
s.abort()
|
||||
s.close()
|
||||
except Exception:
|
||||
pass
|
||||
self.streams = []
|
||||
if cb is not None:
|
||||
cb.audio.running = False
|
||||
cb.vc.stop()
|
||||
|
||||
|
||||
@@ -154,14 +266,16 @@ class App:
|
||||
self.pitch_scale.grid(row=4, column=1, columnspan=2, sticky="ew", padx=10)
|
||||
ttk.Label(f, text="성별이 다른 모델을 고르면 ±12 로 자동으로 맞춥니다. 켜 둔 채로 바꿔도 됩니다.", foreground="#555").grid(row=5, column=0, columnspan=3, sticky="w", padx=10)
|
||||
|
||||
self.in_dev, self.out_dev, self.mon_dev = tk.StringVar(), tk.StringVar(), tk.StringVar()
|
||||
self.in_dev, self.mon_dev = tk.StringVar(), tk.StringVar()
|
||||
self.use_monitor = tk.BooleanVar(value=self.settings.get("use_monitor", False))
|
||||
ttk.Label(f, text="마이크 (입력)").grid(row=6, column=0, sticky="w", **pad)
|
||||
ttk.Label(f, text="마이크").grid(row=6, column=0, sticky="w", **pad)
|
||||
self.in_box = ttk.Combobox(f, textvariable=self.in_dev, state="readonly")
|
||||
self.in_box.grid(row=6, column=1, columnspan=2, sticky="ew", padx=10)
|
||||
ttk.Label(f, text="출력 (디스코드용은 CABLE Input)").grid(row=7, column=0, sticky="w", **pad)
|
||||
self.out_box = ttk.Combobox(f, textvariable=self.out_dev, state="readonly")
|
||||
self.out_box.grid(row=7, column=1, columnspan=2, sticky="ew", padx=10)
|
||||
self.in_box.grid(row=6, column=1, sticky="ew", padx=10)
|
||||
self.in_box.bind("<<ComboboxSelected>>", lambda e: self.show_mic_state())
|
||||
self.reconnect_btn = ttk.Button(f, text="마이크 다시 연결", command=self.reconnect)
|
||||
self.reconnect_btn.grid(row=6, column=2, sticky="e", padx=10)
|
||||
self.mic_state = ttk.Label(f, text="", foreground="#555")
|
||||
self.mic_state.grid(row=7, column=0, columnspan=3, sticky="w", padx=10)
|
||||
ttk.Checkbutton(f, text="내 귀로 듣기", variable=self.use_monitor).grid(row=8, column=0, sticky="w", **pad)
|
||||
self.mon_box = ttk.Combobox(f, textvariable=self.mon_dev, state="readonly")
|
||||
self.mon_box.grid(row=8, column=1, columnspan=2, sticky="ew", padx=10)
|
||||
@@ -208,12 +322,40 @@ class App:
|
||||
except Exception as e:
|
||||
self.ins, self.outs = {}, {}
|
||||
self.status.config(text=f"오디오 장치를 읽지 못했습니다: {e}")
|
||||
self.hooked = hooked_mics()
|
||||
self.in_box["values"] = list(self.ins)
|
||||
self.out_box["values"] = list(self.outs)
|
||||
self.mon_box["values"] = list(self.outs)
|
||||
for var, choices, key in ((self.in_dev, self.ins, "input"), (self.out_dev, self.outs, "output"), (self.mon_dev, self.outs, "monitor")):
|
||||
for var, choices, key in ((self.in_dev, self.ins, "input"), (self.mon_dev, self.outs, "monitor")):
|
||||
saved = self.settings.get(key)
|
||||
var.set(saved if saved in choices else next(iter(choices), ""))
|
||||
self.show_mic_state()
|
||||
|
||||
def show_mic_state(self):
|
||||
name = self.in_dev.get()
|
||||
if not name:
|
||||
self.mic_state.config(text="마이크가 없습니다.")
|
||||
elif is_hooked(name, self.hooked):
|
||||
self.mic_state.config(text="디스코드 · 게임의 입력 장치는 이 마이크 그대로 두세요. 변환을 켜면 이 마이크로 바뀐 목소리가 나갑니다.")
|
||||
else:
|
||||
self.mic_state.config(text="이 마이크에는 아직 변환 모듈이 없습니다. '마이크 다시 연결' 을 눌러 주세요 (새로 꽂은 마이크 등).")
|
||||
|
||||
def reconnect(self):
|
||||
if self.conv.running:
|
||||
messagebox.showinfo("음성 변환기", "변환을 정지한 뒤에 눌러 주세요.")
|
||||
return
|
||||
if not messagebox.askokcancel("음성 변환기", "관리자 권한으로 모든 마이크에 변환 모듈을 붙입니다.\n윈도우 소리가 1~2초 끊겼다가 돌아옵니다."):
|
||||
return
|
||||
self.reconnect_btn.config(state="disabled")
|
||||
self.status.config(text="마이크 연결 중...")
|
||||
|
||||
def run():
|
||||
try:
|
||||
code = reconnect_mics()
|
||||
except Exception as e:
|
||||
code = str(e)
|
||||
self.events.put(("reconnected", code))
|
||||
|
||||
threading.Thread(target=run, daemon=True).start()
|
||||
|
||||
def selected(self):
|
||||
sel = self.model_list.curselection()
|
||||
@@ -237,8 +379,8 @@ class App:
|
||||
if not m:
|
||||
messagebox.showwarning("음성 변환기", "목소리 모델을 골라 주세요.")
|
||||
return
|
||||
if self.in_dev.get() not in self.ins or self.out_dev.get() not in self.outs:
|
||||
messagebox.showwarning("음성 변환기", "마이크와 출력 장치를 골라 주세요.")
|
||||
if self.in_dev.get() not in self.ins:
|
||||
messagebox.showwarning("음성 변환기", "마이크를 골라 주세요.")
|
||||
return
|
||||
mon = self.outs.get(self.mon_dev.get()) if self.use_monitor.get() else None
|
||||
if self.use_monitor.get() and mon is None:
|
||||
@@ -246,7 +388,7 @@ class App:
|
||||
return
|
||||
self.save_settings(m)
|
||||
self.start_btn.config(state="disabled")
|
||||
args = (m, self.pitch.get(), self.ins[self.in_dev.get()], self.outs[self.out_dev.get()], mon,
|
||||
args = (m, self.pitch.get(), self.in_dev.get(), self.ins[self.in_dev.get()], mon,
|
||||
LATENCY.get(self.latency.get(), 250), self.threshold.get(), 0.5)
|
||||
|
||||
def run():
|
||||
@@ -287,13 +429,24 @@ class App:
|
||||
self.on_started(val)
|
||||
elif kind == "failed":
|
||||
self.on_failed(val)
|
||||
elif kind == "reconnected":
|
||||
self.reconnect_btn.config(state="normal")
|
||||
self.load_devices()
|
||||
self.status.config(text="마이크를 다시 연결했습니다." if val == 0 else f"마이크를 연결하지 못했습니다 (코드 {val}).")
|
||||
if self.conv.running and str(self.stop_btn["state"]) == "normal":
|
||||
self.status.config(text=f"● 변환 중: {self.running_name} · 처리 {self.conv.latency_ms():.0f}ms")
|
||||
if self.conv.error is not None:
|
||||
err, self.conv.error = self.conv.error, None
|
||||
self.stop()
|
||||
messagebox.showerror("음성 변환기", f"변환이 멈췄습니다.\n{err}")
|
||||
elif not self.conv.mic_ok():
|
||||
self.status.config(text=f"● 변환 중: {self.running_name} · 마이크 신호 없음 (마이크가 뽑혔거나 윈도우 소리가 다시 시작됨)")
|
||||
else:
|
||||
self.status.config(text=f"● 변환 중: {self.running_name} · 처리 {self.conv.latency_ms():.0f}ms · 디스코드 입력 장치는 이 마이크 그대로")
|
||||
self.root.after(200, self.tick)
|
||||
|
||||
def save_settings(self, m):
|
||||
self.settings.update(model=m.id, pitch=self.pitch.get(), my_gender=self.my_gender.get(), input=self.in_dev.get(),
|
||||
output=self.out_dev.get(), monitor=self.mon_dev.get(), use_monitor=self.use_monitor.get(),
|
||||
monitor=self.mon_dev.get(), use_monitor=self.use_monitor.get(),
|
||||
latency=self.latency.get(), threshold=self.threshold.get())
|
||||
save_json(SETTINGS, self.settings)
|
||||
|
||||
|
||||
129
voice-changer/installer/VoiceChanger.iss
Normal file
129
voice-changer/installer/VoiceChanger.iss
Normal file
@@ -0,0 +1,129 @@
|
||||
; 음성 변환기 설치 프로그램 (Inno Setup 6). 빌드: scripts/build-release.sh 가 만든 dist\payload 를 담는다.
|
||||
; ISCC.exe installer\VoiceChanger.iss → dist\VoiceChangerSetup.exe
|
||||
; 하는 일
|
||||
; 1. 설치할 폴더를 고르게 한다. Python · 엔진 · 모델 · 설정 · 캐시 · 임시 파일이 모두 그 폴더 안에만 생긴다
|
||||
; 2. 그 폴더에 앱 파일을 풀고, 마이크마다 변환 모듈(APO)을 붙인다 (가상 오디오 장치 설치 없음)
|
||||
; 3. Python · 엔진 · torch(CUDA) · 엔진 기본 모델을 그 폴더 안으로 내려받는다 (scripts\install.ps1, 10~20분)
|
||||
; 제거할 때는 마이크 설정을 원래대로 되돌리고, 모델 · 녹음까지 지울지 묻는다.
|
||||
|
||||
#define AppName "음성 변환기"
|
||||
#ifndef AppVersion
|
||||
#define AppVersion "1.0.0"
|
||||
#endif
|
||||
|
||||
[Setup]
|
||||
AppId={{8C3F2A51-6D0B-4E7A-9F3C-2B5E1D7A4C90}
|
||||
AppName={#AppName}
|
||||
AppVersion={#AppVersion}
|
||||
AppPublisher=voice_copy
|
||||
DefaultDirName={sd}\VoiceChanger
|
||||
DisableDirPage=no
|
||||
DisableProgramGroupPage=yes
|
||||
DirExistsWarning=no
|
||||
AllowUNCPath=no
|
||||
PrivilegesRequired=admin
|
||||
ArchitecturesAllowed=x64compatible
|
||||
ArchitecturesInstallIn64BitMode=x64compatible
|
||||
MinVersion=10.0.19041
|
||||
OutputDir=..\dist
|
||||
OutputBaseFilename=VoiceChangerSetup
|
||||
Compression=lzma2
|
||||
SolidCompression=yes
|
||||
WizardStyle=modern
|
||||
UninstallFilesDir={app}\uninstall
|
||||
UninstallDisplayIcon={app}\VoiceChanger.exe
|
||||
UninstallDisplayName={#AppName}
|
||||
|
||||
[Languages]
|
||||
Name: "ko"; MessagesFile: "compiler:Languages\Korean.isl"
|
||||
|
||||
[Messages]
|
||||
ko.SelectDirLabel3=음성 변환기를 설치할 폴더를 골라 주세요.%n%nPython · 변환 엔진 · 목소리 모델 · 설정 · 학습 파일 · 캐시가 모두 이 폴더 안에만 저장됩니다. 설치 중에 약 8GB 를 내려받고, 모델을 만들면 더 늘어나므로 15GB 이상 여유가 있는 드라이브를 골라 주세요.
|
||||
ko.DiskSpaceMBLabel=설치 중에 약 8GB 를 더 내려받습니다. 15GB 이상 비어 있는 드라이브를 권합니다.
|
||||
|
||||
[Tasks]
|
||||
Name: "desktopicon"; Description: "바탕 화면에 바로 가기 만들기"; Flags: unchecked
|
||||
|
||||
[Dirs]
|
||||
; 설치 폴더는 관리자 권한으로 만들지만, 앱(일반 권한)이 모델 · 설정을 써야 하므로 사용자 쓰기 권한을 준다
|
||||
Name: "{app}"; Permissions: users-modify
|
||||
|
||||
[Files]
|
||||
Source: "..\dist\payload\*"; DestDir: "{app}"; Flags: recursesubdirs createallsubdirs ignoreversion
|
||||
|
||||
[Icons]
|
||||
Name: "{autoprograms}\{#AppName}"; Filename: "{app}\VoiceChanger.exe"; WorkingDir: "{app}"
|
||||
Name: "{autodesktop}\{#AppName}"; Filename: "{app}\VoiceChanger.exe"; WorkingDir: "{app}"; Tasks: desktopicon
|
||||
|
||||
[Run]
|
||||
Filename: "{app}\VoiceChanger.exe"; Description: "음성 변환기 실행"; Flags: postinstall nowait skipifsilent unchecked
|
||||
|
||||
[UninstallRun]
|
||||
Filename: "powershell.exe"; Parameters: "-NoProfile -ExecutionPolicy Bypass -File ""{app}\scripts\mic-apo.ps1"" -Uninstall -Root ""{app}"""; Flags: runhidden waituntilterminated; RunOnceId: "MicApoUninstall"
|
||||
|
||||
[Code]
|
||||
function PowerShell(const Args: String; const Show: Integer; var Code: Integer): Boolean;
|
||||
begin
|
||||
Result := Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'),
|
||||
'-NoProfile -ExecutionPolicy Bypass ' + Args, ExpandConstant('{app}'), Show, ewWaitUntilTerminated, Code);
|
||||
end;
|
||||
|
||||
function PrepareToInstall(var NeedsRestart: Boolean): String;
|
||||
var
|
||||
Code: Integer;
|
||||
begin
|
||||
Result := '';
|
||||
{ 다시 설치(업데이트)할 때 오디오 엔진이 쥐고 있는 APO 파일을 바꿀 수 있게 잠깐 오디오 서비스를 멈춘다.
|
||||
설치 뒤 mic-apo.ps1 이 다시 켠다. }
|
||||
if FileExists(ExpandConstant('{app}\apo\VoiceChangerAPO.dll')) then
|
||||
Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'),
|
||||
'-NoProfile -Command "Stop-Service -Name AudioEndpointBuilder -Force"', '', SW_HIDE, ewWaitUntilTerminated, Code);
|
||||
end;
|
||||
|
||||
procedure CurStepChanged(CurStep: TSetupStep);
|
||||
var
|
||||
Code: Integer;
|
||||
begin
|
||||
if CurStep <> ssPostInstall then Exit;
|
||||
|
||||
WizardForm.StatusLabel.Caption := '마이크에 변환 모듈을 붙이는 중... (윈도우 소리가 잠깐 끊깁니다)';
|
||||
if not PowerShell('-File "' + ExpandConstant('{app}\scripts\mic-apo.ps1') + '" -Install -Root "' + ExpandConstant('{app}') + '"', SW_HIDE, Code) or (Code <> 0) then
|
||||
begin
|
||||
Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'), '-NoProfile -Command "Start-Service Audiosrv"', '', SW_HIDE, ewWaitUntilTerminated, Code);
|
||||
SuppressibleMsgBox('마이크에 변환 모듈을 붙이지 못했습니다. 설치가 끝난 뒤 음성 변환기의 "마이크 다시 연결" 을 눌러 주세요.', mbError, MB_OK, IDOK);
|
||||
end;
|
||||
|
||||
WizardForm.StatusLabel.Caption := 'Python · 변환 엔진 · 기본 모델을 설치 폴더로 내려받는 중... (10~20분, 검은 창에 진행 상황이 나옵니다)';
|
||||
if not PowerShell('-File "' + ExpandConstant('{app}\scripts\install.ps1') + '"', SW_SHOWNORMAL, Code) or (Code <> 0) then
|
||||
SuppressibleMsgBox('엔진을 내려받지 못했습니다 (인터넷 연결을 확인해 주세요).' + #13#10 +
|
||||
'설치 폴더의 install.bat 을 실행하면 받은 곳부터 이어서 받습니다.', mbError, MB_OK, IDOK);
|
||||
end;
|
||||
|
||||
procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
|
||||
var
|
||||
App: String;
|
||||
begin
|
||||
{ 마이크 되돌리기([UninstallRun])와 설치 파일 지우기가 끝난 뒤 }
|
||||
if CurUninstallStep <> usPostUninstall then Exit;
|
||||
App := ExpandConstant('{app}');
|
||||
{ 설치 중에 내려받은 것들 (설치 파일 목록에 없어서 직접 지운다) }
|
||||
DelTree(App + '\env', True, True, True);
|
||||
DelTree(App + '\engine', True, True, True);
|
||||
DelTree(App + '\tools', True, True, True);
|
||||
DelTree(App + '\cache', True, True, True);
|
||||
DelTree(App + '\app\__pycache__', True, True, True);
|
||||
RemoveDir(App + '\app');
|
||||
{ 사용자가 만든 것은 물어보고 지운다. 조용히 제거할 때는 남겨 둔다 }
|
||||
if (not UninstallSilent) and (MsgBox('만든 목소리 모델 · 학습 파일 · 녹음 · 설정도 지울까요?' + #13#10 +
|
||||
'(models, training, datasets, config 폴더)' + #13#10#13#10 + '"아니요" 를 누르면 남겨 둡니다.', mbConfirmation, MB_YESNO) = IDYES) then
|
||||
DelTree(App, True, True, True)
|
||||
else
|
||||
begin
|
||||
{ 남긴 폴더 중 비어 있는 것은 정리 (RemoveDir 는 빈 폴더만 지운다) }
|
||||
RemoveDir(App + '\models');
|
||||
RemoveDir(App + '\training');
|
||||
RemoveDir(App + '\datasets');
|
||||
RemoveDir(App + '\config');
|
||||
RemoveDir(App);
|
||||
end;
|
||||
end;
|
||||
14
voice-changer/installer/build.ps1
Normal file
14
voice-changer/installer/build.ps1
Normal file
@@ -0,0 +1,14 @@
|
||||
# 설치 프로그램 빌드 (Windows). scripts/build-release.sh 로 만든 dist\payload 가 있어야 한다.
|
||||
# powershell -ExecutionPolicy Bypass -File installer\build.ps1 [-Iscc <ISCC.exe 경로>]
|
||||
# 결과: dist\VoiceChangerSetup.exe
|
||||
param([string]$Iscc)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$here = Split-Path -Parent $PSScriptRoot
|
||||
if (-not (Test-Path (Join-Path $here 'dist\payload\VoiceChanger.exe'))) { throw 'dist\payload 가 없습니다. scripts/build-release.sh 를 먼저 실행하세요' }
|
||||
if (-not $Iscc) {
|
||||
$Iscc = @("$env:LOCALAPPDATA\Programs\Inno Setup 6\ISCC.exe", "${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe", "$env:ProgramFiles\Inno Setup 6\ISCC.exe") |
|
||||
Where-Object { Test-Path $_ } | Select-Object -First 1
|
||||
}
|
||||
if (-not $Iscc) { throw 'Inno Setup 6 (https://jrsoftware.org/isdl.php) 를 설치하거나 -Iscc 로 ISCC.exe 경로를 주세요' }
|
||||
& $Iscc (Join-Path $here 'installer\VoiceChanger.iss')
|
||||
if ($LASTEXITCODE -ne 0) { throw "ISCC 실패 ($LASTEXITCODE)" }
|
||||
@@ -12,7 +12,7 @@ int WINAPI wWinMain(HINSTANCE h, HINSTANCE p, PWSTR cmd, int show) {
|
||||
_snwprintf(py, MAX_PATH, L"%ls\\env\\Scripts\\pythonw.exe", dir);
|
||||
_snwprintf(script, MAX_PATH, L"%ls\\app\\voice_changer.py", dir);
|
||||
if (GetFileAttributesW(py) == INVALID_FILE_ATTRIBUTES) {
|
||||
MessageBoxW(NULL, L"아직 설치되지 않았습니다.\n같은 폴더의 install.bat 을 먼저 실행해 주세요.", L"음성 변환기", MB_ICONWARNING);
|
||||
MessageBoxW(NULL, L"설치가 아직 끝나지 않았습니다 (엔진을 다 내려받지 못함).\n설치 폴더의 install.bat 을 실행하면 받은 곳부터 이어서 받습니다.", L"음성 변환기", MB_ICONWARNING);
|
||||
return 1;
|
||||
}
|
||||
_snwprintf(line, 3 * MAX_PATH, L"\"%ls\" \"%ls\"", py, script);
|
||||
@@ -20,7 +20,7 @@ int WINAPI wWinMain(HINSTANCE h, HINSTANCE p, PWSTR cmd, int show) {
|
||||
STARTUPINFOW si = {sizeof(si)};
|
||||
PROCESS_INFORMATION pi;
|
||||
if (!CreateProcessW(py, line, NULL, NULL, FALSE, 0, NULL, dir, &si, &pi)) {
|
||||
MessageBoxW(NULL, L"음성 변환기를 시작하지 못했습니다. install.bat 을 다시 실행해 주세요.", L"음성 변환기", MB_ICONERROR);
|
||||
MessageBoxW(NULL, L"음성 변환기를 시작하지 못했습니다. 설치 폴더의 install.bat 을 다시 실행해 주세요.", L"음성 변환기", MB_ICONERROR);
|
||||
return 1;
|
||||
}
|
||||
CloseHandle(pi.hThread);
|
||||
|
||||
@@ -1,17 +1,30 @@
|
||||
#!/usr/bin/env bash
|
||||
# VoiceChanger.exe 를 mingw 로 빌드하고 Windows 배포 zip 을 만든다. 엔진 · torch 는 install.bat 이 게임PC 에서 받는다.
|
||||
# 배포 파일을 만든다 (리눅스, mingw).
|
||||
# dist/payload/ 설치 프로그램에 들어갈 파일 (VoiceChanger.exe · VoiceChangerAPO.dll · 스크립트 · 앱 코드)
|
||||
# dist/voice-changer-win.zip 같은 내용의 zip (설치 프로그램 없이 풀어서 쓸 때)
|
||||
# 설치 프로그램(VoiceChangerSetup.exe)은 Windows 의 Inno Setup 으로 만든다: installer/build.ps1
|
||||
# 엔진 · torch 는 설치할 때 게임PC 에서 받는다.
|
||||
set -euo pipefail
|
||||
here="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
out="${1:-$here/dist}"
|
||||
stage="$(mktemp -d "${TMPDIR:-$HOME/.tmp}/vc-release.XXXXXX")"
|
||||
trap 'rm -rf "$stage"' EXIT
|
||||
pkg="$stage/voice-changer"
|
||||
mkdir -p "$pkg/scripts" "$pkg/models" "$pkg/launcher" "$out"
|
||||
pkg="$out/payload"
|
||||
rm -rf "$pkg"
|
||||
mkdir -p "$pkg/scripts" "$pkg/models" "$pkg/launcher" "$pkg/app" "$pkg/apo" "$out"
|
||||
x86_64-w64-mingw32-gcc -O2 -municode -mwindows -finput-charset=UTF-8 -o "$pkg/VoiceChanger.exe" "$here/launcher/launcher.c"
|
||||
x86_64-w64-mingw32-g++ -O2 -Wall -shared -static -fno-exceptions -fno-rtti -o "$pkg/apo/VoiceChangerAPO.dll" \
|
||||
"$here/apo/vcapo.cpp" "$here/apo/vcapo.def" -lole32 -luuid -ladvapi32
|
||||
cp "$here"/*.bat "$here/README.md" "$pkg/"
|
||||
cp "$here/scripts/install.ps1" "$pkg/scripts/"
|
||||
cp "$here/scripts/install.ps1" "$here/scripts/mic-apo.ps1" "$pkg/scripts/"
|
||||
cp "$here/launcher/launcher.c" "$pkg/launcher/"
|
||||
mkdir -p "$pkg/app" && cp "$here"/app/*.py "$pkg/app/"
|
||||
cp "$here/apo/vcapo.cpp" "$here/apo/vccore.h" "$here/apo/vcapo.def" "$pkg/apo/"
|
||||
cp "$here"/app/*.py "$pkg/app/"
|
||||
touch "$pkg/models/.gitkeep"
|
||||
# Windows PowerShell 5.1 은 BOM 이 없는 .ps1 의 한글을 ANSI 로 읽어 스크립트가 깨진다. 줄바꿈도 CRLF 로 맞춘다
|
||||
for f in "$pkg"/scripts/*.ps1; do
|
||||
[ "$(head -c 3 "$f" | xxd -p)" = "efbbbf" ] || { echo "BOM 없음: $f" >&2; exit 1; }
|
||||
done
|
||||
for f in "$pkg"/scripts/*.ps1 "$pkg"/*.bat; do sed -i 's/\r*$/\r/' "$f"; done
|
||||
rm -f "$out/voice-changer-win.zip"
|
||||
(cd "$stage" && zip -qr "$out/voice-changer-win.zip" voice-changer)
|
||||
(cd "$pkg" && zip -qr "$out/voice-changer-win.zip" .)
|
||||
echo "$pkg"
|
||||
echo "$out/voice-changer-win.zip"
|
||||
|
||||
@@ -42,11 +42,21 @@ if (-not (Test-Path $stamp) -or (Get-Content $stamp) -ne $ApplioCommit) {
|
||||
Set-Content $stamp $ApplioCommit
|
||||
} else { Write-Host "[2/5] 엔진 있음" }
|
||||
|
||||
# 받는 것 · 캐시 · 임시 파일을 모두 이 폴더 안에 둔다 (사용자 폴더 %TEMP% · %LOCALAPPDATA% · 레지스트리에 안 남김)
|
||||
$Temp = Join-Path $Root "cache\temp"
|
||||
New-Item -ItemType Directory -Force $Temp | Out-Null
|
||||
$env:TEMP = $Temp; $env:TMP = $Temp
|
||||
$env:UV_PYTHON_INSTALL_DIR = Join-Path $Tools "python"
|
||||
$env:UV_CACHE_DIR = Join-Path $Tools "uv-cache"
|
||||
$env:UV_PYTHON_BIN_DIR = Join-Path $Tools "python-bin"
|
||||
$env:UV_TOOL_DIR = Join-Path $Tools "uv-tools"
|
||||
$env:UV_NO_CONFIG = "1"
|
||||
$env:PYTHONNOUSERSITE = "1"
|
||||
if (-not (Test-Path (Join-Path $VenvDir "Scripts\python.exe"))) {
|
||||
Write-Host "[3/5] Python 3.12 환경 만들기..."
|
||||
& $Uv venv --python 3.12 $VenvDir
|
||||
& $Uv python install 3.12 --no-bin --no-registry
|
||||
if ($LASTEXITCODE -ne 0) { throw "Python 을 받지 못했습니다" }
|
||||
& $Uv venv --python 3.12 --managed-python --no-python-downloads $VenvDir
|
||||
if ($LASTEXITCODE -ne 0) { throw "Python 환경을 만들지 못했습니다" }
|
||||
} else { Write-Host "[3/5] Python 환경 있음" }
|
||||
|
||||
@@ -59,5 +69,7 @@ Write-Host "[5/5] 기본 모델 받기 · GPU 확인..."
|
||||
& (Join-Path $VenvDir "Scripts\python.exe") (Join-Path $Root "app\setup_engine.py")
|
||||
if ($LASTEXITCODE -ne 0) { throw "기본 모델 받기 또는 GPU 확인에 실패했습니다" }
|
||||
|
||||
# 내려받은 패키지 캐시는 env 에 이미 풀려 있으니 지워서 디스크를 아낀다 (install.bat 을 다시 돌리면 다시 받음)
|
||||
& $Uv cache clean | Out-Null
|
||||
Write-Host ""
|
||||
Write-Host "설치가 끝났습니다. VoiceChanger.exe 로 실행하세요."
|
||||
|
||||
215
voice-changer/scripts/mic-apo.ps1
Normal file
215
voice-changer/scripts/mic-apo.ps1
Normal file
@@ -0,0 +1,215 @@
|
||||
# 마이크 APO 등록 · 해제 (관리자 권한). 설치 프로그램과 앱의 "마이크 다시 연결" 버튼이 실행한다.
|
||||
# mic-apo.ps1 -Install [-Root <설치 폴더>] 마이크마다 APO 를 붙이고 오디오 서비스를 다시 시작
|
||||
# mic-apo.ps1 -Uninstall [-Root <설치 폴더>] 원래 설정으로 되돌림
|
||||
# 바꾼 레지스트리 값의 원래 값은 <설치 폴더>\config\mic-apo-backup.json 에 남겨 두고 해제할 때 되돌린다.
|
||||
param([switch]$Install, [switch]$Uninstall, [string]$Root)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if (-not $Root) { $Root = Split-Path -Parent $PSScriptRoot }
|
||||
$Root = (Resolve-Path $Root).Path
|
||||
|
||||
# apo/vcapo.cpp 의 CLSID_VoiceChangerAPO 와 같아야 한다
|
||||
$Clsid = '{6F1C5E2A-3B7D-4C41-9A0E-5D2B8F61C437}'
|
||||
$Dll = Join-Path $Root 'apo\VoiceChangerAPO.dll'
|
||||
$Config = Join-Path $Root 'config'
|
||||
$BackupFile = Join-Path $Config 'mic-apo-backup.json'
|
||||
$ListFile = Join-Path $Config 'mic-apo.json'
|
||||
$Capture = 'SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Capture'
|
||||
$FX = '{d04e05a6-594b-4fb6-a80d-01af5eed7d1d}'
|
||||
$SFX = "$FX,5" # PKEY_FX_StreamEffectClsid
|
||||
$SFX_COMPOSITE = "$FX,13" # PKEY_CompositeFX_StreamEffectClsid (여러 개를 차례로)
|
||||
$SFX_MODES = '{d3993a3f-99c2-4402-b5ec-a92a0367664b},5' # SFX 가 맡는 처리 모드 (없으면 기본 모드를 넣음)
|
||||
$DEFAULT_MODE = '{C18E2F7E-933D-4965-B7D1-1EEF228D2AF3}'
|
||||
$DISABLE_SYSFX = '{1da5d803-d492-4edd-8c23-e0c0ffee7f0e},5' # "오디오 향상 끔" (FxProperties 에 있음)
|
||||
$DESC = '{a45c254e-df1c-4efd-8020-67d146a850e0},2'
|
||||
$IFACE = '{b3f8fa53-0004-438e-9003-51a46e139bfc},6'
|
||||
|
||||
Add-Type @'
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
public static class VcPriv {
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||
struct TP { public int Count; public long Luid; public int Attr; }
|
||||
[DllImport("advapi32.dll", SetLastError = true)] static extern bool OpenProcessToken(IntPtr h, int acc, out IntPtr tok);
|
||||
[DllImport("advapi32.dll", SetLastError = true)] static extern bool LookupPrivilegeValue(string sys, string name, out long luid);
|
||||
[DllImport("advapi32.dll", SetLastError = true)] static extern bool AdjustTokenPrivileges(IntPtr tok, bool all, ref TP np, int len, IntPtr prev, IntPtr rl);
|
||||
[DllImport("kernel32.dll")] static extern IntPtr GetCurrentProcess();
|
||||
public static void Enable(string name) {
|
||||
IntPtr t; OpenProcessToken(GetCurrentProcess(), 0x28, out t);
|
||||
TP tp = new TP(); tp.Count = 1; tp.Attr = 2; LookupPrivilegeValue(null, name, out tp.Luid);
|
||||
AdjustTokenPrivileges(t, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
|
||||
}
|
||||
}
|
||||
'@
|
||||
$HKLM = [Microsoft.Win32.Registry]::LocalMachine
|
||||
$Admins = New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-544')
|
||||
$RW = [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree
|
||||
$Rights = [System.Security.AccessControl.RegistryRights]
|
||||
|
||||
function Log($m) { Write-Host "[mic-apo] $m" }
|
||||
|
||||
# MMDevices 의 마이크 키에서 관리자는 값 읽기 · 쓰기만 되고 하위 키는 못 만든다.
|
||||
# 그래서 값은 그 권한으로만 바꾼다. FxProperties 키가 아예 없는 마이크에서만 잠깐 소유권을 가져와
|
||||
# 키를 만든 뒤, 그 마이크 키의 보안 설정(SDDL)을 원래대로 바로 되돌린다.
|
||||
$ValueRights = $Rights::QueryValues -bor $Rights::SetValue -bor $Rights::ReadKey
|
||||
function Open-Values([string]$sub) { return $HKLM.OpenSubKey($sub, $RW, $ValueRights) }
|
||||
|
||||
function New-FxKey([string]$sub) {
|
||||
[VcPriv]::Enable('SeTakeOwnershipPrivilege'); [VcPriv]::Enable('SeRestorePrivilege')
|
||||
$k = $HKLM.OpenSubKey($sub, $RW, $Rights::ReadPermissions)
|
||||
$orig = $k.GetAccessControl('All').GetSecurityDescriptorSddlForm('All'); $k.Close()
|
||||
try {
|
||||
$k = $HKLM.OpenSubKey($sub, $RW, $Rights::TakeOwnership)
|
||||
$acl = New-Object System.Security.AccessControl.RegistrySecurity
|
||||
$acl.SetOwner($Admins); $k.SetAccessControl($acl); $k.Close()
|
||||
$k = $HKLM.OpenSubKey($sub, $RW, $Rights::ChangePermissions -bor $Rights::ReadPermissions)
|
||||
$acl = $k.GetAccessControl()
|
||||
$acl.AddAccessRule((New-Object System.Security.AccessControl.RegistryAccessRule($Admins, 'CreateSubKey', 'None', 'None', 'Allow')))
|
||||
$k.SetAccessControl($acl); $k.Close()
|
||||
$k = $HKLM.OpenSubKey($sub, $RW, $Rights::CreateSubKey -bor $Rights::ReadKey)
|
||||
$k.CreateSubKey('FxProperties', $RW).Close(); $k.Close()
|
||||
} finally {
|
||||
$k = $HKLM.OpenSubKey($sub, $RW, $Rights::ChangePermissions -bor $Rights::TakeOwnership -bor $Rights::ReadPermissions)
|
||||
$acl = New-Object System.Security.AccessControl.RegistrySecurity
|
||||
$acl.SetSecurityDescriptorSddlForm($orig)
|
||||
$k.SetAccessControl($acl); $k.Close()
|
||||
}
|
||||
}
|
||||
|
||||
function Get-Val($key, [string]$name) {
|
||||
if (-not $key -or -not ($key.GetValueNames() -contains $name)) { return $null }
|
||||
return @{ kind = $key.GetValueKind($name).ToString(); data = $key.GetValue($name, $null, 'DoNotExpandEnvironmentNames') }
|
||||
}
|
||||
|
||||
function Set-Val($key, [string]$name, $v) {
|
||||
if ($null -eq $v) { if ($key.GetValueNames() -contains $name) { $key.DeleteValue($name) }; return }
|
||||
$data = $v.data
|
||||
if ($v.kind -eq 'MultiString') { $data = [string[]]@($data) }
|
||||
if ($v.kind -eq 'Binary') { $data = [byte[]]@($data) }
|
||||
$key.SetValue($name, $data, [Microsoft.Win32.RegistryValueKind]$v.kind)
|
||||
}
|
||||
|
||||
function Load-Backup {
|
||||
$b = @{}
|
||||
if (Test-Path $BackupFile) {
|
||||
$j = Get-Content $BackupFile -Raw -Encoding UTF8 | ConvertFrom-Json
|
||||
foreach ($p in $j.PSObject.Properties) {
|
||||
$e = @{}
|
||||
foreach ($q in $p.Value.PSObject.Properties) {
|
||||
$e[$q.Name] = if ($null -eq $q.Value) { $null } else { @{ kind = $q.Value.kind; data = $q.Value.data } }
|
||||
}
|
||||
$b[$p.Name] = $e
|
||||
}
|
||||
}
|
||||
return $b
|
||||
}
|
||||
|
||||
function Save-Backup($b) {
|
||||
New-Item -ItemType Directory -Force $Config | Out-Null
|
||||
$b | ConvertTo-Json -Depth 6 | Set-Content $BackupFile -Encoding UTF8
|
||||
}
|
||||
|
||||
function Restart-Audio {
|
||||
# 마이크 설정은 AudioEndpointBuilder 가 들고 있으므로 이것까지 다시 시작해야 새 값을 읽는다
|
||||
Log '오디오 서비스 다시 시작'
|
||||
Restart-Service -Name AudioEndpointBuilder -Force
|
||||
Start-Service -Name Audiosrv
|
||||
}
|
||||
|
||||
function Get-Endpoints {
|
||||
$root = $HKLM.OpenSubKey($Capture)
|
||||
foreach ($guid in $root.GetSubKeyNames()) {
|
||||
$ek = $root.OpenSubKey($guid)
|
||||
$state = [int]$ek.GetValue('DeviceState', 0)
|
||||
$pk = $ek.OpenSubKey('Properties')
|
||||
$desc = if ($pk) { $pk.GetValue($DESC) } else { $null }
|
||||
$iface = if ($pk) { $pk.GetValue($IFACE) } else { $null }
|
||||
# 1 = 사용 중, 8 = 뽑혀 있음 (헤드셋을 꽂으면 바로 쓰게 같이 붙인다)
|
||||
if ($state -eq 1 -or $state -eq 8) { [pscustomobject]@{ guid = $guid; desc = $desc; iface = $iface; state = $state } }
|
||||
}
|
||||
}
|
||||
|
||||
function Install-Apo {
|
||||
if (-not (Test-Path $Dll)) { throw "APO 파일이 없습니다: $Dll" }
|
||||
# audiodg.exe (LOCAL SERVICE) 가 설치 폴더가 어디든 DLL 을 읽을 수 있게
|
||||
& icacls (Split-Path $Dll) /grant '*S-1-5-19:(OI)(CI)RX' '*S-1-15-2-1:(OI)(CI)RX' /T /Q | Out-Null
|
||||
|
||||
$k = $HKLM.CreateSubKey("SOFTWARE\Classes\CLSID\$Clsid")
|
||||
$k.SetValue('', 'Voice Changer APO'); $k.Close()
|
||||
$k = $HKLM.CreateSubKey("SOFTWARE\Classes\CLSID\$Clsid\InprocServer32")
|
||||
$k.SetValue('', $Dll); $k.SetValue('ThreadingModel', 'Both'); $k.Close()
|
||||
$k = $HKLM.CreateSubKey("SOFTWARE\Classes\AudioEngine\AudioProcessingObjects\$Clsid")
|
||||
$k.SetValue('FriendlyName', 'Voice Changer'); $k.SetValue('Copyright', 'voice_copy (MIT)')
|
||||
foreach ($kv in @(@('MajorVersion', 1), @('MinorVersion', 0), @('Flags', 0xd), @('MinInputConnections', 1), @('MaxInputConnections', 1),
|
||||
@('MinOutputConnections', 1), @('MaxOutputConnections', 1), @('MaxInstances', -1), @('NumAPOInterfaces', 1))) {
|
||||
$k.SetValue($kv[0], [int]$kv[1], 'DWord')
|
||||
}
|
||||
$k.SetValue('APOInterface0', '{FD7F2B29-24D0-4b5c-B177-592C39F9CA10}'); $k.Close()
|
||||
|
||||
$bk = Load-Backup
|
||||
$done = @()
|
||||
foreach ($ep in Get-Endpoints) {
|
||||
$sub = "$Capture\$($ep.guid)"
|
||||
try {
|
||||
if (-not $bk.ContainsKey($ep.guid)) { # 처음 붙일 때의 값만 남긴다 (다시 실행해도 덮어쓰지 않음)
|
||||
$bk[$ep.guid] = @{
|
||||
sfx = Get-Val $HKLM.OpenSubKey("$sub\FxProperties") $SFX
|
||||
sfx_composite = Get-Val $HKLM.OpenSubKey("$sub\FxProperties") $SFX_COMPOSITE
|
||||
sfx_modes = Get-Val $HKLM.OpenSubKey("$sub\FxProperties") $SFX_MODES
|
||||
disable_sysfx = Get-Val $HKLM.OpenSubKey("$sub\FxProperties") $DISABLE_SYSFX
|
||||
}
|
||||
Save-Backup $bk
|
||||
}
|
||||
if (-not $HKLM.OpenSubKey("$sub\FxProperties")) { New-FxKey $sub }
|
||||
$fx = Open-Values "$sub\FxProperties"
|
||||
$cur = Get-Val $fx $SFX
|
||||
$comp = Get-Val $fx $SFX_COMPOSITE
|
||||
if ($comp) {
|
||||
# 제조사 효과가 여러 개 있으면 그 뒤에 붙인다 (잡음 제거 등을 거친 소리를 변환)
|
||||
$list = @($comp.data | Where-Object { $_ -ne $Clsid }) + $Clsid
|
||||
$fx.SetValue($SFX_COMPOSITE, [string[]]$list, 'MultiString')
|
||||
} elseif ($cur -and $cur.data -ne $Clsid) {
|
||||
$fx.SetValue($SFX_COMPOSITE, [string[]]@($cur.data, $Clsid), 'MultiString')
|
||||
} else {
|
||||
$fx.SetValue($SFX, $Clsid, 'String')
|
||||
}
|
||||
if (-not ($fx.GetValueNames() -contains $SFX_MODES)) { $fx.SetValue($SFX_MODES, [string[]]@($DEFAULT_MODE), 'MultiString') }
|
||||
# 사용자가 "오디오 향상" 을 꺼 두면 APO 가 통째로 빠지므로 켠다 (해제할 때 되돌림)
|
||||
if ($fx.GetValueNames() -contains $DISABLE_SYSFX) { $fx.DeleteValue($DISABLE_SYSFX) }
|
||||
$fx.Close()
|
||||
$done += $ep
|
||||
Log "연결: $($ep.desc) ($($ep.iface))"
|
||||
} catch {
|
||||
Log "연결 못 함: $($ep.desc) ($($ep.iface)) - $($_.Exception.Message)"
|
||||
}
|
||||
}
|
||||
New-Item -ItemType Directory -Force $Config | Out-Null
|
||||
ConvertTo-Json -InputObject @($done) -Depth 3 | Set-Content $ListFile -Encoding UTF8
|
||||
Restart-Audio
|
||||
if ($done.Count -eq 0) { throw '마이크를 하나도 연결하지 못했습니다' }
|
||||
}
|
||||
|
||||
function Uninstall-Apo {
|
||||
$bk = Load-Backup
|
||||
foreach ($guid in @($bk.Keys)) {
|
||||
$e = $bk[$guid]
|
||||
$sub = "$Capture\$guid"
|
||||
try {
|
||||
$fx = Open-Values "$sub\FxProperties"
|
||||
if ($fx) {
|
||||
Set-Val $fx $SFX $e.sfx
|
||||
Set-Val $fx $SFX_COMPOSITE $e.sfx_composite
|
||||
Set-Val $fx $SFX_MODES $e.sfx_modes
|
||||
Set-Val $fx $DISABLE_SYSFX $e.disable_sysfx
|
||||
$fx.Close()
|
||||
}
|
||||
Log "되돌림: $guid"
|
||||
} catch { Log "되돌리지 못함: $guid - $($_.Exception.Message)" }
|
||||
}
|
||||
foreach ($sub in @("SOFTWARE\Classes\AudioEngine\AudioProcessingObjects\$Clsid", "SOFTWARE\Classes\CLSID\$Clsid")) {
|
||||
if ($HKLM.OpenSubKey($sub)) { $HKLM.DeleteSubKeyTree($sub) }
|
||||
}
|
||||
Remove-Item -Force $BackupFile, $ListFile -ErrorAction SilentlyContinue
|
||||
Restart-Audio
|
||||
}
|
||||
|
||||
if ($Install) { Install-Apo } elseif ($Uninstall) { Uninstall-Apo } else { throw '-Install 또는 -Uninstall 을 주세요' }
|
||||
88
voice-changer/tests/test_converter_pump.py
Normal file
88
voice-changer/tests/test_converter_pump.py
Normal file
@@ -0,0 +1,88 @@
|
||||
"""변환기(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()
|
||||
158
voice-changer/tests/test_mic_bridge.py
Normal file
158
voice-changer/tests/test_mic_bridge.py
Normal file
@@ -0,0 +1,158 @@
|
||||
"""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()
|
||||
Reference in New Issue
Block a user