Files
voice_copy/voice-changer/scripts/mic-apo.ps1
EJClaw c24cd1f9c0 voice-changer: allow installing under user-owned folders (Desktop); move admin-run parts to Program Files
The installer refused folders whose parent is user-owned (Desktop, Documents) because a user could swap
the whole install folder and get the elevated/audiodg-run parts replaced. Instead of refusing, the parts
that run with admin rights or inside audiodg now live in {commonpf}\VoiceChanger, which only admins can
change; the chosen folder keeps the app, Python, engine, models and data.

- VoiceChanger.iss: SysDir = {commonpf}\VoiceChanger holds apo\ (VoiceChangerAPO.dll), scripts\mic-apo.ps1
  and the uninstaller (UninstallFilesDir). CheckParent removed. Upgrade detection also matches the previous
  install dir from the uninstall registry (PrevAppDir) since uninstall\ is no longer inside the app folder.
  Stop the audio service when either the new or the v1.0.1-layout APO exists. Ask before installing into
  a OneDrive-synced folder.
- secure-dir.ps1: drop CheckParent; Prepare takes -Upgrade.
- mic-apo.ps1: -From <previous app folder> migrates a v1.0.1 apo\ or 21b4278 config\ backup (validated as
  before) into the Program Files apo\, removing the emptied old apo\.
- app: admin_root() finds Program Files\VoiceChanger (falls back to the app folder for the zip layout);
  hooked-mic list, mic-apo log and the reconnect button use it.

Windows 11 VM (Inno 6.7.4 build, AppVersion 1.0.2): v1.0.1 at C:\VoiceChanger -> upgrade: backup moved
byte-equal, APO re-pointed to Program Files, old apo\ scripts\mic-apo.ps1 uninstall\ gone; fresh install to
C:\Users\ci\Desktop\VoiceChanger (owner WIN-CI\ci) with full engine download: exit 0, audiodg loads
C:\Program Files\VoiceChanger\apo\VoiceChangerAPO.dll, 440 Hz APO test + Communications stream PASS;
basic-user token can rename the Desktop folder but every Program Files write/rename is ERROR_ACCESS_DENIED;
reinstall over the same folder keeps user files; uninstall restores FxProperties (only the endpoint
timestamp properties differ, same as v1.0.1) and removes both folders.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 22:09:39 +09:00

317 lines
18 KiB
PowerShell

