#include "video_texture.h" #include "video_window.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { // 与 Rust Core 的 TtstdVideoFrame 内存布局保持一致(24 字节)。 struct TtstdVideoFrame { uint64_t seq; uint64_t pts; uint32_t len; uint8_t format; uint8_t flags; uint16_t reserved; }; static_assert(sizeof(TtstdVideoFrame) == 24, "TtstdVideoFrame 布局必须与 Rust 侧一致"); constexpr int32_t kErrBufferTooSmall = -1; constexpr uint8_t kFormatH264 = 1; constexpr uint8_t kFormatHevc = 2; // 与 Rust 侧 media::FLAG_KEYFRAME 一致。 constexpr uint8_t kFlagKeyframe = 0x01; constexpr DWORD kOutputStreamId = 0; constexpr size_t kInitialPayloadCapacity = 512 * 1024; constexpr DWORD kIdleSleepMs = 2; constexpr DWORD kRetrySleepMs = 1000; constexpr DWORD kMaxOutputsPerDrain = 4; // 是否包含解码所需的配置 NAL:H.264 的 SPS(7),HEVC 的 VPS/SPS/PPS(32/33/34)。 bool HasCodecConfig(const uint8_t* data, size_t len, uint8_t format) { size_t offset = 0; for (size_t i = 0; i + 3 < len; ++i) { if (data[i] != 0 || data[i + 1] != 0) { continue; } if (data[i + 2] == 1) { offset = i + 3; } else if (data[i + 2] == 0 && i + 4 < len && data[i + 3] == 1) { offset = i + 4; } else { continue; } if (offset >= len) { return false; } const uint8_t header = data[offset]; if (format == kFormatHevc) { const uint8_t type = static_cast((header >> 1) & 0x3F); if (type == 32 || type == 33 || type == 34) { return true; } } else if ((header & 0x1F) == 7) { return true; } i = offset; } return false; } // 极简 COM 智能指针(工程编译选项关闭了异常,避免依赖 WRL)。 template class ComPtr { public: ComPtr() = default; ~ComPtr() { Reset(); } ComPtr(const ComPtr& other) : ptr_(other.ptr_) { if (ptr_ != nullptr) { ptr_->AddRef(); } } ComPtr(ComPtr&& other) noexcept : ptr_(other.ptr_) { other.ptr_ = nullptr; } ComPtr& operator=(const ComPtr& other) { if (this != &other) { Reset(); ptr_ = other.ptr_; if (ptr_ != nullptr) { ptr_->AddRef(); } } return *this; } ComPtr& operator=(ComPtr&& other) noexcept { if (this != &other) { Reset(); ptr_ = other.ptr_; other.ptr_ = nullptr; } return *this; } T* Get() const { return ptr_; } T* operator->() const { return ptr_; } explicit operator bool() const { return ptr_ != nullptr; } // 供 COM 输出参数使用:清空后返回内部指针地址。 T** Put() { Reset(); return &ptr_; } void Attach(T* raw) { Reset(); ptr_ = raw; } T* Detach() { T* raw = ptr_; ptr_ = nullptr; return raw; } void Reset() { if (ptr_ != nullptr) { ptr_->Release(); ptr_ = nullptr; } } private: T* ptr_ = nullptr; }; template bool ResolveExport(HMODULE module, const char* name, FunctionPtr* target) { FARPROC address = GetProcAddress(module, name); if (address == nullptr) { return false; } void* raw = nullptr; static_assert(sizeof(raw) == sizeof(FARPROC), "FARPROC 尺寸必须与 void* 一致"); std::memcpy(&raw, &address, sizeof(raw)); FunctionPtr typed = nullptr; static_assert(sizeof(typed) == sizeof(raw), "函数指针尺寸必须与 void* 一致"); std::memcpy(&typed, &raw, sizeof(typed)); *target = typed; return true; } // Rust Core 暴露的视频队列读取接口。 class RustVideoApi { public: using NextFn = int32_t (*)(TtstdVideoFrame*, uint8_t*, size_t); using PendingFn = uint32_t (*)(); bool EnsureLoaded() { if (loaded_) { return true; } HMODULE module = GetModuleHandleW(L"ttstdconnect_core.dll"); if (module == nullptr) { module = LoadLibraryW(L"ttstdconnect_core.dll"); } if (module == nullptr) { // 兜底:从可执行文件所在目录加载(Dart 尚未调用 FFI 时)。 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) { error_ = "无法加载 ttstdconnect_core.dll"; return false; } if (!ResolveExport(module, "ttstd_video_next", &next_) || !ResolveExport(module, "ttstd_video_pending", &pending_)) { error_ = "动态库缺少视频队列导出(请重新构建 Rust Core)"; return false; } loaded_ = true; error_.clear(); return true; } const std::string& error() const { return error_; } uint32_t Pending() const { return (loaded_ && pending_ != nullptr) ? pending_() : 0; } int32_t Next(TtstdVideoFrame* meta, uint8_t* buffer, size_t capacity) const { if (!loaded_ || next_ == nullptr) { return 0; } return next_(meta, buffer, capacity); } private: bool loaded_ = false; NextFn next_ = nullptr; PendingFn pending_ = nullptr; std::string error_; }; // 最近一帧 BGRA 画面。渲染线程与解码线程共享。 class FrameStore { public: void Publish(std::shared_ptr> frame, int width, int height, uint64_t pts) { std::lock_guard lock(mutex_); // 上一帧先留作 retired_,等本次替换过去才释放, // 避免渲染线程正在拷贝时被回收。 retired_ = std::move(front_); front_ = std::move(frame); width_ = width; height_ = height; pts_ = pts; ++frames_; } // 渲染线程调用:返回当前帧与尺寸,无画面时返回 nullptr。 const uint8_t* Acquire(int* width, int* height, uint64_t* pts) { std::lock_guard lock(mutex_); if (!front_ || front_->empty() || width_ <= 0 || height_ <= 0) { return nullptr; } *width = width_; *height = height_; *pts = pts_; return front_->data(); } uint64_t frames() { std::lock_guard lock(mutex_); return frames_; } // 独立窗口使用:返回当前帧的共享所有权快照。 // 拿到 shared_ptr 后即使解码线程继续 Publish,绘制期间的帧也不会被回收。 std::shared_ptr> Snapshot(int* width, int* height, uint64_t after_frame) { std::lock_guard lock(mutex_); if (frames_ <= after_frame || !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_; } void size(int* width, int* height) { std::lock_guard lock(mutex_); *width = width_; *height = height_; } private: std::mutex mutex_; std::shared_ptr> front_; std::shared_ptr> retired_; int width_ = 0; int height_ = 0; uint64_t pts_ = 0; uint64_t frames_ = 0; }; // 单通道裁剪到 0..255,展开成无分支写法:每帧要算百万级像素,if 链是热点。 inline uint8_t ClampByte(int value) { return static_cast((std::max)(0, (std::min)(255, value))); } // BT.601 有限范围 NV12 -> BGRA(按显示区域裁剪掉解码补齐的行)。 // // 注意字节序是 B,G,R,A:窗口用 StretchDIBits + 32bpp BI_RGB 直接把这块内存贴屏, // DIB 的内存布局就是 BGRA。写成 RGBA 会让红蓝对调(蓝色壁纸变土黄/粉)。 void ConvertNv12(const uint8_t* data, size_t length, int coded_width, int coded_height, int crop_x, int crop_y, int visible_width, int visible_height, int luma_stride, int chroma_stride, std::vector* out) { const size_t y_size = static_cast(luma_stride) * coded_height; const size_t uv_size = static_cast(chroma_stride) * ((coded_height + 1) / 2); if (length < y_size + uv_size || visible_width <= 0 || visible_height <= 0) { return; } out->assign(static_cast(visible_width) * visible_height * 4, 0xff); const uint8_t* uv_plane = data + y_size; for (int row = 0; row < visible_height; ++row) { const int source_row = crop_y + row; if (source_row < 0 || source_row >= coded_height) { continue; } const uint8_t* y_row = data + static_cast(source_row) * luma_stride + crop_x; const uint8_t* uv_row = uv_plane + static_cast(source_row / 2) * chroma_stride + crop_x; uint8_t* dst = out->data() + static_cast(row) * visible_width * 4; // NV12 的色度是 2x2 采样:一次算好两个像素共用的 U/V 项,省一半查表和乘法。 for (int column = 0; column < visible_width; column += 2) { const int uv_index = column & ~1; const int u = static_cast(uv_row[uv_index]) - 128; const int v = static_cast(uv_row[uv_index + 1]) - 128; const int blue_term = 516 * u + 128; const int green_term = -100 * u - 208 * v + 128; const int red_term = 409 * v + 128; const int pair = visible_width - column >= 2 ? 2 : 1; for (int k = 0; k < pair; ++k) { const int c = static_cast(y_row[column + k]) - 16; const int luma = 298 * (c < 0 ? 0 : c); dst[0] = ClampByte((luma + blue_term) >> 8); dst[1] = ClampByte((luma + green_term) >> 8); dst[2] = ClampByte((luma + red_term) >> 8); dst[3] = 0xff; dst += 4; } } } } // RGB32(XRGB) -> BGRA,顺带补齐 alpha 并处理自底向上的负 stride。 void ConvertRgb32(const uint8_t* data, size_t length, int coded_width, int coded_height, int crop_x, int crop_y, int visible_width, int visible_height, int stride, std::vector* out) { const int row_bytes = coded_width * 4; const int abs_stride = stride < 0 ? -stride : stride; const int source_stride = abs_stride < row_bytes ? row_bytes : abs_stride; if (length < static_cast(source_stride) * coded_height || visible_width <= 0 || visible_height <= 0) { return; } const int visible_bytes = visible_width * 4; out->assign(static_cast(visible_width) * visible_height * 4, 0xff); for (int row = 0; row < visible_height; ++row) { const int logical_row = crop_y + row; if (logical_row < 0 || logical_row >= coded_height) { continue; } const int source_row = stride < 0 ? (coded_height - 1 - logical_row) : logical_row; const uint8_t* src = data + static_cast(source_row) * source_stride + static_cast(crop_x) * 4; uint8_t* dst = out->data() + static_cast(row) * visible_bytes; std::memcpy(dst, src, static_cast(visible_bytes)); for (int column = 0; column < visible_width; ++column) { dst[column * 4 + 3] = 0xff; } } } // Media Foundation 视频解码器封装(H.264 / HEVC)。 class VideoDecoder { public: using FrameCallback = std::function>, int, int, uint64_t)>; VideoDecoder() = default; ~VideoDecoder() { Close(); } VideoDecoder(const VideoDecoder&) = delete; VideoDecoder& operator=(const VideoDecoder&) = delete; bool IsOpen() const { return transform_.Get() != nullptr; } uint8_t format() const { return format_; } const std::string& error() const { return error_; } bool Open(uint8_t format) { Close(); if (!mf_started_) { const HRESULT hr = MFStartup(MF_VERSION, MFSTARTUP_LITE); if (FAILED(hr)) { error_ = "MFStartup 失败"; return false; } mf_started_ = true; } format_ = format; const GUID subtype = (format == kFormatHevc) ? MFVideoFormat_HEVC : MFVideoFormat_H264; if (!CreateTransform(subtype)) { Close(); return false; } if (!SetInputType(subtype)) { error_ = "设置解码器输入类型失败"; Close(); return false; } // 首次协商可能失败(部分解码器要收到数据后才给出输出类型), // 后续在 Drain 中继续尝试。 NegotiateOutputType(); ConfigureLowLatency(); transform_->ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH, 0); transform_->ProcessMessage(MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, 0); transform_->ProcessMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0); error_.clear(); return true; } void Close() { if (transform_) { transform_->ProcessMessage(MFT_MESSAGE_NOTIFY_END_OF_STREAM, 0); transform_->ProcessMessage(MFT_MESSAGE_NOTIFY_END_STREAMING, 0); transform_->ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH, 0); transform_.Reset(); } output_type_.Reset(); output_type_valid_ = false; output_subtype_ = GUID{}; output_width_ = 0; output_height_ = 0; } HRESULT Submit(const uint8_t* data, size_t length, uint64_t pts) { if (!transform_) { return E_FAIL; } ComPtr buffer; HRESULT hr = MFCreateMemoryBuffer(static_cast(length), buffer.Put()); if (FAILED(hr)) { return hr; } BYTE* destination = nullptr; hr = buffer->Lock(&destination, nullptr, nullptr); if (FAILED(hr)) { return hr; } std::memcpy(destination, data, length); buffer->Unlock(); buffer->SetCurrentLength(static_cast(length)); ComPtr sample; hr = MFCreateSample(sample.Put()); if (FAILED(hr)) { return hr; } sample->AddBuffer(buffer.Get()); // Rust 侧 pts 单位为微秒,MF 使用 100 纳秒。 sample->SetSampleTime(static_cast(pts) * 10); sample->SetSampleDuration(0); last_pts_ = pts; return transform_->ProcessInput(kOutputStreamId, sample.Get(), 0); } void Drain(const FrameCallback& on_frame) { if (!transform_) { return; } if (!output_type_valid_ && FAILED(NegotiateOutputType())) { return; } for (DWORD iteration = 0; iteration < kMaxOutputsPerDrain; ++iteration) { MFT_OUTPUT_STREAM_INFO stream_info = {}; if (FAILED(transform_->GetOutputStreamInfo(kOutputStreamId, &stream_info))) { return; } const bool decoder_allocates = (stream_info.dwFlags & (MFT_OUTPUT_STREAM_PROVIDES_SAMPLES | MFT_OUTPUT_STREAM_CAN_PROVIDE_SAMPLES)) != 0; ComPtr provided; ComPtr provided_buffer; if (!decoder_allocates) { if (FAILED(MFCreateSample(provided.Put()))) { return; } const DWORD buffer_size = stream_info.cbSize > 0 ? stream_info.cbSize : (1920u * 1080u * 4u); if (FAILED(MFCreateMemoryBuffer(buffer_size, provided_buffer.Put()))) { return; } if (FAILED(provided->AddBuffer(provided_buffer.Get()))) { return; } } MFT_OUTPUT_DATA_BUFFER output = {}; output.dwStreamID = kOutputStreamId; output.pSample = provided.Get(); DWORD status = 0; const HRESULT hr = transform_->ProcessOutput(0, 1, &output, &status); if (output.pEvents != nullptr) { output.pEvents->Release(); output.pEvents = nullptr; } if (hr == MF_E_TRANSFORM_NEED_MORE_INPUT) { return; } if (hr == MF_E_TRANSFORM_STREAM_CHANGE) { NegotiateOutputType(); continue; } if (FAILED(hr)) { return; } ComPtr produced; if (output.pSample == provided.Get()) { produced = provided; } else { produced.Attach(output.pSample); } if (produced) { LONGLONG sample_time = 0; uint64_t output_pts = last_pts_; if (SUCCEEDED(produced->GetSampleTime(&sample_time)) && sample_time >= 0) { output_pts = static_cast(sample_time) / 10; } ExtractFrame(produced.Get(), output_pts, on_frame); } } } private: // 远程桌面场景要求低延迟:让解码器尽快吐帧,而不是为了「平滑播放」攒缓冲。 void ConfigureLowLatency() { ComPtr codec_api; if (SUCCEEDED(transform_->QueryInterface( __uuidof(ICodecAPI), reinterpret_cast(codec_api.Put())))) { VARIANT value = {}; value.vt = VT_BOOL; value.boolVal = VARIANT_TRUE; codec_api->SetValue(&CODECAPI_AVLowLatencyMode, &value); } ComPtr attributes; if (SUCCEEDED(transform_->GetAttributes(attributes.Put()))) { attributes->SetUINT32(MF_LOW_LATENCY, 1); } } bool CreateTransform(const GUID& subtype) { MFT_REGISTER_TYPE_INFO input_info = {MFMediaType_Video, subtype}; IMFActivate** activates = nullptr; UINT32 count = 0; const HRESULT hr = MFTEnumEx( MFT_CATEGORY_VIDEO_DECODER, MFT_ENUM_FLAG_SYNCMFT | MFT_ENUM_FLAG_LOCALMFT | MFT_ENUM_FLAG_SORTANDFILTER, &input_info, nullptr, &activates, &count); if (FAILED(hr)) { error_ = "枚举视频解码器失败"; return false; } bool activated = false; for (UINT32 index = 0; index < count && !activated; ++index) { if (activates[index] == nullptr) { continue; } ComPtr transform; const HRESULT activate_hr = activates[index]->ActivateObject( __uuidof(IMFTransform), reinterpret_cast(transform.Put())); if (SUCCEEDED(activate_hr) && transform) { transform_ = std::move(transform); activated = true; } } for (UINT32 index = 0; index < count; ++index) { if (activates[index] != nullptr) { activates[index]->Release(); } } CoTaskMemFree(activates); if (!activated) { error_ = (subtype == MFVideoFormat_HEVC) ? "系统没有可用的 HEVC 解码器" : "系统没有可用的 H.264 解码器"; return false; } return true; } bool SetInputType(const GUID& subtype) { ComPtr input_type; if (FAILED(MFCreateMediaType(input_type.Put()))) { return false; } input_type->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video); input_type->SetGUID(MF_MT_SUBTYPE, subtype); if (SUCCEEDED(transform_->SetInputType(kOutputStreamId, input_type.Get(), 0))) { return true; } // 部分解码器要求输入类型中带上帧尺寸。 const UINT32 candidates[][2] = {{1920, 1080}, {1280, 720}, {3840, 2160}}; for (const auto& candidate : candidates) { ComPtr sized_type; if (FAILED(MFCreateMediaType(sized_type.Put()))) { continue; } sized_type->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video); sized_type->SetGUID(MF_MT_SUBTYPE, subtype); MFSetAttributeSize(sized_type.Get(), MF_MT_FRAME_SIZE, candidate[0], candidate[1]); MFSetAttributeRatio(sized_type.Get(), MF_MT_FRAME_RATE, 30, 1); MFSetAttributeRatio(sized_type.Get(), MF_MT_PIXEL_ASPECT_RATIO, 1, 1); if (SUCCEEDED(transform_->SetInputType(kOutputStreamId, sized_type.Get(), 0))) { return true; } } return false; } HRESULT NegotiateOutputType() { output_type_.Reset(); output_type_valid_ = false; if (!transform_) { return E_FAIL; } ComPtr nv12; ComPtr rgb32; ComPtr fallback; for (DWORD index = 0;; ++index) { ComPtr candidate; const HRESULT hr = transform_->GetOutputAvailableType( kOutputStreamId, index, candidate.Put()); if (FAILED(hr)) { break; } GUID subtype = {}; if (FAILED(candidate->GetGUID(MF_MT_SUBTYPE, &subtype))) { continue; } if (IsEqualGUID(subtype, MFVideoFormat_NV12) != 0) { if (!nv12) { nv12 = candidate; } } else if (IsEqualGUID(subtype, MFVideoFormat_RGB32) != 0 || IsEqualGUID(subtype, MFVideoFormat_ARGB32) != 0) { if (!rgb32) { rgb32 = candidate; } } else if (!fallback) { fallback = candidate; } } ComPtr chosen; if (nv12) { chosen = nv12; } else if (rgb32) { chosen = rgb32; } else { chosen = fallback; } if (!chosen) { return MF_E_INVALIDMEDIATYPE; } const HRESULT hr = transform_->SetOutputType(kOutputStreamId, chosen.Get(), 0); if (FAILED(hr)) { return hr; } UINT32 width = 0; UINT32 height = 0; if (FAILED(MFGetAttributeSize(chosen.Get(), MF_MT_FRAME_SIZE, &width, &height)) || width == 0 || height == 0) { return MF_E_INVALIDTYPE; } GUID subtype = {}; if (FAILED(chosen->GetGUID(MF_MT_SUBTYPE, &subtype))) { return MF_E_INVALIDTYPE; } output_subtype_ = subtype; output_width_ = static_cast(width); output_height_ = static_cast(height); // 默认显示区域等于编码尺寸;解码器会补到 16 对齐,多余行通过 // MF_MT_MINIMUM_DISPLAY_APERTURE 裁掉。 crop_x_ = 0; crop_y_ = 0; visible_width_ = output_width_; visible_height_ = output_height_; MFVideoArea area = {}; UINT32 blob_size = 0; if (SUCCEEDED(chosen->GetBlob(MF_MT_MINIMUM_DISPLAY_APERTURE, reinterpret_cast(&area), sizeof(area), &blob_size)) && blob_size == sizeof(area) && area.Area.cx > 0 && area.Area.cy > 0 && area.OffsetX.value >= 0 && area.OffsetY.value >= 0 && area.OffsetX.value + area.Area.cx <= output_width_ && area.OffsetY.value + area.Area.cy <= output_height_) { crop_x_ = area.OffsetX.value; crop_y_ = area.OffsetY.value; visible_width_ = static_cast(area.Area.cx); visible_height_ = static_cast(area.Area.cy); } output_type_ = chosen; output_type_valid_ = true; return S_OK; } void ExtractFrame(IMFSample* sample, uint64_t pts, const FrameCallback& on_frame) { if (!output_type_valid_ || output_width_ <= 0 || output_height_ <= 0) { return; } ComPtr buffer; HRESULT hr = sample->ConvertToContiguousBuffer(buffer.Put()); if (FAILED(hr)) { return; } BYTE* data = nullptr; DWORD length = 0; hr = buffer->Lock(&data, nullptr, &length); if (FAILED(hr)) { return; } UINT32 raw_stride = 0; if (FAILED(output_type_->GetUINT32(MF_MT_DEFAULT_STRIDE, &raw_stride))) { raw_stride = 0; } const int stride = static_cast(raw_stride); const bool is_nv12 = IsEqualGUID(output_subtype_, MFVideoFormat_NV12) != 0; auto frame = std::make_shared>(); if (is_nv12) { const int luma_stride = stride > 0 ? stride : output_width_; ConvertNv12(data, static_cast(length), output_width_, output_height_, crop_x_, crop_y_, visible_width_, visible_height_, luma_stride, luma_stride, frame.get()); } else if (IsEqualGUID(output_subtype_, MFVideoFormat_RGB32) != 0 || IsEqualGUID(output_subtype_, MFVideoFormat_ARGB32) != 0) { ConvertRgb32(data, static_cast(length), output_width_, output_height_, crop_x_, crop_y_, visible_width_, visible_height_, stride, frame.get()); } else { buffer->Unlock(); return; } buffer->Unlock(); if (frame->empty()) { return; } on_frame(std::move(frame), visible_width_, visible_height_, pts); } ComPtr transform_; ComPtr output_type_; GUID output_subtype_ = {}; int output_width_ = 0; int output_height_ = 0; int crop_x_ = 0; int crop_y_ = 0; int visible_width_ = 0; int visible_height_ = 0; bool output_type_valid_ = false; bool mf_started_ = false; uint8_t format_ = kFormatH264; uint64_t last_pts_ = 0; std::string error_; }; // 视频纹理插件:注册外部纹理,并把解码结果交给 Flutter 渲染。 class VideoTexturePlugin : public flutter::Plugin { public: static void RegisterWith(FlutterDesktopPluginRegistrarRef registrar) { auto* windows_registrar = flutter::PluginRegistrarManager::GetInstance() ->GetRegistrar(registrar); auto plugin = std::make_unique(windows_registrar); windows_registrar->AddPlugin(std::move(plugin)); } explicit VideoTexturePlugin(flutter::PluginRegistrarWindows* registrar) : registrar_(registrar), texture_registrar_(registrar->texture_registrar()), frames_(std::make_shared()) { auto shared_frames = frames_; texture_variant_ = std::make_unique( flutter::PixelBufferTexture([this, shared_frames](size_t width, size_t height) { return CopyPixelBuffer(shared_frames.get(), width, height); })); if (texture_registrar_ != nullptr) { texture_id_ = texture_registrar_->RegisterTexture(texture_variant_.get()); } channel_ = std::make_unique>( registrar->messenger(), "ttstd/video", &flutter::StandardMethodCodec::GetInstance()); channel_->SetMethodCallHandler( [this](const flutter::MethodCall& call, std::unique_ptr> result) { HandleMethodCall(call, std::move(result)); }); // 用户点窗口关闭按钮或按 ESC:通知 Flutter 停止投屏。 video_window_.SetCloseHandler([this]() { OnVideoWindowClosed(); }); // 画面里的鼠标操作(点击/拖拽)→ Flutter,再由 Dart 转成触摸控制帧下发。 video_window_.SetInputHandler([this](int action, int x, int y) { if (channel_ == nullptr) { return; } flutter::EncodableMap map; map[flutter::EncodableValue("action")] = flutter::EncodableValue(action); map[flutter::EncodableValue("x")] = flutter::EncodableValue(x); map[flutter::EncodableValue("y")] = flutter::EncodableValue(y); channel_->InvokeMethod("pointer", std::make_unique(map)); }); // 右键/中键:button 1=右键 2=中键,Dart 侧映射成 Android 返回/多任务。 video_window_.SetMouseButtonHandler( [this](int button, int action, int x, int y) { if (channel_ == nullptr) { return; } flutter::EncodableMap map; map[flutter::EncodableValue("button")] = flutter::EncodableValue(button); map[flutter::EncodableValue("action")] = flutter::EncodableValue(action); map[flutter::EncodableValue("x")] = flutter::EncodableValue(x); map[flutter::EncodableValue("y")] = flutter::EncodableValue(y); channel_->InvokeMethod("mouse", std::make_unique(map)); }); // 滚轮:没有指针坐标,被控端用屏幕中心兜底。 video_window_.SetWheelHandler([this](int delta_x, int delta_y) { if (channel_ == nullptr) { return; } flutter::EncodableMap map; map[flutter::EncodableValue("deltaX")] = flutter::EncodableValue(delta_x); map[flutter::EncodableValue("deltaY")] = flutter::EncodableValue(delta_y); channel_->InvokeMethod("wheel", std::make_unique(map)); }); // 键盘:只报 Windows 虚拟键码,Android keycode 的映射留在 Dart 侧。 video_window_.SetKeyboardHandler([this](int action, int vk, int modifiers) { if (channel_ == nullptr) { return; } flutter::EncodableMap map; map[flutter::EncodableValue("action")] = flutter::EncodableValue(action); map[flutter::EncodableValue("vk")] = flutter::EncodableValue(vk); map[flutter::EncodableValue("modifiers")] = flutter::EncodableValue(modifiers); channel_->InvokeMethod("key", std::make_unique(map)); }); worker_ = std::thread([this, shared_frames]() { RunWorker(shared_frames); }); } ~VideoTexturePlugin() override { stop_.store(true); if (worker_.joinable()) { worker_.join(); } // 先摘掉回调,避免析构期间 DestroyWindow 触发 InvokeMethod。 video_window_.SetCloseHandler(nullptr); video_window_.SetInputHandler(nullptr); video_window_.SetMouseButtonHandler(nullptr); video_window_.SetWheelHandler(nullptr); video_window_.SetKeyboardHandler(nullptr); video_window_.Close(); if (texture_registrar_ != nullptr && texture_id_ != 0) { texture_registrar_->UnregisterTexture(texture_id_, std::function()); texture_id_ = 0; } } private: const FlutterDesktopPixelBuffer* CopyPixelBuffer(FrameStore* store, size_t /*width*/, size_t /*height*/) { int width = 0; int height = 0; uint64_t pts = 0; // FrameStore 里的帧是 BGRA(GDI 贴屏用的顺序)。若将来重新用 Flutter 纹理 // 显示画面,必须在这里把 R/B 换回 Flutter 需要的 RGBA 顺序。 const uint8_t* pixels = store->Acquire(&width, &height, &pts); if (pixels == nullptr) { return nullptr; } descriptor_.buffer = pixels; descriptor_.width = static_cast(width); descriptor_.height = static_cast(height); descriptor_.release_callback = nullptr; descriptor_.release_context = nullptr; return &descriptor_; } // 独立窗口被用户关闭:让 Dart 侧停止投屏。 void OnVideoWindowClosed() { if (closing_from_channel_) { closing_from_channel_ = false; return; } if (channel_ == nullptr) { return; } channel_->InvokeMethod("windowClosed", std::make_unique(true)); } void HandleMethodCall( const flutter::MethodCall& call, std::unique_ptr> result) { if (call.method_name() == "textureId") { result->Success(flutter::EncodableValue( static_cast(texture_id_))); return; } if (call.method_name() == "openWindow") { auto store = frames_; // Flutter 侧带上被控端屏幕尺寸,窗口首帧之前就能按正确比例开好。 int hint_width = 0; int hint_height = 0; if (const auto* arguments = std::get_if(call.arguments())) { auto read_int = [arguments](const char* key) -> int { const auto entry = arguments->find(flutter::EncodableValue(key)); if (entry == arguments->end()) { return 0; } if (const auto* value = std::get_if(&entry->second)) { return *value; } if (const auto* value = std::get_if(&entry->second)) { return static_cast(*value); } return 0; }; 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, start = window_start_frame_](int* width, int* height) { return store->Snapshot(width, height, start); }, hint_width, hint_height); result->Success(flutter::EncodableValue(opened)); return; } if (call.method_name() == "closeWindow") { // 由 Flutter 主动关闭时不回调 windowClosed,避免重复下发停止投屏。 // 窗口本来就没开时不要置位,否则下一次用户关窗会被错误抑制。 closing_from_channel_ = video_window_.IsOpen(); 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; int height = 0; frames_->size(&width, &height); map[flutter::EncodableValue("textureId")] = flutter::EncodableValue(static_cast(texture_id_)); const uint64_t decoded = frames_->frames(); map[flutter::EncodableValue("decoded")] = flutter::EncodableValue(static_cast(decoded)); map[flutter::EncodableValue("windowFrames")] = flutter::EncodableValue( static_cast(video_window_.IsOpen() ? decoded - window_start_frame_ : 0)); map[flutter::EncodableValue("pending")] = flutter::EncodableValue(pending_count_.load()); map[flutter::EncodableValue("received")] = flutter::EncodableValue(static_cast(received_)); map[flutter::EncodableValue("width")] = flutter::EncodableValue(static_cast(width)); map[flutter::EncodableValue("height")] = flutter::EncodableValue(static_cast(height)); map[flutter::EncodableValue("pts")] = flutter::EncodableValue(static_cast(frames_->pts())); std::string error; { std::lock_guard lock(diagnostic_mutex_); error = diagnostic_error_; } if (error.empty() && !saw_codec_config_.load() && keyframes_.load() > 0 && frames_->frames() == 0) { // 关键帧都收到了却始终没有 SPS/PPS,解码器会一直「吃数据不出图」且不报错, // 这里显式指出,避免和「还没等到关键帧」或「没收到码流」混为一谈。 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_)); map[flutter::EncodableValue("auBytes")] = flutter::EncodableValue(static_cast(last_bytes_)); map[flutter::EncodableValue("keyframes")] = flutter::EncodableValue(static_cast(keyframes_)); map[flutter::EncodableValue("submitHr")] = flutter::EncodableValue(static_cast(last_hr_)); result->Success(flutter::EncodableValue(map)); return; } result->NotImplemented(); } void RunWorker(std::shared_ptr store) { // Media Foundation 需要 MTA;已初始化时返回 RPC_E_CHANGED_MODE 可忽略。 const HRESULT com_hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED); std::vector buffer(kInitialPayloadCapacity, 0); std::vector pending; TtstdVideoFrame pending_meta = {}; bool has_pending = false; while (!stop_.load()) { // API function pointers and decoder strings belong to the worker thread. // Publish a protected snapshot instead of reading them from the UI thread. { std::lock_guard lock(diagnostic_mutex_); diagnostic_error_ = api_.error() + decoder_.error(); } pending_count_.store(static_cast(api_.Pending())); if (!has_pending) { if (!api_.EnsureLoaded()) { Sleep(kRetrySleepMs); continue; } const int32_t written = api_.Next(&pending_meta, buffer.data(), buffer.size()); if (written == kErrBufferTooSmall) { const size_t required = pending_meta.len > buffer.size() ? pending_meta.len : buffer.size(); buffer.resize(required + 64 * 1024); continue; } if (written <= 0) { Sleep(kIdleSleepMs); continue; } pending.assign(buffer.begin(), buffer.begin() + written); has_pending = true; ++received_; last_format_ = pending_meta.format; last_bytes_ = written; if ((pending_meta.flags & kFlagKeyframe) != 0) { ++keyframes_; } if (!saw_codec_config_.load() && HasCodecConfig(buffer.data(), static_cast(written), pending_meta.format)) { saw_codec_config_.store(true); } } if (!decoder_.IsOpen() || decoder_.format() != pending_meta.format) { if (!decoder_.Open(pending_meta.format)) { // 解码器不可用(例如缺少 HEVC 扩展):丢弃当前帧,稍后重试。 // 失败原因通过 stats.error 暴露给 Dart 诊断日志。 has_pending = false; Sleep(kRetrySleepMs); continue; } } HRESULT hr = decoder_.Submit(pending.data(), pending.size(), pending_meta.pts); if (hr == MF_E_NOTACCEPTING) { decoder_.Drain(MakeFrameCallback(store)); hr = decoder_.Submit(pending.data(), pending.size(), pending_meta.pts); } last_hr_ = static_cast(hr); has_pending = false; if (SUCCEEDED(hr)) { decoder_.Drain(MakeFrameCallback(store)); } } decoder_.Close(); if (SUCCEEDED(com_hr)) { CoUninitialize(); } } // 把解码帧写进纹理并通知引擎重绘。 std::function>, int, int, uint64_t)> MakeFrameCallback(const std::shared_ptr& store) { 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_); } }; } flutter::PluginRegistrarWindows* registrar_ = nullptr; flutter::TextureRegistrar* texture_registrar_ = nullptr; std::unique_ptr texture_variant_; std::unique_ptr> channel_; FlutterDesktopPixelBuffer descriptor_ = {}; std::shared_ptr frames_; uint64_t window_start_frame_ = 0; // 与主窗口纹理共享同一份 FrameStore 的独立串流窗口。 VideoWindow video_window_; // 本次关闭是由 Flutter 主动发起的(不需要再回调 windowClosed)。 bool closing_from_channel_ = false; RustVideoApi api_; VideoDecoder decoder_; std::mutex diagnostic_mutex_; std::string diagnostic_error_; std::atomic pending_count_{0}; std::atomic stop_{false}; std::thread worker_; int64_t texture_id_ = 0; std::atomic received_{0}; std::atomic keyframes_{0}; std::atomic saw_codec_config_{false}; std::atomic last_bytes_{0}; std::atomic last_hr_{0}; std::atomic last_format_{kFormatH264}; }; } // namespace void RegisterVideoTexturePlugin(FlutterDesktopPluginRegistrarRef registrar) { VideoTexturePlugin::RegisterWith(registrar); }