feat: 打通音频整链,被控端送 PCM、主控端 waveOut 播放

- android_receiver:音频改为直接送 PCM16(FLAG_PCM=0x80),不再走 Opus 编码
  (仓库未打包 libopus,MediaCodec Opus 多数设备不可用,主控端也无解码器)
- rust_core:新增 media/audio 播放队列(上限 1 秒、按帧对齐切分、超出丢最旧)
- rust_core:音频分片校验 MAC 后按 FLAG_PCM 入队,旧 Opus 包明确丢弃并记日志
- rust_core:新增 ttstd_audio_next / ttstd_audio_pending / ttstd_audio_stats
- flutter_sender:新增 audio_player(waveOut)轮询播放队列,有数据才打开设备、静音 3 秒自动关闭
- docs:README 增加音频链路章节与 PCM 取舍,AGENTS 记录 FLAG_PCM 约定
This commit is contained in:
tongtong committed 2026-11-27 21:15:17 +08:00
1 parent c6925d0890
commit 37b2cff82b
14 files changed
+468 -19

No files matched your search

@@ -7,6 +7,7 @@ project(runner LANGUAGES CXX)
#
# Any new source files that you add to the application should be added here.
add_executable(${BINARY_NAME} WIN32
"audio_player.cpp"
"flutter_window.cpp"
"main.cpp"
"utils.cpp"
@@ -43,6 +44,8 @@ target_link_libraries(${BINARY_NAME} PRIVATE flutter_wrapper_plugin)
target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib")
# Media Foundation:H.264/HEVC 解码到 Flutter 外部纹理。
target_link_libraries(${BINARY_NAME} PRIVATE "mfplat.lib" "mfuuid.lib" "mf.lib" "ole32.lib")
# 音频播放:waveOut 输出 Rust Core 队列里的 PCM。
target_link_libraries(${BINARY_NAME} PRIVATE "winmm.lib")
target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}")
# Run the Flutter tool portions of the build. This must not be removed.
@@ -0,0 +1,224 @@
#include "audio_player.h"
#include <windows.h>
// windows.h 之后:waveOut* 系列与 WAVEHDR 都在 winmm。
#include <mmsystem.h>
#include <atomic>
#include <cstdint>
#include <memory>
#include <string>
#include <thread>
#include <vector>
namespace {
// 与被控端 AudioPlaybackCapture 的格式保持一致。
constexpr int kSampleRate = 48000;
constexpr int kChannels = 2;
constexpr int kBitsPerSample = 16;
constexpr int kBytesPerSecond =
kSampleRate * kChannels * (kBitsPerSample / 8);
// 每块 20ms,既够小(延迟低)又能吸收 HTTP 抖动。
constexpr int kBufferBytes = kBytesPerSecond / 50;
constexpr int kBufferCount = 8;
// 这么久没新数据就关掉设备:投屏停了不该继续占着音频端点。
constexpr DWORD kIdleCloseMs = 3000;
constexpr DWORD kPollIntervalMs = 5;
std::atomic<bool> g_running{false};
std::thread g_thread;
// Rust Core 暴露的音频队列读取接口。
class RustAudioApi {
public:
using NextFn = int32_t (*)(uint8_t*, size_t);
using PendingFn = uint32_t (*)();
bool EnsureLoaded() {
if (loaded_) {
return true;
}
HMODULE module = GetModuleHandleW(L"ttstdconnect_core.dll");
if (module == nullptr) {
wchar_t exe_path[MAX_PATH] = {};
const DWORD length = GetModuleFileNameW(nullptr, exe_path, MAX_PATH);
if (length > 0 && length < MAX_PATH) {
std::wstring directory(exe_path, length);
const size_t slash = directory.find_last_of(L"\\/");
if (slash != std::wstring::npos) {
directory.resize(slash + 1);
module = LoadLibraryW(
(directory + L"ttstdconnect_core.dll").c_str());
}
}
}
if (module == nullptr) {
return false;
}
next_ = reinterpret_cast<NextFn>(
GetProcAddress(module, "ttstd_audio_next"));
pending_ = reinterpret_cast<PendingFn>(
GetProcAddress(module, "ttstd_audio_pending"));
// 老版本 Core 没有音频导出:静默降级成「没有音频」,不影响视频。
loaded_ = next_ != nullptr && pending_ != nullptr;
return loaded_;
}
uint32_t Pending() const {
return (loaded_ && pending_ != nullptr) ? pending_() : 0;
}
int32_t Next(uint8_t* buffer, size_t capacity) const {
if (!loaded_ || next_ == nullptr) {
return 0;
}
return next_(buffer, capacity);
}
private:
bool loaded_ = false;
NextFn next_ = nullptr;
PendingFn pending_ = nullptr;
};
struct Buffer {
std::vector<uint8_t> data;
WAVEHDR header{};
bool queued = false;
bool prepared = false;
};
void CloseDevice(HWAVEOUT* device, Buffer* buffers) {
if (*device == nullptr) {
return;
}
waveOutReset(*device);
for (int index = 0; index < kBufferCount; ++index) {
if (buffers[index].prepared) {
waveOutUnprepareHeader(*device, &buffers[index].header,
sizeof(WAVEHDR));
buffers[index].prepared = false;
}
buffers[index].queued = false;
}
waveOutClose(*device);
*device = nullptr;
}
bool OpenDevice(HWAVEOUT* device, Buffer* buffers) {
WAVEFORMATEX format{};
format.wFormatTag = WAVE_FORMAT_PCM;
format.nChannels = static_cast<WORD>(kChannels);
format.nSamplesPerSec = static_cast<DWORD>(kSampleRate);
format.wBitsPerSample = static_cast<WORD>(kBitsPerSample);
format.nBlockAlign =
static_cast<WORD>(kChannels * (kBitsPerSample / 8));
format.nAvgBytesPerSec = static_cast<DWORD>(kBytesPerSecond);
format.cbSize = 0;
HWAVEOUT opened = nullptr;
if (waveOutOpen(&opened, WAVE_MAPPER, &format, 0, 0, CALLBACK_NULL) !=
MMSYSERR_NOERROR) {
return false;
}
for (int index = 0; index < kBufferCount; ++index) {
Buffer& buffer = buffers[index];
buffer.data.assign(kBufferBytes, 0);
buffer.header = WAVEHDR{};
buffer.header.lpData = reinterpret_cast<LPSTR>(buffer.data.data());
buffer.header.dwBufferLength = static_cast<DWORD>(kBufferBytes);
if (waveOutPrepareHeader(opened, &buffer.header, sizeof(WAVEHDR)) !=
MMSYSERR_NOERROR) {
CloseDevice(&opened, buffers);
return false;
}
buffer.prepared = true;
buffer.queued = false;
}
*device = opened;
return true;
}
void RunLoop() {
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
RustAudioApi api;
bool api_checked = false;
HWAVEOUT device = nullptr;
std::unique_ptr<Buffer[]> buffers(new Buffer[kBufferCount]);
ULONGLONG last_data_at = GetTickCount64();
while (g_running.load()) {
if (!api_checked) {
if (!api.EnsureLoaded()) {
// Core 还没加载好(Dart 可能尚未调用 FFI),稍后再试。
Sleep(500);
continue;
}
api_checked = true;
}
if (device == nullptr) {
if (api.Pending() > 0 && OpenDevice(&device, buffers.get())) {
last_data_at = GetTickCount64();
} else {
Sleep(kPollIntervalMs);
continue;
}
}
bool fed = false;
for (int index = 0; index < kBufferCount; ++index) {
Buffer& buffer = buffers[index];
if (buffer.queued && (buffer.header.dwFlags & WHDR_DONE) != 0) {
buffer.queued = false;
}
if (buffer.queued) {
continue;
}
const int32_t read =
api.Next(buffer.data.data(), buffer.data.size());
if (read <= 0) {
continue;
}
buffer.header.dwBufferLength = static_cast<DWORD>(read);
buffer.header.dwFlags = 0;
buffer.header.dwLoops = 0;
if (waveOutWrite(device, &buffer.header, sizeof(WAVEHDR)) ==
MMSYSERR_NOERROR) {
buffer.queued = true;
fed = true;
last_data_at = GetTickCount64();
}
}
if (!fed && api.Pending() == 0 &&
GetTickCount64() - last_data_at > kIdleCloseMs) {
CloseDevice(&device, buffers.get());
}
Sleep(kPollIntervalMs);
}
CloseDevice(&device, buffers.get());
}
} // namespace
void StartAudioPlayer() {
if (g_running.exchange(true)) {
return;
}
g_thread = std::thread(RunLoop);
}
void StopAudioPlayer() {
if (!g_running.exchange(false)) {
return;
}
if (g_thread.joinable()) {
g_thread.join();
}
}
@@ -0,0 +1,12 @@
#ifndef RUNNER_AUDIO_PLAYER_H_
#define RUNNER_AUDIO_PLAYER_H_
// 播放 Rust Core 音频队列里的 PCM(48 kHz / 双声道 / 16 bit 小端)。
//
// 和视频纹理一样由 runner 自己起线程轮询 FFI 队列:
// - 有数据才打开 waveOut,静音 3 秒自动关闭,不长期占用音频设备;
// - 不依赖 Dart 侧参与,投屏开始/结束无需额外通道。
void StartAudioPlayer();
void StopAudioPlayer();
#endif // RUNNER_AUDIO_PLAYER_H_
@@ -2,6 +2,7 @@
#include <optional>
#include "audio_player.h"
#include "flutter/generated_plugin_registrant.h"
#include "video_texture.h"
@@ -29,6 +30,8 @@ bool FlutterWindow::OnCreate() {
// 视频解码纹理:把 Rust Core 收到的视频帧解码后交给 Flutter 的 Texture 组件。
RegisterVideoTexturePlugin(
flutter_controller_->engine()->GetRegistrarForPlugin("TTSTDVideoTexture"));
// 音频播放:轮询 Rust Core 的 PCM 队列,用 waveOut 直接出声。
StartAudioPlayer();
SetChildContent(flutter_controller_->view()->GetNativeWindow());
flutter_controller_->engine()->SetNextFrameCallback([&]() {
@@ -44,6 +47,7 @@ bool FlutterWindow::OnCreate() {
}
void FlutterWindow::OnDestroy() {
StopAudioPlayer();
if (flutter_controller_) {
flutter_controller_ = nullptr;
}