# 마이크 APO 등록 · 해제 (관리자 권한). 설치 프로그램과 앱의 "마이크 다시 연결" 버튼이 실행한다.
# mic-apo.ps1 -Install [-Root <폴더>] [-From <이전 설치 폴더>] 마이크마다 APO 를 붙이고 오디오 서비스를 다시 시작
# mic-apo.ps1 -Uninstall [-Root <폴더>] 원래 설정으로 되돌림
# <폴더> 는 apo\ 가 있는 곳이다. 설치 프로그램은 Program Files\VoiceChanger, zip 으로 풀어 쓰면 그 폴더.
# 바꾼 레지스트리 값의 원래 값은 <폴더>\apo\mic-apo-backup.json 에 남겨 두고 해제할 때 되돌린다.
# apo\ 는 관리자만 쓸 수 있는 폴더다 (일반 사용자가 백업을 바꿔 관리자 권한으로 레지스트리를 쓰게 만들 수 없게).
# -From: 이전 버전이 백업을 둔 앱 폴더 (21b4278 은 config\, v1.0.1 까지는 앱 폴더의 apo\). 값을 검증한 뒤 옮긴다.
param([switch]$Install, [switch]$Uninstall, [string]$Root, [string]$From)
$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' # 앱이 읽는 "모듈을 붙인 마이크" 목록
$OldDirs = @($Root) + @(if ($From -and (Test-Path -LiteralPath $From)) { (Resolve-Path -LiteralPath $From).Path })
$OldListFiles = @($OldDirs | ForEach-Object { Join-Path $_ 'config\mic-apo.json' }) # 이전 버전(21b4278)의 목록 위치 (설치 · 제거 때 지움)
# 실행 기록은 관리자만 쓸 수 있는 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)
}
# 백업 값 검증. 이전 버전 백업(config\, 일반 사용자 쓰기 폴더)은 그대로 믿지 않는다.
# 허용: null, CLSID 문자열, CLSID 목록, 알려진 처리 모드 GUID 목록, DISABLE_SYSFX(0/1). 이 APO 자신의 CLSID 는 "원래 값" 에서 뺀다.
$GuidRe = '^\{[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\}$'
$KNOWN_MODES = $CAPTURE_MODES + @(
'{9E90EA20-B493-4FD1-A1A8-7E1361A956CF}', # RAW
'{B26FEB0D-EC94-477C-9494-D1AB8E753F6E}', # MOVIE
'{9CF2A70B-F377-403B-BD6B-360863E0355C}' # NOTIFICATION
)
function Clean-Val([string]$field, $v) {
if ($null -eq $v) { return @{ ok = $true; v = $null } }
$kind = [string]$v.kind; $data = $v.data
switch ($field) {
'sfx' {
if ($kind -ne 'String' -or [string]$data -notmatch $GuidRe) { break }
if ([string]$data -eq $Clsid) { return @{ ok = $true; v = $null } }
return @{ ok = $true; v = @{ kind = 'String'; data = [string]$data } }
}
'sfx_composite' {
$list = @($data | ForEach-Object { [string]$_ })
if ($kind -ne 'MultiString' -or @($list | Where-Object { $_ -notmatch $GuidRe }).Count) { break }
$list = @($list | Where-Object { $_ -ne $Clsid })
if ($list.Count -eq 0) { return @{ ok = $true; v = $null } }
return @{ ok = $true; v = @{ kind = 'MultiString'; data = [string[]]$list } }
}
'sfx_modes' {
$list = @($data | ForEach-Object { [string]$_ })
if ($kind -ne 'MultiString' -or $list.Count -eq 0 -or @($list | Where-Object { $KNOWN_MODES -notcontains $_ }).Count) { break }
return @{ ok = $true; v = @{ kind = 'MultiString'; data = [string[]]$list } }
}
'disable_sysfx' {
if ($kind -ne 'DWord' -or ($data -ne 0 -and $data -ne 1)) { break }
return @{ ok = $true; v = @{ kind = 'DWord'; data = [int]$data } }
}
}
return @{ ok = $false; v = $null }
}
# 지금 레지스트리 값을 "원래 값" 으로 남길 때. 이전 설치가 넣은 이 APO 흔적은 뺀다.
function Current-Original([string]$sub) {
$fx = $HKLM.OpenSubKey("$sub\FxProperties")
$e = @{}
foreach ($f in @(@('sfx', $SFX), @('sfx_composite', $SFX_COMPOSITE), @('sfx_modes', $SFX_MODES), @('disable_sysfx', $DISABLE_SYSFX))) {
$r = Clean-Val $f[0] (Get-Val $fx $f[1])
$e[$f[0]] = $r.v
}
$cur = Get-Val $fx $SFX
$modes = Get-Val $fx $SFX_MODES
# SFX 가 이 APO 이고 모드가 기본 하나뿐이면 이전 버전이 만든 목록이다
if ($cur -and $cur.data -eq $Clsid -and $modes -and @($modes.data).Count -eq 1 -and @($modes.data)[0] -eq $CAPTURE_MODES[0]) { $e.sfx_modes = $null }
return $e
}
function Load-Backup {
$b = @{}
$src = $BackupFile
if (-not (Test-Path -LiteralPath $src)) {
$old = @(foreach ($d in $OldDirs) { Join-Path $d 'apo\mic-apo-backup.json'; Join-Path $d 'config\mic-apo-backup.json' }) |
Where-Object { $_ -ne $BackupFile -and (Test-Path -LiteralPath $_) } | Select-Object -First 1
if ($old) { $src = $old; Log "이전 백업을 옮김: $old" }
}
if (Test-Path $src) {
try { $j = Get-Content $src -Raw -Encoding UTF8 | ConvertFrom-Json } catch { $j = $null; Log "백업을 읽지 못함: $src" }
if ($j) {
foreach ($p in $j.PSObject.Properties) {
if ($p.Name -notmatch $GuidRe -or -not $HKLM.OpenSubKey("$Capture\$($p.Name)")) { Log "백업 항목 무시: $($p.Name)"; continue }
$fallback = Current-Original "$Capture\$($p.Name)"
$e = @{}
foreach ($f in 'sfx', 'sfx_composite', 'sfx_modes', 'disable_sysfx') {
$raw = $p.Value.$f
$in = if ($null -eq $raw) { $null } else { @{ kind = $raw.kind; data = $raw.data } }
$r = Clean-Val $f $in
if ($r.ok) { $e[$f] = $r.v } else { $e[$f] = $fallback[$f]; Log "백업 값 거부($f): $($p.Name)" }
}
$b[$p.Name] = $e
}
}
}
if ($src -ne $BackupFile) {
Save-Backup $b
Remove-Item -LiteralPath $src -Force -ErrorAction SilentlyContinue
$d = Split-Path $src # v1.0.1 까지의 앱 폴더 apo\ 는 비었으면 지운다
if ((Split-Path -Leaf $d) -eq 'apo' -and -not (Get-ChildItem -LiteralPath $d -Force)) { Remove-Item -LiteralPath $d -Force }
}
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] = Current-Original $sub
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')
}
# 드라이버가 원래 갖고 있던 모드 목록은 그대로 둔다 (드라이버 효과가 지원하지 않는 모드를 억지로 켜지 않게).
# 원래 목록이 없었으면(백업이 null) 이 앱이 만든 목록이므로 통화 · 음성 · 미디어 모드까지 넣는다.
# 이전 버전이 넣은 "기본 모드 하나" 목록도 여기서 갱신된다.
$modes = Get-Val $fx $SFX_MODES
if ($null -eq $bk[$ep.guid].sfx_modes -and (-not $modes -or (Compare-Object @($modes.data) $CAPTURE_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
Remove-Item -Force $OldListFiles -ErrorAction SilentlyContinue
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) + $OldListFiles) -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
}