Fix(audio): keep audio packets block-aligned end to end

waveOut only converts whole 65-byte GSM610 blocks; a trailing partial block is
dropped, never carried over. Windows hosts record into a 1000-byte buffer but
the driver fills only 975 (15 blocks) - the last 25 bytes are stale heap the
driver never wrote. Clients ship all 1000 bytes anyway, so PlayBuffer has to
truncate each packet to whole blocks and throw that tail away.

Accumulating the remainder across packets instead - the first attempt at this
fix - inserted 25 bytes of garbage every 1000 bytes and shifted the block
boundary, turning voice monitoring of existing Windows clients into pure noise
while Android stayed fine. Both symptoms are the same "per packet" versus
"across packets" opposition, and per packet is the one that matches the wire.

So the invariant is: one packet carries a whole number of 65-byte blocks, and
nothing is ever carried into the next packet. Windows hosts satisfy it for
free. Android now packs 15 blocks (975 bytes) and pads the rest with zeros to
keep the 1000-byte length that older controllers expect - see AudioHandler.h.

GetRecordBuffer keeps returning the full 1000 bytes on purpose: shortening the
packet would make a v1.4.2 controller memcpy m_ulBufferLength and read past the
end, which is real garbage rather than harmless stale bytes.

Measured against the real waveOut API with a 2 s 1 kHz tone (3250 bytes = 50
blocks = 16000 samples): one 3250-byte buffer played 16000 samples, four
1000-byte buffers played 15360 (25 bytes lost per packet), four 975-byte
buffers played 16000. The encoder was never at fault - the same libgsm WAV49
stream decodes through Windows ACM with a correlation of 0.9999 when handed
over whole.

Also check WHDR_INQUEUE before reusing a header and honour the waveOutWrite
return value, since the old code dropped data silently on WAVERR_BUSY; size the
playback buffers for the largest packet; and unprepare the waveOut headers in
the destructor, which was unpreparing the waveIn headers after they had already
been freed.

Android APKs built before this commit still send unaligned 1000-byte packets
and will sound noisy against this controller - rebuild the APK.

Co-Authored-By: DeepSeek-V4.1-Flash
This commit is contained in:
yuanyuanxiangandDeepSeek-V4.1-Flash committed 2026-11-15 17:05:41 +01:00
1 parent d987941e57
commit 3ae54c808e
5 files changed
+190 -36

No files matched your search

