| 6 |
| // Copyright © 2020 Mikhail Filimonov. All rights reserved. |
| 7 | // |
| 8 |
| 9 | #include "tgcalls/desktop_capturer/DesktopCaptureSourceHelper.h" |
| 10 |
| 11 | #include <iostream> |
| 12 | #include <memory> |
| 13 | #include <algorithm> |
| 14 | #include <chrono> |
| 15 | #include <iostream> |
| 16 | #include <vector> |
| 17 | #include <functional> |
| 18 |
| 19 | #include "tgcalls/desktop_capturer/DesktopCaptureSourceManager.h" |
| 20 | #include "rtc_base/thread.h" |
| 21 | #include "api/video/video_sink_interface.h" |
| 22 | #include "api/video/video_frame.h" |
| 23 | #include "modules/desktop_capture/desktop_and_cursor_composer.h" |
| 24 | #include "modules/desktop_capture/desktop_capturer.h" |
| 25 | #include "system_wrappers/include/clock.h" |
| 26 | #include "api/video/i420_buffer.h" |
| 27 | #include "third_party/libyuv/include/libyuv.h" |
| 28 |
| 29 | #ifdef WEBRTC_MAC |
| 30 | #import <QuartzCore/QuartzCore.h> |
| 31 | #endif // WEBRTC_MAC |
| 32 |
| 33 | namespace tgcalls { |
| 34 | namespace { |
| 35 |
| 36 | #ifdef WEBRTC_MAC |
| 37 | class CaptureScheduler { |
| 38 | public: |
| 39 | void runAsync(std::function<void()> method) { |
| 40 | dispatch_async(dispatch_get_main_queue(), ^{ |
| 41 | method(); |
| 42 | }); |
| 43 | } |
| 44 | void runDelayed(int delayMs, std::function<void()> method) { |
| 45 | const auto time = dispatch_time( |
| 46 | DISPATCH_TIME_NOW, |
| 47 | ((long long)delayMs * NSEC_PER_SEC) / 1000); |
| 48 | dispatch_after(time, dispatch_get_main_queue(), ^{ |
| 49 | method(); |
| 50 | }); |
| 51 | } |
| 52 | }; |
| 53 | #else // WEBRTC_MAC |
| 54 | rtc::Thread *GlobalCapturerThread() { |
| 55 | static auto result = [] { |
| 56 | auto thread = rtc::Thread::Create(); |
| 57 | thread->SetName("WebRTC-DesktopCapturer", nullptr); |
| 58 | thread->Start(); |
| 59 | return thread; |
| 60 | }(); |
| 61 | return result.get(); |
| 62 | } |
| 63 |
| 64 | class CaptureScheduler { |
| 65 | public: |
| 66 | CaptureScheduler() : _thread(GlobalCapturerThread()) { |
| 67 | } |
| 68 |
| 69 | void runAsync(std::function<void()> method) { |
| 70 | _thread->PostTask(std::move(method)); |
| 71 | } |
| 72 | void runDelayed(int delayMs, std::function<void()> method) { |
| 73 | _thread->PostDelayedTask(std::move(method), webrtc::TimeDelta::Millis(delayMs)); |
| 74 | } |
| 75 |
| 76 | private: |
| 77 | rtc::Thread *_thread; |
| 78 |
| 79 | }; |
| 80 | #endif // WEBRTC_MAC |
| 81 |
| 82 | class SourceFrameCallbackImpl : public webrtc::DesktopCapturer::Callback { |
| 83 | public: |
| 84 | SourceFrameCallbackImpl(DesktopSize size, int fps); |
| 85 |
| 86 | void OnCaptureResult( |
| 87 | webrtc::DesktopCapturer::Result result, |
| 88 | std::unique_ptr<webrtc::DesktopFrame> frame) override; |
| 89 | void setOutput( |
| 90 | std::shared_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink); |
| 91 | void setSecondaryOutput( |
| 92 | std::shared_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink); |
| 93 | void setOnFatalError(std::function<void ()>); |
| 94 | void setOnPause(std::function<void (bool)>); |
| 95 | private: |
| 96 | rtc::scoped_refptr<webrtc::I420Buffer> i420_buffer_; |
| 97 | std::shared_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> _sink; |
| 98 | std::shared_ptr< |
| 99 | rtc::VideoSinkInterface<webrtc::VideoFrame>> _secondarySink; |
| 100 | DesktopSize size_; |
| 101 | std::function<void ()> _onFatalError; |
| 102 | std::function<void (bool)> _onPause; |
| 103 | }; |
| 104 |
| 105 | class DesktopSourceRenderer { |
| 106 | public: |
| 107 | DesktopSourceRenderer( |
| 108 | CaptureScheduler &scheduler, |
| 109 | DesktopCaptureSource source, |
| 110 | DesktopCaptureSourceData data); |
| 111 |
| 112 | void start(); |
| 113 | void stop(); |
| 114 | void setOutput(std::shared_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink); |
| 115 | void setSecondaryOutput(std::shared_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink); |
| 116 | void loop(); |
| 117 | void setOnFatalError(std::function<void ()>); |
| 118 | void setOnPause(std::function<void (bool)>); |
| 119 | private: |
| 120 | CaptureScheduler &_scheduler; |
| 121 | std::unique_ptr<webrtc::DesktopCapturer> _capturer; |
| 122 | SourceFrameCallbackImpl _callback; |
| 123 | std::shared_ptr<bool> _timerGuard; |
| 124 | std::function<void()> _onFatalError; |
| 125 | std::function<void(bool)> _onPause; |
| 126 | bool _isRunning = false; |
| 127 | bool _fatalError = false; |
| 128 | bool _currentlyOnPause = false; |
| 129 | double _delayMs = 0.; |
| 130 |
| 131 | }; |
| 132 |
| 133 | SourceFrameCallbackImpl::SourceFrameCallbackImpl(DesktopSize size, int fps) |
| 134 | : size_(size) { |
| 135 | } |
| 136 |
| 137 | void SourceFrameCallbackImpl::OnCaptureResult( |
| 138 | webrtc::DesktopCapturer::Result result, |
| 139 | std::unique_ptr<webrtc::DesktopFrame> frame) { |
| 140 |
| 141 | const auto failed = (result != webrtc::DesktopCapturer::Result::SUCCESS) |
| 142 | || !frame |
| 143 | || frame->size().equals({ 1, 1 }); |
| 144 | if (failed) { |
| 145 | if (result == webrtc::DesktopCapturer::Result::ERROR_PERMANENT) { |
| 146 | if (_onFatalError) { |
| 147 | _onFatalError(); |
| 148 | } |
| 149 | } else if (_onPause) { |
| 150 | _onPause(true); |
| 151 | } |
| 152 | return; |
| 153 | } else if (_onPause) { |
| 154 | _onPause(false); |
| 155 | } |
| 156 |
| 157 | const auto frameSize = frame->size(); |
| 158 | auto fittedSize = (frameSize.width() >= size_.width * 2 |
| 159 | || frameSize.height() >= size_.height * 2) |
| 160 | ? DesktopSize{ frameSize.width() / 2, frameSize.height() / 2 } |
| 161 | : DesktopSize{ frameSize.width(), frameSize.height() }; |
| 162 |
| 163 | fittedSize.width -= (fittedSize.width % 4); |
| 164 | fittedSize.height -= (fittedSize.height % 4); |
| 165 |
| 166 | const auto outputSize = webrtc::DesktopSize{ |
| 167 | fittedSize.width, |
| 168 | fittedSize.height |
| 169 | }; |
| 170 |
| 171 | webrtc::BasicDesktopFrame outputFrame{ outputSize }; |
| 172 |
| 173 | const auto outputRect = webrtc::DesktopRect::MakeSize(outputSize); |
| 174 |
| 175 | const auto outputRectData = outputFrame.data() + |
| 176 | outputFrame.stride() * outputRect.top() + |
| 177 | webrtc::DesktopFrame::kBytesPerPixel * outputRect.left(); |
| 178 |
| 179 |
| 180 | libyuv::ARGBScale( |
| 181 | frame->data(), |
| 182 | frame->stride(), |
| 183 | frame->size().width(), |
| 184 | frame->size().height(), |
| 185 | outputRectData, |
| 186 | outputFrame.stride(), |
| 187 | outputSize.width(), |
| 188 | outputSize.height(), |
| 189 | libyuv::kFilterBilinear); |
| 190 |
| 191 | int width = outputFrame.size().width(); |
| 192 | int height = outputFrame.size().height(); |
| 193 | int stride_y = width; |
| 194 | int stride_uv = (width + 1) / 2; |
| 195 |
| 196 | if (!i420_buffer_ |
| 197 | || i420_buffer_->width() != width |
| 198 | || i420_buffer_->height() != height) { |
| 199 | i420_buffer_ = webrtc::I420Buffer::Create( |
| 200 | width, |
| 201 | height, |
| 202 | stride_y, |
| 203 | stride_uv, |
| 204 | stride_uv); |
| 205 | } |
| 206 |
| 207 | int i420Result = libyuv::ConvertToI420( |
| 208 | outputFrame.data(), |
| 209 | width * height, |
| 210 | i420_buffer_->MutableDataY(), i420_buffer_->StrideY(), |
| 211 | i420_buffer_->MutableDataU(), i420_buffer_->StrideU(), |
| 212 | i420_buffer_->MutableDataV(), i420_buffer_->StrideV(), |
| 213 | 0, 0, |
| 214 | width, height, |
| 215 | width, height, |
| 216 | libyuv::kRotate0, |
| 217 | libyuv::FOURCC_ARGB); |
| 218 |
| 219 |
| 220 | assert(i420Result == 0); |
| 221 | (void)i420Result; |
| 222 | webrtc::VideoFrame nativeVideoFrame = webrtc::VideoFrame( |
| 223 | i420_buffer_, |
| 224 | webrtc::kVideoRotation_0, |
| 225 | webrtc::Clock::GetRealTimeClock()->CurrentTime().us()); |
| 226 | if (const auto sink = _sink.get()) { |
| 227 | _sink->OnFrame(nativeVideoFrame); |
| 228 | } |
| 229 | if (const auto sink = _secondarySink.get()) { |
| 230 | sink->OnFrame(nativeVideoFrame); |
| 231 | } |
| 232 | } |
| 233 |
| 234 | void SourceFrameCallbackImpl::setOutput( |
| 235 | std::shared_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink) { |
| 236 | _sink = std::move(sink); |
| 237 | } |
| 238 |
| 239 | void SourceFrameCallbackImpl::setOnFatalError(std::function<void ()> error) { |
| 240 | _onFatalError = error; |
| 241 | } |
| 242 | void SourceFrameCallbackImpl::setOnPause(std::function<void (bool)> pause) { |
| 243 | _onPause = pause; |
| 244 | } |
| 245 |
| 246 | void SourceFrameCallbackImpl::setSecondaryOutput( |
| 247 | std::shared_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink) { |
| 248 | _secondarySink = std::move(sink); |
| 249 | } |
| 250 |
| 251 | DesktopSourceRenderer::DesktopSourceRenderer( |
| 252 | CaptureScheduler &scheduler, |
| 253 | DesktopCaptureSource source, |
| 254 | DesktopCaptureSourceData data) |
| 255 | : _scheduler(scheduler) |
| 256 | , _callback(data.aspectSize, data.fps) |
| 257 | , _delayMs(1000. / data.fps) { |
| 258 | _callback.setOnFatalError([=] { |
| 259 | stop(); |
| 260 | _fatalError = true; |
| 261 | if (_onFatalError) _onFatalError(); |
| 262 | }); |
| 263 |
| 264 | _callback.setOnPause([=] (bool pause) { |
| 265 | bool previousOnPause = _currentlyOnPause; |
| 266 | _currentlyOnPause = pause; |
| 267 | if (previousOnPause != _currentlyOnPause) { |
| 268 | if (_onPause) _onPause(pause); |
| 269 | } |
| 270 | }); |
| 271 |
| 272 | auto options = webrtc::DesktopCaptureOptions::CreateDefault(); |
| 273 | options.set_disable_effects(true); |
| 274 | options.set_detect_updated_region(true); |
| 275 |
| 276 | #ifdef WEBRTC_WIN |
| 277 | options.set_allow_directx_capturer(true); |
| 278 | #elif defined WEBRTC_MAC |
| 279 | options.set_allow_iosurface(true); |
| 280 | #elif defined WEBRTC_USE_PIPEWIRE |
| 281 | options.set_allow_pipewire(true); |
| 282 | #endif // WEBRTC_WIN || WEBRTC_MAC |
| 283 |
| 284 | _capturer = webrtc::DesktopCapturer::CreateGenericCapturer(options); |
| 285 | if (!_capturer) { |
| 286 | if (source.isWindow()) { |
| 287 | _capturer = webrtc::DesktopCapturer::CreateWindowCapturer(options); |
| 288 | } else { |
| 289 | _capturer = webrtc::DesktopCapturer::CreateScreenCapturer(options); |
| 290 | } |
| 291 | if (!_capturer) { |
| 292 | _fatalError = true; |
| 293 | return; |
| 294 | } |
| 295 | } |
| 296 | if (data.captureMouse) { |
| 297 | _capturer = std::make_unique<webrtc::DesktopAndCursorComposer>( |
| 298 | std::move(_capturer), |
| 299 | options); |
| 300 | } |
| 301 | _capturer->SelectSource(source.uniqueId()); |
| 302 | _capturer->Start(&_callback); |
| 303 | } |
| 304 |
| 305 | void DesktopSourceRenderer::start() { |
| 306 | if (!_capturer || _isRunning) { |
| 307 | return; |
| 308 | } |
| 309 | // ++GlobalCount; |
| 310 | //#ifdef WEBRTC_MAC |
| 311 | // NSLog(@"current capture count: %d", GlobalCount); |
| 312 | //#endif // WEBRTC_MAC |
| 313 |
| 314 | _isRunning = true; |
| 315 | _timerGuard = std::make_shared<bool>(true); |
| 316 | loop(); |
| 317 | } |
| 318 |
| 319 | void DesktopSourceRenderer::stop() { |
| 320 | // if (_isRunning) { |
| 321 | // GlobalCount--; |
| 322 | // |
| 323 | //#ifdef WEBRTC_MAC |
| 324 | // NSLog(@"current capture count: %d", GlobalCount); |
| 325 | //#endif // WEBRTC_MAC |
| 326 | // } |
| 327 | _isRunning = false; |
| 328 | _timerGuard = nullptr; |
| 329 | } |
| 330 |
| 331 | void DesktopSourceRenderer::loop() { |
| 332 | if (!_capturer || !_isRunning) { |
| 333 | return; |
| 334 | } |
| 335 |
| 336 | _capturer->CaptureFrame(); |
| 337 | const auto guard = std::weak_ptr<bool>(_timerGuard); |
| 338 | _scheduler.runDelayed(_delayMs, [=] { |
| 339 | if (guard.lock()) { |
| 340 | loop(); |
| 341 | } |
| 342 | }); |
| 343 | } |
| 344 |
| 345 | void DesktopSourceRenderer::setOnFatalError(std::function<void ()> error) { |
| 346 | if (_fatalError) { |
| 347 | error(); |
| 348 | } else { |
| 349 | _onFatalError = std::move(error); |
| 350 | } |
| 351 | } |
| 352 |
| 353 | void DesktopSourceRenderer::setOnPause(std::function<void (bool)> pause) { |
| 354 | if (_currentlyOnPause) { |
| 355 | pause(true); |
| 356 | } |
| 357 | _onPause = std::move(pause); |
| 358 | } |
| 359 |
| 360 | void DesktopSourceRenderer::setOutput( |
| 361 | std::shared_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink) { |
| 362 | _callback.setOutput(std::move(sink)); |
| 363 | } |
| 364 |
| 365 | void DesktopSourceRenderer::setSecondaryOutput( |
| 366 | std::shared_ptr<rtc::VideoSinkInterface<webrtc::VideoFrame>> sink) { |
| 367 | _callback.setSecondaryOutput(std::move(sink)); |
| 368 | } |
| 369 |
| 370 | } // namespace |
| 371 |
| 372 | struct DesktopCaptureSourceHelper::Renderer { |
| 373 | CaptureScheduler scheduler; |
| 374 | std::unique_ptr<DesktopSourceRenderer> renderer; |
| 375 | }; |
| 376 |
| 377 | DesktopCaptureSource DesktopCaptureSourceForKey( |
| 378 | const std::string &uniqueKey) { |
| 379 | if (!ShouldBeDesktopCapture(uniqueKey)) { |
| 380 | return DesktopCaptureSource::Invalid(); |
| 381 | } |
| 382 | if (uniqueKey == "desktop_capturer_pipewire") { |
| 383 | return DesktopCaptureSource(0, "pipewire", false); |
| 384 | } |
| 385 | const auto windowPrefix = std::string("desktop_capturer_window_"); |
| 386 | const auto isWindow = (uniqueKey.find(windowPrefix) == 0); |
| 387 | DesktopCaptureSourceManager manager(isWindow |
| 388 | ? DesktopCaptureType::Window |
| 389 | : DesktopCaptureType::Screen); |
| 390 | const auto sources = manager.sources(); |
| 391 |
| 392 | // "desktop_capturer_window_".size() == "desktop_capturer_screen_".size() |
| 393 | const auto keyId = std::stoll(uniqueKey.substr(windowPrefix.size())); |
| 394 | for (const auto &source : sources) { |
| 395 | if (source.uniqueId() == keyId) { |
| 396 | return source; |
| 397 | } |
| 398 | } |
| 399 | return DesktopCaptureSource::Invalid(); |
| 400 | } |
| 401 |
| 402 | bool ShouldBeDesktopCapture(const std::string &uniqueKey) { |
| 403 | return (uniqueKey.find("desktop_capturer_") == 0); |
| 404 | } |
| 405 |
| 406 | DesktopCaptureSourceHelper::DesktopCaptureSourceHelper( |
| 407 | DesktopCaptureSource source, |
| 408 | DesktopCaptureSourceData data) |
| 409 | : _renderer(std::make_shared<Renderer>()) { |
| 410 | _renderer->scheduler.runAsync([renderer = _renderer, source, data] { |
| 411 | renderer->renderer = std::make_unique<DesktopSourceRenderer>( |
| 412 | renderer->scheduler, |
| 413 | source, |
| 414 | data); |
| 415 | }); |
| 416 | } |
| 417 |
| 418 | DesktopCaptureSourceHelper::~DesktopCaptureSourceHelper() { |
| 419 | _renderer->scheduler.runAsync([renderer = _renderer] { |
| 420 | }); |
| 421 | } |
| 422 |
| 423 | void DesktopCaptureSourceHelper::setOutput( |
| 424 | std::shared_ptr< |
| 425 | rtc::VideoSinkInterface<webrtc::VideoFrame>> sink) const { |
| 426 | _renderer->scheduler.runAsync([renderer = _renderer, sink] { |
| 427 | renderer->renderer->setOutput(sink); |
| 428 | }); |
| 429 | } |
| 430 |
| 431 | void DesktopCaptureSourceHelper::setSecondaryOutput( |
| 432 | std::shared_ptr< |
| 433 | rtc::VideoSinkInterface<webrtc::VideoFrame>> sink) const { |
| 434 | _renderer->scheduler.runAsync([renderer = _renderer, sink] { |
| 435 | renderer->renderer->setSecondaryOutput(sink); |
| 436 | }); |
| 437 | } |
| 438 |
| 439 | void DesktopCaptureSourceHelper::start() const { |
| 440 | _renderer->scheduler.runAsync([renderer = _renderer] { |
| 441 | renderer->renderer->start(); |
| 442 | }); |
| 443 | } |
| 444 | void DesktopCaptureSourceHelper::setOnFatalError(std::function<void ()> error) const { |
| 445 | _renderer->scheduler.runAsync([renderer = _renderer, error = error] { |
| 446 | renderer->renderer->setOnFatalError(error); |
| 447 | }); |
| 448 | } |
| 449 | void DesktopCaptureSourceHelper::setOnPause(std::function<void (bool)> pause) const { |
| 450 | _renderer->scheduler.runAsync([renderer = _renderer, pause = pause] { |
| 451 | renderer->renderer->setOnPause(pause); |
| 452 | }); |
| 453 | } |
| 454 |
| 455 | void DesktopCaptureSourceHelper::stop() const { |
| 456 | _renderer->scheduler.runAsync([renderer = _renderer] { |
| 457 | renderer->renderer->stop(); |
| 458 | }); |
| 459 | } |
| 460 |
| 461 | } // namespace tgcalls |
| 462 |