blob: 39dc9b93738fff834f7ad02383263362e5181fba [file] [log] [blame]
tommic06b1332016-05-14 11:31:40 -07001/*
2 * Copyright 2016 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
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
Danil Chapovalov826f2e72019-02-20 18:13:09 +010011#include "rtc_base/task_queue_win.h"
tommic06b1332016-05-14 11:31:40 -070012
Yves Gerey665174f2018-06-19 15:03:05 +020013// clang-format off
14// clang formating would change include order.
15
Danil Chapovalov02fddf62018-02-12 12:41:16 +010016// Include winsock2.h before including <windows.h> to maintain consistency with
Niels Möllerb06b0a62018-05-25 10:05:34 +020017// win32.h. To include win32.h directly, it must be broken out into its own
18// build target.
Danil Chapovalov02fddf62018-02-12 12:41:16 +010019#include <winsock2.h>
20#include <windows.h>
Yves Gerey665174f2018-06-19 15:03:05 +020021#include <sal.h> // Must come after windows headers.
Danil Chapovalov02fddf62018-02-12 12:41:16 +010022#include <mmsystem.h> // Must come after windows headers.
Yves Gerey665174f2018-06-19 15:03:05 +020023// clang-format on
tommic06b1332016-05-14 11:31:40 -070024#include <string.h>
tommic06b1332016-05-14 11:31:40 -070025
tommif9d91542017-02-17 02:47:11 -080026#include <algorithm>
Mirko Bonadei317a1f02019-09-17 17:06:18 +020027#include <memory>
tommi0b942152017-03-10 09:33:53 -080028#include <queue>
Danil Chapovalov6f09ae22017-10-12 14:39:25 +020029#include <utility>
tommif9d91542017-02-17 02:47:11 -080030
Danil Chapovalov826f2e72019-02-20 18:13:09 +010031#include "absl/strings/string_view.h"
Markus Handellc89fdd72021-05-05 10:42:04 +020032#include "absl/types/optional.h"
Danil Chapovalov826f2e72019-02-20 18:13:09 +010033#include "api/task_queue/queued_task.h"
34#include "api/task_queue/task_queue_base.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020035#include "rtc_base/arraysize.h"
36#include "rtc_base/checks.h"
37#include "rtc_base/event.h"
38#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010039#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020040#include "rtc_base/platform_thread.h"
Steve Anton10542f22019-01-11 09:11:00 -080041#include "rtc_base/time_utils.h"
Markus Handell18523c32020-07-08 17:55:58 +020042#include "rtc_base/synchronization/mutex.h"
tommic06b1332016-05-14 11:31:40 -070043
Danil Chapovalov826f2e72019-02-20 18:13:09 +010044namespace webrtc {
tommic06b1332016-05-14 11:31:40 -070045namespace {
46#define WM_RUN_TASK WM_USER + 1
47#define WM_QUEUE_DELAYED_TASK WM_USER + 2
48
tommic06b1332016-05-14 11:31:40 -070049void CALLBACK InitializeQueueThread(ULONG_PTR param) {
50 MSG msg;
tommif9d91542017-02-17 02:47:11 -080051 ::PeekMessage(&msg, nullptr, WM_USER, WM_USER, PM_NOREMOVE);
Danil Chapovalov826f2e72019-02-20 18:13:09 +010052 rtc::Event* data = reinterpret_cast<rtc::Event*>(param);
53 data->Set();
tommic06b1332016-05-14 11:31:40 -070054}
tommic9bb7912017-02-24 10:42:14 -080055
Danil Chapovalov826f2e72019-02-20 18:13:09 +010056rtc::ThreadPriority TaskQueuePriorityToThreadPriority(
57 TaskQueueFactory::Priority priority) {
tommic9bb7912017-02-24 10:42:14 -080058 switch (priority) {
Danil Chapovalov826f2e72019-02-20 18:13:09 +010059 case TaskQueueFactory::Priority::HIGH:
Markus Handellc89fdd72021-05-05 10:42:04 +020060 return rtc::ThreadPriority::kRealtime;
Danil Chapovalov826f2e72019-02-20 18:13:09 +010061 case TaskQueueFactory::Priority::LOW:
Markus Handellc89fdd72021-05-05 10:42:04 +020062 return rtc::ThreadPriority::kLow;
Danil Chapovalov826f2e72019-02-20 18:13:09 +010063 case TaskQueueFactory::Priority::NORMAL:
Markus Handellc89fdd72021-05-05 10:42:04 +020064 return rtc::ThreadPriority::kNormal;
tommic9bb7912017-02-24 10:42:14 -080065 }
tommic9bb7912017-02-24 10:42:14 -080066}
tommi5bdee472017-03-03 05:20:12 -080067
tommi0b942152017-03-10 09:33:53 -080068int64_t GetTick() {
tommi5bdee472017-03-03 05:20:12 -080069 static const UINT kPeriod = 1;
70 bool high_res = (timeBeginPeriod(kPeriod) == TIMERR_NOERROR);
Danil Chapovalov826f2e72019-02-20 18:13:09 +010071 int64_t ret = rtc::TimeMillis();
tommi5bdee472017-03-03 05:20:12 -080072 if (high_res)
73 timeEndPeriod(kPeriod);
74 return ret;
75}
tommic06b1332016-05-14 11:31:40 -070076
tommi0b942152017-03-10 09:33:53 -080077class DelayedTaskInfo {
tommif9d91542017-02-17 02:47:11 -080078 public:
tommi0b942152017-03-10 09:33:53 -080079 // Default ctor needed to support priority_queue::pop().
80 DelayedTaskInfo() {}
81 DelayedTaskInfo(uint32_t milliseconds, std::unique_ptr<QueuedTask> task)
82 : due_time_(GetTick() + milliseconds), task_(std::move(task)) {}
83 DelayedTaskInfo(DelayedTaskInfo&&) = default;
tommif9d91542017-02-17 02:47:11 -080084
tommi0b942152017-03-10 09:33:53 -080085 // Implement for priority_queue.
86 bool operator>(const DelayedTaskInfo& other) const {
87 return due_time_ > other.due_time_;
88 }
tommif9d91542017-02-17 02:47:11 -080089
tommi0b942152017-03-10 09:33:53 -080090 // Required by priority_queue::pop().
91 DelayedTaskInfo& operator=(DelayedTaskInfo&& other) = default;
92
93 // See below for why this method is const.
94 void Run() const {
95 RTC_DCHECK(due_time_);
96 task_->Run() ? task_.reset() : static_cast<void>(task_.release());
97 }
98
99 int64_t due_time() const { return due_time_; }
100
101 private:
102 int64_t due_time_ = 0; // Absolute timestamp in milliseconds.
103
104 // |task| needs to be mutable because std::priority_queue::top() returns
105 // a const reference and a key in an ordered queue must not be changed.
106 // There are two basic workarounds, one using const_cast, which would also
107 // make the key (|due_time|), non-const and the other is to make the non-key
108 // (|task|), mutable.
109 // Because of this, the |task| variable is made private and can only be
110 // mutated by calling the |Run()| method.
111 mutable std::unique_ptr<QueuedTask> task_;
112};
113
114class MultimediaTimer {
115 public:
tommi83722262017-03-15 04:36:29 -0700116 // Note: We create an event that requires manual reset.
117 MultimediaTimer() : event_(::CreateEvent(nullptr, true, false, nullptr)) {}
tommif9d91542017-02-17 02:47:11 -0800118
tommi0b942152017-03-10 09:33:53 -0800119 ~MultimediaTimer() {
120 Cancel();
121 ::CloseHandle(event_);
tommif9d91542017-02-17 02:47:11 -0800122 }
123
tommi0b942152017-03-10 09:33:53 -0800124 bool StartOneShotTimer(UINT delay_ms) {
tommif9d91542017-02-17 02:47:11 -0800125 RTC_DCHECK_EQ(0, timer_id_);
126 RTC_DCHECK(event_ != nullptr);
tommif9d91542017-02-17 02:47:11 -0800127 timer_id_ =
128 ::timeSetEvent(delay_ms, 0, reinterpret_cast<LPTIMECALLBACK>(event_), 0,
129 TIME_ONESHOT | TIME_CALLBACK_EVENT_SET);
130 return timer_id_ != 0;
131 }
132
tommi0b942152017-03-10 09:33:53 -0800133 void Cancel() {
tommif9d91542017-02-17 02:47:11 -0800134 if (timer_id_) {
135 ::timeKillEvent(timer_id_);
136 timer_id_ = 0;
137 }
Danil Chapovalovfa733932020-01-13 12:56:13 +0100138 // Now that timer is killed and not able to set the event, reset the event.
139 // Doing it in opposite order is racy because event may be set between
140 // event was reset and timer is killed leaving MultimediaTimer in surprising
141 // state where both event is set and timer is canceled.
142 ::ResetEvent(event_);
tommif9d91542017-02-17 02:47:11 -0800143 }
144
tommi0b942152017-03-10 09:33:53 -0800145 HANDLE* event_for_wait() { return &event_; }
tommif9d91542017-02-17 02:47:11 -0800146
147 private:
tommif9d91542017-02-17 02:47:11 -0800148 HANDLE event_ = nullptr;
149 MMRESULT timer_id_ = 0;
tommif9d91542017-02-17 02:47:11 -0800150
151 RTC_DISALLOW_COPY_AND_ASSIGN(MultimediaTimer);
152};
153
Danil Chapovalov826f2e72019-02-20 18:13:09 +0100154class TaskQueueWin : public TaskQueueBase {
tommi0b942152017-03-10 09:33:53 -0800155 public:
Danil Chapovalov826f2e72019-02-20 18:13:09 +0100156 TaskQueueWin(absl::string_view queue_name, rtc::ThreadPriority priority);
157 ~TaskQueueWin() override = default;
tommi0b942152017-03-10 09:33:53 -0800158
Danil Chapovalov826f2e72019-02-20 18:13:09 +0100159 void Delete() override;
160 void PostTask(std::unique_ptr<QueuedTask> task) override;
161 void PostDelayedTask(std::unique_ptr<QueuedTask> task,
162 uint32_t milliseconds) override;
nisse341c8e42017-09-06 04:38:22 -0700163
164 void RunPendingTasks();
tommi0b942152017-03-10 09:33:53 -0800165
166 private:
Danil Chapovalov826f2e72019-02-20 18:13:09 +0100167 void RunThreadMain();
168 bool ProcessQueuedMessages();
169 void RunDueTasks();
170 void ScheduleNextTimer();
171 void CancelTimers();
nisse341c8e42017-09-06 04:38:22 -0700172
Danil Chapovalov826f2e72019-02-20 18:13:09 +0100173 // Since priority_queue<> by defult orders items in terms of
174 // largest->smallest, using std::less<>, and we want smallest->largest,
175 // we would like to use std::greater<> here. Alas it's only available in
176 // C++14 and later, so we roll our own compare template that that relies on
177 // operator<().
178 template <typename T>
179 struct greater {
180 bool operator()(const T& l, const T& r) { return l > r; }
nisse341c8e42017-09-06 04:38:22 -0700181 };
182
Danil Chapovalov826f2e72019-02-20 18:13:09 +0100183 MultimediaTimer timer_;
184 std::priority_queue<DelayedTaskInfo,
185 std::vector<DelayedTaskInfo>,
186 greater<DelayedTaskInfo>>
187 timer_tasks_;
188 UINT_PTR timer_id_ = 0;
Markus Handellc89fdd72021-05-05 10:42:04 +0200189 rtc::PlatformThread thread_;
Markus Handell18523c32020-07-08 17:55:58 +0200190 Mutex pending_lock_;
danilchapa37de392017-09-09 04:17:22 -0700191 std::queue<std::unique_ptr<QueuedTask>> pending_
192 RTC_GUARDED_BY(pending_lock_);
tommi83722262017-03-15 04:36:29 -0700193 HANDLE in_queue_;
tommi0b942152017-03-10 09:33:53 -0800194};
195
Danil Chapovalov826f2e72019-02-20 18:13:09 +0100196TaskQueueWin::TaskQueueWin(absl::string_view queue_name,
197 rtc::ThreadPriority priority)
Markus Handellc89fdd72021-05-05 10:42:04 +0200198 : in_queue_(::CreateEvent(nullptr, true, false, nullptr)) {
tommi83722262017-03-15 04:36:29 -0700199 RTC_DCHECK(in_queue_);
Markus Handellc89fdd72021-05-05 10:42:04 +0200200 thread_ = rtc::PlatformThread::SpawnJoinable(
201 [this] { RunThreadMain(); }, queue_name,
202 rtc::ThreadAttributes().SetPriority(priority));
203
Danil Chapovalov826f2e72019-02-20 18:13:09 +0100204 rtc::Event event(false, false);
tommic06b1332016-05-14 11:31:40 -0700205 RTC_CHECK(thread_.QueueAPC(&InitializeQueueThread,
Danil Chapovalov826f2e72019-02-20 18:13:09 +0100206 reinterpret_cast<ULONG_PTR>(&event)));
207 event.Wait(rtc::Event::kForever);
tommic06b1332016-05-14 11:31:40 -0700208}
209
Danil Chapovalov826f2e72019-02-20 18:13:09 +0100210void TaskQueueWin::Delete() {
tommic06b1332016-05-14 11:31:40 -0700211 RTC_DCHECK(!IsCurrent());
Markus Handellc89fdd72021-05-05 10:42:04 +0200212 RTC_CHECK(thread_.GetHandle() != absl::nullopt);
213 while (
214 !::PostThreadMessage(GetThreadId(*thread_.GetHandle()), WM_QUIT, 0, 0)) {
kwiberg352444f2016-11-28 15:58:53 -0800215 RTC_CHECK_EQ(ERROR_NOT_ENOUGH_QUOTA, ::GetLastError());
tommic06b1332016-05-14 11:31:40 -0700216 Sleep(1);
217 }
Markus Handellc89fdd72021-05-05 10:42:04 +0200218 thread_.Finalize();
tommi83722262017-03-15 04:36:29 -0700219 ::CloseHandle(in_queue_);
Danil Chapovalov826f2e72019-02-20 18:13:09 +0100220 delete this;
tommic06b1332016-05-14 11:31:40 -0700221}
222
Danil Chapovalov826f2e72019-02-20 18:13:09 +0100223void TaskQueueWin::PostTask(std::unique_ptr<QueuedTask> task) {
Markus Handell18523c32020-07-08 17:55:58 +0200224 MutexLock lock(&pending_lock_);
tommi83722262017-03-15 04:36:29 -0700225 pending_.push(std::move(task));
226 ::SetEvent(in_queue_);
tommic06b1332016-05-14 11:31:40 -0700227}
228
Danil Chapovalov826f2e72019-02-20 18:13:09 +0100229void TaskQueueWin::PostDelayedTask(std::unique_ptr<QueuedTask> task,
230 uint32_t milliseconds) {
tommi0b942152017-03-10 09:33:53 -0800231 if (!milliseconds) {
232 PostTask(std::move(task));
233 return;
234 }
235
236 // TODO(tommi): Avoid this allocation. It is currently here since
237 // the timestamp stored in the task info object, is a 64bit timestamp
238 // and WPARAM is 32bits in 32bit builds. Otherwise, we could pass the
239 // task pointer and timestamp as LPARAM and WPARAM.
240 auto* task_info = new DelayedTaskInfo(milliseconds, std::move(task));
Markus Handellc89fdd72021-05-05 10:42:04 +0200241 RTC_CHECK(thread_.GetHandle() != absl::nullopt);
242 if (!::PostThreadMessage(GetThreadId(*thread_.GetHandle()),
243 WM_QUEUE_DELAYED_TASK, 0,
tommi0b942152017-03-10 09:33:53 -0800244 reinterpret_cast<LPARAM>(task_info))) {
245 delete task_info;
tommic06b1332016-05-14 11:31:40 -0700246 }
247}
248
Danil Chapovalov826f2e72019-02-20 18:13:09 +0100249void TaskQueueWin::RunPendingTasks() {
tommi83722262017-03-15 04:36:29 -0700250 while (true) {
251 std::unique_ptr<QueuedTask> task;
252 {
Markus Handell18523c32020-07-08 17:55:58 +0200253 MutexLock lock(&pending_lock_);
tommi83722262017-03-15 04:36:29 -0700254 if (pending_.empty())
255 break;
256 task = std::move(pending_.front());
257 pending_.pop();
258 }
259
260 if (!task->Run())
261 task.release();
262 }
263}
264
Danil Chapovalov826f2e72019-02-20 18:13:09 +0100265void TaskQueueWin::RunThreadMain() {
266 CurrentTaskQueueSetter set_current(this);
Yves Gerey665174f2018-06-19 15:03:05 +0200267 HANDLE handles[2] = {*timer_.event_for_wait(), in_queue_};
tommib89257a2016-07-12 01:24:36 -0700268 while (true) {
tommif9d91542017-02-17 02:47:11 -0800269 // Make sure we do an alertable wait as that's required to allow APCs to run
270 // (e.g. required for InitializeQueueThread and stopping the thread in
271 // PlatformThread).
tommi0b942152017-03-10 09:33:53 -0800272 DWORD result = ::MsgWaitForMultipleObjectsEx(
tommi83722262017-03-15 04:36:29 -0700273 arraysize(handles), handles, INFINITE, QS_ALLEVENTS, MWMO_ALERTABLE);
tommib89257a2016-07-12 01:24:36 -0700274 RTC_CHECK_NE(WAIT_FAILED, result);
tommi83722262017-03-15 04:36:29 -0700275 if (result == (WAIT_OBJECT_0 + 2)) {
tommi0b942152017-03-10 09:33:53 -0800276 // There are messages in the message queue that need to be handled.
277 if (!ProcessQueuedMessages())
tommib89257a2016-07-12 01:24:36 -0700278 break;
tommi83722262017-03-15 04:36:29 -0700279 }
280
Yves Gerey665174f2018-06-19 15:03:05 +0200281 if (result == WAIT_OBJECT_0 ||
282 (!timer_tasks_.empty() &&
283 ::WaitForSingleObject(*timer_.event_for_wait(), 0) == WAIT_OBJECT_0)) {
tommi0b942152017-03-10 09:33:53 -0800284 // The multimedia timer was signaled.
285 timer_.Cancel();
tommi0b942152017-03-10 09:33:53 -0800286 RunDueTasks();
287 ScheduleNextTimer();
tommi83722262017-03-15 04:36:29 -0700288 }
289
290 if (result == (WAIT_OBJECT_0 + 1)) {
291 ::ResetEvent(in_queue_);
Danil Chapovalov826f2e72019-02-20 18:13:09 +0100292 RunPendingTasks();
tommib89257a2016-07-12 01:24:36 -0700293 }
294 }
tommib89257a2016-07-12 01:24:36 -0700295}
tommic06b1332016-05-14 11:31:40 -0700296
Danil Chapovalov826f2e72019-02-20 18:13:09 +0100297bool TaskQueueWin::ProcessQueuedMessages() {
tommib89257a2016-07-12 01:24:36 -0700298 MSG msg = {};
tommi83722262017-03-15 04:36:29 -0700299 // To protect against overly busy message queues, we limit the time
300 // we process tasks to a few milliseconds. If we don't do that, there's
301 // a chance that timer tasks won't ever run.
302 static const int kMaxTaskProcessingTimeMs = 500;
303 auto start = GetTick();
tommif9d91542017-02-17 02:47:11 -0800304 while (::PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE) &&
tommib89257a2016-07-12 01:24:36 -0700305 msg.message != WM_QUIT) {
tommic06b1332016-05-14 11:31:40 -0700306 if (!msg.hwnd) {
307 switch (msg.message) {
tommi83722262017-03-15 04:36:29 -0700308 // TODO(tommi): Stop using this way of queueing tasks.
tommic06b1332016-05-14 11:31:40 -0700309 case WM_RUN_TASK: {
310 QueuedTask* task = reinterpret_cast<QueuedTask*>(msg.lParam);
311 if (task->Run())
312 delete task;
313 break;
314 }
315 case WM_QUEUE_DELAYED_TASK: {
tommi0b942152017-03-10 09:33:53 -0800316 std::unique_ptr<DelayedTaskInfo> info(
317 reinterpret_cast<DelayedTaskInfo*>(msg.lParam));
318 bool need_to_schedule_timers =
319 timer_tasks_.empty() ||
320 timer_tasks_.top().due_time() > info->due_time();
321 timer_tasks_.emplace(std::move(*info.get()));
322 if (need_to_schedule_timers) {
323 CancelTimers();
324 ScheduleNextTimer();
tommif9d91542017-02-17 02:47:11 -0800325 }
tommic06b1332016-05-14 11:31:40 -0700326 break;
327 }
328 case WM_TIMER: {
tommi0b942152017-03-10 09:33:53 -0800329 RTC_DCHECK_EQ(timer_id_, msg.wParam);
tommif9d91542017-02-17 02:47:11 -0800330 ::KillTimer(nullptr, msg.wParam);
tommi0b942152017-03-10 09:33:53 -0800331 timer_id_ = 0;
332 RunDueTasks();
333 ScheduleNextTimer();
tommic06b1332016-05-14 11:31:40 -0700334 break;
335 }
336 default:
337 RTC_NOTREACHED();
338 break;
339 }
340 } else {
tommif9d91542017-02-17 02:47:11 -0800341 ::TranslateMessage(&msg);
342 ::DispatchMessage(&msg);
tommic06b1332016-05-14 11:31:40 -0700343 }
tommi83722262017-03-15 04:36:29 -0700344
345 if (GetTick() > start + kMaxTaskProcessingTimeMs)
346 break;
tommic06b1332016-05-14 11:31:40 -0700347 }
tommib89257a2016-07-12 01:24:36 -0700348 return msg.message != WM_QUIT;
tommic06b1332016-05-14 11:31:40 -0700349}
tommib89257a2016-07-12 01:24:36 -0700350
Danil Chapovalov826f2e72019-02-20 18:13:09 +0100351void TaskQueueWin::RunDueTasks() {
tommi0b942152017-03-10 09:33:53 -0800352 RTC_DCHECK(!timer_tasks_.empty());
353 auto now = GetTick();
354 do {
355 const auto& top = timer_tasks_.top();
356 if (top.due_time() > now)
357 break;
358 top.Run();
359 timer_tasks_.pop();
360 } while (!timer_tasks_.empty());
361}
362
Danil Chapovalov826f2e72019-02-20 18:13:09 +0100363void TaskQueueWin::ScheduleNextTimer() {
tommi0b942152017-03-10 09:33:53 -0800364 RTC_DCHECK_EQ(timer_id_, 0);
365 if (timer_tasks_.empty())
366 return;
367
368 const auto& next_task = timer_tasks_.top();
369 int64_t delay_ms = std::max(0ll, next_task.due_time() - GetTick());
370 uint32_t milliseconds = rtc::dchecked_cast<uint32_t>(delay_ms);
371 if (!timer_.StartOneShotTimer(milliseconds))
372 timer_id_ = ::SetTimer(nullptr, 0, milliseconds, nullptr);
373}
374
Danil Chapovalov826f2e72019-02-20 18:13:09 +0100375void TaskQueueWin::CancelTimers() {
tommi0b942152017-03-10 09:33:53 -0800376 timer_.Cancel();
377 if (timer_id_) {
378 ::KillTimer(nullptr, timer_id_);
379 timer_id_ = 0;
380 }
381}
382
Danil Chapovalov826f2e72019-02-20 18:13:09 +0100383class TaskQueueWinFactory : public TaskQueueFactory {
384 public:
385 std::unique_ptr<TaskQueueBase, TaskQueueDeleter> CreateTaskQueue(
386 absl::string_view name,
387 Priority priority) const override {
388 return std::unique_ptr<TaskQueueBase, TaskQueueDeleter>(
389 new TaskQueueWin(name, TaskQueuePriorityToThreadPriority(priority)));
390 }
391};
392
393} // namespace
394
395std::unique_ptr<TaskQueueFactory> CreateTaskQueueWinFactory() {
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200396 return std::make_unique<TaskQueueWinFactory>();
nisse341c8e42017-09-06 04:38:22 -0700397}
398
Danil Chapovalov826f2e72019-02-20 18:13:09 +0100399} // namespace webrtc