| 6 | * tree. An additional intellectual property rights grant can be found |
| 7 | * in the file PATENTS. All contributing project authors may |
| 8 | * be found in the AUTHORS file in the root of the source tree. |
| 9 | */ |
| 10 |
| 11 | #include "rtc_base/task_queue_win.h" |
| 12 |
| 13 | // clang-format off |
| 14 | // clang formating would change include order. |
| 15 |
| 16 | // Include winsock2.h before including <windows.h> to maintain consistency with |
| 17 | // win32.h. To include win32.h directly, it must be broken out into its own |
| 18 | // build target. |
| 19 | #include <winsock2.h> |
| 20 | #include <windows.h> |
| 21 | #include <sal.h> // Must come after windows headers. |
| 22 | #include <mmsystem.h> // Must come after windows headers. |
| 23 | // clang-format on |
| 24 | #include <string.h> |
| 25 |
| 26 | #include <algorithm> |
| 27 | #include <memory> |
| 28 | #include <queue> |
| 29 | #include <utility> |
| 30 |
| 31 | #include "absl/strings/string_view.h" |
| 32 | #include "api/task_queue/queued_task.h" |
| 33 | #include "api/task_queue/task_queue_base.h" |
| 34 | #include "rtc_base/arraysize.h" |
| 35 | #include "rtc_base/checks.h" |
| 36 | #include "rtc_base/event.h" |
| 37 | #include "rtc_base/logging.h" |
| 38 | #include "rtc_base/numerics/safe_conversions.h" |
| 39 | #include "rtc_base/platform_thread.h" |
| 40 | #include "rtc_base/time_utils.h" |
| 41 | #include "rtc_base/synchronization/mutex.h" |
| 42 |
| 43 | namespace webrtc { |
| 44 | namespace { |
| 45 | #define WM_RUN_TASK WM_USER + 1 |
| 46 | #define WM_QUEUE_DELAYED_TASK WM_USER + 2 |
| 47 |
| 48 | void CALLBACK InitializeQueueThread(ULONG_PTR param) { |
| 49 | MSG msg; |
| 50 | ::PeekMessage(&msg, nullptr, WM_USER, WM_USER, PM_NOREMOVE); |
| 51 | rtc::Event* data = reinterpret_cast<rtc::Event*>(param); |
| 52 | data->Set(); |
| 53 | } |
| 54 |
| 55 | rtc::ThreadPriority TaskQueuePriorityToThreadPriority( |
| 56 | TaskQueueFactory::Priority priority) { |
| 57 | switch (priority) { |
| 58 | case TaskQueueFactory::Priority::HIGH: |
| 59 | return rtc::kRealtimePriority; |
| 60 | case TaskQueueFactory::Priority::LOW: |
| 61 | return rtc::kLowPriority; |
| 62 | case TaskQueueFactory::Priority::NORMAL: |
| 63 | return rtc::kNormalPriority; |
| 64 | default: |
| 65 | RTC_NOTREACHED(); |
| 66 | break; |
| 67 | } |
| 68 | return rtc::kNormalPriority; |
| 69 | } |
| 70 |
| 71 | int64_t GetTick() { |
| 72 | static const UINT kPeriod = 1; |
| 73 | bool high_res = (timeBeginPeriod(kPeriod) == TIMERR_NOERROR); |
| 74 | int64_t ret = rtc::TimeMillis(); |
| 75 | if (high_res) |
| 76 | timeEndPeriod(kPeriod); |
| 77 | return ret; |
| 78 | } |
| 79 |
| 80 | class DelayedTaskInfo { |
| 81 | public: |
| 82 | // Default ctor needed to support priority_queue::pop(). |
| 83 | DelayedTaskInfo() {} |
| 84 | DelayedTaskInfo(uint32_t milliseconds, std::unique_ptr<QueuedTask> task) |
| 85 | : due_time_(GetTick() + milliseconds), task_(std::move(task)) {} |
| 86 | DelayedTaskInfo(DelayedTaskInfo&&) = default; |
| 87 |
| 88 | // Implement for priority_queue. |
| 89 | bool operator>(const DelayedTaskInfo& other) const { |
| 90 | return due_time_ > other.due_time_; |
| 91 | } |
| 92 |
| 93 | // Required by priority_queue::pop(). |
| 94 | DelayedTaskInfo& operator=(DelayedTaskInfo&& other) = default; |
| 95 |
| 96 | // See below for why this method is const. |
| 97 | void Run() const { |
| 98 | RTC_DCHECK(due_time_); |
| 99 | task_->Run() ? task_.reset() : static_cast<void>(task_.release()); |
| 100 | } |
| 101 |
| 102 | int64_t due_time() const { return due_time_; } |
| 103 |
| 104 | private: |
| 105 | int64_t due_time_ = 0; // Absolute timestamp in milliseconds. |
| 106 |
| 107 | // |task| needs to be mutable because std::priority_queue::top() returns |
| 108 | // a const reference and a key in an ordered queue must not be changed. |
| 109 | // There are two basic workarounds, one using const_cast, which would also |
| 110 | // make the key (|due_time|), non-const and the other is to make the non-key |
| 111 | // (|task|), mutable. |
| 112 | // Because of this, the |task| variable is made private and can only be |
| 113 | // mutated by calling the |Run()| method. |
| 114 | mutable std::unique_ptr<QueuedTask> task_; |
| 115 | }; |
| 116 |
| 117 | class MultimediaTimer { |
| 118 | public: |
| 119 | // Note: We create an event that requires manual reset. |
| 120 | MultimediaTimer() : event_(::CreateEvent(nullptr, true, false, nullptr)) {} |
| 121 |
| 122 | ~MultimediaTimer() { |
| 123 | Cancel(); |
| 124 | ::CloseHandle(event_); |
| 125 | } |
| 126 |
| 127 | bool StartOneShotTimer(UINT delay_ms) { |
| 128 | RTC_DCHECK_EQ(0, timer_id_); |
| 129 | RTC_DCHECK(event_ != nullptr); |
| 130 | timer_id_ = |
| 131 | ::timeSetEvent(delay_ms, 0, reinterpret_cast<LPTIMECALLBACK>(event_), 0, |
| 132 | TIME_ONESHOT | TIME_CALLBACK_EVENT_SET); |
| 133 | return timer_id_ != 0; |
| 134 | } |
| 135 |
| 136 | void Cancel() { |
| 137 | if (timer_id_) { |
| 138 | ::timeKillEvent(timer_id_); |
| 139 | timer_id_ = 0; |
| 140 | } |
| 141 | // Now that timer is killed and not able to set the event, reset the event. |
| 142 | // Doing it in opposite order is racy because event may be set between |
| 143 | // event was reset and timer is killed leaving MultimediaTimer in surprising |
| 144 | // state where both event is set and timer is canceled. |
| 145 | ::ResetEvent(event_); |
| 146 | } |
| 147 |
| 148 | HANDLE* event_for_wait() { return &event_; } |
| 149 |
| 150 | private: |
| 151 | HANDLE event_ = nullptr; |
| 152 | MMRESULT timer_id_ = 0; |
| 153 |
| 154 | RTC_DISALLOW_COPY_AND_ASSIGN(MultimediaTimer); |
| 155 | }; |
| 156 |
| 157 | class TaskQueueWin : public TaskQueueBase { |
| 158 | public: |
| 159 | TaskQueueWin(absl::string_view queue_name, rtc::ThreadPriority priority); |
| 160 | ~TaskQueueWin() override = default; |
| 161 |
| 162 | void Delete() override; |
| 163 | void PostTask(std::unique_ptr<QueuedTask> task) override; |
| 164 | void PostDelayedTask(std::unique_ptr<QueuedTask> task, |
| 165 | uint32_t milliseconds) override; |
| 166 |
| 167 | void RunPendingTasks(); |
| 168 |
| 169 | private: |
| 170 | static void ThreadMain(void* context); |
| 171 |
| 172 | class WorkerThread : public rtc::PlatformThread { |
| 173 | public: |
| 174 | WorkerThread(rtc::ThreadRunFunction func, |
| 175 | void* obj, |
| 176 | absl::string_view thread_name, |
| 177 | rtc::ThreadPriority priority) |
| 178 | : PlatformThread(func, obj, thread_name, priority) {} |
| 179 |
| 180 | bool QueueAPC(PAPCFUNC apc_function, ULONG_PTR data) { |
| 181 | return rtc::PlatformThread::QueueAPC(apc_function, data); |
| 182 | } |
| 183 | }; |
| 184 |
| 185 | void RunThreadMain(); |
| 186 | bool ProcessQueuedMessages(); |
| 187 | void RunDueTasks(); |
| 188 | void ScheduleNextTimer(); |
| 189 | void CancelTimers(); |
| 190 |
| 191 | // Since priority_queue<> by defult orders items in terms of |
| 192 | // largest->smallest, using std::less<>, and we want smallest->largest, |
| 193 | // we would like to use std::greater<> here. Alas it's only available in |
| 194 | // C++14 and later, so we roll our own compare template that that relies on |
| 195 | // operator<(). |
| 196 | template <typename T> |
| 197 | struct greater { |
| 198 | bool operator()(const T& l, const T& r) { return l > r; } |
| 199 | }; |
| 200 |
| 201 | MultimediaTimer timer_; |
| 202 | std::priority_queue<DelayedTaskInfo, |
| 203 | std::vector<DelayedTaskInfo>, |
| 204 | greater<DelayedTaskInfo>> |
| 205 | timer_tasks_; |
| 206 | UINT_PTR timer_id_ = 0; |
| 207 | WorkerThread thread_; |
| 208 | Mutex pending_lock_; |
| 209 | std::queue<std::unique_ptr<QueuedTask>> pending_ |
| 210 | RTC_GUARDED_BY(pending_lock_); |
| 211 | HANDLE in_queue_; |
| 212 | }; |
| 213 |
| 214 | TaskQueueWin::TaskQueueWin(absl::string_view queue_name, |
| 215 | rtc::ThreadPriority priority) |
| 216 | : thread_(&TaskQueueWin::ThreadMain, this, queue_name, priority), |
| 217 | in_queue_(::CreateEvent(nullptr, true, false, nullptr)) { |
| 218 | RTC_DCHECK(in_queue_); |
| 219 | thread_.Start(); |
| 220 | rtc::Event event(false, false); |
| 221 | RTC_CHECK(thread_.QueueAPC(&InitializeQueueThread, |
| 222 | reinterpret_cast<ULONG_PTR>(&event))); |
| 223 | event.Wait(rtc::Event::kForever); |
| 224 | } |
| 225 |
| 226 | void TaskQueueWin::Delete() { |
| 227 | RTC_DCHECK(!IsCurrent()); |
| 228 | while (!::PostThreadMessage(thread_.GetThreadRef(), WM_QUIT, 0, 0)) { |
| 229 | RTC_CHECK_EQ(ERROR_NOT_ENOUGH_QUOTA, ::GetLastError()); |
| 230 | Sleep(1); |
| 231 | } |
| 232 | thread_.Stop(); |
| 233 | ::CloseHandle(in_queue_); |
| 234 | delete this; |
| 235 | } |
| 236 |
| 237 | void TaskQueueWin::PostTask(std::unique_ptr<QueuedTask> task) { |
| 238 | MutexLock lock(&pending_lock_); |
| 239 | pending_.push(std::move(task)); |
| 240 | ::SetEvent(in_queue_); |
| 241 | } |
| 242 |
| 243 | void TaskQueueWin::PostDelayedTask(std::unique_ptr<QueuedTask> task, |
| 244 | uint32_t milliseconds) { |
| 245 | if (!milliseconds) { |
| 246 | PostTask(std::move(task)); |
| 247 | return; |
| 248 | } |
| 249 |
| 250 | // TODO(tommi): Avoid this allocation. It is currently here since |
| 251 | // the timestamp stored in the task info object, is a 64bit timestamp |
| 252 | // and WPARAM is 32bits in 32bit builds. Otherwise, we could pass the |
| 253 | // task pointer and timestamp as LPARAM and WPARAM. |
| 254 | auto* task_info = new DelayedTaskInfo(milliseconds, std::move(task)); |
| 255 | if (!::PostThreadMessage(thread_.GetThreadRef(), WM_QUEUE_DELAYED_TASK, 0, |
| 256 | reinterpret_cast<LPARAM>(task_info))) { |
| 257 | delete task_info; |
| 258 | } |
| 259 | } |
| 260 |
| 261 | void TaskQueueWin::RunPendingTasks() { |
| 262 | while (true) { |
| 263 | std::unique_ptr<QueuedTask> task; |
| 264 | { |
| 265 | MutexLock lock(&pending_lock_); |
| 266 | if (pending_.empty()) |
| 267 | break; |
| 268 | task = std::move(pending_.front()); |
| 269 | pending_.pop(); |
| 270 | } |
| 271 |
| 272 | if (!task->Run()) |
| 273 | task.release(); |
| 274 | } |
| 275 | } |
| 276 |
| 277 | // static |
| 278 | void TaskQueueWin::ThreadMain(void* context) { |
| 279 | static_cast<TaskQueueWin*>(context)->RunThreadMain(); |
| 280 | } |
| 281 |
| 282 | void TaskQueueWin::RunThreadMain() { |
| 283 | CurrentTaskQueueSetter set_current(this); |
| 284 | HANDLE handles[2] = {*timer_.event_for_wait(), in_queue_}; |
| 285 | while (true) { |
| 286 | // Make sure we do an alertable wait as that's required to allow APCs to run |
| 287 | // (e.g. required for InitializeQueueThread and stopping the thread in |
| 288 | // PlatformThread). |
| 289 | DWORD result = ::MsgWaitForMultipleObjectsEx( |
| 290 | arraysize(handles), handles, INFINITE, QS_ALLEVENTS, MWMO_ALERTABLE); |
| 291 | RTC_CHECK_NE(WAIT_FAILED, result); |
| 292 | if (result == (WAIT_OBJECT_0 + 2)) { |
| 293 | // There are messages in the message queue that need to be handled. |
| 294 | if (!ProcessQueuedMessages()) |
| 295 | break; |
| 296 | } |
| 297 |
| 298 | if (result == WAIT_OBJECT_0 || |
| 299 | (!timer_tasks_.empty() && |
| 300 | ::WaitForSingleObject(*timer_.event_for_wait(), 0) == WAIT_OBJECT_0)) { |
| 301 | // The multimedia timer was signaled. |
| 302 | timer_.Cancel(); |
| 303 | RunDueTasks(); |
| 304 | ScheduleNextTimer(); |
| 305 | } |
| 306 |
| 307 | if (result == (WAIT_OBJECT_0 + 1)) { |
| 308 | ::ResetEvent(in_queue_); |
| 309 | RunPendingTasks(); |
| 310 | } |
| 311 | } |
| 312 | } |
| 313 |
| 314 | bool TaskQueueWin::ProcessQueuedMessages() { |
| 315 | MSG msg = {}; |
| 316 | // To protect against overly busy message queues, we limit the time |
| 317 | // we process tasks to a few milliseconds. If we don't do that, there's |
| 318 | // a chance that timer tasks won't ever run. |
| 319 | static const int kMaxTaskProcessingTimeMs = 500; |
| 320 | auto start = GetTick(); |
| 321 | while (::PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE) && |
| 322 | msg.message != WM_QUIT) { |
| 323 | if (!msg.hwnd) { |
| 324 | switch (msg.message) { |
| 325 | // TODO(tommi): Stop using this way of queueing tasks. |
| 326 | case WM_RUN_TASK: { |
| 327 | QueuedTask* task = reinterpret_cast<QueuedTask*>(msg.lParam); |
| 328 | if (task->Run()) |
| 329 | delete task; |
| 330 | break; |
| 331 | } |
| 332 | case WM_QUEUE_DELAYED_TASK: { |
| 333 | std::unique_ptr<DelayedTaskInfo> info( |
| 334 | reinterpret_cast<DelayedTaskInfo*>(msg.lParam)); |
| 335 | bool need_to_schedule_timers = |
| 336 | timer_tasks_.empty() || |
| 337 | timer_tasks_.top().due_time() > info->due_time(); |
| 338 | timer_tasks_.emplace(std::move(*info.get())); |
| 339 | if (need_to_schedule_timers) { |
| 340 | CancelTimers(); |
| 341 | ScheduleNextTimer(); |
| 342 | } |
| 343 | break; |
| 344 | } |
| 345 | case WM_TIMER: { |
| 346 | RTC_DCHECK_EQ(timer_id_, msg.wParam); |
| 347 | ::KillTimer(nullptr, msg.wParam); |
| 348 | timer_id_ = 0; |
| 349 | RunDueTasks(); |
| 350 | ScheduleNextTimer(); |
| 351 | break; |
| 352 | } |
| 353 | default: |
| 354 | RTC_NOTREACHED(); |
| 355 | break; |
| 356 | } |
| 357 | } else { |
| 358 | ::TranslateMessage(&msg); |
| 359 | ::DispatchMessage(&msg); |
| 360 | } |
| 361 |
| 362 | if (GetTick() > start + kMaxTaskProcessingTimeMs) |
| 363 | break; |
| 364 | } |
| 365 | return msg.message != WM_QUIT; |
| 366 | } |
| 367 |
| 368 | void TaskQueueWin::RunDueTasks() { |
| 369 | RTC_DCHECK(!timer_tasks_.empty()); |
| 370 | auto now = GetTick(); |
| 371 | do { |
| 372 | const auto& top = timer_tasks_.top(); |
| 373 | if (top.due_time() > now) |
| 374 | break; |
| 375 | top.Run(); |
| 376 | timer_tasks_.pop(); |
| 377 | } while (!timer_tasks_.empty()); |
| 378 | } |
| 379 |
| 380 | void TaskQueueWin::ScheduleNextTimer() { |
| 381 | RTC_DCHECK_EQ(timer_id_, 0); |
| 382 | if (timer_tasks_.empty()) |
| 383 | return; |
| 384 |
| 385 | const auto& next_task = timer_tasks_.top(); |
| 386 | int64_t delay_ms = std::max(0ll, next_task.due_time() - GetTick()); |
| 387 | uint32_t milliseconds = rtc::dchecked_cast<uint32_t>(delay_ms); |
| 388 | if (!timer_.StartOneShotTimer(milliseconds)) |
| 389 | timer_id_ = ::SetTimer(nullptr, 0, milliseconds, nullptr); |
| 390 | } |
| 391 |
| 392 | void TaskQueueWin::CancelTimers() { |
| 393 | timer_.Cancel(); |
| 394 | if (timer_id_) { |
| 395 | ::KillTimer(nullptr, timer_id_); |
| 396 | timer_id_ = 0; |
| 397 | } |
| 398 | } |
| 399 |
| 400 | class TaskQueueWinFactory : public TaskQueueFactory { |
| 401 | public: |
| 402 | std::unique_ptr<TaskQueueBase, TaskQueueDeleter> CreateTaskQueue( |
| 403 | absl::string_view name, |
| 404 | Priority priority) const override { |
| 405 | return std::unique_ptr<TaskQueueBase, TaskQueueDeleter>( |
| 406 | new TaskQueueWin(name, TaskQueuePriorityToThreadPriority(priority))); |
| 407 | } |
| 408 | }; |
| 409 |
| 410 | } // namespace |
| 411 |
| 412 | std::unique_ptr<TaskQueueFactory> CreateTaskQueueWinFactory() { |
| 413 | return std::make_unique<TaskQueueWinFactory>(); |
| 414 | } |
| 415 |
| 416 | } // namespace webrtc |
| 417 |