| 24 | } |
| 25 | |
| 26 | std::optional<cv::Mat> FramePoolScreencap::screencap() |
| 27 | { |
| 28 | if (!hwnd_) { |
| 29 | LogError << "hwnd_ is nullptr"; |
| 30 | return std::nullopt; |
| 31 | } |
| 32 | if (!cap_frame_pool_) { |
| 33 | if (!init()) { |
| 34 | LogError << "init failed"; |
| 35 | uninit(); |
| 36 | return std::nullopt; |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | // 检查窗口大小是否变化,如果变化则重新创建 frame pool |
| 41 | if (!check_and_handle_size_changed()) { |
| 42 | LogError << "check_and_handle_size_changed failed"; |
| 43 | return std::nullopt; |
| 44 | } |
| 45 | |
| 46 | winrt::Windows::Graphics::Capture::Direct3D11CaptureFrame frame = nullptr; |
| 47 | |
| 48 | try { |
| 49 | // 先清空 FramePool 中可能残留的旧帧 |
| 50 | while (auto old_frame = cap_frame_pool_.TryGetNextFrame()) { |
| 51 | old_frame.Close(); |
| 52 | } |
| 53 | |
| 54 | // 等待新帧到来 |
| 55 | using namespace std::chrono_literals; |
| 56 | auto start_time = std::chrono::steady_clock::now(); |
| 57 | while (duration_since(start_time) < 2000ms) { |
| 58 | std::this_thread::sleep_for(2ms); |
| 59 | frame = cap_frame_pool_.TryGetNextFrame(); |
| 60 | if (frame) { |
| 61 | break; |
| 62 | } |
| 63 | } |
| 64 | } |
| 65 | catch (const winrt::hresult_error& e) { |
| 66 | LogError << "Failed to get frame" << VAR(e.code()) << VAR(winrt::to_string(e.message())); |
| 67 | uninit(); |
| 68 | return std::nullopt; |
| 69 | } |
| 70 | |
| 71 | if (!frame) { |
| 72 | if (cached_image_.empty()) { |
| 73 | LogError << "Failed to get frame and no cached image available"; |
| 74 | return std::nullopt; |
| 75 | } |
| 76 | return cached_image_.clone(); |
| 77 | } |
| 78 | |
| 79 | auto surface = frame.Surface(); |
| 80 | if (!surface) { |
| 81 | LogError << "frame.Surface() is null"; |
| 82 | return std::nullopt; |
| 83 | } |
nothing calls this directly
no test coverage detected