From 0cff2b011a242070e37cab5cbf40f48e43ef02d3 Mon Sep 17 00:00:00 2001 From: tongtongstudio Date: Fri, 27 Nov 2026 09:28:46 +0800 Subject: [PATCH] =?UTF-8?q?feat(sender):=20=E6=94=AF=E6=8C=81=E6=8A=8A?= =?UTF-8?q?=E4=B8=B2=E6=B5=81=E7=94=BB=E9=9D=A2=E5=BC=B9=E5=87=BA=E4=B8=BA?= =?UTF-8?q?=E7=8B=AC=E7=AB=8B=E5=8E=9F=E7=94=9F=E7=AA=97=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 windows/runner/video_window.{h,cpp}:Win32 顶层窗口,GDI 直接绘制解码后的 BGRA 帧,支持拖到任意显示器/最大化/双击或 F11 全屏/ESC 退出 - FrameStore 增加 Snapshot()(shared_ptr 保活),独立窗口与主窗口共享同一份帧,不重复解码、不抢 Rust 单消费者帧队列 - 独立窗口在播时跳过 MarkTextureFrameAvailable,省一次 BGRA 拷贝;主界面显示占位提示 - ttstd/video 通道新增 openWindow/closeWindow/windowOpen,stats 带 windowOpen - VideoView 按真实码流宽高算显示比例,竖屏投屏不再被压成 16:9 --- README.md | 10 +- flutter_sender/lib/core/bridge.dart | 23 ++ .../lib/features/media/video_view.dart | 27 ++- flutter_sender/lib/main.dart | 45 +++- flutter_sender/windows/runner/CMakeLists.txt | 1 + .../windows/runner/video_texture.cpp | 39 +++ .../windows/runner/video_window.cpp | 225 ++++++++++++++++++ flutter_sender/windows/runner/video_window.h | 53 +++++ 8 files changed, 419 insertions(+), 4 deletions(-) create mode 100644 flutter_sender/windows/runner/video_window.cpp create mode 100644 flutter_sender/windows/runner/video_window.h diff --git a/README.md b/README.md index ec3031b..1e2877d 100644 --- a/README.md +++ b/README.md @@ -430,7 +430,15 @@ POST /mirror/request?token= 触发一次投屏确认(便 - **Android 被控**:MediaProjection 每次连接弹授权框(系统限制);免 root 控制只能走 Accessibility,延迟高 - **iOS 被控**:❌ 不做,无系统级采集 API -- **主控端**:Flutter 四端全覆盖,视频 External Texture(Win: D3D11→DXGI 共享;mac: CVPixelBuffer→Metal;Linux: glTexSubImage2D;Android/iOS: 平台纹理) +- **主控端**:Flutter 四端全覆盖,视频 External Texture(Win: 当前为 CPU BGRA + GDI,可升级 D3D11→DXGI 共享;mac: CVPixelBuffer→Metal;Linux: glTexSubImage2D;Android/iOS: 平台纹理) + +### 8.1 Windows 串流独立窗口 + +主界面右上角「串流独立窗口」按钮通过 `ttstd/video` 方法通道(`openWindow` / `closeWindow` / `windowOpen`)拉起一个**原生 Win32 顶层窗口**(`windows/runner/video_window.cpp`),由 GDI 直接绘制解码后的 BGRA 帧: + +- 与主窗口共用同一个 `FrameStore`(`Snapshot()` 返回 `shared_ptr` 保证绘制期间帧不被回收),不额外解码、不再抢 Rust 的单消费者帧队列。 +- 独立窗口在播时不再驱动 Flutter 纹理,省一次 BGRA 拷贝;主界面显示「画面已在独立窗口播放」占位。 +- 支持拖到第二块显示器、最大化、双击/F11 全屏、ESC 退出;按真实码流宽高做 letterbox,竖屏不拉伸。 - **Wayland 主控**:Flutter 本身走 EGL 没问题,只是未来若加 Linux 被控才需要处理 PipeWire portal --- diff --git a/flutter_sender/lib/core/bridge.dart b/flutter_sender/lib/core/bridge.dart index d72d49e..48f7eb1 100644 --- a/flutter_sender/lib/core/bridge.dart +++ b/flutter_sender/lib/core/bridge.dart @@ -269,6 +269,29 @@ class SenderBridge { } } + /// 把串流画面弹出为独立原生窗口(Windows);返回是否成功。 + Future openVideoWindow() async { + try { + final opened = await _video.invokeMethod('openWindow'); + return opened ?? false; + } on MissingPluginException { + return false; + } on PlatformException { + return false; + } + } + + /// 关闭独立串流窗口,把画面收回主窗口。 + Future closeVideoWindow() async { + try { + await _video.invokeMethod('closeWindow'); + } on MissingPluginException { + // 老构建没有独立窗口能力。 + } on PlatformException { + // 关闭失败无需打扰用户。 + } + } + Future pairingUri() async { try { final value = await _method.invokeMethod('pairingUri'); diff --git a/flutter_sender/lib/features/media/video_view.dart b/flutter_sender/lib/features/media/video_view.dart index 3b196a7..3bd8423 100644 --- a/flutter_sender/lib/features/media/video_view.dart +++ b/flutter_sender/lib/features/media/video_view.dart @@ -8,6 +8,8 @@ class VideoView extends StatelessWidget { this.resolution = '', this.pts, this.error = '', + this.standalone = false, + this.aspectRatio = 16 / 9, }); final int? textureId; @@ -18,11 +20,17 @@ class VideoView extends StatelessWidget { /// 原生解码链路的失败原因,为空表示没有错误。 final String error; + /// 画面已弹出到独立窗口:主界面不再渲染纹理,只显示提示。 + final bool standalone; + + /// 按实际码流宽高算出的比例(竖屏投屏时不再是 16:9)。 + final double aspectRatio; + @override Widget build(BuildContext context) { final theme = Theme.of(context); return AspectRatio( - aspectRatio: 16 / 9, + aspectRatio: aspectRatio > 0 ? aspectRatio : 16 / 9, child: ClipRRect( borderRadius: BorderRadius.circular(16), child: DecoratedBox( @@ -39,7 +47,22 @@ class VideoView extends StatelessWidget { child: Stack( fit: StackFit.expand, children: [ - if (textureId != null) + if (standalone) + Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.open_in_new, + size: 72, + color: theme.colorScheme.primary.withValues(alpha: 0.6)), + const SizedBox(height: 12), + Text('画面已在独立窗口播放', style: theme.textTheme.titleMedium), + const SizedBox(height: 4), + Text('把它拖到任意显示器,双击可全屏;关闭独立窗口后画面回到这里', + style: theme.textTheme.bodySmall, + textAlign: TextAlign.center), + ], + ) + else if (textureId != null) Texture(textureId: textureId!) else Column( diff --git a/flutter_sender/lib/main.dart b/flutter_sender/lib/main.dart index 3dc7d58..c5575da 100644 --- a/flutter_sender/lib/main.dart +++ b/flutter_sender/lib/main.dart @@ -60,6 +60,8 @@ class _HomePageState extends State { Map _demoStatus = const {'running': false}; Map _videoStats = const {}; int? _textureId; + /// 串流画面是否已弹出到独立原生窗口。 + bool _videoWindowOpen = false; String? _nativeError; @override @@ -153,14 +155,37 @@ class _HomePageState extends State { final stats = await _bridge.videoStats(); if (!mounted || stats.isEmpty) return; final id = stats['textureId']; + final windowOpen = stats['windowOpen']; setState(() { _videoStats = stats; if (_textureId == null && id is int && id > 0) { _textureId = id; } + if (windowOpen is bool) { + _videoWindowOpen = windowOpen; + } }); } + /// 把串流画面弹出/收回独立原生窗口(Windows)。 + Future _toggleVideoWindow() async { + if (_videoWindowOpen) { + await _bridge.closeVideoWindow(); + if (!mounted) return; + setState(() => _videoWindowOpen = false); + return; + } + final opened = await _bridge.openVideoWindow(); + if (!mounted) return; + if (!opened) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('当前平台不支持独立串流窗口')), + ); + return; + } + setState(() => _videoWindowOpen = true); + } + void _writeDiagnosticLog() { Map status; if (_nativeCore == null) { @@ -327,6 +352,11 @@ class _HomePageState extends State { appBar: AppBar( title: const Text('TTSTD Connect'), actions: [ + IconButton( + tooltip: _videoWindowOpen ? '收回串流窗口' : '串流独立窗口', + onPressed: _toggleVideoWindow, + icon: Icon(_videoWindowOpen ? Icons.close_fullscreen : Icons.open_in_new), + ), IconButton( tooltip: '扫码配对', onPressed: _showPairing, @@ -510,6 +540,16 @@ class _HomePageState extends State { String get _videoError => (_videoStats['error'] as String? ?? '').trim(); + /// 按实际码流宽高算显示比例;竖屏被控端(如 1080x2400)不再被压成 16:9。 + double get _videoAspectRatio { + final width = _videoStats['width']; + final height = _videoStats['height']; + if (width is int && height is int && width > 0 && height > 0) { + return width / height; + } + return 16 / 9; + } + Widget _buildStage() { return Padding( padding: const EdgeInsets.all(16), @@ -517,11 +557,14 @@ class _HomePageState extends State { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ VideoView( - textureId: _textureId, + // 独立窗口在播时不再占用主窗口纹理。 + textureId: _videoWindowOpen ? null : _textureId, connected: _phase.isConnected, resolution: _videoResolution, pts: _videoPts, error: _videoError, + standalone: _videoWindowOpen, + aspectRatio: _videoAspectRatio, ), const SizedBox(height: 16), ConnectBar( diff --git a/flutter_sender/windows/runner/CMakeLists.txt b/flutter_sender/windows/runner/CMakeLists.txt index 25cd32a..8e9f275 100644 --- a/flutter_sender/windows/runner/CMakeLists.txt +++ b/flutter_sender/windows/runner/CMakeLists.txt @@ -11,6 +11,7 @@ add_executable(${BINARY_NAME} WIN32 "main.cpp" "utils.cpp" "video_texture.cpp" + "video_window.cpp" "win32_window.cpp" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" "Runner.rc" diff --git a/flutter_sender/windows/runner/video_texture.cpp b/flutter_sender/windows/runner/video_texture.cpp index 96db538..9594f18 100644 --- a/flutter_sender/windows/runner/video_texture.cpp +++ b/flutter_sender/windows/runner/video_texture.cpp @@ -1,5 +1,7 @@ #include "video_texture.h" +#include "video_window.h" + #include #include #include @@ -262,6 +264,18 @@ class FrameStore { return frames_; } + // 独立窗口使用:返回当前帧的共享所有权快照。 + // 拿到 shared_ptr 后即使解码线程继续 Publish,绘制期间的帧也不会被回收。 + std::shared_ptr> Snapshot(int* width, int* height) { + std::lock_guard lock(mutex_); + if (!front_ || front_->empty() || width_ <= 0 || height_ <= 0) { + return nullptr; + } + *width = width_; + *height = height_; + return front_; + } + uint64_t pts() { std::lock_guard lock(mutex_); return pts_; @@ -860,6 +874,22 @@ class VideoTexturePlugin : public flutter::Plugin { static_cast(texture_id_))); return; } + if (call.method_name() == "openWindow") { + auto store = frames_; + const bool opened = video_window_.Open( + [store](int* width, int* height) { return store->Snapshot(width, height); }); + result->Success(flutter::EncodableValue(opened)); + return; + } + if (call.method_name() == "closeWindow") { + video_window_.Close(); + result->Success(flutter::EncodableValue(true)); + return; + } + if (call.method_name() == "windowOpen") { + result->Success(flutter::EncodableValue(video_window_.IsOpen())); + return; + } if (call.method_name() == "stats") { flutter::EncodableMap map; int width = 0; @@ -886,6 +916,8 @@ class VideoTexturePlugin : public flutter::Plugin { // 这里显式指出,避免和「还没等到关键帧」或「没收到码流」混为一谈。 error = "被控端码流缺少 SPS/PPS,请更新被控端 APK 后重连"; } + map[flutter::EncodableValue("windowOpen")] = + flutter::EncodableValue(video_window_.IsOpen()); map[flutter::EncodableValue("error")] = flutter::EncodableValue(error); map[flutter::EncodableValue("format")] = flutter::EncodableValue(static_cast(last_format_)); @@ -978,6 +1010,11 @@ class VideoTexturePlugin : public flutter::Plugin { return [this, store](std::shared_ptr> frame, int width, int height, uint64_t pts) { store->Publish(std::move(frame), width, height, pts); + if (video_window_.IsOpen()) { + // 画面已经在独立窗口里,没必要再驱动 Flutter 纹理(省一次 BGRA 拷贝)。 + video_window_.OnFrameAvailable(); + return; + } if (texture_registrar_ != nullptr && texture_id_ != 0) { texture_registrar_->MarkTextureFrameAvailable(texture_id_); } @@ -990,6 +1027,8 @@ class VideoTexturePlugin : public flutter::Plugin { std::unique_ptr> channel_; FlutterDesktopPixelBuffer descriptor_ = {}; std::shared_ptr frames_; + // 与主窗口纹理共享同一份 FrameStore 的独立串流窗口。 + VideoWindow video_window_; RustVideoApi api_; VideoDecoder decoder_; std::atomic stop_{false}; diff --git a/flutter_sender/windows/runner/video_window.cpp b/flutter_sender/windows/runner/video_window.cpp new file mode 100644 index 0000000..56fa301 --- /dev/null +++ b/flutter_sender/windows/runner/video_window.cpp @@ -0,0 +1,225 @@ +#include "video_window.h" + +#include + +namespace { + +constexpr wchar_t kWindowClass[] = L"TTSTDVideoWindowClass"; +constexpr wchar_t kWindowTitle[] = L"TTSTD 串流"; +// 解码线程 -> 窗口线程:有新帧,触发一次重绘。 +constexpr UINT kMsgFrameReady = WM_APP + 0x51; + +} // namespace + +VideoWindow::VideoWindow() = default; + +VideoWindow::~VideoWindow() { + Close(); +} + +bool VideoWindow::Open(FrameProvider provider) { + provider_ = std::move(provider); + if (hwnd_ != nullptr) { + ShowWindow(hwnd_, SW_SHOWNORMAL); + SetForegroundWindow(hwnd_); + return true; + } + + HINSTANCE instance = GetModuleHandleW(nullptr); + WNDCLASSEXW window_class = {}; + window_class.cbSize = sizeof(WNDCLASSEXW); + window_class.style = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS; + window_class.lpfnWndProc = &VideoWindow::StaticWndProc; + window_class.hInstance = instance; + window_class.hCursor = LoadCursorW(nullptr, IDC_ARROW); + // 背景由 WM_PAINT 自己填黑,避免无画面时闪白。 + window_class.hbrBackground = nullptr; + window_class.lpszClassName = kWindowClass; + if (RegisterClassExW(&window_class) == 0 && + GetLastError() != ERROR_CLASS_ALREADY_EXISTS) { + provider_ = nullptr; + return false; + } + + RECT rect = {0, 0, 1280, 720}; + AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, FALSE); + HWND hwnd = CreateWindowExW( + 0, kWindowClass, kWindowTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, + CW_USEDEFAULT, rect.right - rect.left, rect.bottom - rect.top, nullptr, + nullptr, instance, this); + if (hwnd == nullptr) { + provider_ = nullptr; + return false; + } + + hwnd_ = hwnd; + open_.store(true); + ShowWindow(hwnd_, SW_SHOWNORMAL); + UpdateWindow(hwnd_); + return true; +} + +void VideoWindow::Close() { + if (hwnd_ != nullptr) { + DestroyWindow(hwnd_); + hwnd_ = nullptr; + } + open_.store(false); + repaint_pending_.store(false); + provider_ = nullptr; + full_screen_ = false; +} + +void VideoWindow::OnFrameAvailable() { + if (!open_.load()) { + return; + } + HWND hwnd = hwnd_; + if (hwnd == nullptr) { + return; + } + // 上一帧的重绘还没处理完就不再投递,避免高频视频把消息队列塞满。 + if (repaint_pending_.exchange(true)) { + return; + } + if (!PostMessageW(hwnd, kMsgFrameReady, 0, 0)) { + repaint_pending_.store(false); + } +} + +LRESULT CALLBACK VideoWindow::StaticWndProc(HWND hwnd, UINT message, + WPARAM wparam, LPARAM lparam) { + if (message == WM_NCCREATE) { + auto* create = reinterpret_cast(lparam); + SetWindowLongPtrW(hwnd, GWLP_USERDATA, + reinterpret_cast(create->lpCreateParams)); + } + auto* self = + reinterpret_cast(GetWindowLongPtrW(hwnd, GWLP_USERDATA)); + if (self != nullptr) { + return self->WndProc(hwnd, message, wparam, lparam); + } + return DefWindowProcW(hwnd, message, wparam, lparam); +} + +LRESULT VideoWindow::WndProc(HWND hwnd, UINT message, WPARAM wparam, + LPARAM lparam) { + switch (message) { + case WM_PAINT: + Paint(); + return 0; + case WM_ERASEBKGND: + // Paint() 内部整块填黑,这里跳过默认擦除以减少闪烁。 + return 1; + case kMsgFrameReady: + repaint_pending_.store(false); + InvalidateRect(hwnd, nullptr, FALSE); + return 0; + case WM_SIZE: + InvalidateRect(hwnd, nullptr, FALSE); + return 0; + case WM_LBUTTONDBLCLK: + ToggleFullScreen(); + return 0; + case WM_KEYDOWN: + if (wparam == VK_ESCAPE) { + if (full_screen_) { + ToggleFullScreen(); + } else { + SendMessageW(hwnd, WM_CLOSE, 0, 0); + } + return 0; + } + if (wparam == VK_F11 || wparam == 'F') { + ToggleFullScreen(); + return 0; + } + break; + case WM_CLOSE: + DestroyWindow(hwnd); + return 0; + case WM_DESTROY: + hwnd_ = nullptr; + open_.store(false); + repaint_pending_.store(false); + provider_ = nullptr; + full_screen_ = false; + return 0; + default: + break; + } + return DefWindowProcW(hwnd, message, wparam, lparam); +} + +void VideoWindow::Paint() { + PAINTSTRUCT paint = {}; + HDC hdc = BeginPaint(hwnd_, &paint); + + RECT client = {}; + GetClientRect(hwnd_, &client); + FillRect(hdc, &client, static_cast(GetStockObject(BLACK_BRUSH))); + + int width = 0; + int height = 0; + std::shared_ptr> frame = + provider_ ? provider_(&width, &height) : nullptr; + + const int client_width = client.right - client.left; + const int client_height = client.bottom - client.top; + if (frame && !frame->empty() && width > 0 && height > 0 && client_width > 0 && + client_height > 0) { + // 保持宽高比,四周留黑边(竖屏串流不会被拉伸)。 + const double scale = std::min( + static_cast(client_width) / static_cast(width), + static_cast(client_height) / static_cast(height)); + const int draw_width = (std::max)(1, static_cast(width * scale)); + const int draw_height = (std::max)(1, static_cast(height * scale)); + const int offset_x = client.left + (client_width - draw_width) / 2; + const int offset_y = client.top + (client_height - draw_height) / 2; + + BITMAPINFO info = {}; + info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); + info.bmiHeader.biWidth = width; + // 负高度 = 顶向下 DIB,与解码输出的内存布局一致。 + info.bmiHeader.biHeight = -height; + info.bmiHeader.biPlanes = 1; + info.bmiHeader.biBitCount = 32; + info.bmiHeader.biCompression = BI_RGB; + + SetStretchBltMode(hdc, COLORONCOLOR); + StretchDIBits(hdc, offset_x, offset_y, draw_width, draw_height, 0, 0, width, + height, frame->data(), &info, DIB_RGB_COLORS, SRCCOPY); + } + + EndPaint(hwnd_, &paint); +} + +void VideoWindow::ToggleFullScreen() { + if (hwnd_ == nullptr) { + return; + } + if (!full_screen_) { + saved_style_ = GetWindowLongW(hwnd_, GWL_STYLE); + saved_placement_.length = sizeof(saved_placement_); + GetWindowPlacement(hwnd_, &saved_placement_); + + MONITORINFO monitor = {}; + monitor.cbSize = sizeof(monitor); + GetMonitorInfoW(MonitorFromWindow(hwnd_, MONITOR_DEFAULTTONEAREST), + &monitor); + + SetWindowLongW(hwnd_, GWL_STYLE, saved_style_ & ~WS_OVERLAPPEDWINDOW); + SetWindowPos(hwnd_, nullptr, monitor.rcMonitor.left, monitor.rcMonitor.top, + monitor.rcMonitor.right - monitor.rcMonitor.left, + monitor.rcMonitor.bottom - monitor.rcMonitor.top, + SWP_NOZORDER | SWP_FRAMECHANGED); + full_screen_ = true; + } else { + SetWindowLongW(hwnd_, GWL_STYLE, saved_style_); + SetWindowPlacement(hwnd_, &saved_placement_); + SetWindowPos(hwnd_, nullptr, 0, 0, 0, 0, + SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED); + full_screen_ = false; + } + InvalidateRect(hwnd_, nullptr, FALSE); +} diff --git a/flutter_sender/windows/runner/video_window.h b/flutter_sender/windows/runner/video_window.h new file mode 100644 index 0000000..2ccba78 --- /dev/null +++ b/flutter_sender/windows/runner/video_window.h @@ -0,0 +1,53 @@ +#ifndef RUNNER_VIDEO_WINDOW_H_ +#define RUNNER_VIDEO_WINDOW_H_ + +#include + +#include +#include +#include +#include +#include + +// 独立串流窗口:一个原生 Win32 顶层窗口,直接用 GDI 绘制解码后的 BGRA 帧。 +// +// 它不依赖 Flutter 引擎(不新建引擎、不跨引擎共享纹理),因此可以随意拖动到 +// 第二块显示器、单独最大化 / 全屏,主窗口最小化也不影响画面。 +class VideoWindow { + public: + // 取当前帧;返回空表示暂无画面。返回的 shared_ptr 保证绘制期间帧不会被回收。 + using FrameProvider = + std::function>(int* width, + int* height)>; + + VideoWindow(); + ~VideoWindow(); + + // 创建并显示窗口(已存在则只前置)。必须在平台线程(消息循环所在线程)调用。 + bool Open(FrameProvider provider); + + // 关闭并销毁窗口。必须在平台线程调用。 + void Close(); + + // 解码线程收到新帧时调用,线程安全。 + void OnFrameAvailable(); + + bool IsOpen() const { return open_.load(); } + + private: + static LRESULT CALLBACK StaticWndProc(HWND hwnd, UINT message, WPARAM wparam, + LPARAM lparam); + LRESULT WndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam); + void Paint(); + void ToggleFullScreen(); + + HWND hwnd_ = nullptr; + std::atomic open_{false}; + std::atomic repaint_pending_{false}; + FrameProvider provider_; + bool full_screen_ = false; + WINDOWPLACEMENT saved_placement_ = {}; + LONG saved_style_ = 0; +}; + +#endif // RUNNER_VIDEO_WINDOW_H_