blob: a149dd88a6b05e0ee402ce5c78713c4042db2c6c [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
11#include "webrtc/base/task_queue.h"
12
tommif9d91542017-02-17 02:47:11 -080013#include <mmsystem.h>
tommic06b1332016-05-14 11:31:40 -070014#include <string.h>
tommic06b1332016-05-14 11:31:40 -070015
tommif9d91542017-02-17 02:47:11 -080016#include <algorithm>
tommi0b942152017-03-10 09:33:53 -080017#include <queue>
tommif9d91542017-02-17 02:47:11 -080018
tommi83722262017-03-15 04:36:29 -070019#include "webrtc/base/arraysize.h"
tommic06b1332016-05-14 11:31:40 -070020#include "webrtc/base/checks.h"
21#include "webrtc/base/logging.h"
tommi0b942152017-03-10 09:33:53 -080022#include "webrtc/base/safe_conversions.h"
23#include "webrtc/base/timeutils.h"
tommic06b1332016-05-14 11:31:40 -070024
25namespace rtc {
26namespace {
27#define WM_RUN_TASK WM_USER + 1
28#define WM_QUEUE_DELAYED_TASK WM_USER + 2
29
tommic9bb7912017-02-24 10:42:14 -080030using Priority = TaskQueue::Priority;
31
tommic06b1332016-05-14 11:31:40 -070032DWORD g_queue_ptr_tls = 0;
33
34BOOL CALLBACK InitializeTls(PINIT_ONCE init_once, void* param, void** context) {
35 g_queue_ptr_tls = TlsAlloc();
36 return TRUE;
37}
38
39DWORD GetQueuePtrTls() {
40 static INIT_ONCE init_once = INIT_ONCE_STATIC_INIT;
tommif9d91542017-02-17 02:47:11 -080041 ::InitOnceExecuteOnce(&init_once, InitializeTls, nullptr, nullptr);
tommic06b1332016-05-14 11:31:40 -070042 return g_queue_ptr_tls;
43}
44
45struct ThreadStartupData {
46 Event* started;
47 void* thread_context;
48};
49
50void CALLBACK InitializeQueueThread(ULONG_PTR param) {
51 MSG msg;
tommif9d91542017-02-17 02:47:11 -080052 ::PeekMessage(&msg, nullptr, WM_USER, WM_USER, PM_NOREMOVE);
tommic06b1332016-05-14 11:31:40 -070053 ThreadStartupData* data = reinterpret_cast<ThreadStartupData*>(param);
tommif9d91542017-02-17 02:47:11 -080054 ::TlsSetValue(GetQueuePtrTls(), data->thread_context);
tommic06b1332016-05-14 11:31:40 -070055 data->started->Set();
56}
tommic9bb7912017-02-24 10:42:14 -080057
58ThreadPriority TaskQueuePriorityToThreadPriority(Priority priority) {
59 switch (priority) {
60 case Priority::HIGH:
61 return kRealtimePriority;
62 case Priority::LOW:
63 return kLowPriority;
64 case Priority::NORMAL:
65 return kNormalPriority;
66 default:
67 RTC_NOTREACHED();
68 break;
69 }
70 return kNormalPriority;
71}
tommi5bdee472017-03-03 05:20:12 -080072
tommi0b942152017-03-10 09:33:53 -080073int64_t GetTick() {
tommi5bdee472017-03-03 05:20:12 -080074 static const UINT kPeriod = 1;
75 bool high_res = (timeBeginPeriod(kPeriod) == TIMERR_NOERROR);
tommi0b942152017-03-10 09:33:53 -080076 int64_t ret = TimeMillis();
tommi5bdee472017-03-03 05:20:12 -080077 if (high_res)
78 timeEndPeriod(kPeriod);
79 return ret;
80}
tommic06b1332016-05-14 11:31:40 -070081
tommi0b942152017-03-10 09:33:53 -080082class DelayedTaskInfo {
tommif9d91542017-02-17 02:47:11 -080083 public:
tommi0b942152017-03-10 09:33:53 -080084 // Default ctor needed to support priority_queue::pop().
85 DelayedTaskInfo() {}
86 DelayedTaskInfo(uint32_t milliseconds, std::unique_ptr<QueuedTask> task)
87 : due_time_(GetTick() + milliseconds), task_(std::move(task)) {}
88 DelayedTaskInfo(DelayedTaskInfo&&) = default;
tommif9d91542017-02-17 02:47:11 -080089
tommi0b942152017-03-10 09:33:53 -080090 // Implement for priority_queue.
91 bool operator>(const DelayedTaskInfo& other) const {
92 return due_time_ > other.due_time_;
93 }
tommif9d91542017-02-17 02:47:11 -080094
tommi0b942152017-03-10 09:33:53 -080095 // Required by priority_queue::pop().
96 DelayedTaskInfo& operator=(DelayedTaskInfo&& other) = default;
97
98 // See below for why this method is const.
99 void Run() const {
100 RTC_DCHECK(due_time_);
101 task_->Run() ? task_.reset() : static_cast<void>(task_.release());
102 }
103
104 int64_t due_time() const { return due_time_; }
105
106 private:
107 int64_t due_time_ = 0; // Absolute timestamp in milliseconds.
108
109 // |task| needs to be mutable because std::priority_queue::top() returns
110 // a const reference and a key in an ordered queue must not be changed.
111 // There are two basic workarounds, one using const_cast, which would also
112 // make the key (|due_time|), non-const and the other is to make the non-key
113 // (|task|), mutable.
114 // Because of this, the |task| variable is made private and can only be
115 // mutated by calling the |Run()| method.
116 mutable std::unique_ptr<QueuedTask> task_;
117};
118
119class MultimediaTimer {
120 public:
tommi83722262017-03-15 04:36:29 -0700121 // Note: We create an event that requires manual reset.
122 MultimediaTimer() : event_(::CreateEvent(nullptr, true, false, nullptr)) {}
tommif9d91542017-02-17 02:47:11 -0800123
tommi0b942152017-03-10 09:33:53 -0800124 ~MultimediaTimer() {
125 Cancel();
126 ::CloseHandle(event_);
tommif9d91542017-02-17 02:47:11 -0800127 }
128
tommi0b942152017-03-10 09:33:53 -0800129 bool StartOneShotTimer(UINT delay_ms) {
tommif9d91542017-02-17 02:47:11 -0800130 RTC_DCHECK_EQ(0, timer_id_);
131 RTC_DCHECK(event_ != nullptr);
tommif9d91542017-02-17 02:47:11 -0800132 timer_id_ =
133 ::timeSetEvent(delay_ms, 0, reinterpret_cast<LPTIMECALLBACK>(event_), 0,
134 TIME_ONESHOT | TIME_CALLBACK_EVENT_SET);
135 return timer_id_ != 0;
136 }
137
tommi0b942152017-03-10 09:33:53 -0800138 void Cancel() {
tommi83722262017-03-15 04:36:29 -0700139 ::ResetEvent(event_);
tommif9d91542017-02-17 02:47:11 -0800140 if (timer_id_) {
141 ::timeKillEvent(timer_id_);
142 timer_id_ = 0;
143 }
tommif9d91542017-02-17 02:47:11 -0800144 }
145
tommi0b942152017-03-10 09:33:53 -0800146 HANDLE* event_for_wait() { return &event_; }
tommif9d91542017-02-17 02:47:11 -0800147
148 private:
tommif9d91542017-02-17 02:47:11 -0800149 HANDLE event_ = nullptr;
150 MMRESULT timer_id_ = 0;
tommif9d91542017-02-17 02:47:11 -0800151
152 RTC_DISALLOW_COPY_AND_ASSIGN(MultimediaTimer);
153};
154
tommi0b942152017-03-10 09:33:53 -0800155} // namespace
156
157class TaskQueue::ThreadState {
158 public:
tommi83722262017-03-15 04:36:29 -0700159 explicit ThreadState(HANDLE in_queue) : in_queue_(in_queue) {}
tommi0b942152017-03-10 09:33:53 -0800160 ~ThreadState() {}
161
162 void RunThreadMain();
163
164 private:
165 bool ProcessQueuedMessages();
166 void RunDueTasks();
167 void ScheduleNextTimer();
168 void CancelTimers();
169
170 // Since priority_queue<> by defult orders items in terms of
171 // largest->smallest, using std::less<>, and we want smallest->largest,
172 // we would like to use std::greater<> here. Alas it's only available in
173 // C++14 and later, so we roll our own compare template that that relies on
174 // operator<().
175 template <typename T>
176 struct greater {
177 bool operator()(const T& l, const T& r) { return l > r; }
178 };
179
180 MultimediaTimer timer_;
181 std::priority_queue<DelayedTaskInfo,
182 std::vector<DelayedTaskInfo>,
183 greater<DelayedTaskInfo>>
184 timer_tasks_;
185 UINT_PTR timer_id_ = 0;
tommi83722262017-03-15 04:36:29 -0700186 HANDLE in_queue_;
tommi0b942152017-03-10 09:33:53 -0800187};
188
tommic9bb7912017-02-24 10:42:14 -0800189TaskQueue::TaskQueue(const char* queue_name, Priority priority /*= NORMAL*/)
190 : thread_(&TaskQueue::ThreadMain,
191 this,
192 queue_name,
tommi83722262017-03-15 04:36:29 -0700193 TaskQueuePriorityToThreadPriority(priority)),
194 in_queue_(::CreateEvent(nullptr, true, false, nullptr)) {
tommic06b1332016-05-14 11:31:40 -0700195 RTC_DCHECK(queue_name);
tommi83722262017-03-15 04:36:29 -0700196 RTC_DCHECK(in_queue_);
tommic06b1332016-05-14 11:31:40 -0700197 thread_.Start();
198 Event event(false, false);
199 ThreadStartupData startup = {&event, this};
200 RTC_CHECK(thread_.QueueAPC(&InitializeQueueThread,
201 reinterpret_cast<ULONG_PTR>(&startup)));
202 event.Wait(Event::kForever);
203}
204
205TaskQueue::~TaskQueue() {
206 RTC_DCHECK(!IsCurrent());
tommif9d91542017-02-17 02:47:11 -0800207 while (!::PostThreadMessage(thread_.GetThreadRef(), WM_QUIT, 0, 0)) {
kwiberg352444f2016-11-28 15:58:53 -0800208 RTC_CHECK_EQ(ERROR_NOT_ENOUGH_QUOTA, ::GetLastError());
tommic06b1332016-05-14 11:31:40 -0700209 Sleep(1);
210 }
211 thread_.Stop();
tommi83722262017-03-15 04:36:29 -0700212 ::CloseHandle(in_queue_);
tommic06b1332016-05-14 11:31:40 -0700213}
214
215// static
216TaskQueue* TaskQueue::Current() {
tommif9d91542017-02-17 02:47:11 -0800217 return static_cast<TaskQueue*>(::TlsGetValue(GetQueuePtrTls()));
tommic06b1332016-05-14 11:31:40 -0700218}
219
220// static
221bool TaskQueue::IsCurrent(const char* queue_name) {
222 TaskQueue* current = Current();
223 return current && current->thread_.name().compare(queue_name) == 0;
224}
225
226bool TaskQueue::IsCurrent() const {
227 return IsThreadRefEqual(thread_.GetThreadRef(), CurrentThreadRef());
228}
229
230void TaskQueue::PostTask(std::unique_ptr<QueuedTask> task) {
tommi83722262017-03-15 04:36:29 -0700231 rtc::CritScope lock(&pending_lock_);
232 pending_.push(std::move(task));
233 ::SetEvent(in_queue_);
tommic06b1332016-05-14 11:31:40 -0700234}
235
236void TaskQueue::PostDelayedTask(std::unique_ptr<QueuedTask> task,
237 uint32_t milliseconds) {
tommi0b942152017-03-10 09:33:53 -0800238 if (!milliseconds) {
239 PostTask(std::move(task));
240 return;
241 }
242
243 // TODO(tommi): Avoid this allocation. It is currently here since
244 // the timestamp stored in the task info object, is a 64bit timestamp
245 // and WPARAM is 32bits in 32bit builds. Otherwise, we could pass the
246 // task pointer and timestamp as LPARAM and WPARAM.
247 auto* task_info = new DelayedTaskInfo(milliseconds, std::move(task));
248 if (!::PostThreadMessage(thread_.GetThreadRef(), WM_QUEUE_DELAYED_TASK, 0,
249 reinterpret_cast<LPARAM>(task_info))) {
250 delete task_info;
tommic06b1332016-05-14 11:31:40 -0700251 }
252}
253
254void TaskQueue::PostTaskAndReply(std::unique_ptr<QueuedTask> task,
255 std::unique_ptr<QueuedTask> reply,
256 TaskQueue* reply_queue) {
257 QueuedTask* task_ptr = task.release();
258 QueuedTask* reply_task_ptr = reply.release();
259 DWORD reply_thread_id = reply_queue->thread_.GetThreadRef();
260 PostTask([task_ptr, reply_task_ptr, reply_thread_id]() {
261 if (task_ptr->Run())
262 delete task_ptr;
263 // If the thread's message queue is full, we can't queue the task and will
264 // have to drop it (i.e. delete).
tommif9d91542017-02-17 02:47:11 -0800265 if (!::PostThreadMessage(reply_thread_id, WM_RUN_TASK, 0,
266 reinterpret_cast<LPARAM>(reply_task_ptr))) {
tommic06b1332016-05-14 11:31:40 -0700267 delete reply_task_ptr;
268 }
269 });
270}
271
272void TaskQueue::PostTaskAndReply(std::unique_ptr<QueuedTask> task,
273 std::unique_ptr<QueuedTask> reply) {
274 return PostTaskAndReply(std::move(task), std::move(reply), Current());
275}
276
tommi83722262017-03-15 04:36:29 -0700277void TaskQueue::RunPendingTasks() {
278 while (true) {
279 std::unique_ptr<QueuedTask> task;
280 {
281 rtc::CritScope lock(&pending_lock_);
282 if (pending_.empty())
283 break;
284 task = std::move(pending_.front());
285 pending_.pop();
286 }
287
288 if (!task->Run())
289 task.release();
290 }
291}
292
tommic06b1332016-05-14 11:31:40 -0700293// static
tommi0f8b4032017-02-22 11:22:05 -0800294void TaskQueue::ThreadMain(void* context) {
tommi83722262017-03-15 04:36:29 -0700295 ThreadState state(static_cast<TaskQueue*>(context)->in_queue_);
tommi0b942152017-03-10 09:33:53 -0800296 state.RunThreadMain();
297}
tommif9d91542017-02-17 02:47:11 -0800298
tommi0b942152017-03-10 09:33:53 -0800299void TaskQueue::ThreadState::RunThreadMain() {
tommi83722262017-03-15 04:36:29 -0700300 HANDLE handles[2] = { *timer_.event_for_wait(), in_queue_ };
tommib89257a2016-07-12 01:24:36 -0700301 while (true) {
tommif9d91542017-02-17 02:47:11 -0800302 // Make sure we do an alertable wait as that's required to allow APCs to run
303 // (e.g. required for InitializeQueueThread and stopping the thread in
304 // PlatformThread).
tommi0b942152017-03-10 09:33:53 -0800305 DWORD result = ::MsgWaitForMultipleObjectsEx(
tommi83722262017-03-15 04:36:29 -0700306 arraysize(handles), handles, INFINITE, QS_ALLEVENTS, MWMO_ALERTABLE);
tommib89257a2016-07-12 01:24:36 -0700307 RTC_CHECK_NE(WAIT_FAILED, result);
tommi83722262017-03-15 04:36:29 -0700308 if (result == (WAIT_OBJECT_0 + 2)) {
tommi0b942152017-03-10 09:33:53 -0800309 // There are messages in the message queue that need to be handled.
310 if (!ProcessQueuedMessages())
tommib89257a2016-07-12 01:24:36 -0700311 break;
tommi83722262017-03-15 04:36:29 -0700312 }
313
314 if (result == WAIT_OBJECT_0 || (!timer_tasks_.empty() &&
315 ::WaitForSingleObject(*timer_.event_for_wait(), 0) == WAIT_OBJECT_0)) {
tommi0b942152017-03-10 09:33:53 -0800316 // The multimedia timer was signaled.
317 timer_.Cancel();
tommi0b942152017-03-10 09:33:53 -0800318 RunDueTasks();
319 ScheduleNextTimer();
tommi83722262017-03-15 04:36:29 -0700320 }
321
322 if (result == (WAIT_OBJECT_0 + 1)) {
323 ::ResetEvent(in_queue_);
324 TaskQueue::Current()->RunPendingTasks();
tommib89257a2016-07-12 01:24:36 -0700325 }
326 }
tommib89257a2016-07-12 01:24:36 -0700327}
tommic06b1332016-05-14 11:31:40 -0700328
tommi0b942152017-03-10 09:33:53 -0800329bool TaskQueue::ThreadState::ProcessQueuedMessages() {
tommib89257a2016-07-12 01:24:36 -0700330 MSG msg = {};
tommi83722262017-03-15 04:36:29 -0700331 // To protect against overly busy message queues, we limit the time
332 // we process tasks to a few milliseconds. If we don't do that, there's
333 // a chance that timer tasks won't ever run.
334 static const int kMaxTaskProcessingTimeMs = 500;
335 auto start = GetTick();
tommif9d91542017-02-17 02:47:11 -0800336 while (::PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE) &&
tommib89257a2016-07-12 01:24:36 -0700337 msg.message != WM_QUIT) {
tommic06b1332016-05-14 11:31:40 -0700338 if (!msg.hwnd) {
339 switch (msg.message) {
tommi83722262017-03-15 04:36:29 -0700340 // TODO(tommi): Stop using this way of queueing tasks.
tommic06b1332016-05-14 11:31:40 -0700341 case WM_RUN_TASK: {
342 QueuedTask* task = reinterpret_cast<QueuedTask*>(msg.lParam);
343 if (task->Run())
344 delete task;
345 break;
346 }
347 case WM_QUEUE_DELAYED_TASK: {
tommi0b942152017-03-10 09:33:53 -0800348 std::unique_ptr<DelayedTaskInfo> info(
349 reinterpret_cast<DelayedTaskInfo*>(msg.lParam));
350 bool need_to_schedule_timers =
351 timer_tasks_.empty() ||
352 timer_tasks_.top().due_time() > info->due_time();
353 timer_tasks_.emplace(std::move(*info.get()));
354 if (need_to_schedule_timers) {
355 CancelTimers();
356 ScheduleNextTimer();
tommif9d91542017-02-17 02:47:11 -0800357 }
tommic06b1332016-05-14 11:31:40 -0700358 break;
359 }
360 case WM_TIMER: {
tommi0b942152017-03-10 09:33:53 -0800361 RTC_DCHECK_EQ(timer_id_, msg.wParam);
tommif9d91542017-02-17 02:47:11 -0800362 ::KillTimer(nullptr, msg.wParam);
tommi0b942152017-03-10 09:33:53 -0800363 timer_id_ = 0;
364 RunDueTasks();
365 ScheduleNextTimer();
tommic06b1332016-05-14 11:31:40 -0700366 break;
367 }
368 default:
369 RTC_NOTREACHED();
370 break;
371 }
372 } else {
tommif9d91542017-02-17 02:47:11 -0800373 ::TranslateMessage(&msg);
374 ::DispatchMessage(&msg);
tommic06b1332016-05-14 11:31:40 -0700375 }
tommi83722262017-03-15 04:36:29 -0700376
377 if (GetTick() > start + kMaxTaskProcessingTimeMs)
378 break;
tommic06b1332016-05-14 11:31:40 -0700379 }
tommib89257a2016-07-12 01:24:36 -0700380 return msg.message != WM_QUIT;
tommic06b1332016-05-14 11:31:40 -0700381}
tommib89257a2016-07-12 01:24:36 -0700382
tommi0b942152017-03-10 09:33:53 -0800383void TaskQueue::ThreadState::RunDueTasks() {
384 RTC_DCHECK(!timer_tasks_.empty());
385 auto now = GetTick();
386 do {
387 const auto& top = timer_tasks_.top();
388 if (top.due_time() > now)
389 break;
390 top.Run();
391 timer_tasks_.pop();
392 } while (!timer_tasks_.empty());
393}
394
395void TaskQueue::ThreadState::ScheduleNextTimer() {
396 RTC_DCHECK_EQ(timer_id_, 0);
397 if (timer_tasks_.empty())
398 return;
399
400 const auto& next_task = timer_tasks_.top();
401 int64_t delay_ms = std::max(0ll, next_task.due_time() - GetTick());
402 uint32_t milliseconds = rtc::dchecked_cast<uint32_t>(delay_ms);
403 if (!timer_.StartOneShotTimer(milliseconds))
404 timer_id_ = ::SetTimer(nullptr, 0, milliseconds, nullptr);
405}
406
407void TaskQueue::ThreadState::CancelTimers() {
408 timer_.Cancel();
409 if (timer_id_) {
410 ::KillTimer(nullptr, timer_id_);
411 timer_id_ = 0;
412 }
413}
414
tommic06b1332016-05-14 11:31:40 -0700415} // namespace rtc