+27 -11
View File
@@ -4,17 +4,19 @@
// 协议与 Windows 客户端完全一致(client/AudioManager.cpp + client/Audio.cpp): // 协议与 Windows 客户端完全一致(client/AudioManager.cpp + client/Audio.cpp):
// 主连接 [COMMAND_AUDIO] → 子连接(ConnAuth)→ 首包单字节 [TOKEN_AUDIO_START] // 主连接 [COMMAND_AUDIO] → 子连接(ConnAuth)→ 首包单字节 [TOKEN_AUDIO_START]
// → 服务端弹出 CAudioDlg 后回单字节 [COMMAND_NEXT] → 双向音频开始 // → 服务端弹出 CAudioDlg 后回单字节 [COMMAND_NEXT] → 双向音频开始
// 上行:[TOKEN_AUDIO_DATA:1][1000 字节 GSM 流](服务端 CAudio::PlayBuffer 固定按 // 上行:[TOKEN_AUDIO_DATA:1][1000 字节]。前 975 字节是 15 个完整 GSM 块,
// 1000 字节一块拷贝,包长必须正好 1000,且不能短——短了服务端会越界读) // 后 25 字节补零。
// waveOut 只转换整数个 65 字节块,末尾不足一块的字节既不转换也不保留,
// 所以 65 字节块绝不能跨包切开 —— 切开的半块会被直接丢掉,块边界一错位
// 整条流就是噪声。服务端 CAudio::PlayBuffer 按包截断到整块,那 25 个零
// 正好被丢掉。包长仍保持 1000:老版本服务端按 m_ulBufferLength 整块
// 拷贝,包长小于 1000 会越界读。
// 下行:服务端直接发裸 GSM 流(无 token,不带长度头),也是 1000 字节一块 // 下行:服务端直接发裸 GSM 流(无 token,不带长度头),也是 1000 字节一块
// //
// 编码格式是服务端 ACM 的 WAVE_FORMAT_GSM610:8000 Hz 单声道, // 编码格式是服务端 ACM 的 WAVE_FORMAT_GSM610:8000 Hz 单声道,
// 65 字节 / 320 采样(40ms)。libgsm 的 WAV49 模式产出完全相同的打包 // 65 字节 / 320 采样(40ms)。libgsm 的 WAV49 模式产出完全相同的打包
// (每块 2 × 160 采样帧:第一帧 32 字节、第二帧 33 字节),见 gsm/README.md。 // (每块 2 × 160 采样帧:第一帧 32 字节、第二帧 33 字节),见 gsm/README.md。
// 编码与解码必须各用一个 gsm 状态:frame_index/frame_chain 是共用的。 // 编码与解码必须各用一个 gsm 状态:frame_index/frame_chain 是共用的。
//
// 语音流是连续的:1000 不是 65 的整数倍,65 字节块会跨包切开,这是允许的——
// 服务端把每个 1000 字节缓冲按顺序写给 waveOut,编解码状态跨缓冲延续。
#include "common/commands.h" #include "common/commands.h"
#include "common/logger.h" #include "common/logger.h"
#include "client/IOCPClient.h" #include "client/IOCPClient.h"
@@ -30,6 +32,12 @@
#define LOGI_AUD(...) android_log_tag(ANDROID_LOG_INFO, "YAMA_AUD", __VA_ARGS__) #define LOGI_AUD(...) android_log_tag(ANDROID_LOG_INFO, "YAMA_AUD", __VA_ARGS__)
#define LOGE_AUD(...) android_log_tag(ANDROID_LOG_ERROR, "YAMA_AUD", __VA_ARGS__) #define LOGE_AUD(...) android_log_tag(ANDROID_LOG_ERROR, "YAMA_AUD", __VA_ARGS__)
// 上行包:15 个 GSM 块(975 字节)+ 25 字节补零 = 1000 字节。
// 补零是为了让包长与老协议一致(老服务端按 m_ulBufferLength 整块 memcpy,
// 包长小于 1000 会越界读),服务端按块截断时正好把这 25 个零丢掉。
static const size_t AUDIO_PKT_BLOCKS = 15 * 65; // 975 = 整块载荷
static const size_t AUDIO_PKT_WIRE = 1000; // 线上包长(含尾部补零)
extern "C" { extern "C" {
#include "gsm.h" #include "gsm.h"
} }
@@ -125,18 +133,26 @@ private:
gsm_encode(m_enc, (gsm_signal*)samples, m_frameBuf + 32); // 33 字节 gsm_encode(m_enc, (gsm_signal*)samples, m_frameBuf + 32); // 33 字节
m_frameFill = 0; m_frameFill = 0;
// 65 字节块可能跨 1000 字节包切分;音频流仍然是连续的 // 一个包只装整数个 65 字节块,剩下的补零 —— 绝不让块跨包切开。
// m_frameBuf 正好一块(65)、AUDIO_PKT_BLOCKS 是 15 块,所以 m_pktFill 恒为
// 65 的倍数,room 恒 ≥ 65,一轮就拷完。room 为 0 只在常量被改成非整块数时
// 才可能出现,那时必须跳出,否则 n=0 会死循环卡住音频线程。
size_t off = 0; size_t off = 0;
while (off < sizeof(m_frameBuf)) { while (off < sizeof(m_frameBuf)) {
const size_t n = std::min(sizeof(m_frameBuf) - off, (size_t)1000 - m_pktFill); const size_t room = AUDIO_PKT_BLOCKS - m_pktFill;
const size_t n = std::min(sizeof(m_frameBuf) - off, room);
if (n == 0)
break;
memcpy(m_pkt + 1 + m_pktFill, m_frameBuf + off, n); memcpy(m_pkt + 1 + m_pktFill, m_frameBuf + off, n);
m_pktFill += n; m_pktFill += n;
off += n; off += n;
if (m_pktFill == 1000) { if (m_pktFill == AUDIO_PKT_BLOCKS) {
m_client->Send2Server((char*)m_pkt, 1 + 1000); memset(m_pkt + 1 + AUDIO_PKT_BLOCKS, 0, AUDIO_PKT_WIRE - AUDIO_PKT_BLOCKS);
m_client->Send2Server((char*)m_pkt, 1 + AUDIO_PKT_WIRE);
m_pktFill = 0; m_pktFill = 0;
if (++m_pktsSent == 1) if (++m_pktsSent == 1)
LOGI_AUD("first uplink packet sent (1+1000 bytes = 615 ms GSM)"); LOGI_AUD("first uplink packet sent (1+%u bytes = %u ms GSM)",
(unsigned)(1 + AUDIO_PKT_WIRE), (unsigned)(AUDIO_PKT_BLOCKS * 40 / 65));
} }
} }
} }
@@ -179,7 +195,7 @@ private:
size_t m_pendingCount; size_t m_pendingCount;
uint8_t m_frameBuf[65]; uint8_t m_frameBuf[65];
size_t m_frameFill; // 0 = 下一帧写 32 字节;32 = 下一帧写 33 字节 size_t m_frameFill; // 0 = 下一帧写 32 字节;32 = 下一帧写 33 字节
uint8_t m_pkt[1 + 1000]; // [TOKEN_AUDIO_DATA][音频] uint8_t m_pkt[1 + AUDIO_PKT_WIRE]; // [TOKEN_AUDIO_DATA][975 字节整块 + 25 补零]
size_t m_pktFill; size_t m_pktFill;
unsigned m_pktsSent; unsigned m_pktsSent;
+34 -6
View File
@@ -1,17 +1,31 @@
@echo off @echo off
:: SimpleRemoter Quick Build Script :: SimpleRemoter Quick Build Script
:: Usage: build.cmd [release|debug] [x64|x86|all] [server|clean|publish|go-server|server-linux|serverd|client] :: Usage: build.cmd [release|debug] [x64|x86|all] [server|clean|publish|go-server|server-linux|serverd|client] [-name NAME]
:: go-server Build Go fallback server only -> Bin\YamaGo_x64.exe :: go-server Build Go fallback server only - Bin\YamaGo_x64.exe
:: go-server publish Same, plus UPX --best compression :: go-server publish Same, plus UPX --best compression
:: server-linux Cross-compile Go server for Linux -> Bin\server_linux_amd64 :: server-linux Cross-compile Go server for Linux - Bin\server_linux_amd64
:: serverd Debug server only (x64) -> Bin\Yama_x64d.exe :: serverd Debug server only (x64) - Bin\Yama_x64d.exe
:: client Debug client (x64) -> x64\Debug\ghost.exe :: client Debug client (x64) - x64\Debug\ghost.exe
:: -name NAME Server output name, writes Bin\NAME_x64.exe instead of
:: Bin\Yama_x64.exe. Use it to build while the Release
:: server is running and Bin\Yama_x64.exe is locked:
:: build.cmd server -name YamaTest
:: Applies to server / serverd / publish.
::
:: NOTE: keep this file pure ASCII. cmd reads .cmd as the OEM code page (936
:: here), so UTF-8 text can swallow the following newline and merge the next
:: command into a comment line - which then turns its ">" into a redirect.
setlocal enabledelayedexpansion setlocal enabledelayedexpansion
:: Capture the script directory before any shift: shift moves %0 along with
:: %1..%9, after which %~dp0 resolves to the current directory instead.
set SCRIPT_DIR=%~dp0
set CONFIG=Release set CONFIG=Release
set PLATFORM=x64 set PLATFORM=x64
set EXTRA_ARGS= set EXTRA_ARGS=
set SERVER_NAME=
:parse_args :parse_args
if "%~1"=="" goto :run if "%~1"=="" goto :run
@@ -28,6 +42,16 @@ if /i "%~1"=="server-linux" (set EXTRA_ARGS=!EXTRA_ARGS! -GoServerLinux& shift&
:: Debug presets: serverd = debug server x64 only, client = debug ghost x64 only :: Debug presets: serverd = debug server x64 only, client = debug ghost x64 only
if /i "%~1"=="serverd" (set CONFIG=Debug& set PLATFORM=x64& set EXTRA_ARGS=!EXTRA_ARGS! -ServerOnly& shift& goto :parse_args) if /i "%~1"=="serverd" (set CONFIG=Debug& set PLATFORM=x64& set EXTRA_ARGS=!EXTRA_ARGS! -ServerOnly& shift& goto :parse_args)
if /i "%~1"=="client" (set CONFIG=Debug& set PLATFORM=x64& set EXTRA_ARGS=!EXTRA_ARGS! -ClientOnly& shift& goto :parse_args) if /i "%~1"=="client" (set CONFIG=Debug& set PLATFORM=x64& set EXTRA_ARGS=!EXTRA_ARGS! -ClientOnly& shift& goto :parse_args)
if /i "%~1"=="-name" (
if "%~2"=="" (
echo ERROR: -name needs a value, e.g. build.cmd server -name YamaTest
exit /b 1
)
set SERVER_NAME=%~2
shift
shift
goto :parse_args
)
echo Unknown argument: %~1 echo Unknown argument: %~1
shift shift
goto :parse_args goto :parse_args
@@ -35,9 +59,13 @@ goto :parse_args
:run :run
echo. echo.
echo Building SimpleRemoter: %CONFIG% ^| %PLATFORM% echo Building SimpleRemoter: %CONFIG% ^| %PLATFORM%
if not "%SERVER_NAME%"=="" echo Server name: %SERVER_NAME%
echo. echo.
powershell -ExecutionPolicy Bypass -File "%~dp0build.ps1" -Config %CONFIG% -Platform %PLATFORM% %EXTRA_ARGS% set NAME_ARG=
if not "%SERVER_NAME%"=="" set NAME_ARG=-ServerName "%SERVER_NAME%"
powershell -ExecutionPolicy Bypass -File "%SCRIPT_DIR%build.ps1" -Config %CONFIG% -Platform %PLATFORM% %EXTRA_ARGS% %NAME_ARG%
if %errorlevel% neq 0 ( if %errorlevel% neq 0 (
echo. echo.
+44 -8
View File
@@ -1,5 +1,5 @@
# SimpleRemoter Build Script # SimpleRemoter Build Script
# Usage: .\build.ps1 [-Config Release|Debug] [-Platform x64|x86|all] [-ServerOnly] [-ClientOnly] [-Clean] [-Publish] # Usage: .\build.ps1 [-Config Release|Debug] [-Platform x64|x86|all] [-ServerOnly] [-ClientOnly] [-Clean] [-Publish] [-ServerName NAME]
# #
# Requirements: # Requirements:
# - Visual Studio 2019 or 2022 # - Visual Studio 2019 or 2022
@@ -19,7 +19,12 @@ param(
[switch]$Clean, # Clean before build [switch]$Clean, # Clean before build
[switch]$Publish, # Publish mode: rebuild all deps + x64 Release + UPX compress [switch]$Publish, # Publish mode: rebuild all deps + x64 Release + UPX compress
[switch]$GoServer, # Build Go fallback server (server/go) -> Bin/YamaGo_x64.exe [switch]$GoServer, # Build Go fallback server (server/go) -> Bin/YamaGo_x64.exe
[switch]$GoServerLinux # Cross-compile the Go server for Linux -> Bin/server_linux_amd64 [switch]$GoServerLinux, # Cross-compile the Go server for Linux -> Bin/server_linux_amd64
# 服务端输出名,默认 Yama(-> Bin\Yama_x64.exe)。vcxproj 里输出名是
# $(SolutionDir)Bin\$(TargetName)_<platform><ext>,所以这里覆盖 TargetName 即可。
# 用途:Release 服务端正在运行、Bin\Yama_x64.exe 被占用时,编译到另一个名字。
[string]$ServerName = ""
) )
$ErrorActionPreference = "Stop" $ErrorActionPreference = "Stop"
@@ -28,6 +33,23 @@ $rootDir = $PSScriptRoot
$binDir = Join-Path $rootDir "Bin" $binDir = Join-Path $rootDir "Bin"
$upxPath = Join-Path $rootDir "server\2015Remote\res\3rd\upx.exe" $upxPath = Join-Path $rootDir "server\2015Remote\res\3rd\upx.exe"
# 服务端输出名。vcxproj 把输出写成 $(SolutionDir)Bin\$(TargetName)_<platform><ext>,
# 覆盖 TargetName 就能换文件名,不用改工程。默认仍是 Yama -> Bin\Yama_x64.exe,
# 行为与以前一致;指定别的名字主要是为了在 Release 服务端运行中
# (Bin\Yama_x64.exe 被独占)时还能编译。
if ($ServerName) {
if ($ServerName -notmatch '^[A-Za-z0-9][A-Za-z0-9_.-]*$') {
Write-Host "ERROR: invalid -ServerName '$ServerName'." -ForegroundColor Red
Write-Host " Use letters, digits, underscore, dot or dash, and do not start with a symbol." -ForegroundColor Yellow
exit 1
}
if ($ClientOnly) {
Write-Host "WARNING: -ServerName does not apply to -ClientOnly (client output is always ghost.exe), ignored." -ForegroundColor Yellow
$ServerName = ""
}
}
$serverTargetName = if ($ServerName) { $ServerName } else { "Yama" }
# Build Go fallback server. No-op (with warning) if Go compiler is not installed. # Build Go fallback server. No-op (with warning) if Go compiler is not installed.
# When -Compress is set, run UPX --best on the output (mirrors C++ publish flow). # When -Compress is set, run UPX --best on the output (mirrors C++ publish flow).
function Build-GoServer { function Build-GoServer {
@@ -289,7 +311,9 @@ function Build-Project {
[string]$Project, [string]$Project,
[string]$Configuration, [string]$Configuration,
[string]$Platform, [string]$Platform,
[bool]$ForceClean = $false [bool]$ForceClean = $false,
# 额外传给 MSBuild 的 /p: 属性,例如 /p:TargetName=YamaTest
[string[]]$ExtraProps = @()
) )
# Solution uses x86/x64, projects use Win32/x64 - MSBuild needs solution platform names # Solution uses x86/x64, projects use Win32/x64 - MSBuild needs solution platform names
@@ -307,6 +331,10 @@ function Build-Project {
"/v:minimal" # Minimal verbosity "/v:minimal" # Minimal verbosity
) )
if ($ExtraProps.Count -gt 0) {
$buildArgs += $ExtraProps
}
if ($Clean -or $ForceClean) { if ($Clean -or $ForceClean) {
# Use :Rebuild target for single project rebuild # Use :Rebuild target for single project rebuild
$buildArgs[1] = "/t:${Project}:Rebuild" $buildArgs[1] = "/t:${Project}:Rebuild"
@@ -407,6 +435,9 @@ Write-Host " Config: $Config" -ForegroundColor Cyan
Write-Host " Platform: $Platform" -ForegroundColor Cyan Write-Host " Platform: $Platform" -ForegroundColor Cyan
Write-Host " VS: $vsYear" -ForegroundColor Cyan Write-Host " VS: $vsYear" -ForegroundColor Cyan
Write-Host " Clean: $Clean" -ForegroundColor Cyan Write-Host " Clean: $Clean" -ForegroundColor Cyan
if ($ServerName) {
Write-Host " Server: $serverTargetName" -ForegroundColor Cyan
}
if ($Publish) { if ($Publish) {
Write-Host " UPX: Yes" -ForegroundColor Cyan Write-Host " UPX: Yes" -ForegroundColor Cyan
} }
@@ -426,10 +457,15 @@ if (-not $ServerOnly) {
} }
Write-Host "" Write-Host ""
Write-Host "Step 2: Building server (Yama)..." -ForegroundColor Magenta Write-Host "Step 2: Building server ($serverTargetName)..." -ForegroundColor Magenta
# 指定了 -ServerName 就覆盖 TargetName,让输出落到 Bin\<名称>_x64.exe,
# 从而绕开正在运行的 Bin\Yama_x64.exe(被独占时链接会报 LNK1104)。
$serverMsBuildProps = @()
if ($ServerName) { $serverMsBuildProps += "/p:TargetName=$ServerName" }
foreach ($plat in $platforms) { foreach ($plat in $platforms) {
Build-Project -Project $serverProject -Configuration $Config -Platform $plat -ForceClean $Publish Build-Project -Project $serverProject -Configuration $Config -Platform $plat -ForceClean $Publish -ExtraProps $serverMsBuildProps
} }
# UPX compression in Publish mode # UPX compression in Publish mode
@@ -438,7 +474,7 @@ if ($Publish) {
Write-Host "" Write-Host ""
Write-Host "Step 3: UPX compression..." -ForegroundColor Magenta Write-Host "Step 3: UPX compression..." -ForegroundColor Magenta
$binPath = Join-Path (Join-Path $rootDir "Bin") "Yama_x64.exe" $binPath = Join-Path (Join-Path $rootDir "Bin") "${serverTargetName}_x64.exe"
if (-not (Test-Path $upxPath)) { if (-not (Test-Path $upxPath)) {
Write-Host "ERROR: UPX not found at $upxPath" -ForegroundColor Red Write-Host "ERROR: UPX not found at $upxPath" -ForegroundColor Red
@@ -490,13 +526,13 @@ if ($finalOutput) {
# Check both possible output locations (project has custom OutputFile) # Check both possible output locations (project has custom OutputFile)
$suffix = if ($plat -eq "x86") { "_x86" } else { "_x64" } $suffix = if ($plat -eq "x86") { "_x86" } else { "_x64" }
if ($Config -eq "Debug") { $suffix += "d" } if ($Config -eq "Debug") { $suffix += "d" }
$binPath = Join-Path (Join-Path $rootDir "Bin") "Yama$suffix.exe" $binPath = Join-Path (Join-Path $rootDir "Bin") "${serverTargetName}${suffix}.exe"
$outDir = if ($plat -eq "x86") { "Release" } else { "x64\Release" } $outDir = if ($plat -eq "x86") { "Release" } else { "x64\Release" }
if ($Config -eq "Debug") { if ($Config -eq "Debug") {
$outDir = if ($plat -eq "x86") { "Debug" } else { "x64\Debug" } $outDir = if ($plat -eq "x86") { "Debug" } else { "x64\Debug" }
} }
$stdPath = Join-Path (Join-Path $rootDir $outDir) "Yama.exe" $stdPath = Join-Path (Join-Path $rootDir $outDir) "${serverTargetName}.exe"
# Prefer Bin output, fallback to standard path # Prefer Bin output, fallback to standard path
$outPath = if (Test-Path $binPath) { $binPath } elseif (Test-Path $stdPath) { $stdPath } else { $null } $outPath = if (Test-Path $binPath) { $binPath } elseif (Test-Path $stdPath) { $stdPath } else { $null }
+73 -11
View File
@@ -44,7 +44,9 @@ CAudio::CAudio()
m_InAudioData[i] = new BYTE[m_ulBufferLength]; m_InAudioData[i] = new BYTE[m_ulBufferLength];
m_InAudioHeader[i] = new WAVEHDR; m_InAudioHeader[i] = new WAVEHDR;
m_OutAudioData[i] = new BYTE[m_ulBufferLength]; // 播放缓冲按 AUDIO_OUT_MAX(16 个 GSM 块 = 1040 字节)分配:一个包最多
// 交给 waveOut 这么多,超出的部分在 PlayBuffer 里分多次写。
m_OutAudioData[i] = new BYTE[AUDIO_OUT_MAX];
m_OutAudioHeader[i] = new WAVEHDR; m_OutAudioHeader[i] = new WAVEHDR;
} }
} }
@@ -88,9 +90,12 @@ CAudio::~CAudio()
if (m_bIsWaveOutUsed) { if (m_bIsWaveOutUsed) {
waveOutReset(m_hWaveOut); waveOutReset(m_hWaveOut);
// 这里原来 unprepare 的是 m_InAudioHeader —— 那是录音侧的头,而且上面
// 已经 delete 掉了(悬垂指针),unprepare 的对象完全错了。播放侧要收的是
// m_OutAudioHeader。
for (int i = 0; i < 2; ++i) { for (int i = 0; i < 2; ++i) {
if (m_InAudioHeader[i]) if (m_OutAudioHeader[i])
waveOutUnprepareHeader(m_hWaveOut, m_InAudioHeader[i], sizeof(WAVEHDR)); waveOutUnprepareHeader(m_hWaveOut, m_OutAudioHeader[i], sizeof(WAVEHDR));
} }
waveOutClose(m_hWaveOut); waveOutClose(m_hWaveOut);
} }
@@ -150,6 +155,13 @@ LPBYTE CAudio::GetRecordBuffer(LPDWORD dwBufferSize)
SetEvent(m_hStartRecord); SetEvent(m_hStartRecord);
WaitForSingleObject(m_hEventWaveIn, INFINITE); WaitForSingleObject(m_hEventWaveIn, INFINITE);
// 这里故意仍按 m_ulBufferLength(1000)整包返回,不用 dwBytesRecorded 裁短。
//
// waveIn 录 GSM610 时驱动只写整数个 65 字节块,1000 字节的缓冲实际只填 975,
// 尾部 25 字节是驱动从未写过的残留。看着像垃圾,但播放侧按块截断时会正好把
// 这 25 字节丢掉,所以它在线上是无害的;反过来,包长一旦小于 1000,老主控
// (v1.4.2 及更早)的 PlayBuffer 按 m_ulBufferLength 整块 memcpy 就会越界读,
// 读到的才是真垃圾。保持 1000 才能让新客户端连老主控。
*dwBufferSize = m_ulBufferLength; *dwBufferSize = m_ulBufferLength;
return m_InAudioData[m_nWaveInIndex]; //返出真正数据 return m_InAudioData[m_nWaveInIndex]; //返出真正数据
} }
@@ -196,14 +208,60 @@ DWORD WINAPI CAudio::waveInCallBack(LPVOID lParam)
BOOL CAudio::PlayBuffer(LPBYTE szBuffer, DWORD dwBufferSize) BOOL CAudio::PlayBuffer(LPBYTE szBuffer, DWORD dwBufferSize)
{ {
if (!m_bIsWaveOutUsed && !InitializeWaveOut()) //1 音频格式 2 播音设备 if (!m_bIsWaveOutUsed && !InitializeWaveOut()) //1 音频格式 2 播音设备
return NULL; return FALSE;
if (!szBuffer || !dwBufferSize)
return FALSE;
for (int i = 0; i < dwBufferSize; i += m_ulBufferLength) { // 按包截断到整数个 65 字节块,余数直接丢弃 —— 不能攒到下一包。
memcpy(m_OutAudioData[m_nWaveOutIndex], szBuffer, m_ulBufferLength); //
waveOutWrite(m_hWaveOut, m_OutAudioHeader[m_nWaveOutIndex], sizeof(WAVEHDR)); // waveOut 只转换整块,末尾不足一块的字节既不转换也不保留。曾经的写法是把
m_nWaveOutIndex = 1 - m_nWaveOutIndex; // 余数攒起来跨包拼接(当成一条连续的流处理),在 Android 那种「包与包之间
// 连续」的上行流上是对的,却把既有 Windows 客户端的监听整条搞成了噪声:
// Windows 主机用 waveIn 录 GSM610,1000 字节的缓冲驱动只写 975 字节,尾部
// 25 字节是驱动从未写过的堆残留,客户端把这 1000 字节整包发上来。攒余数就
// 等于每 1000 字节往 GSM 流里插进 25 字节垃圾,块边界从第二包起全部错位。
// 按包截断则正好丢掉这 25 字节残留,和老版本行为一致。
//
// 代价是发送侧必须保证「一个包 = 整数个块」:Windows 端天然满足(驱动只写
// 整块),Android 端见 AudioHandler.h 的 975 字节整块打包。
DWORD n = (dwBufferSize / AUDIO_GSM_BLOCK) * AUDIO_GSM_BLOCK;
if (n == 0)
return FALSE;
// 一个包可能超过一块播放缓冲,分多次写。AUDIO_OUT_MAX 本身是 65 的整数倍,
// 所以每一段都是整块。
for (DWORD off = 0; off < n; off += AUDIO_OUT_MAX) {
DWORD len = n - off;
if (len > AUDIO_OUT_MAX)
len = AUDIO_OUT_MAX;
if (!WriteAligned(szBuffer + off, len))
break; // 设备忙:剩下的整块丢掉,丢整块不会破坏对齐
} }
return true; return TRUE;
}
// 把 len 字节(必须是 65 的整数倍)交给 waveOut。两个缓冲轮转,还在队列里的不能
// 复用:waveOutWrite 会返回 WAVERR_BUSY 且数据被静默丢弃,原实现忽略返回值,
// 丢包没有任何痕迹。
BOOL CAudio::WriteAligned(LPBYTE p, DWORD len)
{
if (!p || len == 0 || len > AUDIO_OUT_MAX ||
(len % AUDIO_GSM_BLOCK) != 0)
return FALSE;
LPWAVEHDR h = m_OutAudioHeader[m_nWaveOutIndex];
if (h->dwFlags & WHDR_INQUEUE)
return FALSE;
memcpy(m_OutAudioData[m_nWaveOutIndex], p, len);
h->dwBufferLength = len;
MMRESULT mmResult = waveOutWrite(m_hWaveOut, h, sizeof(WAVEHDR));
if (mmResult != MMSYSERR_NOERROR) {
Mprintf("waveOutWrite(%lu) failed: %u\n", len, (unsigned)mmResult);
return FALSE;
}
m_nWaveOutIndex = 1 - m_nWaveOutIndex;
return TRUE;
} }
BOOL CAudio::InitializeWaveOut() BOOL CAudio::InitializeWaveOut()
@@ -212,16 +270,20 @@ BOOL CAudio::InitializeWaveOut()
return FALSE; return FALSE;
for (int i = 0; i < 2; ++i) for (int i = 0; i < 2; ++i)
memset(m_OutAudioData[i], 0, m_ulBufferLength); //声音数据 memset(m_OutAudioData[i], 0, AUDIO_OUT_MAX); //声音数据
MMRESULT mmResult; MMRESULT mmResult;
mmResult = waveOutOpen(&m_hWaveOut, (WORD)WAVE_MAPPER, &(m_GSMWavefmt.wfx), (LONG)0, (LONG)0, CALLBACK_NULL); mmResult = waveOutOpen(&m_hWaveOut, (WORD)WAVE_MAPPER, &(m_GSMWavefmt.wfx), (LONG)0, (LONG)0, CALLBACK_NULL);
if (mmResult != MMSYSERR_NOERROR) if (mmResult != MMSYSERR_NOERROR)
return false; return false;
m_nWaveOutIndex = 0;
for (int i = 0; i < 2; ++i) { for (int i = 0; i < 2; ++i) {
m_OutAudioHeader[i]->lpData = (LPSTR)m_OutAudioData[i]; m_OutAudioHeader[i]->lpData = (LPSTR)m_OutAudioData[i];
m_OutAudioHeader[i]->dwBufferLength = m_ulBufferLength; // 按最大容量 prepare;实际每次写入的长度在 WriteAligned 里按整块数设置,
// 只会更短,不会越过这块缓冲。
m_OutAudioHeader[i]->dwBufferLength = AUDIO_OUT_MAX;
m_OutAudioHeader[i]->dwFlags = 0; m_OutAudioHeader[i]->dwFlags = 0;
m_OutAudioHeader[i]->dwLoops = 0; m_OutAudioHeader[i]->dwLoops = 0;
waveOutPrepareHeader(m_hWaveOut, m_OutAudioHeader[i], sizeof(WAVEHDR)); waveOutPrepareHeader(m_hWaveOut, m_OutAudioHeader[i], sizeof(WAVEHDR));
+12
View File
@@ -11,6 +11,16 @@
#include <MMSYSTEM.H> #include <MMSYSTEM.H>
#include <MMReg.h> #include <MMReg.h>
// GSM610 的 ACM 编解码器按 65 字节块(wfx.nBlockAlign)工作。waveOutWrite /
// waveIn 对末尾不足一块的字节既不转换也不保留,直接丢弃 —— 实测 4 个 1000 字节
// 缓冲只播出 15360 采样(少 640),而 4 个 975 字节缓冲正好 16000。
//
// 所以线协议的不变式是:**一个音频包必须由整数个 65 字节块组成**。
// 播放侧按包截断、余数丢弃(见 Audio.cpp 的 PlayBuffer);发送侧各自保证自己
// 发出去的包是整块(Windows 端 waveIn 驱动本来就只写整块,Android 端见
// AudioHandler.h)。余数绝不能攒到下一包 —— 原因见 PlayBuffer 的注释。
#define AUDIO_GSM_BLOCK 65
#define AUDIO_OUT_MAX (16 * AUDIO_GSM_BLOCK) // 1040 = 16 块 = 640ms
class CAudio class CAudio
{ {
@@ -40,6 +50,8 @@ public:
LPBYTE m_OutAudioData[2]; //两个数据 保持声音的连续 LPBYTE m_OutAudioData[2]; //两个数据 保持声音的连续
BOOL PlayBuffer(LPBYTE szBuffer, DWORD dwBufferSize); BOOL PlayBuffer(LPBYTE szBuffer, DWORD dwBufferSize);
BOOL InitializeWaveOut(); BOOL InitializeWaveOut();
// 把整块数据交给 waveOut。两个缓冲轮转,还在队列里的不能复用
BOOL WriteAligned(LPBYTE p, DWORD len);
}; };
#endif // !defined(AFX_AUDIO_H__56854DE7_5FE4_486F_9AFC_CE3726EF7CBC__INCLUDED_) #endif // !defined(AFX_AUDIO_H__56854DE7_5FE4_486F_9AFC_CE3726EF7CBC__INCLUDED_)