diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index d17bd8c..655fa6f 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -52,24 +52,32 @@ jobs: } - run: dotnet test tests/VolumeBridge.Tests -c Release - - run: dotnet publish src/VolumeBridge -c Release -r win-x64 -o out - - name: Build installer + - name: Build single exe shell: pwsh run: | - choco install innosetup -y --no-progress - $iscc = "${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe" - & $iscc "/DAppVersion=${{ steps.ver.outputs.version }}" "/DPayloadDir=$PWD\out" "/O$PWD\installer\output" installer\VolumeBridge.iss - if ($LASTEXITCODE -ne 0) { throw "ISCC failed" } - $h = (Get-FileHash installer\output\VolumeBridgeSetup.exe -Algorithm SHA256).Hash.ToLowerInvariant() - "$h VolumeBridgeSetup.exe" | Set-Content -NoNewline -Encoding ascii installer\output\VolumeBridgeSetup.exe.sha256 + if (Test-Path dist) { Remove-Item -Recurse -Force dist } + dotnet build src/VolumeBridge -c Release "-p:ApoDll=$PWD\out\VolumeBridgeApo.dll" -p:RequireApo=true -o dist + if ($LASTEXITCODE -ne 0) { throw "dotnet build failed" } + $files = @(Get-ChildItem -Force dist) + if ($files.Count -ne 1 -or $files[0].Name -ne 'VolumeBridge.exe') { + $names = ($files | ForEach-Object Name) -join ', ' + throw "dist must contain only VolumeBridge.exe, found: $names" + } + $size = $files[0].Length + "VolumeBridge.exe size: $size bytes ($([math]::Round($size / 1KB, 1)) KB / $([math]::Round($size / 1MB, 2)) MB)" + if ($size -gt 5MB) { + throw "VolumeBridge.exe is $size bytes, exceeding the 5 MB limit" + } + $h = (Get-FileHash dist\VolumeBridge.exe -Algorithm SHA256).Hash.ToLowerInvariant() + "$h VolumeBridge.exe" | Set-Content -NoNewline -Encoding ascii dist\VolumeBridge.exe.sha256 - uses: actions/upload-artifact@v4 with: - name: VolumeBridgeSetup + name: VolumeBridge path: | - installer/output/VolumeBridgeSetup.exe - installer/output/VolumeBridgeSetup.exe.sha256 + dist/VolumeBridge.exe + dist/VolumeBridge.exe.sha256 if-no-files-found: error - name: Publish release @@ -78,5 +86,5 @@ jobs: env: GH_TOKEN: ${{ github.token }} run: | - gh release create $env:GITHUB_REF_NAME installer/output/VolumeBridgeSetup.exe installer/output/VolumeBridgeSetup.exe.sha256 ` + gh release create $env:GITHUB_REF_NAME dist/VolumeBridge.exe dist/VolumeBridge.exe.sha256 ` --title "VolumeBridge $env:GITHUB_REF_NAME" --notes-file docs/release-notes.md --verify-tag diff --git a/README.md b/README.md index 8a78727..e913902 100644 --- a/README.md +++ b/README.md @@ -23,31 +23,33 @@ VolumeBridge attenuates the audio inside the Windows audio engine before it reac ## Install and use -**Requirements:** Windows 10 (1903+) or Windows 11, 64-bit (x64). Administrator rights are needed to install; the app itself runs without elevation. +**Requirements:** Windows 10 (1903+) or Windows 11, 64-bit (x64). Portable single executable — no installer needed. One administrator (UAC) prompt is needed to enable or remove the plugin; the app itself runs without elevation. + +> **Upgrading from 0.4.0 or earlier:** Uninstall the old installed version in **Settings → Apps** first, then run the new `VolumeBridge.exe`. 1. **Switch your speaker to USB audio mode** and connect it to your PC. On the JBL Flip 6, hold **Bluetooth + Play for about 10 seconds** (check your model's instructions if using another speaker). **Quit Voicemeeter** if it is running so it does not hold the speaker exclusively. -2. **Download and run `VolumeBridgeSetup.exe`** from the [latest release](https://github.com/ZanderH-code/volumebridge/releases/latest). Keep **"Enable the zero-latency volume plugin"** ticked. Windows audio will pause for about 2 seconds during setup. -3. **Open VolumeBridge** and click **Set as default output**. -4. **Check the status and enable startup:** play audio and confirm the window shows **● Working (zero latency)**, then tick **Start at logon**. +2. **Download and run `VolumeBridge.exe`** from the [latest release](https://github.com/ZanderH-code/volumebridge/releases/latest) (place it anywhere you like). Because the executable is unsigned, Windows SmartScreen may show a warning — click **More info → Run anyway**. +3. **Click Enable plugin** (one UAC prompt). Windows audio will pause for about 2 seconds while the plugin is registered. +4. **Click Set as default output**, play audio to confirm the window shows **● Working (zero latency)**, then tick **Start at logon**. ### Everyday controls - **Max volume cap:** Defaults to **-12 dB** so 100% on the Windows slider is not deafening. Adjustable in the window from **0 to -30 dB**. - **Output device picker:** Automatically picks a playback device whose name contains `JBL` or `Zgmicro`, or you can select another device manually. - **Window and tray:** Closing the window minimizes VolumeBridge to the system tray so it stays out of the way. -- **Language:** Choose English or 简体中文 in the installer, and switch anytime in the app. -- **Updates:** One-click update check from GitHub Releases (downloads are SHA-256 verified). -- **Clean uninstall:** Uninstalling from Settings → Apps restores all original Windows audio settings. +- **Language:** Follows your Windows display language by default, and switches between English and 简体中文 anytime in the app. +- **Updates:** One-click update check from GitHub Releases (downloads are SHA-256 verified and update the exe in place). +- **Clean uninstall:** Click **Remove plugin** in the window (restores all original Windows audio settings and removes the logon task), then quit and delete `VolumeBridge.exe`. ## Trade-offs and troubleshooting -Zero-latency mode modifies one Windows audio setting so the plugin can load. Know these trade-offs before installing: +Zero-latency mode modifies one Windows audio setting so the plugin can load. Know these trade-offs before enabling it: - **Protected audio path is turned off (`DisableProtectedAudioDG=1`):** The plugin is not signed by Microsoft, so Windows needs this setting to load it (Equalizer APO does the same). A few DRM players (such as certain protected 4K audio streams) may be affected. - **Keep Audio enhancements on:** In **Settings → System → Sound → [your speaker]**, **Audio enhancements** must stay set to **Device Default Effects**. Turning it off makes Windows skip the plugin. - **Exclusive mode bypasses the plugin:** Apps that take exclusive WASAPI control bypass the Windows audio engine and will not be attenuated. - **USB port changes or Windows feature updates:** Moving the speaker to a different USB port or installing a major Windows update can drop the plugin setting. The VolumeBridge window will tell you, and clicking **Enable plugin** restores it. -- **If sound stops working after installing:** Uninstall VolumeBridge in **Settings → Apps** (which restores everything), or set the speaker's **Audio enhancements** to **Off**. +- **If sound stops working after enabling:** Click **Remove plugin** in VolumeBridge (which restores everything), or set the speaker's **Audio enhancements** to **Off**. ## Supported devices @@ -94,16 +96,20 @@ Settings in `%LOCALAPPDATA%\VolumeBridge\config.json`: | `maxOutputDb` | `-12` | Output level at 100% slider (dB); `0` = speaker's full level | | `outputKeywords` | `["JBL", "Zgmicro"]` | Case-insensitive name keywords for automatic device selection | | `outputDeviceId` | `null` | Fixed output endpoint ID (set by the device picker) | -| `language` | `"auto"` | `"en"`, `"zh"`, or `"auto"` (follows installer choice) | +| `language` | `"auto"` | `"en"`, `"zh"`, or `"auto"` (follows Windows display language) | ## Building from source ```powershell +# 1. Build the C++ APO DLL (from a Visual Studio x64 Developer Prompt) +./apo/build.ps1 -Out "$PWD\out" + +# 2. Run tests and build the portable single exe (.NET Framework 4.8) dotnet test tests/VolumeBridge.Tests -dotnet publish src/VolumeBridge -c Release -r win-x64 -o out +dotnet build src/VolumeBridge -c Release "-p:ApoDll=$PWD\out\VolumeBridgeApo.dll" -p:RequireApo=true -o dist ``` -The GitHub Actions workflow (`.github/workflows/build.yml`) builds the C++ APO (`apo/`) and the Inno Setup installer on Windows, and publishes a GitHub Release on every `v*` tag. Design notes and history are in [docs/PLAN.md](docs/PLAN.md) (Chinese). +The GitHub Actions workflow (`.github/workflows/build.yml`) builds the C++ APO (`apo/`) and embeds it into the single portable `VolumeBridge.exe` on Windows, and publishes a GitHub Release on every `v*` tag. Design notes and history are in [docs/PLAN.md](docs/PLAN.md) (Chinese). ## Credits and licenses diff --git a/README.zh-CN.md b/README.zh-CN.md index b60c48b..45e9303 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -23,31 +23,33 @@ VolumeBridge 在 Windows 音频引擎内部、声音发往音箱之前,按系 ## 安装与使用 -**系统要求:** Windows 10(1903 及以上)或 Windows 11,64 位(x64)。安装时需要管理员权限,平时以普通权限运行。 +**系统要求:** Windows 10(1903 及以上)或 Windows 11,64 位(x64)。绿色单文件,无需安装。启用或移除插件时需要一次管理员(UAC)确认,平时以普通权限运行。 + +> **从 0.4.0 及更早版本升级:** 请先在 **设置 → 应用** 中卸载旧的安装版,再运行新版 `VolumeBridge.exe`。 1. **把音箱切到 USB 音频模式**并连上电脑。JBL Flip 6 的操作是同时按住**蓝牙键 + 播放键约 10 秒**(其他型号请按对应方式操作)。如果正在运行 Voicemeeter,**请先退出**,避免它独占音箱。 -2. **下载并运行 `VolumeBridgeSetup.exe`**(前往 [最新 Release](https://github.com/ZanderH-code/volumebridge/releases/latest))。安装时保持勾选**“现在为音箱启用零延迟音量插件”**。过程中 Windows 声音会中断约 2 秒。 -3. **打开 VolumeBridge**,点击**设为默认输出**。 -4. **确认生效并设置自启:** 播放任意声音,看到窗口显示 **● 正在工作(零延迟)** 即表示生效;勾选**开机自动启动**即可。 +2. **下载并运行 `VolumeBridge.exe`**(前往 [最新 Release](https://github.com/ZanderH-code/volumebridge/releases/latest),放在任意文件夹即可)。由于程序未做代码签名,Windows SmartScreen 可能会弹出提示,点击**更多信息 → 仍要运行**即可。 +3. **点击启用插件**(一次 UAC 管理员确认)。过程中 Windows 声音会中断约 2 秒。 +4. **点击设为默认输出**,播放任意声音确认窗口显示 **● 正在工作(零延迟)**,再勾选**开机自动启动**即可。 ### 日常使用 - **最大音量上限:** 默认 **-12 dB**,避免滑块拉满时震耳欲聋;可在窗口中自由调节(**0 到 -30 dB**)。 - **输出设备选择:** 默认自动匹配名称包含 `JBL` 或 `Zgmicro` 的播放设备,也可以在下拉框里手动指定其他设备。 - **窗口与托盘:** 关闭窗口后会隐藏到系统托盘继续运行,不占任务栏。 -- **界面语言:** 支持简体中文 / English,安装时选择,也可以在程序里随时切换。 -- **检查更新:** 支持从 GitHub Releases 一键更新(下载包会做 SHA-256 校验)。 -- **干净卸载:** 在“设置 → 应用”中卸载 VolumeBridge 时,会自动恢复所有被修改的 Windows 音频设置。 +- **界面语言:** 默认跟随 Windows 显示语言,也可在程序里随时切换简体中文 / English。 +- **检查更新:** 支持从 GitHub Releases 一键原地更新(下载文件会做 SHA-256 校验)。 +- **干净卸载:** 在窗口中点击**移除插件**(会自动恢复所有被修改的 Windows 音频设置并取消开机自启),然后退出并删除 `VolumeBridge.exe` 即可。 ## 代价与排障 -零延迟模式需要改动一项 Windows 音频设置以加载插件,安装前请了解以下几点: +零延迟模式需要改动一项 Windows 音频设置以加载插件,启用前请了解以下几点: - **需要关闭受保护音频路径(`DisableProtectedAudioDG=1`):** 插件未经微软签名,Windows 需要关闭此项才能加载它(Equalizer APO 也是同样做法)。少数 DRM 播放器(如部分受保护的 4K 音频流)可能受影响。 - **保持“音频增强”开启:** 在 **设置 → 系统 → 声音 → 该音箱** 中,**音频增强**必须保持为**设备默认效果**。如果改成“关”,Windows 会跳过插件。 - **独占模式会绕过插件:** 以 WASAPI 独占模式播放的程序不经过 Windows 音频引擎,音量插件不会生效。 - **换 USB 口或 Windows 大版本更新:** 换插 USB 口或升级 Windows 大版本后,插件设置可能被重置。窗口会提示状态异常,点一下**启用插件**即可恢复。 -- **如果装完后没声音:** 直接在**设置 → 应用**中卸载 VolumeBridge(会还原所有设置),或者把该音箱的**音频增强**改成**关**。 +- **如果启用后没声音:** 在 VolumeBridge 中点击**移除插件**(会还原所有设置),或者把该音箱的**音频增强**改成**关**。 ## 兼容性与支持设备 @@ -94,16 +96,20 @@ Voicemeeter 需要经过虚拟声卡再二次输出,会引入延迟、占用 | `maxOutputDb` | `-12` | 滑块 100% 时的输出上限(dB),`0` 表示音箱原始最大音量 | | `outputKeywords` | `["JBL", "Zgmicro"]` | 自动识别输出设备的名称关键字(不区分大小写) | | `outputDeviceId` | `null` | 固定指定的输出设备 ID(由界面下拉框写入) | -| `language` | `"auto"` | `"zh"` / `"en"`,`"auto"` 跟随安装时的语言选择 | +| `language` | `"auto"` | `"zh"` / `"en"`,`"auto"` 跟随 Windows 显示语言 | ## 从源码构建 ```powershell +# 1. 构建 C++ APO 插件(在 Visual Studio x64 开发者命令提示符中) +./apo/build.ps1 -Out "$PWD\out" + +# 2. 运行测试并构建绿色单文件 exe(.NET Framework 4.8) dotnet test tests/VolumeBridge.Tests -dotnet publish src/VolumeBridge -c Release -r win-x64 -o out +dotnet build src/VolumeBridge -c Release "-p:ApoDll=$PWD\out\VolumeBridgeApo.dll" -p:RequireApo=true -o dist ``` -GitHub Actions(`.github/workflows/build.yml`)会在 Windows 上构建 C++ 音量插件(`apo/`)与 Inno Setup 安装包,并在推送 `v*` 标签时自动发布 Release。设计思路与评审记录见 [docs/PLAN.md](docs/PLAN.md)。 +GitHub Actions(`.github/workflows/build.yml`)会在 Windows 上构建 C++ 音量插件(`apo/`)并嵌入单个绿色版 `VolumeBridge.exe`,并在推送 `v*` 标签时自动发布 Release。设计思路与评审记录见 [docs/PLAN.md](docs/PLAN.md)。 ## 致谢与许可 diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md index 6d0d205..6805024 100644 --- a/THIRD-PARTY-NOTICES.md +++ b/THIRD-PARTY-NOTICES.md @@ -13,3 +13,29 @@ The above copyright notice and this permission notice shall be included in all c THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` + +## PolySharp + +Build-time source generator only (https://github.com/Sergio0694/PolySharp); no runtime assembly is redistributed. Licensed under the MIT License: + +``` +Copyright (c) 2022 Sergio Pedri + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` diff --git a/docs/PLAN.md b/docs/PLAN.md index 496d6e0..9b61fca 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -1,5 +1,7 @@ # VolumeBridge 实施计划 +> **现状(0.5.0)**:改为基于 Windows 10 1903+/11 自带 .NET Framework 4.8 的**绿色单文件 `VolumeBridge.exe`**(内置 NAudio 与 `VolumeBridgeApo.dll`,移除 Inno Setup 安装包),支持程序内直接部署/更新/移除插件与原地自更新。 +> > **现状(0.4.0)**:产品只保留**零延迟 APO 模式**(`apo/VolumeBridgeApo.cpp`,音箱端点效果 EFX),已在 JBL Flip 6 + Windows 11 26H2 上实测可用。下文的 v3 虚拟音箱方案(USB/IP + UAC1)曾作为 0.2.x–0.3.x 的"兼容模式"发布,0.4.0 起已移除,代码保留在 Git 历史中(标签 v0.3.3 及以前)。 > > APO 调试中的关键经验: diff --git a/docs/release-notes.md b/docs/release-notes.md index 46f4af8..c1eb579 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -1,8 +1,14 @@ -**中文** — 下载下面的 `VolumeBridgeSetup.exe` 运行即可。安装前请退出 Voicemeeter。使用说明见 [README](https://github.com/ZanderH-code/volumebridge/blob/main/README.zh-CN.md)。 +**中文** — 下载下面的 `VolumeBridge.exe` 直接运行即可(无需安装)。首次运行前请退出 Voicemeeter。使用说明见 [README](https://github.com/ZanderH-code/volumebridge/blob/main/README.zh-CN.md)。 -**English** — Download and run `VolumeBridgeSetup.exe` below. Quit Voicemeeter first. See the [README](https://github.com/ZanderH-code/volumebridge/blob/main/README.md). +**English** — Download and run `VolumeBridge.exe` below (portable, no installer). Quit Voicemeeter first. See the [README](https://github.com/ZanderH-code/volumebridge/blob/main/README.md). -`VolumeBridgeSetup.exe.sha256` is used by the in-app updater to verify the download. +`VolumeBridge.exe.sha256` is used by the in-app updater to verify the download. + +### 0.5.0 +- 改为单个绿色可执行文件 `VolumeBridge.exe`(基于 Windows 自带的 .NET Framework 4.8,不到 1 MB,取代原来的 67 MB 安装包)。 / Single portable `VolumeBridge.exe` targeting in-box .NET Framework 4.8 (under 1 MB instead of the 67 MB installer); no installer needed. +- 插件部署与卸载直接内置到程序中:点**启用插件**会释放并注册内置的零延迟插件;新增**移除插件**按钮一键还原音频设置、注销插件并取消开机自启。 / Plugin deploy and removal are built into the exe: **Enable plugin** extracts and registers the embedded APO; new **Remove plugin** button restores audio settings, unregisters the plugin, and removes autostart. +- 支持单文件原地一键更新;如果移动了 `VolumeBridge.exe` 的位置,启动时会自动同步开机自启任务路径。 / In-place single-exe self-update; moving `VolumeBridge.exe` automatically updates the logon task path at startup. +- **从 0.4.0 升级注意:** 由于不再提供安装包资产,0.4.0 内置的更新检查会提示“已是最新版本”,请先在 **设置 → 应用** 中卸载 0.4.0,再手动下载本版本的 `VolumeBridge.exe`。 / **Upgrading from 0.4.0:** 0.4.0's updater will report "latest" because the setup asset is gone — uninstall 0.4.0 in **Settings → Apps** first, then download `VolumeBridge.exe` manually. ### 0.4.0 - 只保留零延迟模式:移除兼容(虚拟音箱)模式,安装包不再附带 usbip-win2 驱动,体积明显变小、界面更简单。 / Zero-latency mode only: the compatible (virtual speaker) mode is removed and usbip-win2 is no longer bundled; smaller installer, simpler window. diff --git a/installer/ChineseSimplified.isl b/installer/ChineseSimplified.isl deleted file mode 100644 index df4aa4b..0000000 --- a/installer/ChineseSimplified.isl +++ /dev/null @@ -1,417 +0,0 @@ -; *** Inno Setup version 6.5.0+ Chinese Simplified messages *** -; -; To download user-contributed translations of this file, go to: -; https://jrsoftware.org/files/istrans/ -; -; Note: When translating this text, do not add periods (.) to the end of -; messages that didn't have them already, because on those messages Inno -; Setup adds the periods automatically (appending a period would result in -; two periods being displayed). -; -; Maintainer: Zhenghan Yang (Kira) -; Email: 847320916@QQ.com -; Github: https://github.com/kira-96/Inno-Setup-Chinese-Simplified-Translation -; Encoding: UTF-8 -; Translation based on network resource -; - -[LangOptions] -; The following three entries are very important. Be sure to read and -; understand the '[LangOptions] section' topic in the help file. -LanguageName=简体中文 -; About LanguageID, to reference link: -; https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-lcid/a9eac961-e77d-41a6-90a5-ce1a8b0cdb9c -LanguageID=$0804 -; LanguageCodePage should always be set if possible, even if this file is Unicode -; For English it's set to zero anyway because English only uses ASCII characters -LanguageCodePage=936 -; If the language you are translating to requires special font faces or -; sizes, uncomment any of the following entries and change them accordingly. -;DialogFontName= -;DialogFontSize=9 -;DialogFontBaseScaleWidth=7 -;DialogFontBaseScaleHeight=15 -;WelcomeFontName=Segoe UI -;WelcomeFontSize=14 - -[Messages] - -; *** Application titles -SetupAppTitle=安装 -SetupWindowTitle=安装 - %1 -UninstallAppTitle=卸载 -UninstallAppFullTitle=%1 卸载 - -; *** Misc. common -InformationTitle=信息 -ConfirmTitle=确认 -ErrorTitle=错误 - -; *** SetupLdr messages -SetupLdrStartupMessage=现在将安装 %1。您想要继续吗? -LdrCannotCreateTemp=无法创建临时文件。安装程序已中止 -LdrCannotExecTemp=无法执行临时目录中的文件。安装程序已中止 -HelpTextNote= - -; *** Startup error messages -LastErrorMessage=%1。%n%n错误 %2: %3 -SetupFileMissing=安装目录中缺少文件 %1。请修正这个问题或者获取程序的新副本。 -SetupFileCorrupt=安装文件已损坏。请获取程序的新副本。 -SetupFileCorruptOrWrongVer=安装文件已损坏,或是与这个安装程序的版本不兼容。请修正这个问题或获取新的程序副本。 -InvalidParameter=无效的命令行参数:%n%n%1 -SetupAlreadyRunning=安装程序已在运行。 -WindowsVersionNotSupported=此程序不支持当前计算机运行的 Windows 版本。 -WindowsServicePackRequired=此程序需要 %1 服务包 %2 或更高版本。 -NotOnThisPlatform=此程序不能在 %1 上运行。 -OnlyOnThisPlatform=此程序只能在 %1 上运行。 -OnlyOnTheseArchitectures=此程序只能安装到为下列处理器架构设计的 Windows 版本中:%n%n%1 -WinVersionTooLowError=此程序需要 %1 版本 %2 或更高。 -WinVersionTooHighError=此程序不能安装于 %1 版本 %2 或更高。 -AdminPrivilegesRequired=在安装此程序时您必须以管理员身份登录。 -PowerUserPrivilegesRequired=在安装此程序时您必须以管理员身份或高级用户组身份登录。 -SetupAppRunningError=安装程序检测到 %1 当前正在运行。%n%n请先关闭正在运行的程序,然后点击“确定”继续,或点击“取消”退出。 -UninstallAppRunningError=卸载程序检测到 %1 当前正在运行。%n%n请先关闭正在运行的程序,然后点击“确定”继续,或点击“取消”退出。 - -; *** Startup questions -PrivilegesRequiredOverrideTitle=选择安装程序安装模式 -PrivilegesRequiredOverrideInstruction=选择安装模式 -PrivilegesRequiredOverrideText1=%1 可以为所有用户安装(需要管理员权限),或仅为您安装。 -PrivilegesRequiredOverrideText2=%1 可以仅为您安装,或为所有用户安装(需要管理员权限)。 -PrivilegesRequiredOverrideAllUsers=为所有用户安装(&A) -PrivilegesRequiredOverrideAllUsersRecommended=为所有用户安装(&A)(推荐) -PrivilegesRequiredOverrideCurrentUser=仅为我安装(&M) -PrivilegesRequiredOverrideCurrentUserRecommended=仅为我安装(&M)(推荐) - -; *** Misc. errors -ErrorCreatingDir=安装程序无法创建目录“%1” -ErrorTooManyFilesInDir=无法在目录“%1”中创建文件,因为里面包含太多文件。 - -; *** Setup common messages -ExitSetupTitle=退出安装程序 -ExitSetupMessage=安装程序尚未完成。如果现在退出,将不会安装该程序。%n%n您之后可以再次运行安装程序完成安装。%n%n现在退出安装程序吗? -AboutSetupMenuItem=关于安装程序(&A)... -AboutSetupTitle=关于安装程序 -AboutSetupMessage=%1 版本 %2%n%3%n%n%1 主页:%n%4 -AboutSetupNote= -TranslatorNote=简体中文翻译由 Kira(847320916@qq.com)维护。项目地址:https://github.com/kira-96/Inno-Setup-Chinese-Simplified-Translation - -; *** Buttons -ButtonBack=< 上一步(&B) -ButtonNext=下一步(&N) > -ButtonInstall=安装(&I) -ButtonOK=确定 -ButtonCancel=取消 -ButtonYes=是(&Y) -ButtonYesToAll=全是(&A) -ButtonNo=否(&N) -ButtonNoToAll=全否(&O) -ButtonFinish=完成(&F) -ButtonBrowse=浏览(&B)... -ButtonWizardBrowse=浏览(&R)... -ButtonNewFolder=新建文件夹(&M) - -; *** "Select Language" dialog messages -SelectLanguageTitle=选择安装语言 -SelectLanguageLabel=选择安装时使用的语言。 - -; *** Common wizard text -ClickNext=点击“下一步”继续,或点击“取消”退出安装程序。 -BeveledLabel= -BrowseDialogTitle=浏览文件夹 -BrowseDialogLabel=在下面的列表中选择一个文件夹,然后点击“确定”。 -NewFolderName=新建文件夹 - -; *** "Welcome" wizard page -WelcomeLabel1=欢迎使用 [name] 安装向导 -WelcomeLabel2=即将在您的计算机上安装 [name/ver]。%n%n建议您在继续安装前关闭所有其他应用程序。 - -; *** "Password" wizard page -WizardPassword=密码 -PasswordLabel1=此安装程序需要密码验证。 -PasswordLabel3=请输入密码,然后点击“下一步”继续。密码区分大小写。 -PasswordEditLabel=密码(&P): -IncorrectPassword=您输入的密码不正确,请重新输入。 - -; *** "License Agreement" wizard page -WizardLicense=许可协议 -LicenseLabel=请在继续安装前阅读以下重要信息。 -LicenseLabel3=请阅读下列许可协议。在继续安装前您必须同意这些协议条款。 -LicenseAccepted=我同意此协议(&A) -LicenseNotAccepted=我不同意此协议(&D) - -; *** "Information" wizard pages -WizardInfoBefore=信息 -InfoBeforeLabel=请在继续安装前阅读以下重要信息。 -InfoBeforeClickLabel=准备好继续安装后,点击“下一步”。 -WizardInfoAfter=信息 -InfoAfterLabel=请在继续安装前阅读以下重要信息。 -InfoAfterClickLabel=准备好继续安装后,点击“下一步”。 - -; *** "User Information" wizard page -WizardUserInfo=用户信息 -UserInfoDesc=请输入您的信息。 -UserInfoName=用户名(&U): -UserInfoOrg=组织(&O): -UserInfoSerial=序列号(&S): -UserInfoNameRequired=请输入用户名。 - -; *** "Select Destination Location" wizard page -WizardSelectDir=选择目标位置 -SelectDirDesc=您想将 [name] 安装在哪里? -SelectDirLabel3=安装程序将安装 [name] 到下面的文件夹中。 -SelectDirBrowseLabel=点击“下一步”继续。如果您想选择其他文件夹,点击“浏览”。 -DiskSpaceGBLabel=至少需要有 [gb] GB 的可用磁盘空间。 -DiskSpaceMBLabel=至少需要有 [mb] MB 的可用磁盘空间。 -CannotInstallToNetworkDrive=安装程序无法安装到一个网络驱动器。 -CannotInstallToUNCPath=安装程序无法安装到一个 UNC 路径。 -InvalidPath=您必须输入一个带驱动器盘符的完整路径,例如:%n%nC:\App%n%n或UNC路径:%n%n\\server\share -InvalidDrive=您选定的驱动器或 UNC 共享不存在或不能访问。请选择其他位置。 -DiskSpaceWarningTitle=磁盘空间不足 -DiskSpaceWarning=安装程序至少需要 %1 KB 的可用空间才能安装,但选定驱动器只有 %2 KB 的可用空间。%n%n您确定要继续吗? -DirNameTooLong=文件夹名称或路径太长。 -InvalidDirName=文件夹名称无效。 -BadDirName32=文件夹名称不能包含下列任何字符:%n%n%1 -DirExistsTitle=文件夹已存在 -DirExists=文件夹:%n%n%1%n%n已经存在。您确定安装到这个文件夹中吗? -DirDoesntExistTitle=文件夹不存在 -DirDoesntExist=文件夹:%n%n%1%n%n不存在。您想要创建此文件夹吗? - -; *** "Select Components" wizard page -WizardSelectComponents=选择组件 -SelectComponentsDesc=您想安装哪些程序组件? -SelectComponentsLabel2=选中您想安装的组件;取消您不想安装的组件。然后点击“下一步”继续。 -FullInstallation=完全安装 -; if possible don't translate 'Compact' as 'Minimal' (I mean 'Minimal' in your language) -CompactInstallation=简洁安装 -CustomInstallation=自定义安装 -NoUninstallWarningTitle=组件已存在 -NoUninstallWarning=安装程序检测到下列组件已安装在您的计算机中:%n%n%1%n%n取消选中这些组件不会卸载它们。%n%n您确定要继续吗? -ComponentSize1=%1 KB -ComponentSize2=%1 MB -ComponentsDiskSpaceGBLabel=当前选择的组件需要至少 [gb] GB 的磁盘空间。 -ComponentsDiskSpaceMBLabel=当前选择的组件需要至少 [mb] MB 的磁盘空间。 - -; *** "Select Additional Tasks" wizard page -WizardSelectTasks=选择附加任务 -SelectTasksDesc=您想要安装程序执行哪些附加任务? -SelectTasksLabel2=选择您想要安装程序在安装 [name] 时执行的附加任务,然后点击“下一步”。 - -; *** "Select Start Menu Folder" wizard page -WizardSelectProgramGroup=选择开始菜单文件夹 -SelectStartMenuFolderDesc=安装程序应该在哪里放置程序的快捷方式? -SelectStartMenuFolderLabel3=安装程序将在下列“开始”菜单文件夹中创建程序的快捷方式。 -SelectStartMenuFolderBrowseLabel=点击“下一步”继续。如果您想选择其他文件夹,点击“浏览”。 -MustEnterGroupName=您必须输入一个文件夹名称。 -GroupNameTooLong=文件夹名称或路径太长。 -InvalidGroupName=文件夹名称无效。 -BadGroupName=文件夹名称不能包含下列任何字符:%n%n%1 -NoProgramGroupCheck2=不创建开始菜单文件夹(&D) - -; *** "Ready to Install" wizard page -WizardReady=准备安装 -ReadyLabel1=安装程序准备就绪,现在可以开始安装 [name] 到您的计算机。 -ReadyLabel2a=点击“安装”继续此安装程序。如果您想重新查看或修改任何设置,点击“上一步”。 -ReadyLabel2b=点击“安装”继续此安装程序。 -ReadyMemoUserInfo=用户信息: -ReadyMemoDir=目标位置: -ReadyMemoType=安装类型: -ReadyMemoComponents=已选择组件: -ReadyMemoGroup=开始菜单文件夹: -ReadyMemoTasks=附加任务: - -; *** TDownloadWizardPage wizard page and DownloadTemporaryFile -DownloadingLabel2=正在下载文件... -ButtonStopDownload=停止下载(&S) -StopDownload=您确定要停止下载吗? -ErrorDownloadAborted=下载已中止。 -ErrorDownloadFailed=下载失败:%1 %2。 -ErrorDownloadSizeFailed=获取大小失败:%1 %2。 -ErrorProgress=无效的进度:%1 / %2。 -ErrorFileSize=文件大小错误:预期 %1,实际 %2。 - -; *** TExtractionWizardPage wizard page and ExtractArchive -ExtractingLabel=正在提取文件... -ButtonStopExtraction=停止提取(&S) -StopExtraction=您确定要停止提取吗? -ErrorExtractionAborted=提取已中止。 -ErrorExtractionFailed=提取失败:%1 - -; *** Archive extraction failure details -ArchiveIncorrectPassword=密码不正确。 -ArchiveIsCorrupted=压缩包已损坏。 -ArchiveUnsupportedFormat=不支持的压缩包格式。 - -; *** "Preparing to Install" wizard page -WizardPreparing=正在准备安装 -PreparingDesc=安装程序正在准备安装 [name] 到您的计算机。 -PreviousInstallNotCompleted=先前的程序安装或卸载未完成,需要您重启计算机以完成该安装。%n%n在重启计算机后,再次运行安装程序以完成 [name] 的安装。 -CannotContinue=安装程序不能继续。请点击“取消”退出。 -ApplicationsFound=以下应用程序正在使用将由安装程序更新的文件。建议您允许安装程序自动关闭这些应用程序。 -ApplicationsFound2=以下应用程序正在使用将由安装程序更新的文件。建议您允许安装程序自动关闭这些应用程序。安装完成后,安装程序将尝试重新启动这些应用程序。 -CloseApplications=自动关闭应用程序(&A) -DontCloseApplications=不要关闭应用程序(&D) -ErrorCloseApplications=安装程序无法自动关闭所有应用程序。建议您在继续之前,关闭所有在使用需要由安装程序更新的文件的应用程序。 -PrepareToInstallNeedsRestart=安装程序必须重启您的计算机。计算机重启后,请再次运行安装程序以完成 [name] 的安装。%n%n要立即重启吗? - -; *** "Installing" wizard page -WizardInstalling=正在安装 -InstallingLabel=安装程序正在安装 [name] 到您的计算机,请稍候。 - -; *** "Setup Completed" wizard page -FinishedHeadingLabel=完成 [name] 安装向导 -FinishedLabelNoIcons=安装程序已在您的计算机中安装了 [name]。 -FinishedLabel=安装程序已在您的计算机中安装了 [name]。您可以通过已安装的快捷方式运行此应用程序。 -ClickFinish=点击“完成”退出安装程序。 -FinishedRestartLabel=为完成 [name] 的安装,安装程序必须重新启动您的计算机。要立即重启吗? -FinishedRestartMessage=为完成 [name] 的安装,安装程序必须重新启动您的计算机。%n%n要立即重启吗? -ShowReadmeCheck=是,我想查阅自述文件 -YesRadio=是,立即重启计算机(&Y) -NoRadio=否,稍后重启计算机(&N) -; used for example as 'Run MyProg.exe' -RunEntryExec=运行 %1 -; used for example as 'View Readme.txt' -RunEntryShellExec=查阅 %1 - -; *** "Setup Needs the Next Disk" stuff -ChangeDiskTitle=安装程序需要下一张磁盘 -SelectDiskLabel2=请插入磁盘 %1 并点击“确定”。%n%n如果这个磁盘中的文件可以在下列文件夹之外的文件夹中找到,请输入正确的路径或点击“浏览”。 -PathLabel=路径(&P): -FileNotInDir2=“%2”中找不到文件“%1”。请插入正确的磁盘或选择其他文件夹。 -SelectDirectoryLabel=请指定下一张磁盘的位置。 - -; *** Installation phase messages -SetupAborted=安装程序未完成安装。%n%n请修正这个问题并重新运行安装程序。 -AbortRetryIgnoreSelectAction=选择操作 -AbortRetryIgnoreRetry=重试(&T) -AbortRetryIgnoreIgnore=忽略错误并继续(&I) -AbortRetryIgnoreCancel=取消安装 -RetryCancelSelectAction=选择操作 -RetryCancelRetry=重试(&T) -RetryCancelCancel=取消 - -; *** Installation status messages -StatusClosingApplications=正在关闭应用程序... -StatusCreateDirs=正在创建目录... -StatusExtractFiles=正在提取文件... -StatusDownloadFiles=正在下载文件... -StatusCreateIcons=正在创建快捷方式... -StatusCreateIniEntries=正在创建 INI 条目... -StatusCreateRegistryEntries=正在创建注册表条目... -StatusRegisterFiles=正在注册文件... -StatusSavingUninstall=正在保存卸载信息... -StatusRunProgram=正在完成安装... -StatusRestartingApplications=正在重启应用程序... -StatusRollback=正在撤销更改... - -; *** Misc. errors -ErrorInternal2=内部错误:%1。 -ErrorFunctionFailedNoCode=%1 失败。 -ErrorFunctionFailed=%1 失败;错误代码 %2。 -ErrorFunctionFailedWithMessage=%1 失败;错误代码 %2。%n%3 -ErrorExecutingProgram=无法执行文件:%n%1 - -; *** Registry errors -ErrorRegOpenKey=打开注册表项时出错:%n%1\%2 -ErrorRegCreateKey=创建注册表项时出错:%n%1\%2 -ErrorRegWriteKey=写入注册表项时出错:%n%1\%2 - -; *** INI errors -ErrorIniEntry=在文件“%1”中创建 INI 条目时出错。 - -; *** File copying errors -FileAbortRetryIgnoreSkipNotRecommended=跳过此文件(&S)(不推荐) -FileAbortRetryIgnoreIgnoreNotRecommended=忽略错误并继续(&I)(不推荐) -SourceIsCorrupted=源文件已损坏。 -SourceDoesntExist=源文件“%1”不存在。 -SourceVerificationFailed=源文件验证失败:%1 -VerificationSignatureDoesntExist=签名文件“%1”不存在。 -VerificationSignatureInvalid=签名文件“%1”无效。 -VerificationKeyNotFound=签名文件“%1”使用了未知的密钥。 -VerificationFileNameIncorrect=文件名不正确。 -VerificationFileTagIncorrect=文件标签不正确。 -VerificationFileSizeIncorrect=文件大小不正确。 -VerificationFileHashIncorrect=文件哈希值不正确。 -ExistingFileReadOnly2=无法替换已存在的文件,它是只读的。 -ExistingFileReadOnlyRetry=移除只读属性并重试(&R) -ExistingFileReadOnlyKeepExisting=保留已存在的文件(&K) -ErrorReadingExistingDest=尝试读取已存在的文件时出错: -FileExistsSelectAction=选择操作 -FileExists2=文件已经存在。 -FileExistsOverwriteExisting=覆盖已存在的文件(&O) -FileExistsKeepExisting=保留已存在的文件(&K) -FileExistsOverwriteOrKeepAll=为接下来的冲突文件执行此操作(&D) -ExistingFileNewerSelectAction=选择操作 -ExistingFileNewer2=已存在的文件比安装程序将要安装的文件还要新。 -ExistingFileNewerOverwriteExisting=覆盖已存在的文件(&O) -ExistingFileNewerKeepExisting=保留已存在的文件(&K)(推荐) -ExistingFileNewerOverwriteOrKeepAll=为接下来的冲突文件执行此操作(&D) -ErrorChangingAttr=尝试更改下列已存在的文件属性时出错: -ErrorCreatingTemp=尝试在目标目录创建文件时出错: -ErrorReadingSource=尝试读取下列源文件时出错: -ErrorCopying=尝试复制下列文件时出错: -ErrorDownloading=尝试下载文件时出错: -ErrorExtracting=尝试提取压缩包时出错: -ErrorReplacingExistingFile=尝试替换已存在的文件时出错: -ErrorRestartReplace=重启并替换失败: -ErrorRenamingTemp=尝试重命名下列目标目录中的一个文件时出错: -ErrorRegisterServer=无法注册 DLL/OCX:%1 -ErrorRegSvr32Failed=RegSvr32 失败;退出代码 %1。 -ErrorRegisterTypeLib=无法注册类型库:%1 - -; *** Uninstall display name markings -; used for example as 'My Program (32-bit)' -UninstallDisplayNameMark=%1 (%2) -; used for example as 'My Program (32-bit, All users)' -UninstallDisplayNameMarks=%1 (%2, %3) -UninstallDisplayNameMark32Bit=32 位 -UninstallDisplayNameMark64Bit=64 位 -UninstallDisplayNameMarkAllUsers=所有用户 -UninstallDisplayNameMarkCurrentUser=当前用户 - -; *** Post-installation errors -ErrorOpeningReadme=尝试打开自述文件时出错。 -ErrorRestartingComputer=安装程序无法重启计算机,请手动重启。 - -; *** Uninstaller messages -UninstallNotFound=文件“%1”不存在。无法卸载。 -UninstallOpenError=文件“%1”不能被打开。无法卸载 -UninstallUnsupportedVer=此版本的卸载程序无法识别卸载日志文件“%1”的格式。无法卸载。 -UninstallUnknownEntry=卸载日志中遇到一个未知条目(%1)。 -ConfirmUninstall=您确认要完全移除 %1 及其所有组件吗? -UninstallOnlyOnWin64=仅允许在 64 位 Windows 中卸载此程序。 -OnlyAdminCanUninstall=仅使用管理员权限的用户能完成此卸载。 -UninstallStatusLabel=正在从您的计算机中移除 %1,请稍候。 -UninstalledAll=已顺利从您的计算机中移除 %1。 -UninstalledMost=%1 卸载完成。%n%n有部分内容未能被删除,但您可以手动删除它们。 -UninstalledAndNeedsRestart=为完成 %1 的卸载,需要重启您的计算机。%n%n要立即重启吗? -UninstallDataCorrupted=文件“%1”已损坏。无法卸载。 - -; *** Uninstallation phase messages -ConfirmDeleteSharedFileTitle=删除共享文件? -ConfirmDeleteSharedFile2=系统表示下列共享文件已不再有任何程序使用。您希望卸载程序删除此共享文件吗?%n%n如果仍有程序正在使用此文件,删除后这些程序可能无法正常运行。如果您不能确定,请选择“否”,保留此文件在系统中不会造成任何损害。 -SharedFileNameLabel=文件名: -SharedFileLocationLabel=位置: -WizardUninstalling=卸载状态 -StatusUninstalling=正在卸载 %1... - -; *** Shutdown block reasons -ShutdownBlockReasonInstallingApp=正在安装 %1。 -ShutdownBlockReasonUninstallingApp=正在卸载 %1。 - -; The custom messages below aren't used by Setup itself, but if you make -; use of them in your scripts, you'll want to translate them. - -[CustomMessages] - -NameAndVersion=%1 版本 %2 -AdditionalIcons=附加快捷方式: -CreateDesktopIcon=创建桌面快捷方式(&D) -CreateQuickLaunchIcon=创建快速启动栏快捷方式(&Q) -ProgramOnTheWeb=%1 网站 -UninstallProgram=卸载 %1 -LaunchProgram=运行 %1 -AssocFileExtension=将 %2 文件扩展名与 %1 建立关联(&A) -AssocingFileExtension=正在将 %2 文件扩展名与 %1 建立关联... -AutoStartProgramGroupDescription=启动: -AutoStartProgram=自动启动 %1 -AddonHostProgramNotFound=您选择的文件夹中无法找到 %1。%n%n您确定要继续吗? diff --git a/installer/VolumeBridge.iss b/installer/VolumeBridge.iss deleted file mode 100644 index 417981e..0000000 --- a/installer/VolumeBridge.iss +++ /dev/null @@ -1,233 +0,0 @@ -; VolumeBridge installer: VolumeBridge.exe + the zero-latency volume plugin (VolumeBridgeApo.dll). -; Build (CI): iscc /DAppVersion=x.y.z /DPayloadDir= installer\VolumeBridge.iss - -#ifndef AppVersion - #define AppVersion "0.0.0" -#endif -#ifndef PayloadDir - #define PayloadDir "..\out" -#endif -; Versions up to 0.3.x could install usbip-win2; uninstall still offers to remove it. -; AppId of usbip-win2's own Inno Setup installer (userspace/innosetup/setup.iss). -#define UsbipUninstallKey "Software\Microsoft\Windows\CurrentVersion\Uninstall\{199505b0-b93d-4521-a8c7-897818e0205a}_is1" -#define MarkerKey "Software\VolumeBridge" - -[Setup] -AppId={{6F1C2B7E-4A0B-4D8E-9C55-5642B0A1D001} -AppName=VolumeBridge -AppVersion={#AppVersion} -AppPublisher=VolumeBridge -DefaultDirName={autopf}\VolumeBridge -DefaultGroupName=VolumeBridge -DisableProgramGroupPage=yes -; Fixed location: the exe decides where config/logs go by checking for Program Files (AppPaths.DataDir). -DisableDirPage=yes -PrivilegesRequired=admin -ArchitecturesAllowed=x64compatible -ArchitecturesInstallIn64BitMode=x64compatible -MinVersion=10.0.18362 -OutputBaseFilename=VolumeBridgeSetup -Compression=lzma2 -SolidCompression=yes -WizardStyle=modern -; A running VolumeBridge is handled in InitializeSetup/InitializeUninstall (wait for it to exit), -; not with AppMutex, so one-click updates (silent) do not abort while the app is shutting down. -UninstallDisplayName=VolumeBridge -; Language dialog (English / 简体中文); silent updates reuse the previous choice. -ShowLanguageDialog=yes -UsePreviousLanguage=yes - -[Languages] -Name: "english"; MessagesFile: "compiler:Default.isl" -; Official translation from jrsoftware/issrc (not yet shipped with Inno Setup 6.7.1), vendored. -Name: "chinesesimplified"; MessagesFile: "ChineseSimplified.isl" - -[Messages] -english.WelcomeLabel2=This will install VolumeBridge {#AppVersion}.%n%nZero-latency mode adds a small volume plugin to your speaker's audio effects. To load it, Windows' protected audio path is turned off (a few DRM players may be affected), and the Windows Audio service restarts once (sound stops for ~2 seconds). Everything is restored on uninstall. -chinesesimplified.WelcomeLabel2=将安装 VolumeBridge {#AppVersion}。%n%n零延迟模式会在音箱的音效设置中加入一个小型音量插件。为了让 Windows 加载它,会关闭“受保护音频路径”(少数 DRM 播放可能受影响),并重启一次 Windows 音频服务(声音中断约 2 秒)。卸载时全部恢复。 - -[CustomMessages] -english.TaskApo=Enable the zero-latency volume plugin for the speaker now (recommended) -chinesesimplified.TaskApo=现在为音箱启用零延迟音量插件(推荐) -english.StartApp=Start VolumeBridge now -chinesesimplified.StartApp=立即启动 VolumeBridge -english.AppRunning=VolumeBridge is running. Right-click its tray icon, choose "Quit", then click Retry. -chinesesimplified.AppRunning=VolumeBridge 正在运行。请右键托盘图标选择“退出”,然后点“重试”。 -english.RemoveUsbipAsk=VolumeBridge installed the usbip-win2 driver. Remove it too?%n%n(Choose No if other software uses usbip-win2. Its uninstaller asks for a restart when done.) -chinesesimplified.RemoveUsbipAsk=VolumeBridge 安装时一并安装了 usbip-win2 驱动。是否也卸载它?%n%n(如果其他软件也在使用 usbip-win2,请选“否”。它的卸载程序会在完成后提示重启。) -english.RemoveUsbipFailed=Could not start the usbip-win2 uninstaller (%1). You can remove "USBip" in Settings → Apps. -chinesesimplified.RemoveUsbipFailed=无法启动 usbip-win2 卸载程序(%1)。可在“设置 → 应用”中手动卸载 USBip。 - -[Tasks] -Name: "apo"; Description: "{cm:TaskApo}" - -[Dirs] -; Shared state between the tray app (user) and the plugin (audiodg, LOCAL SERVICE). -Name: "{commonappdata}\VolumeBridge"; Permissions: everyone-modify - -[Files] -Source: "{#PayloadDir}\VolumeBridge.exe"; DestDir: "{app}"; Flags: ignoreversion -; Loaded by audiodg.exe; PrepareToInstall stops the audio service so it can be replaced. -Source: "{#PayloadDir}\VolumeBridgeApo.dll"; DestDir: "{app}"; Flags: ignoreversion restartreplace uninsrestartdelete -Source: "..\THIRD-PARTY-NOTICES.md"; DestDir: "{app}"; Flags: ignoreversion -Source: "..\LICENSE"; DestDir: "{app}"; DestName: "LICENSE.txt"; Flags: ignoreversion - -[Icons] -Name: "{group}\VolumeBridge"; Filename: "{app}\VolumeBridge.exe"; WorkingDir: "{app}" -Name: "{group}\{cm:UninstallProgram,VolumeBridge}"; Filename: "{uninstallexe}" - -[Run] -Filename: "{sys}\regsvr32.exe"; Parameters: "/s ""{app}\VolumeBridgeApo.dll"""; Flags: runhidden waituntilterminated -; Windows Audio was stopped for the upgrade: start it first, otherwise --apo-setup sees no speakers. -Filename: "{sys}\net.exe"; Parameters: "start audiosrv"; Flags: runhidden waituntilterminated -Filename: "{app}\VolumeBridge.exe"; Parameters: "--apo-setup"; Flags: runhidden waituntilterminated; Tasks: apo -Filename: "{app}\VolumeBridge.exe"; WorkingDir: "{app}"; Description: "{cm:StartApp}"; Flags: postinstall nowait skipifsilent runasoriginaluser -; One-click update from the app runs this installer with /SILENT; reopen the app afterwards. -Filename: "{app}\VolumeBridge.exe"; Parameters: "--updated"; WorkingDir: "{app}"; Flags: nowait runasoriginaluser; Check: WizardSilent - -[UninstallDelete] -Type: files; Name: "{app}\language.txt" - -[UninstallRun] -; Restore the speakers' original effect settings and DisableProtectedAudioDG, then unregister the plugin. -Filename: "{app}\VolumeBridge.exe"; Parameters: "--apo-remove"; Flags: runhidden waituntilterminated; RunOnceId: "RemoveApo" -Filename: "{sys}\regsvr32.exe"; Parameters: "/u /s ""{app}\VolumeBridgeApo.dll"""; Flags: runhidden waituntilterminated; RunOnceId: "UnregisterApo" -Filename: "{sys}\schtasks.exe"; Parameters: "/Delete /TN VolumeBridge /F"; Flags: runhidden; RunOnceId: "DeleteAutostartTask" - -[Code] -var - AudioStopped: Boolean; - -const - RunningMutex = 'Global\VolumeBridge.Running'; - { Tells the app (waiting after starting this installer) that UAC was accepted, so it can quit. } - UpdatingMutex = 'Global\VolumeBridge.Updating'; - -{ Waits up to TimeoutMs for a running VolumeBridge to exit; interactive runs may retry. } -function WaitForAppExit(TimeoutMs: Integer; Silent: Boolean): Boolean; -var - Waited: Integer; -begin - repeat - Waited := 0; - while CheckForMutexes(RunningMutex) and (Waited < TimeoutMs) do - begin - Sleep(250); - Waited := Waited + 250; - end; - Result := not CheckForMutexes(RunningMutex); - if Result or Silent then - Exit; - until MsgBox(CustomMessage('AppRunning'), mbError, MB_RETRYCANCEL) <> IDRETRY; -end; - -function InitializeSetup(): Boolean; -begin - { Runs in the elevated setup process, i.e. after UAC was accepted. } - CreateMutex(UpdatingMutex); - { Silent = one-click update: the app is exiting by itself, give it time. Interactive: ask quickly. } - if WizardSilent() then - Result := WaitForAppExit(30000, True) - else - Result := WaitForAppExit(2000, False); -end; - -function InitializeUninstall(): Boolean; -begin - Result := WaitForAppExit(5000, UninstallSilent()); -end; - -{ Upgrades: audiodg.exe keeps VolumeBridgeApo.dll loaded; stop the audio service so it can be - replaced. The Run section starts it again. } -function PrepareToInstall(var NeedsRestart: Boolean): String; -var - ResultCode: Integer; -begin - Result := ''; - if FileExists(ExpandConstant('{app}\VolumeBridgeApo.dll')) then - AudioStopped := Exec(ExpandConstant('{sys}\net.exe'), 'stop audiosrv /y', '', SW_HIDE, ewWaitUntilTerminated, ResultCode); -end; - -{ Whatever happened (finished, cancelled, failed), never leave Windows Audio stopped. } -procedure DeinitializeSetup(); -var - ResultCode: Integer; -begin - if AudioStopped then - Exec(ExpandConstant('{sys}\net.exe'), 'start audiosrv', '', SW_HIDE, ewWaitUntilTerminated, ResultCode); -end; - -{ The app's UI follows the installer language unless the user picks another one in the app. } -procedure CurStepChanged(CurStep: TSetupStep); -var - Lang: String; -begin - if CurStep <> ssPostInstall then - Exit; - if ActiveLanguage() = 'chinesesimplified' then - Lang := 'zh' - else - Lang := 'en'; - SaveStringToFile(ExpandConstant('{app}\language.txt'), Lang, False); -end; - -{ "C:\...\unins000.exe" /LOG -> C:\...\unins000.exe } -function ExecutableFromCommandLine(const Cmd: String): String; -var - S: String; - P: Integer; -begin - S := Trim(Cmd); - if (Length(S) > 0) and (S[1] = '"') then - begin - Delete(S, 1, 1); - P := Pos('"', S); - if P > 0 then - S := Copy(S, 1, P - 1); - Result := S; - end - else - begin - P := Pos(' /', S); - if P > 0 then - Result := Copy(S, 1, P - 1) - else - Result := S; - end; -end; - -{ Optionally hands off to usbip-win2's own uninstaller (with its progress window). It is not waited - for: its second phase outlives the first, and it shows its own restart prompt only after the - driver packages are removed, so we never offer a reboot that could interrupt it. } -procedure MaybeRemoveUsbip(); -var - Marker: Cardinal; - Uninstaller, Exe: String; - ResultCode: Integer; -begin - if not RegQueryDWordValue(HKLM64, '{#MarkerKey}', 'InstalledUsbip', Marker) or (Marker <> 1) then - Exit; - if RegQueryStringValue(HKLM64, '{#UsbipUninstallKey}', 'UninstallString', Uninstaller) - and not UninstallSilent() then - begin - Exe := ExecutableFromCommandLine(Uninstaller); - if SuppressibleMsgBox(CustomMessage('RemoveUsbipAsk'), mbConfirmation, MB_YESNO, IDNO) = IDYES then - begin - if not Exec(Exe, '/SILENT', '', SW_SHOW, ewNoWait, ResultCode) then - SuppressibleMsgBox(FmtMessage(CustomMessage('RemoveUsbipFailed'), [SysErrorMessage(ResultCode)]), mbError, MB_OK, IDOK); - end; - end; - // Only our marker: the same key holds the FxProperties backups (restored by --apo-remove). - RegDeleteValue(HKLM64, '{#MarkerKey}', 'InstalledUsbip'); -end; - -procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep); -begin - { usDone: after our "removed" dialog is closed, so our uninstaller no longer blocks the - restart that usbip-win2's uninstaller offers. } - if CurUninstallStep = usDone then - begin - MaybeRemoveUsbip(); - RegDeleteKeyIfEmpty(HKLM64, '{#MarkerKey}'); - end; -end; diff --git a/src/VolumeBridge/Audio/ApoController.cs b/src/VolumeBridge/Audio/ApoController.cs index 8ac7555..d0db9a9 100644 --- a/src/VolumeBridge/Audio/ApoController.cs +++ b/src/VolumeBridge/Audio/ApoController.cs @@ -8,11 +8,13 @@ namespace VolumeBridge.Audio; public enum ApoState { - NoSpeaker, // no matching playback device connected - NotInstalled, // APO not registered for this speaker (or unsigned APOs blocked) - EnhancementsOff, // "Audio enhancements" = Off: Windows skips effects - Idle, // registered, nothing playing right now (APO not running) - Working, // APO is processing audio + LegacyInstallPresent, // old Inno Setup version is still installed; must uninstall it first + NoSpeaker, // no matching playback device connected + NotInstalled, // APO not registered for this speaker (or unsigned APOs blocked) + Outdated, // registered APO DLL differs from the one embedded in this exe + EnhancementsOff, // "Audio enhancements" = Off: Windows skips effects + Idle, // registered, nothing playing right now (APO not running) + Working, // APO is processing audio } public sealed record ApoStatus( @@ -21,10 +23,11 @@ public sealed record ApoStatus( string? SpeakerId, float SliderScalar, bool Muted, - ApoReport? Report) + ApoReport? Report, + bool PluginPresent = false) { public string VolumeText => Muted ? T("静音", "Muted") - : string.Create(CultureInfo.InvariantCulture, $"{Math.Round(SliderScalar * 100)}% ({(SliderScalar <= 0.001f ? "-∞" : (20 * Math.Log10(SliderScalar)).ToString("0.0", CultureInfo.InvariantCulture))} dB)"); + : FormattableString.Invariant($"{Math.Round(SliderScalar * 100)}% ({(SliderScalar <= 0.001f ? "-∞" : (20 * Math.Log10(SliderScalar)).ToString("0.0", CultureInfo.InvariantCulture))} dB)"); public string SourceText => Report?.Source switch { @@ -126,10 +129,14 @@ void Refresh() } finally { foreach (var d in renders) d.Dispose(); } + bool legacy = ApoRegistration.IsLegacyInstallerPresent(); + bool pluginPresent = ApoRegistration.IsAnyPluginInstalled(); + if (target is null) { Unsubscribe(); - Set(new ApoStatus(ApoState.NoSpeaker, null, null, 1, false, _shared?.Read())); + Set(new ApoStatus(legacy ? ApoState.LegacyInstallPresent : ApoState.NoSpeaker, + null, null, 1, false, _shared?.Read(), pluginPresent)); return; } @@ -149,18 +156,20 @@ void Refresh() var report = _shared?.Read(); bool registered = ApoRegistration.IsRegistered(target.Id) && ApoRegistration.UnsignedApoAllowed() && ApoRegistration.ComRegistered(); - ApoState state = !registered ? ApoState.NotInstalled + ApoState state = legacy ? ApoState.LegacyInstallPresent + : !registered ? ApoState.NotInstalled + : ApoRegistration.IsPluginOutdated() ? ApoState.Outdated : ApoRegistration.EnhancementsDisabled(target.Id) ? ApoState.EnhancementsOff : report is { Instances: > 0, HeartbeatAgeMs: < 3000 } ? ApoState.Working : ApoState.Idle; - Set(new ApoStatus(state, target.Name, target.Id, scalar, muted, report)); + Set(new ApoStatus(state, target.Name, target.Id, scalar, muted, report, pluginPresent)); } void OnVolume(AudioVolumeNotificationData data) => Publish(data.MasterVolume, data.Muted); void Publish(float scalar, bool muted) { - float gain = muted ? 0f : Math.Clamp(scalar, 0f, 1f); + float gain = muted ? 0f : Math.Max(0f, Math.Min(1f, scalar)); lock (_gate) // controller thread and COM notification thread { if (gain == _lastWritten) return; @@ -182,8 +191,8 @@ void Set(ApoStatus s) lock (_gate) _status = s; } - public static string StatusLine(ApoStatus s) => string.Create(CultureInfo.InvariantCulture, - $"apo state={s.State} speaker=\"{s.SpeakerName}\" slider={s.SliderScalar:0.000} mute={(s.Muted ? 1 : 0)} " + - $"instances={s.Report?.Instances} source={s.Report?.Source} gain={s.Report?.TargetGain:0.000} init={s.Report?.InitKind} " + - $"notifs={s.Report?.Notifications} beatAge={(s.Report?.HeartbeatAgeMs is long a && a < long.MaxValue ? a : -1)}ms rate={s.Report?.SampleRate} ch={s.Report?.Channels}"); + public static string StatusLine(ApoStatus s) => + FormattableString.Invariant($"apo state={s.State} speaker=\"{s.SpeakerName}\" slider={s.SliderScalar:0.000} mute={(s.Muted ? 1 : 0)} ") + + FormattableString.Invariant($"instances={s.Report?.Instances} source={s.Report?.Source} gain={s.Report?.TargetGain:0.000} init={s.Report?.InitKind} ") + + FormattableString.Invariant($"notifs={s.Report?.Notifications} beatAge={(s.Report?.HeartbeatAgeMs is long a && a < long.MaxValue ? a : -1)}ms rate={s.Report?.SampleRate} ch={s.Report?.Channels}"); } diff --git a/src/VolumeBridge/Audio/ApoRegistration.cs b/src/VolumeBridge/Audio/ApoRegistration.cs index 1f7646d..675cc25 100644 --- a/src/VolumeBridge/Audio/ApoRegistration.cs +++ b/src/VolumeBridge/Audio/ApoRegistration.cs @@ -1,10 +1,12 @@ using System.ComponentModel; using System.Diagnostics; +using System.Reflection; using System.Runtime.InteropServices; using System.Security.AccessControl; using System.Security.Principal; using System.ServiceProcess; using Microsoft.Win32; +using VolumeBridge.Core; namespace VolumeBridge.Audio; @@ -14,7 +16,7 @@ namespace VolumeBridge.Audio; /// Administrators get write access (same approach as Equalizer APO's configurator). The original /// FxProperties values are backed up once and restored on removal. /// -public static partial class ApoRegistration +public static class ApoRegistration { public const string ApoClsid = "{B2800674-8C35-428D-A3EA-750171E7DD5C}"; @@ -22,6 +24,16 @@ public static partial class ApoRegistration const string BackupRoot = @"SOFTWARE\VolumeBridge\FxBackup"; const string StateKey = @"SOFTWARE\VolumeBridge"; const string AudioKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Audio"; + const string LegacyUninstallKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{6F1C2B7E-4A0B-4D8E-9C55-5642B0A1D001}_is1"; + const string ApoResourceName = "VolumeBridgeApo.dll"; + const uint MoveFileDelayUntilReboot = 0x4; + + static readonly Lazy EmbeddedApoHash = new(ComputeEmbeddedApoSha256); + static readonly object HashCacheGate = new(); + static string? _cachedFilePath; + static DateTime _cachedFileMtime; + static long _cachedFileLen; + static string? _cachedFileHash; // PKEY_FX_EndpointEffectClsid, PKEY_CompositeFX_EndpointEffectClsid, PKEY_EFX_ProcessingModes_Supported_For_Streaming const string EfxSingle = "{d04e05a6-594b-4fb6-a80d-01af5eed7d1d},7"; @@ -38,7 +50,7 @@ public static partial class ApoRegistration /// A CLSID string, or null for blank / all-zero entries. static string? RealClsid(string? s) => - string.IsNullOrWhiteSpace(s) || !Guid.TryParse(s, out var g) || g == Guid.Empty ? null : s.Trim(); + string.IsNullOrWhiteSpace(s) || !Guid.TryParse(s, out var g) || g == Guid.Empty ? null : s!.Trim(); /// "Audio enhancements: Off" for this endpoint (stored in FxProperties). Readable unelevated. public static bool EnhancementsDisabled(string endpointId) @@ -53,7 +65,7 @@ public static bool EnhancementsDisabled(string endpointId) } /// "{0.0.0.00000000}.{guid}" → "{guid}" (the registry key name). - public static string KeyName(string endpointId) => endpointId[(endpointId.LastIndexOf('.') + 1)..]; + public static string KeyName(string endpointId) => endpointId.Substring(endpointId.LastIndexOf('.') + 1); /// True when the endpoint's EFX slot (single or composite) contains our APO. Readable unelevated. public static bool IsRegistered(string endpointId) @@ -73,10 +85,246 @@ public static bool UnsignedApoAllowed() } /// True when the APO's COM class is registered (regsvr32 ran). - public static bool ComRegistered() + public static bool ComRegistered() => GetRegisteredApoPath() is string path && File.Exists(path); + + /// Path of the registered APO DLL from InprocServer32, or null if not registered. + public static string? GetRegisteredApoPath() { using var k = Registry.LocalMachine.OpenSubKey($@"SOFTWARE\Classes\CLSID\{ApoClsid}\InprocServer32"); - return k?.GetValue(null) is string path && File.Exists(path); + string? path = k?.GetValue(null) as string; + return string.IsNullOrWhiteSpace(path) ? null : path!.Trim().Trim('"'); + } + + /// True when the old Inno Setup installation (0.4.0 and earlier) is still installed. Readable unelevated. + public static bool IsLegacyInstallerPresent() + { + try + { + using var hklm64 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64); + using var k = hklm64.OpenSubKey(LegacyUninstallKey); + return k is not null; + } + catch (Exception) { return false; } + } + + /// True when the registered APO DLL differs from the one embedded in this exe. + public static bool IsPluginOutdated() + { + string? embedded = EmbeddedApoHash.Value; + if (embedded is null) return false; + string? regPath = GetRegisteredApoPath(); + if (regPath is null || !File.Exists(regPath)) return false; + string? actual = GetCachedFileSha256(regPath); + return actual is not null && !string.Equals(actual, embedded, StringComparison.OrdinalIgnoreCase); + } + + /// True when any plugin registration, backup, or deployed DLL is present on the machine. + public static bool IsAnyPluginInstalled() + { + if (ComRegistered()) return true; + try + { + using var state = Registry.LocalMachine.OpenSubKey(StateKey); + if (state is not null) + { + if (state.GetValue("PrevDisableProtectedAudioDG") is not null) return true; + using var backup = state.OpenSubKey("FxBackup"); + if (backup is not null && backup.SubKeyCount > 0) return true; + } + string dir = PluginInstallDir; + if (Directory.Exists(dir) && EnumeratePluginDlls(dir).Any()) return true; + } + catch (Exception) { } + return false; + } + + public static string PluginInstallDir => + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "VolumeBridge"); + + /// + /// Elevated: extract the embedded APO DLL to %ProgramFiles%\VolumeBridge\VolumeBridgeApo-<8hex>.dll, + /// register it with regsvr32, and ensure %ProgramData%\VolumeBridge is writable by Everyone. + /// Returns the deployed DLL path. + /// + public static string DeployAndRegisterDll(Action log) + { + EnsureProgramDataWritable(log); + + byte[] bytes = ReadEmbeddedApoBytes() + ?? throw new InvalidOperationException("This build does not contain an embedded VolumeBridgeApo.dll."); + string hash = UpdateCheck.Sha256Hex(bytes); + string dir = PluginInstallDir; + Directory.CreateDirectory(dir); + string dllPath = Path.Combine(dir, $"VolumeBridgeApo-{hash.Substring(0, 8)}.dll"); + + if (File.Exists(dllPath) && string.Equals(UpdateCheck.Sha256FileHex(dllPath), hash, StringComparison.OrdinalIgnoreCase)) + { + log($"APO DLL already up to date: {dllPath}"); + } + else + { + File.WriteAllBytes(dllPath, bytes); + log($"extracted APO DLL ({bytes.Length} bytes, sha256={hash.Substring(0, 8)}): {dllPath}"); + } + + RunRegsvr32(dllPath, unregister: false, log); + return dllPath; + } + + /// Best-effort cleanup of old APO DLLs in %ProgramFiles%\VolumeBridge except . + public static void CleanupOldDlls(string? keepPath, bool removeDirIfEmpty, Action log) + { + string dir = PluginInstallDir; + if (!Directory.Exists(dir)) return; + string? keepFull = keepPath is null ? null : Path.GetFullPath(keepPath); + foreach (string f in EnumeratePluginDlls(dir).ToList()) + { + if (keepFull is not null && string.Equals(Path.GetFullPath(f), keepFull, StringComparison.OrdinalIgnoreCase)) + continue; + DeleteOrDelayReboot(f, log); + } + if (removeDirIfEmpty) + { + try + { + if (!Directory.EnumerateFileSystemEntries(dir).Any()) + { + Directory.Delete(dir); + log($"removed empty directory: {dir}"); + } + } + catch (Exception e) { log($"could not remove {dir}: {e.Message}"); } + } + } + + /// Elevated: restore audio settings, unregister the COM DLL, delete plugin DLLs and empty state key. + public static void FullRemove(Action log) + { + string? regPath = GetRegisteredApoPath(); + RemoveAll(log); + + if (regPath is not null && File.Exists(regPath)) + { + try { RunRegsvr32(regPath, unregister: true, log); } + catch (Exception e) { log($"regsvr32 /u failed (continuing): {e.Message}"); } + } + + CleanupOldDlls(keepPath: null, removeDirIfEmpty: true, log); + DeleteStateKeyIfEmpty(log); + } + + static IEnumerable EnumeratePluginDlls(string dir) + { + foreach (string f in Directory.EnumerateFiles(dir, "VolumeBridgeApo-*.dll")) yield return f; + string unversioned = Path.Combine(dir, "VolumeBridgeApo.dll"); + if (File.Exists(unversioned)) yield return unversioned; + } + + static void DeleteOrDelayReboot(string path, Action log) + { + try + { + File.Delete(path); + log($"deleted old DLL: {path}"); + } + catch (Exception e) when (e is IOException or UnauthorizedAccessException) + { + if (MoveFileExW(path, null, MoveFileDelayUntilReboot)) + log($"DLL in use, scheduled delete on reboot: {path}"); + else + log($"could not delete or schedule delete for {path}: win32={Marshal.GetLastWin32Error()}"); + } + } + + static void RunRegsvr32(string dllPath, bool unregister, Action log) + { + string regsvr = Path.Combine(Environment.SystemDirectory, "regsvr32.exe"); + string args = unregister ? $"/u /s \"{dllPath}\"" : $"/s \"{dllPath}\""; + using var p = Process.Start(new ProcessStartInfo(regsvr, args) + { + UseShellExecute = false, + CreateNoWindow = true, + })!; + if (!p.WaitForExit(30_000)) + { + try { p.Kill(); } catch (Exception) { } + throw new InvalidOperationException($"regsvr32 {args} timed out"); + } + log($"regsvr32 {args} -> exit {p.ExitCode}"); + if (p.ExitCode != 0) + throw new InvalidOperationException($"regsvr32 {args} failed with exit code {p.ExitCode}"); + } + + static void EnsureProgramDataWritable(Action log) + { + try + { + string dir = Path.GetDirectoryName(ApoShared.FilePath)!; + Directory.CreateDirectory(dir); + var di = new DirectoryInfo(dir); + var sec = di.GetAccessControl(); + var everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null); + sec.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.Modify, + InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow)); + di.SetAccessControl(sec); + } + catch (Exception e) { log($"could not set ProgramData ACL (continuing): {e.Message}"); } + } + + static void DeleteStateKeyIfEmpty(Action log) + { + try + { + using var k = Registry.LocalMachine.OpenSubKey(StateKey); + if (k is null) return; + if (k.SubKeyCount == 0 && k.ValueCount == 0) + { + Registry.LocalMachine.DeleteSubKey(StateKey, throwOnMissingSubKey: false); + log($@"removed empty HKLM\{StateKey}"); + } + } + catch (Exception e) { log($@"could not clean HKLM\{StateKey}: {e.Message}"); } + } + + static byte[]? ReadEmbeddedApoBytes() + { + using var s = Assembly.GetExecutingAssembly().GetManifestResourceStream(ApoResourceName); + if (s is null) return null; + using var ms = new MemoryStream(); + s.CopyTo(ms); + return ms.ToArray(); + } + + static string? ComputeEmbeddedApoSha256() + { + byte[]? bytes = ReadEmbeddedApoBytes(); + return bytes is null ? null : UpdateCheck.Sha256Hex(bytes); + } + + static string? GetCachedFileSha256(string path) + { + try + { + var fi = new FileInfo(path); + if (!fi.Exists) return null; + DateTime mtime = fi.LastWriteTimeUtc; + long len = fi.Length; + lock (HashCacheGate) + { + if (_cachedFilePath == path && _cachedFileMtime == mtime && _cachedFileLen == len && _cachedFileHash is not null) + return _cachedFileHash; + } + string hash = UpdateCheck.Sha256FileHex(path); + lock (HashCacheGate) + { + _cachedFilePath = path; + _cachedFileMtime = mtime; + _cachedFileLen = len; + _cachedFileHash = hash; + } + return hash; + } + catch (Exception) { return null; } } /// Elevated: allow unsigned APOs (remembering the previous value) and add our APO to the endpoints. @@ -183,7 +431,7 @@ static void Dump(RegistryKey fx, string title, Action log) string text = v switch { string[] a => string.Join(" | ", a), - byte[] b => Convert.ToHexString(b.Length > 32 ? b[..32] : b) + (b.Length > 32 ? "…" : ""), + byte[] b => BitConverter.ToString(b, 0, Math.Min(b.Length, 32)).Replace("-", "") + (b.Length > 32 ? "…" : ""), _ => v?.ToString() ?? "", }; log($" {name} [{fx.GetValueKind(name)}] = {text}"); @@ -268,7 +516,7 @@ public static void RestartAudioService(Action log) audio.Refresh(); if (audio.Status != ServiceControllerStatus.Stopped) { - try { audio.Stop(stopDependentServices: true); } catch (InvalidOperationException e) { log($"stop: {e.Message}"); } + try { audio.Stop(); } catch (InvalidOperationException e) { log($"stop: {e.Message}"); } try { audio.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(30)); } catch (System.ServiceProcess.TimeoutException) { log("Audiosrv did not stop within 30 s"); } } @@ -310,8 +558,8 @@ static void EnablePrivilege(string name) { if (!LookupPrivilegeValueW(null, name, out long luid)) throw new Win32Exception(); var tp = new TokenPrivileges { Count = 1, Luid = luid, Attributes = 0x2 }; // SE_PRIVILEGE_ENABLED - if (!AdjustTokenPrivileges(token, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero) || Marshal.GetLastPInvokeError() != 0) - throw new Win32Exception(Marshal.GetLastPInvokeError(), $"cannot enable {name} (run as administrator)"); + if (!AdjustTokenPrivileges(token, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero) || Marshal.GetLastWin32Error() != 0) + throw new Win32Exception(Marshal.GetLastWin32Error(), $"cannot enable {name} (run as administrator)"); } finally { CloseHandle(token); } } @@ -324,23 +572,27 @@ struct TokenPrivileges public int Attributes; } - [LibraryImport("kernel32.dll")] - private static partial IntPtr GetCurrentProcess(); + [DllImport("kernel32.dll")] + private static extern IntPtr GetCurrentProcess(); - [LibraryImport("kernel32.dll")] + [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] - private static partial bool CloseHandle(IntPtr h); + private static extern bool CloseHandle(IntPtr h); - [LibraryImport("advapi32.dll", SetLastError = true)] + [DllImport("advapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] - private static partial bool OpenProcessToken(IntPtr process, int access, out IntPtr token); + private static extern bool OpenProcessToken(IntPtr process, int access, out IntPtr token); - [LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] + [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] - private static partial bool LookupPrivilegeValueW(string? system, string name, out long luid); + private static extern bool LookupPrivilegeValueW(string? system, string name, out long luid); - [LibraryImport("advapi32.dll", SetLastError = true)] + [DllImport("advapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] - private static partial bool AdjustTokenPrivileges(IntPtr token, [MarshalAs(UnmanagedType.Bool)] bool disableAll, + private static extern bool AdjustTokenPrivileges(IntPtr token, [MarshalAs(UnmanagedType.Bool)] bool disableAll, ref TokenPrivileges newState, int bufferLength, IntPtr previous, IntPtr returnLength); + + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool MoveFileExW(string existingFileName, string? newFileName, uint flags); } diff --git a/src/VolumeBridge/Audio/ApoShared.cs b/src/VolumeBridge/Audio/ApoShared.cs index a0fa60d..7029707 100644 --- a/src/VolumeBridge/Audio/ApoShared.cs +++ b/src/VolumeBridge/Audio/ApoShared.cs @@ -1,4 +1,5 @@ using System.IO.MemoryMappedFiles; +using System.Runtime.InteropServices; namespace VolumeBridge.Audio; @@ -32,7 +33,7 @@ public ApoShared() Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!); var fs = new FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete); if (fs.Length < Size) fs.SetLength(Size); - _map = MemoryMappedFile.CreateFromFile(fs, null, Size, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, leaveOpen: false); + _map = MemoryMappedFile.CreateFromFile(fs, null, Size, MemoryMappedFileAccess.ReadWrite, null, HandleInheritability.None, leaveOpen: false); _view = _map.CreateViewAccessor(0, Size); if (_view.ReadUInt32(OMagic) != Magic) { @@ -46,7 +47,7 @@ public ApoShared() /// Publishes the gain for the APO's fallback path (used when it gets no volume notifications). public void WriteGain(float gain) { - _view.Write(OAppGain, Math.Clamp(gain, 0f, 1f)); + _view.Write(OAppGain, Clamp01(gain)); _seq = _seq == uint.MaxValue ? 1 : _seq + 1; _view.Write(OAppSeq, _seq); } @@ -54,14 +55,14 @@ public void WriteGain(float gain) /// Output ceiling (linear) the APO multiplies on top of the slider; persists in the file. public void WriteCap(float capGain) { - _view.Write(OCapGain, Math.Clamp(capGain, 0f, 1f)); + _view.Write(OCapGain, Clamp01(capGain)); _view.Write(OCapSet, 1u); } public ApoReport Read() { ulong beat = _view.ReadUInt64(OHeartbeat); - long age = beat == 0 ? long.MaxValue : Environment.TickCount64 - (long)beat; + long age = beat == 0 ? long.MaxValue : unchecked((long)(GetTickCount64() - beat)); return new ApoReport( (int)_view.ReadUInt32(OInstances), (ApoSource)_view.ReadUInt32(OSource), @@ -75,6 +76,11 @@ public ApoReport Read() (int)_view.ReadUInt32(ONotifs)); } + static float Clamp01(float v) => v < 0f ? 0f : v > 1f ? 1f : v; + + [DllImport("kernel32.dll")] + static extern ulong GetTickCount64(); + public void Dispose() { _view.Dispose(); diff --git a/src/VolumeBridge/Audio/Autostart.cs b/src/VolumeBridge/Audio/Autostart.cs index 3eabe07..6cb714a 100644 --- a/src/VolumeBridge/Audio/Autostart.cs +++ b/src/VolumeBridge/Audio/Autostart.cs @@ -2,6 +2,7 @@ using System.Security; using System.Security.Principal; using System.Text; +using System.Xml; namespace VolumeBridge.Audio; @@ -58,24 +59,83 @@ public static void Uninstall() if (code != 0 && IsInstalled()) throw new InvalidOperationException($"schtasks /Delete failed ({code}): {output.Trim()}"); } + /// If the logon task exists but points to a different exe (e.g. user moved the portable exe), silently update it. + public static void SyncPathIfInstalled(string exePath, Action log) + { + try + { + var (code, output) = Run("/Query", "/TN", TaskName, "/XML"); + if (code != 0 || string.IsNullOrWhiteSpace(output)) return; + var doc = new XmlDocument(); + doc.LoadXml(output); + var ns = new XmlNamespaceManager(doc.NameTable); + ns.AddNamespace("t", "http://schemas.microsoft.com/windows/2004/02/mit/task"); + string? cmd = doc.SelectSingleNode("//t:Actions/t:Exec/t:Command", ns)?.InnerText?.Trim().Trim('"'); + if (string.IsNullOrEmpty(cmd)) return; + if (!string.Equals(Path.GetFullPath(cmd), Path.GetFullPath(exePath), StringComparison.OrdinalIgnoreCase)) + { + Install(exePath); + log($"updated autostart task path: \"{cmd}\" -> \"{exePath}\""); + } + } + catch (Exception e) + { + log($"autostart path sync skipped: {e.Message}"); + } + } + static (int Code, string Output) Run(params string[] args) { - var psi = new ProcessStartInfo("schtasks.exe") + var psi = new ProcessStartInfo("schtasks.exe", QuoteArgs(args)) { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true, }; - foreach (var a in args) psi.ArgumentList.Add(a); using var p = Process.Start(psi)!; var stdout = p.StandardOutput.ReadToEndAsync(); var stderr = p.StandardError.ReadToEndAsync(); if (!p.WaitForExit(15_000)) { - p.Kill(entireProcessTree: true); + try { p.Kill(); } catch (Exception) { } return (-1, "timeout"); } return (p.ExitCode, stdout.Result + stderr.Result); } + + internal static string QuoteArgs(IEnumerable args) + { + var sb = new StringBuilder(); + foreach (string a in args) + { + if (sb.Length > 0) sb.Append(' '); + if (a.Length == 0 || a.IndexOfAny([' ', '\t', '\n', '\v', '"']) >= 0) + { + sb.Append('"'); + int backslashes = 0; + foreach (char c in a) + { + if (c == '\\') backslashes++; + else if (c == '"') + { + sb.Append('\\', backslashes * 2 + 1).Append('"'); + backslashes = 0; + } + else + { + if (backslashes > 0) { sb.Append('\\', backslashes); backslashes = 0; } + sb.Append(c); + } + } + if (backslashes > 0) sb.Append('\\', backslashes * 2); + sb.Append('"'); + } + else + { + sb.Append(a); + } + } + return sb.ToString(); + } } diff --git a/src/VolumeBridge/Core/AppConfig.cs b/src/VolumeBridge/Core/AppConfig.cs index 8ce3169..a35d03d 100644 --- a/src/VolumeBridge/Core/AppConfig.cs +++ b/src/VolumeBridge/Core/AppConfig.cs @@ -1,5 +1,5 @@ -using System.Text.Json; -using System.Text.Json.Serialization; +using System.Globalization; +using System.Text; namespace VolumeBridge.Core; @@ -17,20 +17,11 @@ public sealed class AppConfig public double MaxOutputDb { get; set; } = -12; /// Linear factor for , limited to -60..0 dB. - [JsonIgnore] - public float OutputCapGain => (float)Math.Pow(10, Math.Clamp(MaxOutputDb, -60, 0) / 20.0); + public float OutputCapGain => (float)Math.Pow(10, Math.Max(-60, Math.Min(0, MaxOutputDb)) / 20.0); - /// UI language: "auto" (installer choice, else Windows), "zh" or "en". + /// UI language: "auto" (Windows display language), "zh" or "en". public string Language { get; set; } = "auto"; - static readonly JsonSerializerOptions Json = new() - { - WriteIndented = true, - PropertyNamingPolicy = JsonNamingPolicy.CamelCase, - ReadCommentHandling = JsonCommentHandling.Skip, - AllowTrailingCommas = true, - }; - /// Loads config from , writing defaults first if the file is missing. /// Settings of older versions that no longer exist are ignored. public static AppConfig LoadOrCreate(string path) @@ -44,8 +35,46 @@ public static AppConfig LoadOrCreate(string path) return FromJson(File.ReadAllText(path)); } - public static AppConfig FromJson(string json) => - JsonSerializer.Deserialize(json, Json) ?? new AppConfig(); + public static AppConfig FromJson(string json) + { + var cfg = new AppConfig(); + if (MiniJson.Parse(json) is not Dictionary obj) return cfg; + + if (obj.TryGetValue("outputKeywords", out var kwVal) && kwVal is List kwList) + cfg.OutputKeywords = kwList.OfType().ToList(); + + if (obj.TryGetValue("outputDeviceId", out var idVal)) + cfg.OutputDeviceId = idVal as string; + + if (obj.TryGetValue("maxOutputDb", out var dbVal) && dbVal is double db) + cfg.MaxOutputDb = db; + + if (obj.TryGetValue("language", out var langVal) && langVal is string lang) + cfg.Language = lang; - public string ToJson() => JsonSerializer.Serialize(this, Json); + return cfg; + } + + public string ToJson() + { + var sb = new StringBuilder(); + sb.AppendLine("{"); + sb.Append(" \"outputKeywords\": ["); + for (int i = 0; i < OutputKeywords.Count; i++) + { + if (i > 0) sb.Append(", "); + sb.Append(MiniJson.Quote(OutputKeywords[i])); + } + sb.AppendLine("],"); + sb.Append(" \"outputDeviceId\": "); + sb.Append(OutputDeviceId is null ? "null" : MiniJson.Quote(OutputDeviceId)); + sb.AppendLine(","); + sb.Append(" \"maxOutputDb\": "); + sb.Append(MaxOutputDb.ToString("G", CultureInfo.InvariantCulture)); + sb.AppendLine(","); + sb.Append(" \"language\": "); + sb.AppendLine(MiniJson.Quote(Language)); + sb.Append("}"); + return sb.ToString(); + } } diff --git a/src/VolumeBridge/Core/AppPaths.cs b/src/VolumeBridge/Core/AppPaths.cs index fda0202..2c9e054 100644 --- a/src/VolumeBridge/Core/AppPaths.cs +++ b/src/VolumeBridge/Core/AppPaths.cs @@ -3,29 +3,9 @@ namespace VolumeBridge.Core; /// Where config.json and logs live. public static class AppPaths { - /// - /// Next to the exe for a portable copy. When the exe is installed under Program Files (not writable - /// by the unelevated user, and must stay that way), use %LOCALAPPDATA%\VolumeBridge instead. - /// - public static string DataDir(string exeDir, IEnumerable programFilesDirs, string localAppData) - { - string exe = Normalize(exeDir); - foreach (var pf in programFilesDirs) - { - if (string.IsNullOrEmpty(pf)) continue; - string root = Normalize(pf); - if (exe.StartsWith(root, StringComparison.OrdinalIgnoreCase)) - return Path.Combine(localAppData, "VolumeBridge"); - } - return exeDir; - } + /// Always %LOCALAPPDATA%\VolumeBridge so a portable exe never scatters files in Downloads. + public static string DataDir(string localAppData) => Path.Combine(localAppData, "VolumeBridge"); public static string DataDir() => DataDir( - AppContext.BaseDirectory, - [Environment.GetEnvironmentVariable("ProgramFiles"), Environment.GetEnvironmentVariable("ProgramFiles(x86)"), - Environment.GetEnvironmentVariable("ProgramW6432")], Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)); - - static string Normalize(string p) => - Path.TrimEndingDirectorySeparator(Path.GetFullPath(p)) + Path.DirectorySeparatorChar; } diff --git a/src/VolumeBridge/Core/DeviceMatcher.cs b/src/VolumeBridge/Core/DeviceMatcher.cs index c32a6cd..47ffaa2 100644 --- a/src/VolumeBridge/Core/DeviceMatcher.cs +++ b/src/VolumeBridge/Core/DeviceMatcher.cs @@ -8,7 +8,7 @@ public sealed record OutputMatch(DeviceInfo? Device, string? Error); public static class DeviceMatcher { static bool Has(DeviceInfo d, string keyword) => - keyword.Length > 0 && d.Name.Contains(keyword, StringComparison.OrdinalIgnoreCase); + keyword.Length > 0 && d.Name.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) >= 0; /// The speaker: the exact if set, else the single keyword match. public static OutputMatch FindOutput(IReadOnlyList keywords, string? deviceId, IReadOnlyList renders) diff --git a/src/VolumeBridge/Core/FileLog.cs b/src/VolumeBridge/Core/FileLog.cs index 835e852..b7d5078 100644 --- a/src/VolumeBridge/Core/FileLog.cs +++ b/src/VolumeBridge/Core/FileLog.cs @@ -39,7 +39,8 @@ public void Write(string message) { _writer.Dispose(); string old = System.IO.Path.ChangeExtension(_path, ".1.log"); - File.Move(_path, old, overwrite: true); + if (File.Exists(old)) File.Delete(old); + File.Move(_path, old); _writer = Open(append: false); } _writer.WriteLine(line); diff --git a/src/VolumeBridge/Core/Loc.cs b/src/VolumeBridge/Core/Loc.cs index 463bb56..a2629b9 100644 --- a/src/VolumeBridge/Core/Loc.cs +++ b/src/VolumeBridge/Core/Loc.cs @@ -7,18 +7,13 @@ public enum UiLanguage { Chinese, English } /// Two-language UI text: Loc.T("中文", "English"). public static class Loc { - public const string InstallerChoiceFile = "language.txt"; - public static UiLanguage Current { get; set; } = UiLanguage.English; public static string T(string zh, string en) => Current == UiLanguage.Chinese ? zh : en; - /// - /// config.json "language" ("zh"/"en") wins; otherwise the language picked in the installer - /// (language.txt next to the exe); otherwise the Windows display language. - /// - public static UiLanguage Resolve(string? configured, string? installerChoice, CultureInfo uiCulture) => - Parse(configured) ?? Parse(installerChoice) + /// config.json "language" ("zh"/"en") wins; otherwise the Windows display language. + public static UiLanguage Resolve(string? configured, CultureInfo uiCulture) => + Parse(configured) ?? (uiCulture.TwoLetterISOLanguageName == "zh" ? UiLanguage.Chinese : UiLanguage.English); public static UiLanguage? Parse(string? s) => s?.Trim().ToLowerInvariant() switch diff --git a/src/VolumeBridge/Core/MiniJson.cs b/src/VolumeBridge/Core/MiniJson.cs new file mode 100644 index 0000000..bb45ad9 --- /dev/null +++ b/src/VolumeBridge/Core/MiniJson.cs @@ -0,0 +1,208 @@ +using System.Globalization; +using System.Text; + +namespace VolumeBridge.Core; + +/// +/// Tiny self-contained JSON parser/writer (supports // comments and trailing commas for config.json). +/// Keeps net48 builds free of System.Text.Json's runtime DLL dependencies. +/// +public static class MiniJson +{ + public static object? Parse(string json) + { + var p = new Parser(json); + object? value = p.ReadValue(); + p.SkipTrivia(); + if (!p.End) throw new FormatException($"Unexpected trailing character '{p.Current}' at position {p.Pos}"); + return value; + } + + public static string Quote(string s) + { + var sb = new StringBuilder(s.Length + 2); + sb.Append('"'); + foreach (char c in s) + { + switch (c) + { + case '"': sb.Append("\\\""); break; + case '\\': sb.Append("\\\\"); break; + case '\b': sb.Append("\\b"); break; + case '\f': sb.Append("\\f"); break; + case '\n': sb.Append("\\n"); break; + case '\r': sb.Append("\\r"); break; + case '\t': sb.Append("\\t"); break; + default: + if (c < 0x20) sb.Append("\\u").Append(((int)c).ToString("x4", CultureInfo.InvariantCulture)); + else sb.Append(c); + break; + } + } + sb.Append('"'); + return sb.ToString(); + } + + sealed class Parser(string s) + { + int _i; + + public int Pos => _i; + public bool End => _i >= s.Length; + public char Current => s[_i]; + + public void SkipTrivia() + { + while (_i < s.Length) + { + char c = s[_i]; + if (c is ' ' or '\t' or '\r' or '\n') { _i++; continue; } + if (c == '/' && _i + 1 < s.Length && s[_i + 1] == '/') + { + _i += 2; + while (_i < s.Length && s[_i] != '\n') _i++; + continue; + } + if (c == '/' && _i + 1 < s.Length && s[_i + 1] == '*') + { + _i += 2; + int end = s.IndexOf("*/", _i, StringComparison.Ordinal); + if (end < 0) throw new FormatException("Unterminated block comment"); + _i = end + 2; + continue; + } + break; + } + } + + public object? ReadValue() + { + SkipTrivia(); + if (End) throw new FormatException("Unexpected end of JSON"); + return s[_i] switch + { + '{' => ReadObject(), + '[' => ReadArray(), + '"' => ReadString(), + 't' => ReadLiteral("true", true), + 'f' => ReadLiteral("false", false), + 'n' => ReadLiteral("null", null), + '-' or (>= '0' and <= '9') => ReadNumber(), + _ => throw new FormatException($"Unexpected character '{s[_i]}' at position {_i}"), + }; + } + + Dictionary ReadObject() + { + _i++; // '{' + var obj = new Dictionary(StringComparer.Ordinal); + while (true) + { + SkipTrivia(); + if (End) throw new FormatException("Unterminated JSON object"); + if (s[_i] == '}') { _i++; return obj; } + if (s[_i] != '"') throw new FormatException($"Expected string key at position {_i}"); + string key = ReadString(); + SkipTrivia(); + if (End || s[_i] != ':') throw new FormatException($"Expected ':' at position {_i}"); + _i++; + obj[key] = ReadValue(); + SkipTrivia(); + if (End) throw new FormatException("Unterminated JSON object"); + if (s[_i] == ',') { _i++; continue; } + if (s[_i] == '}') { _i++; return obj; } + throw new FormatException($"Expected ',' or '}}' at position {_i}"); + } + } + + List ReadArray() + { + _i++; // '[' + var list = new List(); + while (true) + { + SkipTrivia(); + if (End) throw new FormatException("Unterminated JSON array"); + if (s[_i] == ']') { _i++; return list; } + list.Add(ReadValue()); + SkipTrivia(); + if (End) throw new FormatException("Unterminated JSON array"); + if (s[_i] == ',') { _i++; continue; } + if (s[_i] == ']') { _i++; return list; } + throw new FormatException($"Expected ',' or ']' at position {_i}"); + } + } + + string ReadString() + { + _i++; // '"' + var sb = new StringBuilder(); + while (_i < s.Length) + { + char c = s[_i++]; + if (c == '"') return sb.ToString(); + if (c == '\\') + { + if (_i >= s.Length) throw new FormatException("Unterminated string escape"); + char e = s[_i++]; + switch (e) + { + case '"': sb.Append('"'); break; + case '\\': sb.Append('\\'); break; + case '/': sb.Append('/'); break; + case 'b': sb.Append('\b'); break; + case 'f': sb.Append('\f'); break; + case 'n': sb.Append('\n'); break; + case 'r': sb.Append('\r'); break; + case 't': sb.Append('\t'); break; + case 'u': + if (_i + 4 > s.Length) throw new FormatException("Incomplete \\u escape"); + string hex = s.Substring(_i, 4); + if (!int.TryParse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out int code)) + throw new FormatException($"Invalid \\u escape: \\u{hex}"); + sb.Append((char)code); + _i += 4; + break; + default: + throw new FormatException($"Invalid escape '\\{e}'"); + } + } + else + { + sb.Append(c); + } + } + throw new FormatException("Unterminated JSON string"); + } + + double ReadNumber() + { + int start = _i; + if (s[_i] == '-') _i++; + while (_i < s.Length && s[_i] is >= '0' and <= '9') _i++; + if (_i < s.Length && s[_i] == '.') + { + _i++; + while (_i < s.Length && s[_i] is >= '0' and <= '9') _i++; + } + if (_i < s.Length && s[_i] is 'e' or 'E') + { + _i++; + if (_i < s.Length && s[_i] is '+' or '-') _i++; + while (_i < s.Length && s[_i] is >= '0' and <= '9') _i++; + } + string num = s.Substring(start, _i - start); + if (!double.TryParse(num, NumberStyles.Float, CultureInfo.InvariantCulture, out double value)) + throw new FormatException($"Invalid JSON number '{num}'"); + return value; + } + + object? ReadLiteral(string expected, object? result) + { + if (_i + expected.Length > s.Length || string.CompareOrdinal(s, _i, expected, 0, expected.Length) != 0) + throw new FormatException($"Expected '{expected}' at position {_i}"); + _i += expected.Length; + return result; + } + } +} diff --git a/src/VolumeBridge/Core/UpdateCheck.cs b/src/VolumeBridge/Core/UpdateCheck.cs index 7762dee..11f38b7 100644 --- a/src/VolumeBridge/Core/UpdateCheck.cs +++ b/src/VolumeBridge/Core/UpdateCheck.cs @@ -1,39 +1,50 @@ +using System.Net; +using System.Net.Http; using System.Security.Cryptography; -using System.Text.Json; namespace VolumeBridge.Core; -public sealed record ReleaseInfo(Version Version, string Tag, string SetupUrl, string ChecksumUrl, string PageUrl); +public sealed record ReleaseInfo(Version Version, string Tag, string ExeUrl, string ChecksumUrl, string PageUrl); /// Latest-release lookup on GitHub Releases (public repo, no token). public static class UpdateCheck { public const string Repo = "ZanderH-code/volumebridge"; - public const string SetupAsset = "VolumeBridgeSetup.exe"; - public const string ChecksumAsset = "VolumeBridgeSetup.exe.sha256"; + public const string ExeAsset = "VolumeBridge.exe"; + public const string ChecksumAsset = "VolumeBridge.exe.sha256"; static readonly string LatestUrl = $"https://api.github.com/repos/{Repo}/releases/latest"; +#if NETFRAMEWORK + static UpdateCheck() + { + ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; + } +#endif + /// Parses the GitHub "latest release" JSON; null if it lacks a version tag or the two assets. public static ReleaseInfo? Parse(string json) { - using var doc = JsonDocument.Parse(json); - var root = doc.RootElement; - if (root.TryGetProperty("draft", out var draft) && draft.GetBoolean()) return null; - if (root.TryGetProperty("prerelease", out var pre) && pre.GetBoolean()) return null; - string tag = root.GetProperty("tag_name").GetString() ?? ""; + if (MiniJson.Parse(json) is not Dictionary root) return null; + if (root.TryGetValue("draft", out var draft) && draft is true) return null; + if (root.TryGetValue("prerelease", out var pre) && pre is true) return null; + string tag = root.TryGetValue("tag_name", out var tagVal) ? tagVal as string ?? "" : ""; if (!TryParseVersion(tag, out var version)) return null; - string? setup = null, sum = null; - foreach (var a in root.GetProperty("assets").EnumerateArray()) + string? exe = null, sum = null; + if (root.TryGetValue("assets", out var assetsVal) && assetsVal is List assets) { - string name = a.GetProperty("name").GetString() ?? ""; - string url = a.GetProperty("browser_download_url").GetString() ?? ""; - if (!url.StartsWith($"https://github.com/{Repo}/releases/download/", StringComparison.Ordinal)) continue; - if (name == SetupAsset) setup = url; - else if (name == ChecksumAsset) sum = url; + foreach (var item in assets) + { + if (item is not Dictionary a) continue; + string name = a.TryGetValue("name", out var nv) ? nv as string ?? "" : ""; + string url = a.TryGetValue("browser_download_url", out var uv) ? uv as string ?? "" : ""; + if (!url.StartsWith($"https://github.com/{Repo}/releases/download/", StringComparison.Ordinal)) continue; + if (name == ExeAsset) exe = url; + else if (name == ChecksumAsset) sum = url; + } } - string page = root.TryGetProperty("html_url", out var h) ? h.GetString() ?? "" : ""; - return setup is null || sum is null ? null : new ReleaseInfo(version, tag, setup, sum, page); + string page = root.TryGetValue("html_url", out var h) ? h as string ?? "" : ""; + return exe is null || sum is null ? null : new ReleaseInfo(version, tag, exe, sum, page); } /// "v1.2.3" / "1.2.3" → 1.2.3 (missing parts are 0). @@ -41,8 +52,8 @@ public static bool TryParseVersion(string tag, out Version version) { string t = tag.Trim().TrimStart('v', 'V'); int dash = t.IndexOfAny(['-', '+']); - if (dash >= 0) t = t[..dash]; - if (Version.TryParse(t.Contains('.') ? t : t + ".0", out var v)) + if (dash >= 0) t = t.Substring(0, dash); + if (Version.TryParse(t.IndexOf('.') >= 0 ? t : t + ".0", out var v)) { version = new Version(v.Major, v.Minor, Math.Max(v.Build, 0)); return true; @@ -66,43 +77,61 @@ public static bool IsNewer(Version candidate, Version current) => using var req = new HttpRequestMessage(HttpMethod.Get, LatestUrl); req.Headers.Accept.ParseAdd("application/vnd.github+json"); using var resp = await http.SendAsync(req, ct); - if (resp.StatusCode == System.Net.HttpStatusCode.NotFound) return null; // no release yet + if (resp.StatusCode == HttpStatusCode.NotFound) return null; // no release yet resp.EnsureSuccessStatusCode(); - return Parse(await resp.Content.ReadAsStringAsync(ct)); + return Parse(await resp.Content.ReadAsStringAsync()); } - /// Downloads the installer to and verifies it against the published SHA-256. + /// Downloads the exe to and verifies it against the published SHA-256. public static async Task DownloadVerifiedAsync(HttpClient http, ReleaseInfo r, string dir, IProgress? progress, CancellationToken ct) { - string expected = ParseChecksum(await http.GetStringAsync(r.ChecksumUrl, ct)) + string checksumText; + using (var cresp = await http.GetAsync(r.ChecksumUrl, ct)) + { + cresp.EnsureSuccessStatusCode(); + checksumText = await cresp.Content.ReadAsStringAsync(); + } + string expected = ParseChecksum(checksumText) ?? throw new InvalidDataException(Loc.T("发布页上的校验文件格式不正确", "The checksum file on the release page is malformed")); Directory.CreateDirectory(dir); - string path = Path.Combine(dir, $"VolumeBridgeSetup-{r.Version}.exe"); - using (var resp = await http.GetAsync(r.SetupUrl, HttpCompletionOption.ResponseHeadersRead, ct)) + string path = Path.Combine(dir, $"VolumeBridge-{r.Version}.exe"); + using (var resp = await http.GetAsync(r.ExeUrl, HttpCompletionOption.ResponseHeadersRead, ct)) { resp.EnsureSuccessStatusCode(); long? total = resp.Content.Headers.ContentLength; - await using var src = await resp.Content.ReadAsStreamAsync(ct); - await using var dst = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None); + using var src = await resp.Content.ReadAsStreamAsync(); + using var dst = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None); var buf = new byte[81920]; long done = 0; int n; - while ((n = await src.ReadAsync(buf, ct)) > 0) + while ((n = await src.ReadAsync(buf, 0, buf.Length, ct)) > 0) { - await dst.WriteAsync(buf.AsMemory(0, n), ct); + await dst.WriteAsync(buf, 0, n, ct); done += n; if (total > 0) progress?.Report((double)done / total.Value); } } - string actual; - await using (var f = File.OpenRead(path)) actual = Convert.ToHexString(await SHA256.HashDataAsync(f, ct)).ToLowerInvariant(); + string actual = await Task.Run(() => Sha256FileHex(path), ct); if (actual != expected) { File.Delete(path); - throw new InvalidDataException(Loc.T("下载的安装包校验失败,已删除", "The downloaded installer failed verification and was deleted")); + throw new InvalidDataException(Loc.T("下载的文件校验失败,已删除", "The downloaded file failed verification and was deleted")); } return path; } + + public static string Sha256Hex(byte[] data) + { + using var sha = SHA256.Create(); + return BitConverter.ToString(sha.ComputeHash(data)).Replace("-", "").ToLowerInvariant(); + } + + public static string Sha256FileHex(string path) + { + using var sha = SHA256.Create(); + using var f = File.OpenRead(path); + return BitConverter.ToString(sha.ComputeHash(f)).Replace("-", "").ToLowerInvariant(); + } } diff --git a/src/VolumeBridge/Program.cs b/src/VolumeBridge/Program.cs index 5b6f0d3..3cfce60 100644 --- a/src/VolumeBridge/Program.cs +++ b/src/VolumeBridge/Program.cs @@ -1,4 +1,7 @@ using System.Diagnostics; +using System.Globalization; +using System.Reflection; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using VolumeBridge.Audio; @@ -7,7 +10,7 @@ namespace VolumeBridge; -static partial class Program +static class Program { const string Usage = """ VolumeBridge - make the Windows volume slider and mute control a fixed-volume USB speaker. @@ -28,6 +31,34 @@ VolumeBridge Open the window (closing it keeps running [STAThread] static int Main(string[] args) + { + AppDomain.CurrentDomain.AssemblyResolve += ResolveEmbeddedAssembly; + return Run(args); + } + + // AssemblyResolve can fire more than once for the same name (e.g. from VolumeBridge and from NAudio.Wasapi); + // loading the bytes twice would create two copies of every NAudio type, so each assembly is loaded once. + static readonly Dictionary EmbeddedAssemblies = new(StringComparer.OrdinalIgnoreCase); + + static Assembly? ResolveEmbeddedAssembly(object? sender, ResolveEventArgs args) + { + string? simple = new AssemblyName(args.Name).Name; + if (string.IsNullOrEmpty(simple)) return null; + lock (EmbeddedAssemblies) + { + if (EmbeddedAssemblies.TryGetValue(simple!, out var loaded)) return loaded; + using var s = Assembly.GetExecutingAssembly().GetManifestResourceStream(simple + ".dll"); + if (s is null) return null; + using var ms = new MemoryStream(); + s.CopyTo(ms); + var asm = Assembly.Load(ms.ToArray()); + EmbeddedAssemblies[simple!] = asm; + return asm; + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static int Run(string[] args) { string mode = args.Length == 0 ? "--gui" : args[0]; bool gui = mode is "--gui" or "--tray" or "--updated"; @@ -55,7 +86,7 @@ static int Main(string[] args) Process.Start(new ProcessStartInfo(dataDir) { UseShellExecute = true }); return 0; case "--install-autostart": - return Try(() => Autostart.Install(Environment.ProcessPath!), "autostart installed"); + return Try(() => Autostart.Install(Application.ExecutablePath), "autostart installed"); case "--uninstall-autostart": return Try(Autostart.Uninstall, "autostart removed"); case "--apo-setup" or "--apo-remove": @@ -67,13 +98,14 @@ static int Main(string[] args) return 2; } - // One instance per machine. The installer waits on the same mutex. + // One instance per machine. After a self-update (--updated), the old process is still exiting. Mutex? single = null; bool first; try { single = new Mutex(false, MutexName); - try { first = single.WaitOne(0); } + int waitMs = mode == "--updated" ? 15_000 : 0; + try { first = single.WaitOne(waitMs); } catch (AbandonedMutexException) { first = true; } } catch (UnauthorizedAccessException) { first = false; } // held by an elevated instance @@ -101,7 +133,7 @@ static int Main(string[] args) MessageBox.Show($"Cannot read {configPath}: {e.Message}", "VolumeBridge", MessageBoxButtons.OK, MessageBoxIcon.Error); return 2; } - Loc.Current = Loc.Resolve(config.Language, ReadInstallerLanguage(), System.Globalization.CultureInfo.CurrentUICulture); + Loc.Current = Loc.Resolve(config.Language, CultureInfo.CurrentUICulture); int exitCode = RunGui(mode, config, dataDir, configPath); try { single?.ReleaseMutex(); } catch (ApplicationException) { /* not owned */ } @@ -111,7 +143,6 @@ static int Main(string[] args) static int RunGui(string mode, AppConfig config, string dataDir, string configPath) { - Application.SetHighDpiMode(HighDpiMode.PerMonitorV2); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); @@ -141,9 +172,15 @@ static int ApoAdmin(string mode, string[] args, string dataDir) AppDomain.CurrentDomain.UnhandledException += (_, e) => log.Write($"{mode} crashed: {e.ExceptionObject}"); try { + if (ApoRegistration.IsLegacyInstallerPresent()) + { + // The old installed version owns %ProgramFiles%\VolumeBridge; its own uninstaller restores everything. + log.Write($"refusing {mode}: an older installed version of VolumeBridge (Inno Setup) is still present. Uninstall it in Settings -> Apps first."); + return 2; + } if (mode == "--apo-remove") { - ApoRegistration.RemoveAll(log.Write); + ApoRegistration.FullRemove(log.Write); return 0; } string configPath = Path.Combine(dataDir, AppConfig.FileName); @@ -155,7 +192,9 @@ static int ApoAdmin(string mode, string[] args, string dataDir) log.Write("no matching speaker connected; nothing changed (enable it later from the VolumeBridge window)"); return 0; } + string dllPath = ApoRegistration.DeployAndRegisterDll(log.Write); ApoRegistration.Install(ids, log.Write); + ApoRegistration.CleanupOldDlls(keepPath: dllPath, removeDirIfEmpty: false, log.Write); return 0; } catch (Exception e) @@ -178,17 +217,6 @@ static List FindSpeakers(AppConfig config) finally { foreach (var d in list) d.Dispose(); } } - /// Language picked in the installer (written next to the exe), if any. - static string? ReadInstallerLanguage() - { - try - { - string f = Path.Combine(AppContext.BaseDirectory, Loc.InstallerChoiceFile); - return File.Exists(f) ? File.ReadAllText(f).Trim() : null; - } - catch (Exception) { return null; } - } - static int Try(Action action, string done) { try @@ -204,11 +232,11 @@ static int Try(Action action, string done) } } - [LibraryImport("kernel32.dll")] + [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] - private static partial bool AttachConsole(int processId); + private static extern bool AttachConsole(int processId); - [LibraryImport("kernel32.dll")] + [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] - private static partial bool AllocConsole(); + private static extern bool AllocConsole(); } diff --git a/src/VolumeBridge/Ui/AppIcon.cs b/src/VolumeBridge/Ui/AppIcon.cs index 9bef9ed..24e1717 100644 --- a/src/VolumeBridge/Ui/AppIcon.cs +++ b/src/VolumeBridge/Ui/AppIcon.cs @@ -5,7 +5,7 @@ namespace VolumeBridge.Ui; /// Speaker glyph drawn at runtime (no binary assets in the repo). -static partial class AppIcon +static class AppIcon { /// Returns an Icon that owns its handle (safe to Dispose). public static Icon Create(int size, bool ok) @@ -35,7 +35,7 @@ public static Icon Create(int size, bool ok) finally { DestroyIcon(h); } } - [LibraryImport("user32.dll")] + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] - private static partial bool DestroyIcon(IntPtr handle); + private static extern bool DestroyIcon(IntPtr handle); } diff --git a/src/VolumeBridge/Ui/MainForm.cs b/src/VolumeBridge/Ui/MainForm.cs index 96f759c..f4d6f04 100644 --- a/src/VolumeBridge/Ui/MainForm.cs +++ b/src/VolumeBridge/Ui/MainForm.cs @@ -22,6 +22,7 @@ sealed class MainForm : Form readonly Label _outputCaption = new() { AutoSize = true, Margin = new Padding(0, 6, 0, 0) }; readonly ComboBox _outputs = new() { DropDownStyle = ComboBoxStyle.DropDownList, Width = 330 }; readonly Button _enableApo = new() { AutoSize = true }; + readonly Button _removeApo = new() { AutoSize = true }; readonly Label _capCaption = new() { AutoSize = true, Margin = new Padding(0, 6, 0, 0) }; readonly NumericUpDown _cap = new() { Minimum = -30, Maximum = 0, Increment = 1, Width = 60 }; readonly Label _capUnit = new() { AutoSize = true, Margin = new Padding(0, 6, 0, 0) }; @@ -65,7 +66,7 @@ public MainForm(TrayApp app, Icon icon) root.Controls.Add(_volumeCaption); root.Controls.Add(_volume); root.Controls.Add(Spacer()); - root.Controls.Add(Row(_virtualCaption, _virtual, _makeDefault, _enableApo)); + root.Controls.Add(Row(_virtualCaption, _virtual, _makeDefault, _enableApo, _removeApo)); root.Controls.Add(Row(_outputCaption, _outputs)); root.Controls.Add(Row(_capCaption, _cap, _capUnit)); root.Controls.Add(Spacer()); @@ -81,10 +82,12 @@ public MainForm(TrayApp app, Icon icon) _language.SelectedIndex = Current == UiLanguage.Chinese ? 0 : 1; _language.SelectedIndexChanged += (_, _) => _app.SetLanguage(_language.SelectedIndex == 0 ? UiLanguage.Chinese : UiLanguage.English); - _cap.Value = (decimal)Math.Clamp(Math.Round(_app.Config.MaxOutputDb), -30, 0); + _cap.Value = (decimal)Math.Max(-30, Math.Min(0, Math.Round(_app.Config.MaxOutputDb))); _cap.ValueChanged += (_, _) => _app.SetMaxOutputDb((double)_cap.Value); _enableApo.Click += async (_, _) => await EnableApo(); _enableApo.Visible = false; + _removeApo.Click += async (_, _) => await RemoveApo(); + _removeApo.Visible = false; _makeDefault.Click += (_, _) => MakeDefault(); _outputs.DropDown += (_, _) => LoadOutputs(); _outputs.SelectedIndexChanged += (_, _) => OutputChosen(); @@ -104,6 +107,7 @@ public void ApplyTexts() _capCaption.Text = T("最大音量(滑块 100% 时):", "Maximum volume (slider at 100%):"); _capUnit.Text = T("dB(0 = 音箱原始最大音量)", "dB (0 = the speaker's own full level)"); _enableApo.Text = T("启用插件", "Enable plugin"); + _removeApo.Text = T("移除插件", "Remove plugin"); _volumeCaption.Text = T("Windows 音量", "Windows volume"); _makeDefault.Text = T("设为默认输出", "Set as default output"); _outputCaption.Text = T("输出设备:", "Output device:"); @@ -155,6 +159,35 @@ async Task EnableApo() "VolumeBridge", MessageBoxButtons.OK, MessageBoxIcon.Warning); } + async Task RemoveApo() + { + if (MessageBox.Show(this, + T("将移除 VolumeBridge 音量插件并恢复 Windows 原有音频设置:\n\n• 还原所有音箱的音效设置和“受保护音频路径”设置\n• 注销并删除插件 DLL\n• 重新启动 Windows 音频服务(声音中断约 2 秒)\n• 移除开机自动启动任务\n\n需要管理员确认。继续吗?", + "This removes the VolumeBridge volume plugin and restores the original Windows audio settings:\n\n• restores all speaker effect settings and the protected audio path setting\n• unregisters and deletes the plugin DLL\n• restarts the Windows Audio service (sound stops for ~2 s)\n• removes the start-at-logon task\n\nNeeds administrator approval. Continue?"), + "VolumeBridge", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK) + return; + _removeApo.Enabled = false; + _enableApo.Enabled = false; + bool ok = await _app.RemoveApoAsync(); + _removeApo.Enabled = true; + _enableApo.Enabled = true; + if (!ok) + { + MessageBox.Show(this, T("移除插件失败或已取消。详情见 C:\\ProgramData\\VolumeBridge\\apo-setup.log。", + "Removing the plugin failed or was cancelled. See C:\\ProgramData\\VolumeBridge\\apo-setup.log."), + "VolumeBridge", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + try { Autostart.Uninstall(); } catch (Exception) { } + _settingAutostart = true; + _autostart.Checked = SafeIsAutostart(); + _settingAutostart = false; + MessageBox.Show(this, + T("插件已移除,原有音频设置已恢复,开机自启已取消。\n\n现在可以退出并直接删除 VolumeBridge.exe。\n如需清理配置与日志,也可删除 %LOCALAPPDATA%\\VolumeBridge 和 C:\\ProgramData\\VolumeBridge。", + "The plugin has been removed, original audio settings restored, and start-at-logon removed.\n\nYou can now quit and delete VolumeBridge.exe.\nOptionally, you can also delete %LOCALAPPDATA%\\VolumeBridge and C:\\ProgramData\\VolumeBridge."), + "VolumeBridge", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + /// Zero-latency mode status. public void ShowApo(ApoStatus a) { @@ -163,10 +196,15 @@ public void ShowApo(ApoStatus a) _virtualCaption.Text = T("音量插件:", "Volume plugin:"); (string head, Color color, string detail) = a.State switch { + ApoState.LegacyInstallPresent => (T("● 检测到旧的安装版", "● Legacy installed version detected"), Color.Firebrick, + T("检测到旧的安装版 VolumeBridge,请先在 设置 → 应用 中卸载它,再点启用插件。", + "An older installed version of VolumeBridge was detected. Please uninstall it in Settings → Apps first, then click Enable plugin.")), ApoState.NoSpeaker => (T("● 未找到音箱", "● Speaker not found"), Color.DarkOrange, T("请连接音箱,或在下方“输出设备”中选择它。", "Connect the speaker, or pick it under \"Output device\".")), ApoState.NotInstalled => (T("● 音量插件未启用", "● Volume plugin not enabled"), Color.Firebrick, T($"{a.SpeakerName}:点击“启用插件”(需要管理员确认)。", $"{a.SpeakerName}: click \"Enable plugin\" (needs administrator approval).")), + ApoState.Outdated => (T("● 音量插件需要更新", "● Volume plugin update available"), Color.DarkOrange, + T($"{a.SpeakerName}:当前程序包含新版插件,点击“更新插件”(需要管理员确认)。", $"{a.SpeakerName}: this version includes an updated plugin; click \"Update plugin\" (needs administrator approval).")), ApoState.EnhancementsOff => (T("● 音频增强已关闭", "● Audio enhancements are off"), Color.Firebrick, T("设置 → 系统 → 声音 → 该音箱 → 音频增强,改为“设备默认效果”。", "Settings → System → Sound → the speaker → Audio enhancements: set to \"Device Default Effects\".")), ApoState.Idle => (T("● 已就绪(零延迟)", "● Ready (zero latency)"), Color.ForestGreen, @@ -179,11 +217,15 @@ public void ShowApo(ApoStatus a) _detail.Text = detail; _volume.Text = a.VolumeText; - _enableApo.Visible = a.State == ApoState.NotInstalled; + _enableApo.Text = a.State == ApoState.Outdated ? T("更新插件", "Update plugin") : T("启用插件", "Enable plugin"); + _enableApo.Visible = a.State is ApoState.NotInstalled or ApoState.Outdated; + _removeApo.Visible = a.PluginPresent && a.State != ApoState.LegacyInstallPresent; _virtual.Text = a.State switch { + ApoState.LegacyInstallPresent => T("需先卸载旧版", "uninstall old version first"), ApoState.NoSpeaker => "—", ApoState.NotInstalled => T("未启用", "not enabled"), + ApoState.Outdated => T("需要更新", "update available"), _ => T("已启用", "enabled"), }; @@ -202,10 +244,10 @@ public void ShowApo(ApoStatus a) _detail.Text += T("\n注意:该音箱不是默认输出,点击“设为默认输出”。", "\nNote: the speaker is not the default output; click \"Set as default output\"."); var r = a.Report; - _stats.Text = r is null ? "" : string.Create(CultureInfo.InvariantCulture, - $"{T("增益", "Gain")} {(r.TargetGain <= 0.0001f ? "-∞" : (20 * Math.Log10(r.TargetGain)).ToString("0.0", CultureInfo.InvariantCulture))} dB " + - $"{T("音量来源", "Volume source")}: {a.SourceText}\n" + - $"{T("插件实例", "Plugin instances")} {r.Instances} {r.SampleRate} Hz {r.Channels} ch {T("附加延迟", "Added latency")} 0 ms"); + _stats.Text = r is null ? "" : + FormattableString.Invariant($"{T("增益", "Gain")} {(r.TargetGain <= 0.0001f ? "-∞" : (20 * Math.Log10(r.TargetGain)).ToString("0.0", CultureInfo.InvariantCulture))} dB ") + + FormattableString.Invariant($"{T("音量来源", "Volume source")}: {a.SourceText}\n") + + FormattableString.Invariant($"{T("插件实例", "Plugin instances")} {r.Instances} {r.SampleRate} Hz {r.Channels} ch {T("附加延迟", "Added latency")} 0 ms"); } void MakeDefault() @@ -279,7 +321,7 @@ void ToggleAutostart() if (_settingAutostart) return; try { - if (_autostart.Checked) Autostart.Install(Environment.ProcessPath!); + if (_autostart.Checked) Autostart.Install(Application.ExecutablePath); else Autostart.Uninstall(); } catch (Exception e) diff --git a/src/VolumeBridge/Ui/TrayApp.cs b/src/VolumeBridge/Ui/TrayApp.cs index e4f6f4f..7b3fd0f 100644 --- a/src/VolumeBridge/Ui/TrayApp.cs +++ b/src/VolumeBridge/Ui/TrayApp.cs @@ -1,5 +1,6 @@ using System.Diagnostics; using System.Drawing; +using System.Net.Http; using System.Reflection; using Microsoft.Win32; using VolumeBridge.Audio; @@ -14,8 +15,6 @@ namespace VolumeBridge.Ui; /// sealed class TrayApp : ApplicationContext { - /// Created by the elevated installer process once UAC is accepted (see installer InitializeSetup). - const string UpdatingMutex = @"Global\VolumeBridge.Updating"; static readonly TimeSpan LogEvery = TimeSpan.FromSeconds(60); readonly FileLog _log; @@ -65,9 +64,9 @@ public TrayApp(AppConfig config, ApoController apo, FileLog log, string dataDir, _timer.Tick += (_, _) => Tick(); _timer.Start(); - // Attach runs usbip.exe and may take a few seconds: keep it off the UI thread. Apo.Start(); - CleanUpOldInstallers(); + Task.Run(() => Autostart.SyncPathIfInstalled(Application.ExecutablePath, _log.Write)); + CleanUpOldUpdateFiles(); if (!startHidden) ShowWindow(); if (notice is not null) _tray.ShowBalloonTip(5000, "VolumeBridge", notice, ToolTipIcon.Info); @@ -81,29 +80,42 @@ public TrayApp(AppConfig config, ApoController apo, FileLog log, string dataDir, bool _updating; /// - /// Installers downloaded by earlier one-click updates are no longer needed. Runs in the background - /// with retries: right after an update, the installer that relaunched us may still be running from there. + /// Cleans up <exe>.old and temporary downloads from earlier one-click updates. Runs in + /// the background with retries because the previous process may still be exiting right after --updated. /// - void CleanUpOldInstallers() + void CleanUpOldUpdateFiles() { var ct = _quit.Token; + string oldExe = Application.ExecutablePath + ".old"; Task.Run(async () => { for (int attempt = 0; attempt < 6 && !ct.IsCancellationRequested; attempt++) { - try { await Task.Delay(TimeSpan.FromSeconds(10), ct); } catch (OperationCanceledException) { return; } - if (_updating || !Directory.Exists(UpdateDir)) return; // a new download owns the folder + try { await Task.Delay(TimeSpan.FromSeconds(attempt == 0 ? 3 : 10), ct); } + catch (OperationCanceledException) { return; } + if (_updating) return; // a new update owns the files + bool left = false; - foreach (var f in Directory.EnumerateFiles(UpdateDir)) + if (File.Exists(oldExe)) { - try { File.Delete(f); } + try { File.Delete(oldExe); } catch (Exception e) when (e is IOException or UnauthorizedAccessException) { left = true; } } - if (!left) + if (Directory.Exists(UpdateDir)) { - try { Directory.Delete(UpdateDir); } catch (Exception) { } - return; + bool dirLeft = false; + foreach (var f in Directory.EnumerateFiles(UpdateDir)) + { + try { File.Delete(f); } + catch (Exception e) when (e is IOException or UnauthorizedAccessException) { dirLeft = true; } + } + if (!dirLeft) + { + try { Directory.Delete(UpdateDir); } catch (Exception) { } + } + else left = true; } + if (!left) return; } }, ct); } @@ -142,7 +154,7 @@ void Tick() bool ok = a.State is ApoState.Working or ApoState.Idle; string tip = ok ? "VolumeBridge: " + a.VolumeText : "VolumeBridge: " + T("需要处理", "needs attention"); _tray.Icon = ok ? _iconOk : _iconIdle; - _tray.Text = tip.Length > 63 ? tip[..63] : tip; + _tray.Text = tip.Length > 63 ? tip.Substring(0, 63) : tip; if (_form.Visible) _form.ShowApo(a); if (DateTime.UtcNow - _lastLog >= LogEvery) { @@ -163,18 +175,23 @@ public void SetMaxOutputDb(double db) public void ReopenOutput() => Apo.Recheck(); /// Runs the elevated plugin setup for (one UAC prompt). - public async Task EnableApoAsync(string endpointId) + public Task EnableApoAsync(string endpointId) => RunElevatedApoAsync($"--apo-setup \"{endpointId}\""); + + /// Runs the elevated plugin removal (one UAC prompt). + public Task RemoveApoAsync() => RunElevatedApoAsync("--apo-remove"); + + async Task RunElevatedApoAsync(string arguments) { try { - using var p = Process.Start(new ProcessStartInfo(Environment.ProcessPath!, $"--apo-setup \"{endpointId}\"") + using var p = Process.Start(new ProcessStartInfo(Application.ExecutablePath, arguments) { UseShellExecute = true, Verb = "runas", WindowStyle = ProcessWindowStyle.Hidden, })!; - await p.WaitForExitAsync(); - _log.Write($"apo-setup exited with {p.ExitCode}"); + await Task.Run(() => p.WaitForExit()); + _log.Write($"{arguments} exited with {p.ExitCode}"); Apo.Recheck(); return p.ExitCode == 0; } @@ -235,8 +252,8 @@ protected override void Dispose(bool disposing) } /// - /// GitHub latest release → download + SHA-256 check → run the installer → quit once the installer - /// is elevated (it then waits for us to exit, installs, and relaunches VolumeBridge). + /// GitHub latest release → download + SHA-256 check → rename running exe to .old → place new exe → + /// launch with --updated → quit. Rolls back on failure; opens the release page if the folder is not writable. /// public async Task CheckForUpdatesAsync(IWin32Window owner, Button button) { @@ -258,11 +275,20 @@ public async Task CheckForUpdatesAsync(IWin32Window owner, Button button) return; } if (MessageBox.Show(owner, - T($"发现新版本 {latest.Tag}(当前 {CurrentVersion.ToString(3)})。\n\n现在下载并安装吗?安装时需要管理员确认,完成后会自动重新打开。", - $"Version {latest.Tag} is available (you have {CurrentVersion.ToString(3)}).\n\nDownload and install it now? Installing needs administrator approval; VolumeBridge reopens afterwards."), + T($"发现新版本 {latest.Tag}(当前 {CurrentVersion.ToString(3)})。\n\n现在下载并更新吗?完成后会自动重新打开。", + $"Version {latest.Tag} is available (you have {CurrentVersion.ToString(3)}).\n\nDownload and update now? VolumeBridge will reopen automatically."), "VolumeBridge", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) return; + string currentExe = Application.ExecutablePath; + string exeDir = Path.GetDirectoryName(currentExe)!; + if (!IsDirectoryWritable(exeDir)) + { + _log.Write($"exe directory is not writable ({exeDir}); opening release page"); + OpenUrl(latest.PageUrl); + return; + } + string shown = ""; var progress = new Progress(p => { @@ -271,30 +297,47 @@ public async Task CheckForUpdatesAsync(IWin32Window owner, Button button) shown = text; button.Text = text; }); - string setup = await UpdateCheck.DownloadVerifiedAsync(http, latest, + string downloaded = await UpdateCheck.DownloadVerifiedAsync(http, latest, UpdateDir, progress, ct); if (Gone()) return; - _log.Write($"update {latest.Tag} downloaded and verified: {setup}"); - - // Inno's loader runs unelevated and starts an elevated child itself, so Process.Start returns - // before UAC is answered. Quit only once the elevated installer signals it is running; if the - // loader exits first, UAC was declined. - button.Text = T("等待管理员确认…", "Waiting for administrator approval…"); - using var installer = Process.Start(new ProcessStartInfo(setup, "/SILENT /SUPPRESSMSGBOXES /NORESTART") { UseShellExecute = true })!; - while (!ct.IsCancellationRequested) + _log.Write($"update {latest.Tag} downloaded and verified: {downloaded}"); + + string oldExe = currentExe + ".old"; + bool renamed = false; + try { - if (InstallerElevated()) + if (File.Exists(oldExe)) File.Delete(oldExe); + File.Move(currentExe, oldExe); + renamed = true; + // Copy instead of Move so updates work even if %TEMP% and the exe are on different drives. + File.Copy(downloaded, currentExe, overwrite: true); + try { File.Delete(downloaded); } catch (Exception) { } + Process.Start(new ProcessStartInfo(currentExe, "--updated") { UseShellExecute = false }); + _log.Write($"updated to {latest.Tag}; quitting old instance"); + Quit(); + return; + } + catch (Exception ex) + { + _log.Write($"self-update swap failed: {ex}"); + if (renamed) { - _log.Write("installer is running elevated; quitting for the update"); - Quit(); - return; + try + { + if (File.Exists(currentExe)) File.Delete(currentExe); + if (File.Exists(oldExe)) File.Move(oldExe, currentExe); + } + catch (Exception rb) { _log.Write($"rollback failed: {rb}"); } } - if (installer.HasExited) + if (!Gone()) { - MessageBox.Show(owner, T("已取消更新。", "Update cancelled."), "VolumeBridge", MessageBoxButtons.OK, MessageBoxIcon.Information); - return; + var res = MessageBox.Show(owner, + T($"更新失败:{ex.Message}\n\n是否打开发布页手动下载?", + $"Update failed: {ex.Message}\n\nOpen the release page to download manually?"), + "VolumeBridge", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); + if (res == DialogResult.Yes) OpenUrl(latest.PageUrl); } - await Task.Delay(100, ct); + return; } } catch (OperationCanceledException) when (Quitting) { } @@ -307,6 +350,7 @@ public async Task CheckForUpdatesAsync(IWin32Window owner, Button button) } finally { + _updating = false; if (!Gone()) { button.Text = T("检查更新", "Check for updates"); // current language, even if switched meanwhile @@ -315,14 +359,21 @@ public async Task CheckForUpdatesAsync(IWin32Window owner, Button button) } } - static bool InstallerElevated() + static bool IsDirectoryWritable(string dir) { + string probe = Path.Combine(dir, $".vb-write-test-{Guid.NewGuid():N}"); try { - if (!Mutex.TryOpenExisting(UpdatingMutex, out var m)) return false; - m.Dispose(); + using (File.Create(probe)) { } + File.Delete(probe); return true; } - catch (UnauthorizedAccessException) { return true; } // exists, owned by the elevated installer + catch (Exception) { return false; } + } + + static void OpenUrl(string url) + { + if (string.IsNullOrWhiteSpace(url)) return; + try { Process.Start(new ProcessStartInfo(url) { UseShellExecute = true }); } catch (Exception) { } } } diff --git a/src/VolumeBridge/VolumeBridge.csproj b/src/VolumeBridge/VolumeBridge.csproj index 5668d78..9f71ea4 100644 --- a/src/VolumeBridge/VolumeBridge.csproj +++ b/src/VolumeBridge/VolumeBridge.csproj @@ -3,30 +3,51 @@ WinExe true - 0.4.0 + 0.5.0 VolumeBridge - net8.0-windows + net48 + x64 + latest enable enable - PerMonitorV2 VolumeBridge VolumeBridge - true true - - - - true - true - true - true - false + app.manifest embedded + false + false + + + + + + + - + + + + + + + + + + + + + <_EmbedDlls Include="@(ReferenceCopyLocalPaths)" Condition="'%(Extension)' == '.dll'" /> + + + + + + diff --git a/src/VolumeBridge/app.manifest b/src/VolumeBridge/app.manifest new file mode 100644 index 0000000..d9e7c79 --- /dev/null +++ b/src/VolumeBridge/app.manifest @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + true/pm + PerMonitorV2 + + + diff --git a/tests/VolumeBridge.Tests/CoreTests.cs b/tests/VolumeBridge.Tests/CoreTests.cs index 4defa8d..1dfaf1a 100644 --- a/tests/VolumeBridge.Tests/CoreTests.cs +++ b/tests/VolumeBridge.Tests/CoreTests.cs @@ -30,26 +30,49 @@ public class AppConfigTests [Fact] public void ReadsOlderConfigs_IgnoringRemovedSettings() { - var json = "{ // 0.3.x config\n \"mode\": \"virtual\", \"usbipPort\": 3240, \"outputKeywords\": [\"Flip\"], \"maxOutputDb\": -20, }"; + var json = "{ // 0.3.x / 0.4.0 config\n \"mode\": \"virtual\", \"usbipPort\": 3240, \"outputKeywords\": [\"Flip\"], \"maxOutputDb\": -20, \"language\": \"zh\", }"; var c = AppConfig.FromJson(json); Assert.Equal(["Flip"], c.OutputKeywords); Assert.Equal(-20, c.MaxOutputDb); + Assert.Equal("zh", c.Language); Assert.Equal(0.1f, c.OutputCapGain, 3); Assert.DoesNotContain("outputCapGain", c.ToJson(), StringComparison.OrdinalIgnoreCase); } + + [Fact] + public void RoundTripsAllFields_AndPreservesDefaults() + { + var original = new AppConfig + { + OutputKeywords = ["JBL", "DAC \"USB\""], + OutputDeviceId = "{0.0.0.00000000}.{12345678-1234-1234-1234-123456789abc}", + MaxOutputDb = -15.5, + Language = "en", + }; + string json = original.ToJson(); + Assert.DoesNotContain("outputCapGain", json, StringComparison.OrdinalIgnoreCase); + + var parsed = AppConfig.FromJson(json); + Assert.Equal(original.OutputKeywords, parsed.OutputKeywords); + Assert.Equal(original.OutputDeviceId, parsed.OutputDeviceId); + Assert.Equal(original.MaxOutputDb, parsed.MaxOutputDb); + Assert.Equal(original.Language, parsed.Language); + + var empty = AppConfig.FromJson("{}"); + Assert.Equal(["JBL", "Zgmicro"], empty.OutputKeywords); + Assert.Null(empty.OutputDeviceId); + Assert.Equal(-12, empty.MaxOutputDb); + Assert.Equal("auto", empty.Language); + } } public class AppPathsTests { [Fact] - public void ProgramFilesInstall_UsesLocalAppData_PortableUsesExeDir() + public void AlwaysUsesLocalAppData() { - string pf = Path.Combine(Path.GetTempPath(), "pf"); string lad = Path.Combine(Path.GetTempPath(), "lad"); - Assert.Equal(Path.Combine(lad, "VolumeBridge"), AppPaths.DataDir(Path.Combine(pf, "VolumeBridge") + Path.DirectorySeparatorChar, [null, pf], lad)); - - string portable = Path.Combine(Path.GetTempPath(), "pfx", "VolumeBridge"); - Assert.Equal(portable, AppPaths.DataDir(portable, [pf], lad)); // "pfx" is not under "pf" + Assert.Equal(Path.Combine(lad, "VolumeBridge"), AppPaths.DataDir(lad)); } } @@ -58,23 +81,25 @@ public class UpdateCheckTests static string Release(string tag, bool prerelease = false, string owner = "ZanderH-code/volumebridge") => $$""" {"tag_name":"{{tag}}","draft":false,"prerelease":{{(prerelease ? "true" : "false")}},"html_url":"https://github.com/x", "assets":[ - {"name":"VolumeBridgeSetup.exe","browser_download_url":"https://github.com/{{owner}}/releases/download/{{tag}}/VolumeBridgeSetup.exe"}, - {"name":"VolumeBridgeSetup.exe.sha256","browser_download_url":"https://github.com/{{owner}}/releases/download/{{tag}}/VolumeBridgeSetup.exe.sha256"}]} + {"name":"VolumeBridge.exe","browser_download_url":"https://github.com/{{owner}}/releases/download/{{tag}}/VolumeBridge.exe"}, + {"name":"VolumeBridge.exe.sha256","browser_download_url":"https://github.com/{{owner}}/releases/download/{{tag}}/VolumeBridge.exe.sha256"}]} """; [Fact] public void Parse_ReadsVersionAndAssets() { - var r = UpdateCheck.Parse(Release("v0.3.1"))!; - Assert.Equal(new Version(0, 3, 1), r.Version); - Assert.EndsWith("/v0.3.1/VolumeBridgeSetup.exe", r.SetupUrl); + var r = UpdateCheck.Parse(Release("v0.5.0"))!; + Assert.Equal(new Version(0, 5, 0), r.Version); + Assert.EndsWith("/v0.5.0/VolumeBridge.exe", r.ExeUrl); + Assert.EndsWith("/v0.5.0/VolumeBridge.exe.sha256", r.ChecksumUrl); + Assert.Equal("https://github.com/x", r.PageUrl); } [Fact] public void Parse_RejectsPrereleaseAndForeignDownloadHosts() { - Assert.Null(UpdateCheck.Parse(Release("v0.3.1", prerelease: true))); - Assert.Null(UpdateCheck.Parse(Release("v0.3.1", owner: "someone/else"))); + Assert.Null(UpdateCheck.Parse(Release("v0.5.0", prerelease: true))); + Assert.Null(UpdateCheck.Parse(Release("v0.5.0", owner: "someone/else"))); } [Theory] @@ -93,7 +118,7 @@ public void IsNewer_ComparesNumerically(string tag, string current, bool newer) public void Checksum_FirstTokenOfSha256sumLine() { string h = new('a', 64); - Assert.Equal(h, UpdateCheck.ParseChecksum($"{h.ToUpperInvariant()} VolumeBridgeSetup.exe\n")); + Assert.Equal(h, UpdateCheck.ParseChecksum($"{h.ToUpperInvariant()} VolumeBridge.exe\n")); Assert.Null(UpdateCheck.ParseChecksum("not a hash")); } } @@ -119,11 +144,12 @@ public class LocTests static readonly System.Globalization.CultureInfo Zh = new("zh-CN"), En = new("en-US"), De = new("de-DE"); [Fact] - public void ConfigWins_ThenInstallerChoice_ThenWindowsLanguage() + public void ConfigWins_ThenWindowsLanguage() { - Assert.Equal(UiLanguage.English, Loc.Resolve("en", "zh", Zh)); - Assert.Equal(UiLanguage.Chinese, Loc.Resolve("auto", "zh", En)); - Assert.Equal(UiLanguage.Chinese, Loc.Resolve(null, null, Zh)); - Assert.Equal(UiLanguage.English, Loc.Resolve("auto", "", De)); + Assert.Equal(UiLanguage.English, Loc.Resolve("en", Zh)); + Assert.Equal(UiLanguage.Chinese, Loc.Resolve("auto", Zh)); + Assert.Equal(UiLanguage.English, Loc.Resolve("auto", En)); + Assert.Equal(UiLanguage.Chinese, Loc.Resolve(null, Zh)); + Assert.Equal(UiLanguage.English, Loc.Resolve("auto", De)); } }