#include "video_window.h" #include #include #include namespace { constexpr wchar_t kWindowClass[] = L"TTSTDVideoWindowClass"; constexpr wchar_t kWindowTitle[] = L"TTSTD 串流"; // 解码线程 -> 窗口线程:有新帧,触发一次重绘。 constexpr UINT kMsgFrameReady = WM_APP + 0x51; // 窗口线程内部:视频宽高比变化,需要按比例重设窗口大小。 constexpr UINT kMsgApplyAspect = WM_APP + 0x52; // 拖动时限流下发移动事件(约 60Hz),避免高频 WM_MOUSEMOVE 塞满控制通道。 constexpr ULONGLONG kMoveIntervalMs = 16; // 最小客户区尺寸,避免窗口被拖成一条缝。 constexpr int kMinClientWidth = 320; constexpr int kMinClientHeight = 180; // 窗口最多占工作区的这个比例,竖屏串流也不会铺满整个屏幕。 constexpr double kMaxWorkAreaFraction = 0.8; // 未知被控端尺寸时的兜底比例(常见手机竖屏 9:16)。 constexpr double kDefaultAspect = 9.0 / 16.0; // 按比例算出「不超过工作区 80%、不小于最小值」的客户区尺寸。 void FitClientSize(double aspect, const RECT& work, int* client_width, int* client_height) { const int work_width = (std::max)(1, static_cast(work.right - work.left)); const int work_height = (std::max)(1, static_cast(work.bottom - work.top)); const int max_width = static_cast(work_width * kMaxWorkAreaFraction); const int max_height = static_cast(work_height * kMaxWorkAreaFraction); int width = max_height > 0 ? static_cast(static_cast(max_height) * aspect) : max_height; int height = max_height; if (width > max_width) { width = max_width; height = static_cast(static_cast(width) / aspect); } *client_width = (std::max)(width, kMinClientWidth); *client_height = (std::max)(height, kMinClientHeight); } } // namespace VideoWindow::VideoWindow() = default; VideoWindow::~VideoWindow() { Close(); } bool VideoWindow::Open(FrameProvider provider, int hint_width, int hint_height) { 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; 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; } // 不提供最大化按钮:画面窗口只按视频比例缩放。 const DWORD style = WS_OVERLAPPEDWINDOW & ~WS_MAXIMIZEBOX; // 被控端屏幕尺寸已知时直接按它的比例开局,竖屏手机不会被开成横向大窗。 double aspect = kDefaultAspect; if (hint_width > 0 && hint_height > 0) { aspect = static_cast(hint_width) / static_cast(hint_height); } RECT work = {0, 0, 1280, 720}; if (!SystemParametersInfoW(SPI_GETWORKAREA, 0, &work, 0)) { work = RECT{0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN)}; } int client_width = 0; int client_height = 0; FitClientSize(aspect, work, &client_width, &client_height); RECT rect = {0, 0, client_width, client_height}; AdjustWindowRect(&rect, style, FALSE); const int window_width = rect.right - rect.left; const int window_height = rect.bottom - rect.top; const int work_width = work.right - work.left; const int work_height = work.bottom - work.top; const int x = work.left + (std::max)(0, (work_width - window_width) / 2); const int y = work.top + (std::max)(0, (work_height - window_height) / 2); HWND hwnd = CreateWindowExW(0, kWindowClass, kWindowTitle, style, x, y, window_width, window_height, nullptr, nullptr, instance, this); if (hwnd == nullptr) { provider_ = nullptr; return false; } hwnd_ = hwnd; aspect_ratio_ = aspect; // 预先记下已应用的宽高比:首帧与预期一致时就不会再跳一次尺寸。 applied_aspect_ = aspect; 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); ReleaseBackBuffer(); provider_ = nullptr; aspect_ratio_ = 0.0; applied_aspect_ = 0.0; frame_width_ = 0; frame_height_ = 0; image_rect_ = RECT{}; dragging_ = false; } void VideoWindow::SetCloseHandler(CloseHandler handler) { close_handler_ = std::move(handler); } void VideoWindow::SetInputHandler(InputHandler handler) { input_handler_ = std::move(handler); } void VideoWindow::SetMouseButtonHandler(MouseButtonHandler handler) { mouse_button_handler_ = std::move(handler); } void VideoWindow::SetWheelHandler(WheelHandler handler) { wheel_handler_ = std::move(handler); } void VideoWindow::SetKeyboardHandler(KeyboardHandler handler) { keyboard_handler_ = std::move(handler); } 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 kMsgApplyAspect: ApplyAspectToWindow(aspect_ratio_); return 0; case WM_GETMINMAXINFO: { auto* info = reinterpret_cast(lparam); RECT rect = {0, 0, kMinClientWidth, kMinClientHeight}; AdjustWindowRectEx(&rect, GetWindowLongW(hwnd, GWL_STYLE), FALSE, GetWindowLongW(hwnd, GWL_EXSTYLE)); info->ptMinTrackSize.x = rect.right - rect.left; info->ptMinTrackSize.y = rect.bottom - rect.top; return 0; } case WM_SIZING: { auto* rect = reinterpret_cast(lparam); AdjustSizingRect(rect, wparam); return TRUE; } case WM_SIZE: InvalidateRect(hwnd, nullptr, FALSE); return 0; case WM_LBUTTONDOWN: // 画面内点击 = 在手机上点一下:先捕获鼠标,拖动时才能持续收到 WM_MOUSEMOVE。 SetFocus(hwnd); SetCapture(hwnd); dragging_ = true; last_move_tick_ = GetTickCount64(); DispatchPointerAt(0, POINT{GET_X_LPARAM(lparam), GET_Y_LPARAM(lparam)}); return 0; case WM_MOUSEMOVE: { // 只有按住左键才下发移动(悬停不注入),并做 60Hz 限流。 if (!dragging_) { return 0; } const ULONGLONG now = GetTickCount64(); if (now - last_move_tick_ < kMoveIntervalMs) { return 0; } last_move_tick_ = now; DispatchPointerAt(2, POINT{GET_X_LPARAM(lparam), GET_Y_LPARAM(lparam)}); return 0; } case WM_LBUTTONUP: { if (!dragging_) { return 0; } // 先清标志再 ReleaseCapture:否则 WM_CAPTURECHANGED 会补发一次取消。 dragging_ = false; ReleaseCapture(); DispatchPointerAt(1, POINT{GET_X_LPARAM(lparam), GET_Y_LPARAM(lparam)}); return 0; } case WM_CAPTURECHANGED: { // 窗口失焦、被别处抢走鼠标:补一个 cancel,避免手机上残留按下的手指。 if (dragging_) { dragging_ = false; DispatchPointerAt(3, last_point_); } return 0; } case WM_RBUTTONDOWN: case WM_RBUTTONUP: case WM_MBUTTONDOWN: case WM_MBUTTONUP: { // 右键 = 手机上的「返回」,中键 = 「多任务」(映射在 Dart 侧做,这里只报按键)。 const bool right = message == WM_RBUTTONDOWN || message == WM_RBUTTONUP; const bool down = message == WM_RBUTTONDOWN || message == WM_MBUTTONDOWN; // 右键拖动时不想选中画面,按下前先抢焦点。 if (down) { SetFocus(hwnd); } DispatchMouseButtonAt(right ? 1 : 2, down ? 0 : 1, POINT{GET_X_LPARAM(lparam), GET_Y_LPARAM(lparam)}); return 0; } case WM_MOUSEWHEEL: { // 一格 = WHEEL_DELTA(120)。Win32 正数表示向前滚(看到更早的内容), // 协议里 deltaY 正数表示「向下滚」(手指上滑,看到更后面的内容),所以取反。 const int steps = -GET_WHEEL_DELTA_WPARAM(wparam) / WHEEL_DELTA; if (steps == 0) { return 0; } WheelHandler handler = wheel_handler_; if (handler) { handler(0, steps); } return 0; } case WM_KEYDOWN: if (wparam == VK_ESCAPE) { // 关窗即停止投屏(由 close_handler_ 通知 Flutter)。 SendMessageW(hwnd, WM_CLOSE, 0, 0); return 0; } DispatchKey(0, static_cast(wparam)); return 0; case WM_KEYUP: DispatchKey(1, static_cast(wparam)); return 0; case WM_SYSKEYDOWN: // Alt 组合键(Alt+F4 关窗等)仍要交给系统,先转发一份再放行。 if (wparam == VK_F4) { break; } DispatchKey(0, static_cast(wparam)); break; case WM_SYSKEYUP: DispatchKey(1, static_cast(wparam)); break; case WM_CLOSE: DestroyWindow(hwnd); return 0; case WM_DESTROY: { hwnd_ = nullptr; open_.store(false); repaint_pending_.store(false); ReleaseBackBuffer(); provider_ = nullptr; aspect_ratio_ = 0.0; applied_aspect_ = 0.0; frame_width_ = 0; frame_height_ = 0; image_rect_ = RECT{}; dragging_ = false; CloseHandler handler = close_handler_; if (handler) { handler(); } 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); const int client_width = client.right - client.left; const int client_height = client.bottom - client.top; // 先整帧画进离屏缓冲,最后一次性 BitBlt 上去。 // FillRect(黑) 和 StretchDIBits(画面) 是两次独立的 GDI 调用,直接画在窗口上时 // DWM 可能正好合成到「已填黑、还没拉伸」的中间态,表现为操作时画面闪一下黑。 HDC target = hdc; if (client_width > 0 && client_height > 0) { EnsureBackBuffer(hdc, client_width, client_height); if (back_dc_ != nullptr) { target = back_dc_; } } int width = 0; int height = 0; std::shared_ptr> frame = provider_ ? provider_(&width, &height) : nullptr; if (frame && !frame->empty() && width > 0 && height > 0 && client_width > 0 && client_height > 0) { const double aspect = static_cast(width) / static_cast(height); aspect_ratio_ = aspect; // 首帧(或分辨率/方向变化)时把窗口调成同比例的尺寸。 if (std::fabs(aspect - applied_aspect_) > 0.01) { PostMessageW(hwnd_, kMsgApplyAspect, 0, 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; // 画面正好铺满客户区时不用先刷黑:StretchDIBits 会把整块覆盖掉, // 省掉每秒几十次的全屏填充(1080p 一帧就是 8MB 内存带宽)。 if (draw_width < client_width || draw_height < client_height) { FillRect(target, &client, static_cast(GetStockObject(BLACK_BRUSH))); } // 记住这一帧的尺寸和实际绘制矩形,鼠标点击时据此换算成画面像素。 frame_width_ = width; frame_height_ = height; image_rect_ = RECT{offset_x, offset_y, offset_x + draw_width, offset_y + draw_height}; 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(target, COLORONCOLOR); StretchDIBits(target, offset_x, offset_y, draw_width, draw_height, 0, 0, width, height, frame->data(), &info, DIB_RGB_COLORS, SRCCOPY); } else { FillRect(target, &client, static_cast(GetStockObject(BLACK_BRUSH))); // 还没有画面:清掉坐标映射,避免拿上一路的尺寸误点。 frame_width_ = 0; frame_height_ = 0; image_rect_ = RECT{}; // 还没画面时给个提示:窗口是在点「请求投屏」后就弹出的, // 纯黑会让人以为卡死。 HGDIOBJ previous = SelectObject(target, GetStockObject(DEFAULT_GUI_FONT)); SetBkMode(target, TRANSPARENT); SetTextColor(target, RGB(170, 170, 170)); RECT text_rect = client; DrawTextW(target, L"等待被控端画面…\r\n请在手机弹窗中点击「允许」", -1, &text_rect, DT_CENTER | DT_VCENTER | DT_WORDBREAK); SelectObject(target, previous); } if (target != hdc) { BitBlt(hdc, 0, 0, client_width, client_height, target, 0, 0, SRCCOPY); } EndPaint(hwnd_, &paint); } void VideoWindow::EnsureBackBuffer(HDC reference, int width, int height) { if (back_dc_ != nullptr && back_width_ == width && back_height_ == height) { return; } ReleaseBackBuffer(); HDC dc = CreateCompatibleDC(reference); if (dc == nullptr) { return; } HBITMAP bitmap = CreateCompatibleBitmap(reference, width, height); if (bitmap == nullptr) { DeleteDC(dc); return; } back_previous_ = SelectObject(dc, bitmap); back_dc_ = dc; back_bitmap_ = bitmap; back_width_ = width; back_height_ = height; } void VideoWindow::ReleaseBackBuffer() { if (back_dc_ != nullptr) { if (back_previous_ != nullptr) { SelectObject(back_dc_, back_previous_); } DeleteDC(back_dc_); } back_dc_ = nullptr; back_previous_ = nullptr; if (back_bitmap_ != nullptr) { DeleteObject(back_bitmap_); } back_bitmap_ = nullptr; back_width_ = 0; back_height_ = 0; } bool VideoWindow::ClientToFrame(POINT point, int* x, int* y) const { const int width = image_rect_.right - image_rect_.left; const int height = image_rect_.bottom - image_rect_.top; if (frame_width_ <= 0 || frame_height_ <= 0 || width <= 0 || height <= 0) { return false; } // 黑边区域不算点击,否则会点到画面外的坐标。 if (point.x < image_rect_.left || point.x >= image_rect_.right || point.y < image_rect_.top || point.y >= image_rect_.bottom) { return false; } const int frame_x = (point.x - image_rect_.left) * frame_width_ / width; const int frame_y = (point.y - image_rect_.top) * frame_height_ / height; *x = (std::min)((std::max)(frame_x, 0), frame_width_ - 1); *y = (std::min)((std::max)(frame_y, 0), frame_height_ - 1); return true; } void VideoWindow::DispatchPointerAt(int action, POINT point) { last_point_ = point; InputHandler handler = input_handler_; if (!handler) { return; } int x = 0; int y = 0; if (!ClientToFrame(point, &x, &y)) { return; } handler(action, x, y); } void VideoWindow::DispatchMouseButtonAt(int button, int action, POINT point) { last_point_ = point; MouseButtonHandler handler = mouse_button_handler_; if (!handler) { return; } int x = 0; int y = 0; if (!ClientToFrame(point, &x, &y)) { return; } handler(button, action, x, y); } void VideoWindow::DispatchKey(int action, int vk) { KeyboardHandler handler = keyboard_handler_; if (!handler) { return; } handler(action, vk, CurrentModifiers()); } int VideoWindow::CurrentModifiers() const { int modifiers = 0; if ((GetKeyState(VK_CONTROL) & 0x8000) != 0) { modifiers |= 0x01; } if ((GetKeyState(VK_MENU) & 0x8000) != 0) { modifiers |= 0x02; } if ((GetKeyState(VK_SHIFT) & 0x8000) != 0) { modifiers |= 0x04; } if (((GetKeyState(VK_LWIN) | GetKeyState(VK_RWIN)) & 0x8000) != 0) { modifiers |= 0x08; } return modifiers; } void VideoWindow::ApplyAspectToWindow(double aspect) { if (hwnd_ == nullptr || aspect <= 0.0) { return; } MONITORINFO monitor = {}; monitor.cbSize = sizeof(monitor); const HMONITOR target = MonitorFromWindow(hwnd_, MONITOR_DEFAULTTONEAREST); if (target == nullptr || !GetMonitorInfoW(target, &monitor)) { return; } applied_aspect_ = aspect; const RECT work = monitor.rcWork; const int work_width = work.right - work.left; const int work_height = work.bottom - work.top; int client_width = 0; int client_height = 0; FitClientSize(aspect, work, &client_width, &client_height); RECT rect = {0, 0, client_width, client_height}; AdjustWindowRectEx(&rect, GetWindowLongW(hwnd_, GWL_STYLE), FALSE, GetWindowLongW(hwnd_, GWL_EXSTYLE)); const int window_width = rect.right - rect.left; const int window_height = rect.bottom - rect.top; const int x = work.left + (work_width - window_width) / 2; const int y = work.top + (work_height - window_height) / 2; SetWindowPos(hwnd_, nullptr, x, y, window_width, window_height, SWP_NOZORDER | SWP_NOACTIVATE); } void VideoWindow::AdjustSizingRect(RECT* rect, WPARAM edge) const { if (rect == nullptr || aspect_ratio_ <= 0.0) { return; } RECT window_rect = {}; RECT client_rect = {}; GetWindowRect(hwnd_, &window_rect); GetClientRect(hwnd_, &client_rect); const int frame_width = (window_rect.right - window_rect.left) - client_rect.right; const int frame_height = (window_rect.bottom - window_rect.top) - client_rect.bottom; int client_width = (rect->right - rect->left) - frame_width; int client_height = (rect->bottom - rect->top) - frame_height; client_width = (std::max)(client_width, kMinClientWidth); client_height = (std::max)(client_height, kMinClientHeight); switch (edge) { case WMSZ_TOP: case WMSZ_BOTTOM: // 上下拖动:以高度为准算宽度,水平居中。 client_width = static_cast(client_height * aspect_ratio_); break; default: // 左右边与四角:以宽度为准算高度。 client_height = static_cast(client_width / aspect_ratio_); break; } client_height = (std::max)(client_height, kMinClientHeight); client_width = (std::max)(client_width, kMinClientWidth); const int width = client_width + frame_width; const int height = client_height + frame_height; switch (edge) { case WMSZ_TOPLEFT: // 右下角固定。 rect->left = rect->right - width; rect->top = rect->bottom - height; break; case WMSZ_TOPRIGHT: // 左下角固定。 rect->right = rect->left + width; rect->top = rect->bottom - height; break; case WMSZ_BOTTOMLEFT: // 右上角固定。 rect->left = rect->right - width; rect->bottom = rect->top + height; break; case WMSZ_BOTTOMRIGHT: // 左上角固定。 rect->right = rect->left + width; rect->bottom = rect->top + height; break; case WMSZ_LEFT: // 右边固定,垂直居中。 rect->left = rect->right - width; { const int center_y = (rect->top + rect->bottom) / 2; rect->top = center_y - height / 2; rect->bottom = rect->top + height; } break; case WMSZ_RIGHT: // 左边固定,垂直居中。 rect->right = rect->left + width; { const int center_y = (rect->top + rect->bottom) / 2; rect->top = center_y - height / 2; rect->bottom = rect->top + height; } break; case WMSZ_TOP: // 底边固定,水平居中。 rect->top = rect->bottom - height; { const int center_x = (rect->left + rect->right) / 2; rect->left = center_x - width / 2; rect->right = rect->left + width; } break; default: // WMSZ_BOTTOM:顶边固定,水平居中。 rect->bottom = rect->top + height; { const int center_x = (rect->left + rect->right) / 2; rect->left = center_x - width / 2; rect->right = rect->left + width; } break; } }