Files
voice_copy/voice-changer/scripts/mic-apo.ps1
EJClaw ffc553851a voice-changer: fix review findings (install-folder ACL, scoped uninstall delete, comm-mode APO, reconnect)
- 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 <noreply@anthropic.com>
2026-11-11 18:00:20 +09:00

241 lines
13 KiB
PowerShell

# 마이크 APO 등록 · 해제 (관리자 권한). 설치 프로그램과 앱의 "마이크 다시 연결" 버튼이 실행한다.
# mic-apo.ps1 -Install [-Root <설치 폴더>] 마이크마다 APO 를 붙이고 오디오 서비스를 다시 시작
# mic-apo.ps1 -Uninstall [-Root <설치 폴더>] 원래 설정으로 되돌림
# 바꾼 레지스트리 값의 원래 값은 <설치 폴더>\apo\mic-apo-backup.json 에 남겨 두고 해제할 때 되돌린다.
# apo\ 는 관리자만 쓸 수 있는 폴더다 (일반 사용자가 백업을 바꿔 관리자 권한으로 레지스트리를 쓰게 만들 수 없게).
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 'apo'
$BackupFile = Join-Path $Config 'mic-apo-backup.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 가 맡는 처리 모드 (없을 때만 아래 목록을 넣음)
# 녹음 쪽 처리 모드 (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'
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"; Write-RunLog $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[]]$CAPTURE_MODES, '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
}
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
}