From ffc553851ab0e60a8f591fd8899197bdd9f329cb Mon Sep 17 00:00:00 2001 From: EJClaw Date: Wed, 11 Nov 2026 18:00:20 +0900 Subject: [PATCH] voice-changer: fix review findings (install-folder ACL, scoped uninstall delete, comm-mode APO, reconnect) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - installer: lock the install folder (admins/SYSTEM full, Users read) and grant Users modify only on data dirs (models/training/datasets/config/cache/env/engine/tools); download the engine as the original (non-elevated) user; refuse non-empty folders; uninstall deletes only app-managed dirs - mic-apo.ps1: backup/list/log moved to admin-only apo\; register SFX for DEFAULT, COMMUNICATIONS, SPEECH and MEDIA when the endpoint has no mode list; admin TEMP for Add-Type; run log + trap - app: '마이크 다시 연결' launches one elevated PowerShell via ShellExecuteExW(runas) with double-quoted -File args and waits for its exit code; shows apo\mic-apo.log on failure - tests: reconnect argument splitting (Korean/space/quote/drive root) Verified on the Windows 11 VM: basic-user token gets ERROR_ACCESS_DENIED on scripts/apo/exe/ uninstall/app and write access only on data dirs; Communications-category capture receives the converted signal (440 Hz); reconnect exits 0 from a Korean+space install path. Co-Authored-By: Claude Opus 5.5 --- voice-changer/README.md | 5 +- voice-changer/app/voice_changer.py | 71 ++++++++++++++---- voice-changer/installer/VoiceChanger.iss | 95 ++++++++++++++++++++---- voice-changer/scripts/mic-apo.ps1 | 41 ++++++++-- voice-changer/tests/test_reconnect.py | 72 ++++++++++++++++++ 5 files changed, 248 insertions(+), 36 deletions(-) create mode 100644 voice-changer/tests/test_reconnect.py diff --git a/voice-changer/README.md b/voice-changer/README.md index 465dc5a..b46e359 100644 --- a/voice-changer/README.md +++ b/voice-changer/README.md @@ -12,6 +12,7 @@ 1. `VoiceChangerSetup.exe` 를 실행합니다 (관리자 권한 확인 창이 뜹니다). 2. **설치할 폴더**를 고릅니다. 기본값은 `C:\VoiceChanger` 이고, 다른 드라이브(`D:\...`)나 한글 · 띄어쓰기가 들어간 경로도 됩니다. + 비어 있는 폴더나 새 폴더만 됩니다 (다른 파일이 든 폴더는 거절합니다). Python · 엔진 · torch · 목소리 모델 · 설정 · 학습 파일 · 캐시 · 임시 파일이 **모두 이 폴더 안에만** 저장됩니다. 설치하면서 약 8GB 를 내려받고 모델을 만들수록 늘어나므로 15GB 이상 비어 있는 드라이브를 고르세요. 3. 설치 프로그램이 마이크마다 변환 모듈을 붙이고(윈도우 소리가 1~2초 끊김), 검은 창에서 Python 3.12 · 엔진(Applio) · @@ -23,6 +24,7 @@ 디스코드 · 게임의 입력 장치는 **평소 쓰던 마이크 그대로** 두면 됩니다. - 내려받다가 끊기면 설치 폴더의 `install.bat` 을 실행합니다. 받은 곳부터 이어서 받습니다. +- 권한: 설치 폴더와 실행 파일 · `app\` · `scripts\` · `apo\` · `uninstall\` 은 관리자만 고칠 수 있습니다. 일반 사용자는 `models` · `training` · `datasets` · `config` · `cache` · `env` · `engine` · `tools` 에만 씁니다. 엔진 내려받기(`install.ps1`)는 관리자 권한 없이 돕니다. - 폴더 밖에 남는 것은 윈도우가 관리하는 항목뿐입니다: 시작 메뉴 바로 가기, 프로그램 제거 목록, 마이크 모듈 등록(레지스트리). 사용자 폴더(`%APPDATA%` · `%LOCALAPPDATA%` · `%TEMP%` · `.cache`)에는 아무것도 쓰지 않습니다. - 제거: 설정 → 앱 → 음성 변환기 → 제거. 마이크 설정을 원래대로 되돌리고, 만든 모델 · 녹음 · 설정까지 지울지 묻습니다. @@ -30,7 +32,8 @@ ### 마이크 모듈은 어떻게 동작하나 윈도우는 마이크 소리를 앱에 넘기기 전에 오디오 처리 모듈(APO, Equalizer APO 와 같은 방식)을 거칩니다. -설치 프로그램이 `apo\VoiceChangerAPO.dll` 을 각 마이크의 처리 단계에 붙입니다 (`scripts\mic-apo.ps1`, 바꾼 값의 원래 값은 `config\mic-apo-backup.json`). +설치 프로그램이 `apo\VoiceChangerAPO.dll` 을 각 마이크의 처리 단계에 붙입니다 (`scripts\mic-apo.ps1`, 바꾼 값의 원래 값은 `apo\mic-apo-backup.json`). +통화 앱(디스코드 등)이 여는 통화(Communications) 모드 스트림에도 붙도록 기본 · 통화 · 음성 · 미디어 모드로 등록합니다. 드라이버가 이미 모드 목록을 갖고 있으면 그 목록을 그대로 둡니다. - 변환기가 꺼져 있으면 아무것도 하지 않습니다. 원래 목소리가 그대로 나갑니다 - 변환을 켜면 고른 마이크의 소리를 변환기로 넘기고, 바뀐 목소리를 대신 내보냅니다. 바뀐 소리가 아직 없을 때는 무음이라 원래 목소리가 새지 않습니다 diff --git a/voice-changer/app/voice_changer.py b/voice-changer/app/voice_changer.py index c5dae51..d36d819 100644 --- a/voice-changer/app/voice_changer.py +++ b/voice-changer/app/voice_changer.py @@ -7,14 +7,13 @@ 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 CONFIG, ROOT, SETTINGS, load_json, save_json, use_engine +from common import 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} @@ -32,9 +31,9 @@ def list_devices(): def hooked_mics() -> list: - """설치할 때 마이크 모듈을 붙인 마이크들 (scripts/mic-apo.ps1 이 남긴 목록).""" + """설치할 때 마이크 모듈을 붙인 마이크들 (scripts/mic-apo.ps1 이 apo\\ 에 남긴 목록).""" try: - items = json.loads((CONFIG / "mic-apo.json").read_text(encoding="utf-8-sig")) + items = json.loads((ROOT / "apo" / "mic-apo.json").read_text(encoding="utf-8-sig")) except (OSError, ValueError): return [] items = items if isinstance(items, list) else [items] @@ -45,13 +44,54 @@ 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_params(root=None) -> str: + """관리자 PowerShell 에 넘길 인자. Windows 경로에는 " 가 들어갈 수 없어서 큰따옴표로만 감싸면 공백 · 한글 경로도 안전하다.""" + root = ROOT if root is None else root + script, r = str(root / "scripts" / "mic-apo.ps1"), str(root) + if r.endswith("\\"): # "D:\" 처럼 \ 로 끝나면 닫는 따옴표가 이스케이프되므로 "D:\." 로 + r += "." + return f'-NoProfile -ExecutionPolicy Bypass -File "{script}" -Install -Root "{r}"' + + +def mic_apo_log_tail(lines: int = 8) -> str: + """scripts/mic-apo.ps1 이 apo\\mic-apo.log 에 남긴 마지막 기록.""" + try: + text = (ROOT / "apo" / "mic-apo.log").read_text(encoding="utf-8-sig", errors="replace") + except OSError: + return "(기록 없음)" + return "\n".join(text.strip().splitlines()[-lines:]) + + 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 + """관리자 권한으로 mic-apo.ps1 -Install 을 돌린다 (UAC 확인 창이 뜸). 스크립트의 종료 코드를 돌려준다. + ShellExecuteExW("runas") 로 PowerShell 하나만 띄우고 끝날 때까지 기다린다. -1223 = 사용자가 UAC 를 취소함.""" + import ctypes + from ctypes import wintypes + + class SHELLEXECUTEINFOW(ctypes.Structure): + _fields_ = [("cbSize", wintypes.DWORD), ("fMask", wintypes.ULONG), ("hwnd", wintypes.HWND), + ("lpVerb", wintypes.LPCWSTR), ("lpFile", wintypes.LPCWSTR), ("lpParameters", wintypes.LPCWSTR), + ("lpDirectory", wintypes.LPCWSTR), ("nShow", ctypes.c_int), ("hInstApp", wintypes.HINSTANCE), + ("lpIDList", ctypes.c_void_p), ("lpClass", wintypes.LPCWSTR), ("hkeyClass", wintypes.HKEY), + ("dwHotKey", wintypes.DWORD), ("hIconOrMonitor", wintypes.HANDLE), ("hProcess", wintypes.HANDLE)] + + shell32 = ctypes.WinDLL("shell32", use_last_error=True) + k32 = ctypes.WinDLL("kernel32", use_last_error=True) + k32.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD] + k32.GetExitCodeProcess.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD)] + k32.CloseHandle.argtypes = [wintypes.HANDLE] + sei = SHELLEXECUTEINFOW(cbSize=ctypes.sizeof(SHELLEXECUTEINFOW), fMask=0x40, # SEE_MASK_NOCLOSEPROCESS + lpVerb="runas", lpFile="powershell.exe", lpParameters=reconnect_params(), + lpDirectory=str(ROOT), nShow=0) + if not shell32.ShellExecuteExW(ctypes.byref(sei)): + return -ctypes.get_last_error() + try: + k32.WaitForSingleObject(sei.hProcess, 0xFFFFFFFF) + code = wintypes.DWORD() + k32.GetExitCodeProcess(sei.hProcess, ctypes.byref(code)) + return int(code.value) + finally: + k32.CloseHandle(sei.hProcess) class Converter: @@ -144,9 +184,7 @@ class Converter: f"'{mic_name}' 에 마이크 모듈이 붙어 있지 않습니다 (모듈이 붙은 마이크: {seen}).\n" "'마이크 다시 연결' 을 누르고, 윈도우 소리 설정에서 이 마이크의 '오디오 향상' 이 켜져 있는지 확인해 주세요." ) - if monitor_id is not None: - from rvc.realtime.audio import queue_latest # noqa: F401 (엔진과 같은 모니터 큐) - + if monitor_id is not None: # 엔진의 모니터 큐(cb.audio.mon_queue)를 헤드셋으로 dev = sd.query_devices(monitor_id) api = sd.query_hostapis(dev["hostapi"])["name"] mon = sd.OutputStream( @@ -432,7 +470,12 @@ class App: elif kind == "reconnected": self.reconnect_btn.config(state="normal") self.load_devices() - self.status.config(text="마이크를 다시 연결했습니다." if val == 0 else f"마이크를 연결하지 못했습니다 (코드 {val}).") + if val == 0: + self.status.config(text="마이크를 다시 연결했습니다.") + else: + self.status.config(text="마이크 연결을 취소했습니다." if val == -1223 else f"마이크를 연결하지 못했습니다 (코드 {val}).") + if val != -1223: + messagebox.showerror("음성 변환기", f"마이크를 연결하지 못했습니다 (코드 {val}).\n\n{mic_apo_log_tail()}") if self.conv.running and str(self.stop_btn["state"]) == "normal": if self.conv.error is not None: err, self.conv.error = self.conv.error, None diff --git a/voice-changer/installer/VoiceChanger.iss b/voice-changer/installer/VoiceChanger.iss index c1b30dd..c7dcf36 100644 --- a/voice-changer/installer/VoiceChanger.iss +++ b/voice-changer/installer/VoiceChanger.iss @@ -44,10 +44,6 @@ 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 @@ -62,12 +58,77 @@ Filename: "{app}\VoiceChanger.exe"; Description: "음성 변환기 실행"; Flag Filename: "powershell.exe"; Parameters: "-NoProfile -ExecutionPolicy Bypass -File ""{app}\scripts\mic-apo.ps1"" -Uninstall -Root ""{app}"""; Flags: runhidden waituntilterminated; RunOnceId: "MicApoUninstall" [Code] +const + { 일반 사용자가 쓸 수 있는 폴더: 앱(일반 권한)이 만드는 데이터와, 일반 권한으로 내려받는 엔진 · Python. + 관리자 권한으로 실행되는 것(설치 폴더 루트의 exe, app\, scripts\, apo\, uninstall\)은 여기에 두지 않는다. } + UserDirs = 'models,training,datasets,config,cache,env,engine,tools'; + 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 IsEmptyDir(const Dir: String): Boolean; +var + F: TFindRec; +begin + Result := True; + if FindFirst(AddBackslash(Dir) + '*', F) then + try + repeat + if (F.Name <> '.') and (F.Name <> '..') then + begin + Result := False; + Exit; + end; + until not FindNext(F); + finally + FindClose(F); + end; +end; + +{ 다른 파일이 들어 있는 폴더에는 설치하지 않는다. 설치 폴더의 권한을 잠그고, 제거할 때 지우기 때문. + 이 앱을 이미 설치한 폴더(업데이트)나 비어 있는 · 새 폴더만 받는다. } +function NextButtonClick(CurPageID: Integer): Boolean; +var + Dir: String; +begin + Result := True; + if CurPageID <> wpSelectDir then Exit; + Dir := WizardDirValue; + if DirExists(Dir) and not IsEmptyDir(Dir) and not FileExists(AddBackslash(Dir) + 'uninstall\unins000.exe') then + begin + SuppressibleMsgBox('이 폴더에는 이미 다른 파일이 있습니다.' + #13#10 + + '비어 있는 폴더나 새 폴더를 골라 주세요. (예: ' + AddBackslash(Dir) + 'VoiceChanger)', mbError, MB_OK, IDOK); + Result := False; + end; +end; + +{ 설치 폴더는 관리자 · SYSTEM 만 고칠 수 있게 잠그고(상위 폴더에서 물려받는 "인증된 사용자 수정" 권한을 끊음), + 일반 사용자에게는 UserDirs 폴더만 수정 권한을 준다. 일반 사용자가 관리자 권한으로 실행되는 + scripts\mic-apo.ps1 · 제거 프로그램 · APO DLL 을 바꿔치기할 수 없게 하기 위함. } +procedure LockDownAppDir; +var + Code, I: Integer; + App, Rest, D: String; +begin + App := ExpandConstant('{app}'); + Exec(ExpandConstant('{sys}\icacls.exe'), '"' + App + '" /inheritance:r /grant:r *S-1-5-18:(OI)(CI)F *S-1-5-32-544:(OI)(CI)F *S-1-5-32-545:(OI)(CI)RX', + '', SW_HIDE, ewWaitUntilTerminated, Code); + Log('icacls lock exit=' + IntToStr(Code)); + Rest := UserDirs + ','; + while Rest <> '' do + begin + I := Pos(',', Rest); + D := Copy(Rest, 1, I - 1); + Rest := Copy(Rest, I + 1, Length(Rest)); + ForceDirectories(App + '\' + D); + Exec(ExpandConstant('{sys}\icacls.exe'), '"' + App + '\' + D + '" /grant *S-1-5-32-545:(OI)(CI)M', '', SW_HIDE, ewWaitUntilTerminated, Code); + Log('icacls user dir ' + D + ' exit=' + IntToStr(Code)); + end; +end; + function PrepareToInstall(var NeedsRestart: Boolean): String; var Code: Integer; @@ -85,6 +146,7 @@ var Code: Integer; begin if CurStep <> ssPostInstall then Exit; + LockDownAppDir; WizardForm.StatusLabel.Caption := '마이크에 변환 모듈을 붙이는 중... (윈도우 소리가 잠깐 끊깁니다)'; if not PowerShell('-File "' + ExpandConstant('{app}\scripts\mic-apo.ps1') + '" -Install -Root "' + ExpandConstant('{app}') + '"', SW_HIDE, Code) or (Code <> 0) then @@ -94,7 +156,10 @@ begin end; WizardForm.StatusLabel.Caption := 'Python · 변환 엔진 · 기본 모델을 설치 폴더로 내려받는 중... (10~20분, 검은 창에 진행 상황이 나옵니다)'; - if not PowerShell('-File "' + ExpandConstant('{app}\scripts\install.ps1') + '"', SW_SHOWNORMAL, Code) or (Code <> 0) then + { 일반 권한(설치를 시작한 사용자)으로 받는다. 관리자 권한으로 사용자 쓰기 폴더(env · engine)의 코드를 돌리지 않게. } + if not ExecAsOriginalUser(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'), + '-NoProfile -ExecutionPolicy Bypass -File "' + ExpandConstant('{app}\scripts\install.ps1') + '"', + ExpandConstant('{app}'), SW_SHOWNORMAL, ewWaitUntilTerminated, Code) or (Code <> 0) then SuppressibleMsgBox('엔진을 내려받지 못했습니다 (인터넷 연결을 확인해 주세요).' + #13#10 + '설치 폴더의 install.bat 을 실행하면 받은 곳부터 이어서 받습니다.', mbError, MB_OK, IDOK); end; @@ -114,16 +179,20 @@ begin DelTree(App + '\app\__pycache__', True, True, True); RemoveDir(App + '\app'); { 사용자가 만든 것은 물어보고 지운다. 조용히 제거할 때는 남겨 둔다 } + { 앱이 만든 폴더만 지운다. 설치 폴더 자체는 비어 있을 때만 지운다 (RemoveDir 는 빈 폴더만 지움) } 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); + DelTree(App + '\models', True, True, True); + DelTree(App + '\training', True, True, True); + DelTree(App + '\datasets', True, True, True); + DelTree(App + '\config', True, True, True); end; + RemoveDir(App + '\models'); + RemoveDir(App + '\training'); + RemoveDir(App + '\datasets'); + RemoveDir(App + '\config'); + DeleteFile(App + '\apo\mic-apo.log'); + RemoveDir(App + '\apo'); + RemoveDir(App); end; diff --git a/voice-changer/scripts/mic-apo.ps1 b/voice-changer/scripts/mic-apo.ps1 index e9e696a..6cbf78b 100644 --- a/voice-changer/scripts/mic-apo.ps1 +++ b/voice-changer/scripts/mic-apo.ps1 @@ -1,7 +1,8 @@ # 마이크 APO 등록 · 해제 (관리자 권한). 설치 프로그램과 앱의 "마이크 다시 연결" 버튼이 실행한다. # mic-apo.ps1 -Install [-Root <설치 폴더>] 마이크마다 APO 를 붙이고 오디오 서비스를 다시 시작 # mic-apo.ps1 -Uninstall [-Root <설치 폴더>] 원래 설정으로 되돌림 -# 바꾼 레지스트리 값의 원래 값은 <설치 폴더>\config\mic-apo-backup.json 에 남겨 두고 해제할 때 되돌린다. +# 바꾼 레지스트리 값의 원래 값은 <설치 폴더>\apo\mic-apo-backup.json 에 남겨 두고 해제할 때 되돌린다. +# apo\ 는 관리자만 쓸 수 있는 폴더다 (일반 사용자가 백업을 바꿔 관리자 권한으로 레지스트리를 쓰게 만들 수 없게). param([switch]$Install, [switch]$Uninstall, [string]$Root) $ErrorActionPreference = 'Stop' if (-not $Root) { $Root = Split-Path -Parent $PSScriptRoot } @@ -10,15 +11,30 @@ $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' +$Config = Join-Path $Root 'apo' $BackupFile = Join-Path $Config 'mic-apo-backup.json' -$ListFile = Join-Path $Config 'mic-apo.json' +$ListFile = Join-Path $Config 'mic-apo.json' # 앱이 읽는 "모듈을 붙인 마이크" 목록 +# 실행 기록은 관리자만 쓸 수 있는 apo\mic-apo.log 에 남긴다 (앱이 실패 이유를 보여 줄 때 읽음) +$LogFile = Join-Path $Config 'mic-apo.log' +function Write-RunLog($m) { try { Add-Content -Path $LogFile -Value "[$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] $m" -Encoding UTF8 } catch {} } +trap { Write-RunLog ("실패: " + ($_ | Out-String).Trim()); Write-Host "[mic-apo] 실패: $($_.Exception.Message)"; exit 1 } +# 관리자 권한으로 도는 스크립트라 임시 파일(Add-Type 컴파일 결과 등)은 관리자만 쓰는 Windows 임시 폴더에 둔다. +# 앱이 물려준 TEMP(설치 폴더의 cache\temp)는 일반 사용자도 쓸 수 있는 곳이라 쓰지 않는다. +$env:TEMP = Join-Path $env:SystemRoot 'Temp'; $env:TMP = $env:TEMP +Write-RunLog ("시작: " + $(if ($Install) { '-Install' } elseif ($Uninstall) { '-Uninstall' } else { '(없음)' })) $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}' +$SFX_MODES = '{d3993a3f-99c2-4402-b5ec-a92a0367664b},5' # SFX 가 맡는 처리 모드 (없을 때만 아래 목록을 넣음) +# 녹음 쪽 처리 모드 (ksmedia.h AUDIO_SIGNALPROCESSINGMODE_*): 기본 · 통화(디스코드 등 VoIP) · 음성 · 미디어. +# RAW 는 "처리 없이" 를 요청한 스트림이라 넣지 않는다. +$CAPTURE_MODES = @( + '{C18E2F7E-933D-4965-B7D1-1EEF228D2AF3}', # DEFAULT + '{98951333-B9CD-48B1-A0A3-FF40682D73F7}', # COMMUNICATIONS + '{FC1CFC9B-B9D6-4CFA-B5E0-4BB2166878B2}', # SPEECH + '{4780004E-7133-41D8-8C74-660DADD2C0EE}' # MEDIA +) $DISABLE_SYSFX = '{1da5d803-d492-4edd-8c23-e0c0ffee7f0e},5' # "오디오 향상 끔" (FxProperties 에 있음) $DESC = '{a45c254e-df1c-4efd-8020-67d146a850e0},2' $IFACE = '{b3f8fa53-0004-438e-9003-51a46e139bfc},6' @@ -45,7 +61,7 @@ $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" } +function Log($m) { Write-Host "[mic-apo] $m"; Write-RunLog $m } # MMDevices 의 마이크 키에서 관리자는 값 읽기 · 쓰기만 되고 하위 키는 못 만든다. # 그래서 값은 그 권한으로만 바꾼다. FxProperties 키가 아예 없는 마이크에서만 잠깐 소유권을 가져와 @@ -172,7 +188,8 @@ function Install-Apo { } else { $fx.SetValue($SFX, $Clsid, 'String') } - if (-not ($fx.GetValueNames() -contains $SFX_MODES)) { $fx.SetValue($SFX_MODES, [string[]]@($DEFAULT_MODE), 'MultiString') } + # 드라이버가 이미 모드 목록을 갖고 있으면 그대로 둔다 (드라이버 효과가 지원하지 않는 모드를 억지로 켜지 않게) + if (-not ($fx.GetValueNames() -contains $SFX_MODES)) { $fx.SetValue($SFX_MODES, [string[]]$CAPTURE_MODES, 'MultiString') } # 사용자가 "오디오 향상" 을 꺼 두면 APO 가 통째로 빠지므로 켠다 (해제할 때 되돌림) if ($fx.GetValueNames() -contains $DISABLE_SYSFX) { $fx.DeleteValue($DISABLE_SYSFX) } $fx.Close() @@ -212,4 +229,12 @@ function Uninstall-Apo { Restart-Audio } -if ($Install) { Install-Apo } elseif ($Uninstall) { Uninstall-Apo } else { throw '-Install 또는 -Uninstall 을 주세요' } +try { + if ($Install) { Install-Apo } elseif ($Uninstall) { Uninstall-Apo } else { throw '-Install 또는 -Uninstall 을 주세요' } + Write-RunLog '끝: 성공' + exit 0 +} catch { + Write-RunLog ("실패: " + ($_ | Out-String).Trim()) + Write-Host "[mic-apo] 실패: $($_.Exception.Message)" + exit 1 +} diff --git a/voice-changer/tests/test_reconnect.py b/voice-changer/tests/test_reconnect.py new file mode 100644 index 0000000..9e735d2 --- /dev/null +++ b/voice-changer/tests/test_reconnect.py @@ -0,0 +1,72 @@ +"""'마이크 다시 연결' 이 관리자 PowerShell 에 넘기는 인자가 공백 · 한글 · 작은따옴표 · 드라이브 루트 경로에서도 깨지지 않는지.""" +import os +import sys +import tempfile +import unittest +from pathlib import Path, PureWindowsPath + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "app")) +os.environ.setdefault("VC_ROOT", tempfile.mkdtemp()) + +try: + import tkinter # noqa: F401 (voice_changer 가 불러옴) +except ImportError: + tkinter = None + + +def split_windows_args(s: str) -> list: + """CommandLineToArgvW 규칙 (백슬래시 + 따옴표 처리 포함).""" + args, cur, i, quoted, has = [], [], 0, False, False + while i < len(s): + c = s[i] + if c == "\\": + n = 0 + while i < len(s) and s[i] == "\\": + n += 1 + i += 1 + if i < len(s) and s[i] == '"': + cur.append("\\" * (n // 2)) + if n % 2: + cur.append('"') + i += 1 + has = True + continue + cur.append("\\" * n) + has = True + continue + if c == '"': + quoted = not quoted + has = True + elif c in " \t" and not quoted: + if has: + args.append("".join(cur)) + cur, has = [], False + else: + cur.append(c) + has = True + i += 1 + if has: + args.append("".join(cur)) + return args + + +@unittest.skipUnless(tkinter, "tkinter 없음") +class ReconnectParamsTest(unittest.TestCase): + def test_korean_space_quote_path(self): + from voice_changer import reconnect_params + + root = PureWindowsPath(r"C:\음성 변환기 테스트\it's here") + args = split_windows_args(reconnect_params(root)) + self.assertEqual(args, ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", + r"C:\음성 변환기 테스트\it's here\scripts\mic-apo.ps1", "-Install", "-Root", r"C:\음성 변환기 테스트\it's here"]) + + def test_drive_root(self): + from voice_changer import reconnect_params + + args = split_windows_args(reconnect_params(PureWindowsPath("D:\\"))) + self.assertEqual(args[4], r"D:\scripts\mic-apo.ps1") + self.assertEqual(args[-1], "D:\\.") # 닫는 따옴표가 \ 에 먹히지 않음 + + +if __name__ == "__main__": + unittest.main()