fix: 修正投屏授权状态与窗口生命周期,避免串流状态错乱

This commit is contained in:
tongtong committed 2026-11-28 02:59:49 +08:00
1 parent a0b77a3e7a
commit 4c9d006d11
6 files changed
+134 -90

No files matched your search

@@ -10,6 +10,7 @@ class MirrorBar extends StatelessWidget {
required this.connected,
required this.streaming,
required this.windowOpen,
required this.granted,
required this.busy,
required this.resolution,
required this.frames,
@@ -20,6 +21,7 @@ class MirrorBar extends StatelessWidget {
final bool connected;
final bool streaming;
final bool windowOpen;
final bool granted;
final bool busy;
final String resolution;
final int frames;
@@ -72,7 +74,7 @@ class MirrorBar extends StatelessWidget {
SizedBox(
width: double.infinity,
child: FilledButton.icon(
onPressed: connected && !busy && !streaming ? onRequest : null,
onPressed: connected && !busy && !windowOpen ? onRequest : null,
icon: Icon(
streaming ? Icons.cast_connected : Icons.play_circle_outline,
),
@@ -86,28 +88,30 @@ class MirrorBar extends StatelessWidget {
}
String _statusText() {
if (error.isNotEmpty) return '异常';
if (streaming) return '接收画面中';
if (error.isNotEmpty) return '异常';
if (windowOpen && granted) return '已允许,等待画面';
if (windowOpen) return '等待被控端确认';
if (connected) return '已连接,未投屏';
return '未连接';
}
Color _statusColor(ThemeData theme) {
if (error.isNotEmpty) return theme.colorScheme.error;
if (streaming) return Colors.green;
if (error.isNotEmpty) return theme.colorScheme.error;
if (windowOpen) return Colors.orange;
if (connected) return theme.colorScheme.primary;
return theme.colorScheme.outline;
}
String _detailText() {
if (error.isNotEmpty) return error;
if (!connected) return '先在上方连接被控端,再请求投屏';
if (streaming) {
final size = resolution.isEmpty ? '未知分辨率' : resolution;
return '$size · 已接收 $frames 帧 · 关闭独立窗口会立即停止投屏';
}
if (error.isNotEmpty) return error;
if (windowOpen && granted) return '被控端已允许投屏,正在等待首帧';
if (windowOpen) return '已向被控端发送投屏请求,请在其弹窗中点击「允许」';
return '点击「请求投屏」会按视频比例弹出独立窗口播放画面';
}
+60 -63
View File
@@ -85,16 +85,14 @@ class _HomePageState extends State<HomePage> {
bool _videoWindowOpen = false;
/// 正在拉起窗口并下发投屏请求。
bool _mirrorRequesting = false;
/// 最近一次统计到的累计解码帧数,用于判断是否还在收画面。
int _lastDecoded = 0;
/// 最近一次收到新帧的时间;超过 [streamingIdleTimeout] 视为已停止推流。
DateTime? _lastFrameAt;
bool _mirrorGranted = false;
bool _videoStreaming = false;
int _videoWindowGeneration = 0;
/// 因关窗而停流只下发一次 stopMirror。
bool _stopSentForWindowClose = false;
/// 最近一次同步过的剪贴板文本(收/发都记),用来避免两端来回回送同一条内容。
String? _lastClipboardText;
static const Duration streamingIdleTimeout = Duration(seconds: 2);
String? _nativeError;
@override
@@ -199,16 +197,22 @@ class _HomePageState extends State<HomePage> {
if (connected && keyEstablished) {
_connectWatchdog?.cancel();
_phase = ConnectionPhase.direct;
} else if (sessionEnded) {
// 中继线程退出后 status 不再有进行中的会话,别把界面卡在「连接中」。
_phase = ConnectionPhase.idle;
} else if (wasConnected) {
// 直连监听仍在运行时继续等设备重连。
_phase = running && !sessionEnded
? ConnectionPhase.probing
: ConnectionPhase.idle;
} else if ((running || relay) &&
_phase != ConnectionPhase.idle &&
_phase != ConnectionPhase.failed) {
_phase = ConnectionPhase.probing;
}
});
if (sessionEnded) _snack('中继会话已断开');
if (wasConnected && !_phase.isConnected && _videoWindowOpen) {
unawaited(_abortMirror('被控端已断开,串流窗口已关闭'));
} else if (sessionEnded) {
_snack('中继会话已断开');
}
// 刚连上时主动下发一次会话配置,顺带把权限等级请求发过去;
// 被控端会用 msgType=10 回送裁剪后的有效等级。
if (!wasConnected && _phase.isConnected) {
@@ -256,8 +260,10 @@ class _HomePageState extends State<HomePage> {
/// 4=已停止 5=出错。以前没有这条通道,被控端拒绝后主控端只能干等画面。
void _handleMirrorEvent(int action, String text) {
_diagnosticLog.write('mirror event action=$action text=$text');
if (!_videoWindowOpen || _stopSentForWindowClose) return;
switch (action) {
case 2:
setState(() => _mirrorGranted = true);
_snack('被控端已允许投屏');
case 3:
unawaited(_abortMirror(text.isEmpty ? '被控端拒绝了投屏请求' : '被控端拒绝了投屏请求:$text'));
@@ -274,15 +280,19 @@ class _HomePageState extends State<HomePage> {
/// 不能再给对端补发一条 stopMirror。
Future<void> _abortMirror(String message) async {
_stopSentForWindowClose = true;
if (_videoWindowOpen) {
await _bridge.closeVideoWindow();
}
if (!mounted) return;
final close = _bridge.closeVideoWindow();
_clearMirrorState();
await close;
if (mounted && !_videoWindowOpen) _snack(message);
}
void _clearMirrorState() {
setState(() {
_videoWindowGeneration++;
_videoWindowOpen = false;
_lastFrameAt = null;
_mirrorGranted = false;
_videoStreaming = false;
});
_snack(message);
}
/// 被控端回送的权限等级(msgType=10,payload 是 JSON)。
@@ -390,15 +400,14 @@ class _HomePageState extends State<HomePage> {
/// 轮询原生解码统计:纹理 ID、分辨率、PTS 与失败原因。
Future<void> _refreshVideoStats() async {
if (!mounted) return;
final generation = _videoWindowGeneration;
final stats = await _bridge.videoStats();
if (!mounted || stats.isEmpty) return;
if (!mounted || generation != _videoWindowGeneration || stats.isEmpty) {
return;
}
final id = stats['textureId'];
final windowOpen = stats['windowOpen'];
final decoded = stats['decoded'];
final decodedCount = decoded is int ? decoded : 0;
// 帧计数变化说明还在收画面;累计值不变就说明推流已停。
final framesAdvanced = decodedCount != _lastDecoded;
final windowFrames = stats['windowFrames'];
// 原生窗口被用户关掉(方法通道回调丢失时的兜底)。
final closedByUser = windowOpen is bool && !windowOpen && _videoWindowOpen;
@@ -407,15 +416,11 @@ class _HomePageState extends State<HomePage> {
if (_textureId == null && id is int && id > 0) {
_textureId = id;
}
if (windowOpen is bool) {
_videoWindowOpen = windowOpen;
}
if (framesAdvanced) {
_lastDecoded = decodedCount;
_lastFrameAt = DateTime.now();
}
if (closedByUser) {
_lastFrameAt = null;
if (_videoWindowOpen &&
windowOpen == true &&
windowFrames is int &&
windowFrames > 0) {
_videoStreaming = true;
}
});
@@ -428,29 +433,34 @@ class _HomePageState extends State<HomePage> {
///
/// 被控端会弹窗确认,确认后才开始推流;这段时间窗口显示「等待画面」。
Future<void> _requestMirror() async {
if (_videoWindowOpen || _mirrorRequesting) return;
if (!_phase.isConnected) {
_snack('请先连接被控端');
return;
}
setState(() {
_mirrorRequesting = true;
// 新一轮请求:清掉上一轮「关窗已停流」的标记与旧帧时间。
_stopSentForWindowClose = false;
_lastFrameAt = null;
});
final generation = _videoWindowGeneration;
try {
if (!_videoWindowOpen) {
final size = _deviceScreenSize();
final opened = await _bridge.openVideoWindow(
width: size?.$1,
height: size?.$2,
);
if (!mounted) return;
if (!opened) {
_snack('当前平台不支持独立串流窗口');
return;
}
setState(() => _videoWindowOpen = true);
final size = _deviceScreenSize();
final opened = await _bridge.openVideoWindow(
width: size?.$1,
height: size?.$2,
);
if (!mounted || generation != _videoWindowGeneration) return;
if (!opened) {
_snack('当前平台不支持独立串流窗口');
return;
}
setState(() {
_videoWindowGeneration++;
_videoWindowOpen = true;
});
if (!_phase.isConnected) {
await _abortMirror('被控端已断开,串流窗口已关闭');
return;
}
// 先下发会话配置,被控端据此决定编码器参数后再开流。
_applySessionConfig();
@@ -481,10 +491,7 @@ class _HomePageState extends State<HomePage> {
if (_stopSentForWindowClose) return;
_stopSentForWindowClose = true;
setState(() {
_videoWindowOpen = false;
_lastFrameAt = null;
});
_clearMirrorState();
if (_phase.isConnected) {
_bridge.sendControl('stopMirror', const {});
_diagnosticLog.write('video window closed -> stopMirror');
@@ -966,9 +973,9 @@ class _HomePageState extends State<HomePage> {
// 断开时连串流窗口一起关掉,否则重连后窗口还挂在那儿显示上一路的旧帧。
if (_videoWindowOpen) {
_stopSentForWindowClose = true;
await _bridge.closeVideoWindow();
_videoWindowOpen = false;
_lastFrameAt = null;
final close = _bridge.closeVideoWindow();
_clearMirrorState();
await close;
}
await _bridge.disconnect();
if (!mounted) return;
@@ -1252,21 +1259,10 @@ class _HomePageState extends State<HomePage> {
String get _videoError => (_videoStats['error'] as String? ?? '').trim();
int get _videoFrames {
final decoded = _videoStats['decoded'];
final decoded = _videoStats['windowFrames'];
return decoded is int ? decoded : 0;
}
/// 是否正在接收画面。
///
/// 三个条件同时满足才算:独立窗口还开着、没有解码错误、最近 [streamingIdleTimeout]
/// 内还有新帧。累计帧数只增不减,单看它会导致关窗后永远显示「接收画面中」。
bool get _videoStreaming {
if (!_videoWindowOpen || _videoError.isNotEmpty) return false;
final last = _lastFrameAt;
if (last == null) return false;
return DateTime.now().difference(last) < streamingIdleTimeout;
}
Widget _buildStage() {
return Padding(
padding: const EdgeInsets.all(16),
@@ -1284,6 +1280,7 @@ class _HomePageState extends State<HomePage> {
connected: _phase.isConnected,
streaming: _videoStreaming,
windowOpen: _videoWindowOpen,
granted: _mirrorGranted,
busy: _mirrorRequesting,
resolution: _videoResolution,
frames: _videoFrames,
@@ -267,9 +267,11 @@ class FrameStore {
// 独立窗口使用:返回当前帧的共享所有权快照。
// 拿到 shared_ptr 后即使解码线程继续 Publish,绘制期间的帧也不会被回收。
std::shared_ptr<std::vector<uint8_t>> Snapshot(int* width, int* height) {
std::shared_ptr<std::vector<uint8_t>> Snapshot(int* width, int* height,
uint64_t after_frame) {
std::lock_guard<std::mutex> lock(mutex_);
if (!front_ || front_->empty() || width_ <= 0 || height_ <= 0) {
if (frames_ <= after_frame || !front_ || front_->empty() || width_ <= 0 ||
height_ <= 0) {
return nullptr;
}
*width = width_;
@@ -988,8 +990,13 @@ class VideoTexturePlugin : public flutter::Plugin {
hint_width = read_int("width");
hint_height = read_int("height");
}
if (!video_window_.IsOpen()) {
window_start_frame_ = store->frames();
}
const bool opened = video_window_.Open(
[store](int* width, int* height) { return store->Snapshot(width, height); },
[store, start = window_start_frame_](int* width, int* height) {
return store->Snapshot(width, height, start);
},
hint_width, hint_height);
result->Success(flutter::EncodableValue(opened));
return;
@@ -1013,8 +1020,13 @@ class VideoTexturePlugin : public flutter::Plugin {
frames_->size(&width, &height);
map[flutter::EncodableValue("textureId")] =
flutter::EncodableValue(static_cast<int64_t>(texture_id_));
const uint64_t decoded = frames_->frames();
map[flutter::EncodableValue("decoded")] =
flutter::EncodableValue(static_cast<int64_t>(frames_->frames()));
flutter::EncodableValue(static_cast<int64_t>(decoded));
map[flutter::EncodableValue("windowFrames")] = flutter::EncodableValue(
static_cast<int64_t>(video_window_.IsOpen()
? decoded - window_start_frame_
: 0));
map[flutter::EncodableValue("pending")] =
flutter::EncodableValue(static_cast<int64_t>(api_.Pending()));
map[flutter::EncodableValue("received")] =
@@ -1143,6 +1155,7 @@ class VideoTexturePlugin : public flutter::Plugin {
std::unique_ptr<flutter::MethodChannel<flutter::EncodableValue>> channel_;
FlutterDesktopPixelBuffer descriptor_ = {};
std::shared_ptr<FrameStore> frames_;
uint64_t window_start_frame_ = 0;
// 与主窗口纹理共享同一份 FrameStore 的独立串流窗口。
VideoWindow video_window_;
// 本次关闭是由 Flutter 主动发起的(不需要再回调 windowClosed)。
+41 -18
View File
@@ -227,14 +227,25 @@ LRESULT VideoWindow::WndProc(HWND hwnd, UINT message, WPARAM wparam,
case WM_SIZE:
InvalidateRect(hwnd, nullptr, FALSE);
return 0;
case WM_LBUTTONDOWN:
case WM_LBUTTONDOWN: {
const POINT point{GET_X_LPARAM(lparam), GET_Y_LPARAM(lparam)};
int x = 0;
int y = 0;
if (dragging_ || !input_handler_ || !ClientToFrame(point, &x, &y)) {
return 0;
}
// 画面内点击 = 在手机上点一下:先捕获鼠标,拖动时才能持续收到 WM_MOUSEMOVE。
SetFocus(hwnd);
SetCapture(hwnd);
if (GetCapture() != hwnd) {
return 0;
}
dragging_ = true;
last_move_tick_ = GetTickCount64();
DispatchPointerAt(0, POINT{GET_X_LPARAM(lparam), GET_Y_LPARAM(lparam)});
last_touch_ = POINT{x, y};
input_handler_(0, x, y);
return 0;
}
case WM_MOUSEMOVE: {
// 只有按住左键才下发移动(悬停不注入),并做 60Hz 限流。
if (!dragging_) {
@@ -253,19 +264,15 @@ LRESULT VideoWindow::WndProc(HWND hwnd, UINT message, WPARAM wparam,
return 0;
}
// 先清标志再 ReleaseCapture:否则 WM_CAPTURECHANGED 会补发一次取消。
dragging_ = false;
ReleaseCapture();
DispatchPointerAt(1, POINT{GET_X_LPARAM(lparam), GET_Y_LPARAM(lparam)});
EndDrag(hwnd, 1, POINT{GET_X_LPARAM(lparam), GET_Y_LPARAM(lparam)});
return 0;
}
case WM_CAPTURECHANGED: {
case WM_CANCELMODE:
case WM_KILLFOCUS:
case WM_CAPTURECHANGED:
// 窗口失焦、被别处抢走鼠标:补一个 cancel,避免手机上残留按下的手指。
if (dragging_) {
dragging_ = false;
DispatchPointerAt(3, last_point_);
}
return 0;
}
EndDrag(hwnd, 3, POINT{});
break;
case WM_RBUTTONDOWN:
case WM_RBUTTONUP:
case WM_MBUTTONDOWN:
@@ -319,6 +326,7 @@ LRESULT VideoWindow::WndProc(HWND hwnd, UINT message, WPARAM wparam,
DestroyWindow(hwnd);
return 0;
case WM_DESTROY: {
EndDrag(hwnd, 3, POINT{});
hwnd_ = nullptr;
open_.store(false);
repaint_pending_.store(false);
@@ -493,21 +501,36 @@ bool VideoWindow::ClientToFrame(POINT point, int* x, int* y) const {
}
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)) {
// 已开始的拖动可以越过画面边缘。画面暂时不可用时,抬起仍用最后的触点。
if (action != 3 && image_rect_.left < image_rect_.right &&
image_rect_.top < image_rect_.bottom) {
point.x = std::clamp(point.x, image_rect_.left, image_rect_.right - 1);
point.y = std::clamp(point.y, image_rect_.top, image_rect_.bottom - 1);
int x = 0;
int y = 0;
if (ClientToFrame(point, &x, &y)) {
last_touch_ = POINT{x, y};
}
}
handler(action, last_touch_.x, last_touch_.y);
}
void VideoWindow::EndDrag(HWND hwnd, int action, POINT point) {
if (!dragging_) {
return;
}
handler(action, x, y);
dragging_ = false;
if (GetCapture() == hwnd) {
ReleaseCapture();
}
DispatchPointerAt(action, point);
}
void VideoWindow::DispatchMouseButtonAt(int button, int action, POINT point) {
last_point_ = point;
MouseButtonHandler handler = mouse_button_handler_;
if (!handler) {
return;
+2 -1
View File
@@ -79,6 +79,7 @@ class VideoWindow {
// 客户区坐标 -> 画面像素;返回 false 表示点在黑边上或还没有画面。
bool ClientToFrame(POINT point, int* x, int* y) const;
void DispatchPointerAt(int action, POINT point);
void EndDrag(HWND hwnd, int action, POINT point);
void DispatchMouseButtonAt(int button, int action, POINT point);
void DispatchKey(int action, int vk);
// 当前修饰键状态(按协议位定义拼装)。
@@ -115,7 +116,7 @@ class VideoWindow {
RECT image_rect_ = {};
// 左键按下期间才下发移动事件,悬停不注入。
bool dragging_ = false;
POINT last_point_ = {};
POINT last_touch_ = {};
ULONGLONG last_move_tick_ = 0;
};