| OLD | NEW |
| 1 /* | 1 /* |
| 2 * Copyright 2016 The WebRTC Project Authors. All rights reserved. | 2 * Copyright 2016 The WebRTC Project Authors. All rights reserved. |
| 3 * | 3 * |
| 4 * Use of this source code is governed by a BSD-style license | 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 | 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 | 6 * tree. An additional intellectual property rights grant can be found |
| 7 * in the file PATENTS. All contributing project authors may | 7 * in the file PATENTS. All contributing project authors may |
| 8 * be found in the AUTHORS file in the root of the source tree. | 8 * be found in the AUTHORS file in the root of the source tree. |
| 9 */ | 9 */ |
| 10 | 10 |
| 11 #include "webrtc/base/task_queue.h" | 11 #include "webrtc/base/task_queue.h" |
| 12 | 12 |
| 13 #include <mmsystem.h> | 13 #include <mmsystem.h> |
| 14 #include <string.h> | 14 #include <string.h> |
| 15 | 15 |
| 16 #include <algorithm> | 16 #include <algorithm> |
| 17 #include <queue> |
| 17 | 18 |
| 18 #include "webrtc/base/arraysize.h" | |
| 19 #include "webrtc/base/checks.h" | 19 #include "webrtc/base/checks.h" |
| 20 #include "webrtc/base/logging.h" | 20 #include "webrtc/base/logging.h" |
| 21 #include "webrtc/base/safe_conversions.h" |
| 22 #include "webrtc/base/timeutils.h" |
| 21 | 23 |
| 22 namespace rtc { | 24 namespace rtc { |
| 23 namespace { | 25 namespace { |
| 24 #define WM_RUN_TASK WM_USER + 1 | 26 #define WM_RUN_TASK WM_USER + 1 |
| 25 #define WM_QUEUE_DELAYED_TASK WM_USER + 2 | 27 #define WM_QUEUE_DELAYED_TASK WM_USER + 2 |
| 26 | 28 |
| 27 using Priority = TaskQueue::Priority; | 29 using Priority = TaskQueue::Priority; |
| 28 | 30 |
| 29 DWORD g_queue_ptr_tls = 0; | 31 DWORD g_queue_ptr_tls = 0; |
| 30 | 32 |
| (...skipping 29 matching lines...) Expand all Loading... |
| 60 return kLowPriority; | 62 return kLowPriority; |
| 61 case Priority::NORMAL: | 63 case Priority::NORMAL: |
| 62 return kNormalPriority; | 64 return kNormalPriority; |
| 63 default: | 65 default: |
| 64 RTC_NOTREACHED(); | 66 RTC_NOTREACHED(); |
| 65 break; | 67 break; |
| 66 } | 68 } |
| 67 return kNormalPriority; | 69 return kNormalPriority; |
| 68 } | 70 } |
| 69 | 71 |
| 70 #if defined(_WIN64) | 72 int64_t GetTick() { |
| 71 DWORD GetTick() { | |
| 72 static const UINT kPeriod = 1; | 73 static const UINT kPeriod = 1; |
| 73 bool high_res = (timeBeginPeriod(kPeriod) == TIMERR_NOERROR); | 74 bool high_res = (timeBeginPeriod(kPeriod) == TIMERR_NOERROR); |
| 74 DWORD ret = timeGetTime(); | 75 int64_t ret = TimeMillis(); |
| 75 if (high_res) | 76 if (high_res) |
| 76 timeEndPeriod(kPeriod); | 77 timeEndPeriod(kPeriod); |
| 77 return ret; | 78 return ret; |
| 78 } | 79 } |
| 79 #endif | |
| 80 } // namespace | |
| 81 | 80 |
| 82 class TaskQueue::MultimediaTimer { | 81 class DelayedTaskInfo { |
| 83 public: | 82 public: |
| 84 // kMaxTimers defines the limit of how many MultimediaTimer instances should | 83 // Default ctor needed to support priority_queue::pop(). |
| 85 // be created. | 84 DelayedTaskInfo() {} |
| 86 // Background: The maximum number of supported handles for Wait functions, is | 85 DelayedTaskInfo(uint32_t milliseconds, std::unique_ptr<QueuedTask> task) |
| 87 // MAXIMUM_WAIT_OBJECTS - 1 (63). | 86 : due_time_(GetTick() + milliseconds), task_(std::move(task)) {} |
| 88 // There are some ways to work around the limitation but as it turns out, the | 87 DelayedTaskInfo(DelayedTaskInfo&&) = default; |
| 89 // limit of concurrently active multimedia timers per process, is much lower, | |
| 90 // or 16. So there isn't much value in going to the lenghts required to | |
| 91 // overcome the Wait limitations. | |
| 92 // kMaxTimers is larger than 16 though since it is possible that 'complete' or | |
| 93 // signaled timers that haven't been handled, are counted as part of | |
| 94 // kMaxTimers and thus a multimedia timer can actually be queued even though | |
| 95 // as far as we're concerned, there are more than 16 that are pending. | |
| 96 static const int kMaxTimers = MAXIMUM_WAIT_OBJECTS - 1; | |
| 97 | 88 |
| 98 // Controls how many MultimediaTimer instances a queue can hold before | 89 // Implement for priority_queue. |
| 99 // attempting to garbage collect (GC) timers that aren't in use. | 90 bool operator>(const DelayedTaskInfo& other) const { |
| 100 static const int kInstanceThresholdGC = 8; | 91 return due_time_ > other.due_time_; |
| 92 } |
| 101 | 93 |
| 94 // Required by priority_queue::pop(). |
| 95 DelayedTaskInfo& operator=(DelayedTaskInfo&& other) = default; |
| 96 |
| 97 // See below for why this method is const. |
| 98 void Run() const { |
| 99 RTC_DCHECK(due_time_); |
| 100 task_->Run() ? task_.reset() : static_cast<void>(task_.release()); |
| 101 } |
| 102 |
| 103 int64_t due_time() const { return due_time_; } |
| 104 |
| 105 private: |
| 106 int64_t due_time_ = 0; // Absolute timestamp in milliseconds. |
| 107 |
| 108 // |task| needs to be mutable because std::priority_queue::top() returns |
| 109 // a const reference and a key in an ordered queue must not be changed. |
| 110 // There are two basic workarounds, one using const_cast, which would also |
| 111 // make the key (|due_time|), non-const and the other is to make the non-key |
| 112 // (|task|), mutable. |
| 113 // Because of this, the |task| variable is made private and can only be |
| 114 // mutated by calling the |Run()| method. |
| 115 mutable std::unique_ptr<QueuedTask> task_; |
| 116 }; |
| 117 |
| 118 class MultimediaTimer { |
| 119 public: |
| 102 MultimediaTimer() : event_(::CreateEvent(nullptr, false, false, nullptr)) {} | 120 MultimediaTimer() : event_(::CreateEvent(nullptr, false, false, nullptr)) {} |
| 103 | 121 |
| 104 MultimediaTimer(MultimediaTimer&& timer) | 122 ~MultimediaTimer() { |
| 105 : event_(timer.event_), | 123 Cancel(); |
| 106 timer_id_(timer.timer_id_), | 124 ::CloseHandle(event_); |
| 107 task_(std::move(timer.task_)) { | |
| 108 RTC_DCHECK(event_); | |
| 109 timer.event_ = nullptr; | |
| 110 timer.timer_id_ = 0; | |
| 111 } | 125 } |
| 112 | 126 |
| 113 ~MultimediaTimer() { Close(); } | 127 bool StartOneShotTimer(UINT delay_ms) { |
| 114 | |
| 115 // Implementing this operator is required because of the way | |
| 116 // some stl algorithms work, such as std::rotate(). | |
| 117 MultimediaTimer& operator=(MultimediaTimer&& timer) { | |
| 118 if (this != &timer) { | |
| 119 Close(); | |
| 120 event_ = timer.event_; | |
| 121 timer.event_ = nullptr; | |
| 122 task_ = std::move(timer.task_); | |
| 123 timer_id_ = timer.timer_id_; | |
| 124 timer.timer_id_ = 0; | |
| 125 } | |
| 126 return *this; | |
| 127 } | |
| 128 | |
| 129 bool StartOneShotTimer(std::unique_ptr<QueuedTask> task, UINT delay_ms) { | |
| 130 RTC_DCHECK_EQ(0, timer_id_); | 128 RTC_DCHECK_EQ(0, timer_id_); |
| 131 RTC_DCHECK(event_ != nullptr); | 129 RTC_DCHECK(event_ != nullptr); |
| 132 RTC_DCHECK(!task_.get()); | |
| 133 RTC_DCHECK(task.get()); | |
| 134 task_ = std::move(task); | |
| 135 timer_id_ = | 130 timer_id_ = |
| 136 ::timeSetEvent(delay_ms, 0, reinterpret_cast<LPTIMECALLBACK>(event_), 0, | 131 ::timeSetEvent(delay_ms, 0, reinterpret_cast<LPTIMECALLBACK>(event_), 0, |
| 137 TIME_ONESHOT | TIME_CALLBACK_EVENT_SET); | 132 TIME_ONESHOT | TIME_CALLBACK_EVENT_SET); |
| 138 return timer_id_ != 0; | 133 return timer_id_ != 0; |
| 139 } | 134 } |
| 140 | 135 |
| 141 std::unique_ptr<QueuedTask> Cancel() { | 136 void Cancel() { |
| 142 if (timer_id_) { | 137 if (timer_id_) { |
| 143 ::timeKillEvent(timer_id_); | 138 ::timeKillEvent(timer_id_); |
| 144 timer_id_ = 0; | 139 timer_id_ = 0; |
| 145 } | 140 } |
| 146 return std::move(task_); | |
| 147 } | 141 } |
| 148 | 142 |
| 149 void OnEventSignaled() { | 143 HANDLE* event_for_wait() { return &event_; } |
| 150 RTC_DCHECK_NE(0, timer_id_); | |
| 151 timer_id_ = 0; | |
| 152 task_->Run() ? task_.reset() : static_cast<void>(task_.release()); | |
| 153 } | |
| 154 | |
| 155 HANDLE event() const { return event_; } | |
| 156 | |
| 157 bool is_active() const { return timer_id_ != 0; } | |
| 158 | 144 |
| 159 private: | 145 private: |
| 160 void Close() { | |
| 161 Cancel(); | |
| 162 | |
| 163 if (event_) { | |
| 164 ::CloseHandle(event_); | |
| 165 event_ = nullptr; | |
| 166 } | |
| 167 } | |
| 168 | |
| 169 HANDLE event_ = nullptr; | 146 HANDLE event_ = nullptr; |
| 170 MMRESULT timer_id_ = 0; | 147 MMRESULT timer_id_ = 0; |
| 171 std::unique_ptr<QueuedTask> task_; | |
| 172 | 148 |
| 173 RTC_DISALLOW_COPY_AND_ASSIGN(MultimediaTimer); | 149 RTC_DISALLOW_COPY_AND_ASSIGN(MultimediaTimer); |
| 174 }; | 150 }; |
| 175 | 151 |
| 152 } // namespace |
| 153 |
| 154 class TaskQueue::ThreadState { |
| 155 public: |
| 156 ThreadState() {} |
| 157 ~ThreadState() {} |
| 158 |
| 159 void RunThreadMain(); |
| 160 |
| 161 private: |
| 162 bool ProcessQueuedMessages(); |
| 163 void RunDueTasks(); |
| 164 void ScheduleNextTimer(); |
| 165 void CancelTimers(); |
| 166 |
| 167 // Since priority_queue<> by defult orders items in terms of |
| 168 // largest->smallest, using std::less<>, and we want smallest->largest, |
| 169 // we would like to use std::greater<> here. Alas it's only available in |
| 170 // C++14 and later, so we roll our own compare template that that relies on |
| 171 // operator<(). |
| 172 template <typename T> |
| 173 struct greater { |
| 174 bool operator()(const T& l, const T& r) { return l > r; } |
| 175 }; |
| 176 |
| 177 MultimediaTimer timer_; |
| 178 std::priority_queue<DelayedTaskInfo, |
| 179 std::vector<DelayedTaskInfo>, |
| 180 greater<DelayedTaskInfo>> |
| 181 timer_tasks_; |
| 182 UINT_PTR timer_id_ = 0; |
| 183 }; |
| 184 |
| 176 TaskQueue::TaskQueue(const char* queue_name, Priority priority /*= NORMAL*/) | 185 TaskQueue::TaskQueue(const char* queue_name, Priority priority /*= NORMAL*/) |
| 177 : thread_(&TaskQueue::ThreadMain, | 186 : thread_(&TaskQueue::ThreadMain, |
| 178 this, | 187 this, |
| 179 queue_name, | 188 queue_name, |
| 180 TaskQueuePriorityToThreadPriority(priority)) { | 189 TaskQueuePriorityToThreadPriority(priority)) { |
| 181 RTC_DCHECK(queue_name); | 190 RTC_DCHECK(queue_name); |
| 182 thread_.Start(); | 191 thread_.Start(); |
| 183 Event event(false, false); | 192 Event event(false, false); |
| 184 ThreadStartupData startup = {&event, this}; | 193 ThreadStartupData startup = {&event, this}; |
| 185 RTC_CHECK(thread_.QueueAPC(&InitializeQueueThread, | 194 RTC_CHECK(thread_.QueueAPC(&InitializeQueueThread, |
| (...skipping 27 matching lines...) Expand all Loading... |
| 213 | 222 |
| 214 void TaskQueue::PostTask(std::unique_ptr<QueuedTask> task) { | 223 void TaskQueue::PostTask(std::unique_ptr<QueuedTask> task) { |
| 215 if (::PostThreadMessage(thread_.GetThreadRef(), WM_RUN_TASK, 0, | 224 if (::PostThreadMessage(thread_.GetThreadRef(), WM_RUN_TASK, 0, |
| 216 reinterpret_cast<LPARAM>(task.get()))) { | 225 reinterpret_cast<LPARAM>(task.get()))) { |
| 217 task.release(); | 226 task.release(); |
| 218 } | 227 } |
| 219 } | 228 } |
| 220 | 229 |
| 221 void TaskQueue::PostDelayedTask(std::unique_ptr<QueuedTask> task, | 230 void TaskQueue::PostDelayedTask(std::unique_ptr<QueuedTask> task, |
| 222 uint32_t milliseconds) { | 231 uint32_t milliseconds) { |
| 223 WPARAM wparam; | 232 if (!milliseconds) { |
| 224 #if defined(_WIN64) | 233 PostTask(std::move(task)); |
| 225 // GetTickCount() returns a fairly coarse tick count (resolution or about 8ms) | 234 return; |
| 226 // so this compensation isn't that accurate, but since we have unused 32 bits | 235 } |
| 227 // on Win64, we might as well use them. | 236 |
| 228 wparam = (static_cast<WPARAM>(GetTick()) << 32) | milliseconds; | 237 // TODO(tommi): Avoid this allocation. It is currently here since |
| 229 #else | 238 // the timestamp stored in the task info object, is a 64bit timestamp |
| 230 wparam = milliseconds; | 239 // and WPARAM is 32bits in 32bit builds. Otherwise, we could pass the |
| 231 #endif | 240 // task pointer and timestamp as LPARAM and WPARAM. |
| 232 if (::PostThreadMessage(thread_.GetThreadRef(), WM_QUEUE_DELAYED_TASK, wparam, | 241 auto* task_info = new DelayedTaskInfo(milliseconds, std::move(task)); |
| 233 reinterpret_cast<LPARAM>(task.get()))) { | 242 if (!::PostThreadMessage(thread_.GetThreadRef(), WM_QUEUE_DELAYED_TASK, 0, |
| 234 task.release(); | 243 reinterpret_cast<LPARAM>(task_info))) { |
| 244 delete task_info; |
| 235 } | 245 } |
| 236 } | 246 } |
| 237 | 247 |
| 238 void TaskQueue::PostTaskAndReply(std::unique_ptr<QueuedTask> task, | 248 void TaskQueue::PostTaskAndReply(std::unique_ptr<QueuedTask> task, |
| 239 std::unique_ptr<QueuedTask> reply, | 249 std::unique_ptr<QueuedTask> reply, |
| 240 TaskQueue* reply_queue) { | 250 TaskQueue* reply_queue) { |
| 241 QueuedTask* task_ptr = task.release(); | 251 QueuedTask* task_ptr = task.release(); |
| 242 QueuedTask* reply_task_ptr = reply.release(); | 252 QueuedTask* reply_task_ptr = reply.release(); |
| 243 DWORD reply_thread_id = reply_queue->thread_.GetThreadRef(); | 253 DWORD reply_thread_id = reply_queue->thread_.GetThreadRef(); |
| 244 PostTask([task_ptr, reply_task_ptr, reply_thread_id]() { | 254 PostTask([task_ptr, reply_task_ptr, reply_thread_id]() { |
| 245 if (task_ptr->Run()) | 255 if (task_ptr->Run()) |
| 246 delete task_ptr; | 256 delete task_ptr; |
| 247 // If the thread's message queue is full, we can't queue the task and will | 257 // If the thread's message queue is full, we can't queue the task and will |
| 248 // have to drop it (i.e. delete). | 258 // have to drop it (i.e. delete). |
| 249 if (!::PostThreadMessage(reply_thread_id, WM_RUN_TASK, 0, | 259 if (!::PostThreadMessage(reply_thread_id, WM_RUN_TASK, 0, |
| 250 reinterpret_cast<LPARAM>(reply_task_ptr))) { | 260 reinterpret_cast<LPARAM>(reply_task_ptr))) { |
| 251 delete reply_task_ptr; | 261 delete reply_task_ptr; |
| 252 } | 262 } |
| 253 }); | 263 }); |
| 254 } | 264 } |
| 255 | 265 |
| 256 void TaskQueue::PostTaskAndReply(std::unique_ptr<QueuedTask> task, | 266 void TaskQueue::PostTaskAndReply(std::unique_ptr<QueuedTask> task, |
| 257 std::unique_ptr<QueuedTask> reply) { | 267 std::unique_ptr<QueuedTask> reply) { |
| 258 return PostTaskAndReply(std::move(task), std::move(reply), Current()); | 268 return PostTaskAndReply(std::move(task), std::move(reply), Current()); |
| 259 } | 269 } |
| 260 | 270 |
| 261 // static | 271 // static |
| 262 void TaskQueue::ThreadMain(void* context) { | 272 void TaskQueue::ThreadMain(void* context) { |
| 263 HANDLE timer_handles[MultimediaTimer::kMaxTimers]; | 273 ThreadState state; |
| 264 // Active multimedia timers. | 274 state.RunThreadMain(); |
| 265 std::vector<MultimediaTimer> mm_timers; | 275 } |
| 266 // Tasks that have been queued by using SetTimer/WM_TIMER. | |
| 267 DelayedTasks delayed_tasks; | |
| 268 | 276 |
| 277 void TaskQueue::ThreadState::RunThreadMain() { |
| 269 while (true) { | 278 while (true) { |
| 270 RTC_DCHECK(mm_timers.size() <= arraysize(timer_handles)); | |
| 271 DWORD count = 0; | |
| 272 for (const auto& t : mm_timers) { | |
| 273 if (!t.is_active()) | |
| 274 break; | |
| 275 timer_handles[count++] = t.event(); | |
| 276 } | |
| 277 // Make sure we do an alertable wait as that's required to allow APCs to run | 279 // Make sure we do an alertable wait as that's required to allow APCs to run |
| 278 // (e.g. required for InitializeQueueThread and stopping the thread in | 280 // (e.g. required for InitializeQueueThread and stopping the thread in |
| 279 // PlatformThread). | 281 // PlatformThread). |
| 280 DWORD result = ::MsgWaitForMultipleObjectsEx(count, timer_handles, INFINITE, | 282 DWORD result = ::MsgWaitForMultipleObjectsEx( |
| 281 QS_ALLEVENTS, MWMO_ALERTABLE); | 283 1, timer_.event_for_wait(), INFINITE, QS_ALLEVENTS, MWMO_ALERTABLE); |
| 282 RTC_CHECK_NE(WAIT_FAILED, result); | 284 RTC_CHECK_NE(WAIT_FAILED, result); |
| 283 // If we're not waiting for any timers, then count will be equal to | 285 if (result == (WAIT_OBJECT_0 + 1)) { |
| 284 // WAIT_OBJECT_0. If we're waiting for timers, then |count| represents | 286 // There are messages in the message queue that need to be handled. |
| 285 // "One more than the number of timers", which means that there's a | 287 if (!ProcessQueuedMessages()) |
| 286 // message in the queue that needs to be handled. | |
| 287 // If |result| is less than |count|, then its value will be the index of the | |
| 288 // timer that has been signaled. | |
| 289 if (result == (WAIT_OBJECT_0 + count)) { | |
| 290 if (!ProcessQueuedMessages(&delayed_tasks, &mm_timers)) | |
| 291 break; | 288 break; |
| 292 } else if (result < (WAIT_OBJECT_0 + count)) { | 289 } else if (result == WAIT_OBJECT_0) { |
| 293 mm_timers[result].OnEventSignaled(); | 290 // The multimedia timer was signaled. |
| 294 RTC_DCHECK(!mm_timers[result].is_active()); | 291 timer_.Cancel(); |
| 295 // Reuse timer events by moving inactive timers to the back of the vector. | 292 RTC_DCHECK(!timer_tasks_.empty()); |
| 296 // When new delayed tasks are queued, they'll get reused. | 293 RunDueTasks(); |
| 297 if (mm_timers.size() > 1) { | 294 ScheduleNextTimer(); |
| 298 auto it = mm_timers.begin() + result; | |
| 299 std::rotate(it, it + 1, mm_timers.end()); | |
| 300 } | |
| 301 | |
| 302 // Collect some garbage. | |
| 303 if (mm_timers.size() > MultimediaTimer::kInstanceThresholdGC) { | |
| 304 const auto inactive = std::find_if( | |
| 305 mm_timers.begin(), mm_timers.end(), | |
| 306 [](const MultimediaTimer& t) { return !t.is_active(); }); | |
| 307 if (inactive != mm_timers.end()) { | |
| 308 // Since inactive timers are always moved to the back, we can | |
| 309 // safely delete all timers following the first inactive one. | |
| 310 mm_timers.erase(inactive, mm_timers.end()); | |
| 311 } | |
| 312 } | |
| 313 } else { | 295 } else { |
| 314 RTC_DCHECK_EQ(WAIT_IO_COMPLETION, result); | 296 RTC_DCHECK_EQ(WAIT_IO_COMPLETION, result); |
| 315 } | 297 } |
| 316 } | 298 } |
| 317 } | 299 } |
| 318 | 300 |
| 319 // static | 301 bool TaskQueue::ThreadState::ProcessQueuedMessages() { |
| 320 bool TaskQueue::ProcessQueuedMessages(DelayedTasks* delayed_tasks, | |
| 321 std::vector<MultimediaTimer>* timers) { | |
| 322 MSG msg = {}; | 302 MSG msg = {}; |
| 323 while (::PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE) && | 303 while (::PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE) && |
| 324 msg.message != WM_QUIT) { | 304 msg.message != WM_QUIT) { |
| 325 if (!msg.hwnd) { | 305 if (!msg.hwnd) { |
| 326 switch (msg.message) { | 306 switch (msg.message) { |
| 327 case WM_RUN_TASK: { | 307 case WM_RUN_TASK: { |
| 328 QueuedTask* task = reinterpret_cast<QueuedTask*>(msg.lParam); | 308 QueuedTask* task = reinterpret_cast<QueuedTask*>(msg.lParam); |
| 329 if (task->Run()) | 309 if (task->Run()) |
| 330 delete task; | 310 delete task; |
| 331 break; | 311 break; |
| 332 } | 312 } |
| 333 case WM_QUEUE_DELAYED_TASK: { | 313 case WM_QUEUE_DELAYED_TASK: { |
| 334 std::unique_ptr<QueuedTask> task( | 314 std::unique_ptr<DelayedTaskInfo> info( |
| 335 reinterpret_cast<QueuedTask*>(msg.lParam)); | 315 reinterpret_cast<DelayedTaskInfo*>(msg.lParam)); |
| 336 uint32_t milliseconds = msg.wParam & 0xFFFFFFFF; | 316 bool need_to_schedule_timers = |
| 337 #if defined(_WIN64) | 317 timer_tasks_.empty() || |
| 338 // Subtract the time it took to queue the timer. | 318 timer_tasks_.top().due_time() > info->due_time(); |
| 339 const DWORD now = GetTick(); | 319 timer_tasks_.emplace(std::move(*info.get())); |
| 340 DWORD post_time = now - (msg.wParam >> 32); | 320 if (need_to_schedule_timers) { |
| 341 milliseconds = | 321 CancelTimers(); |
| 342 post_time > milliseconds ? 0 : milliseconds - post_time; | 322 ScheduleNextTimer(); |
| 343 #endif | |
| 344 bool timer_queued = false; | |
| 345 if (timers->size() < MultimediaTimer::kMaxTimers) { | |
| 346 MultimediaTimer* timer = nullptr; | |
| 347 auto available = std::find_if( | |
| 348 timers->begin(), timers->end(), | |
| 349 [](const MultimediaTimer& t) { return !t.is_active(); }); | |
| 350 if (available != timers->end()) { | |
| 351 timer = &(*available); | |
| 352 } else { | |
| 353 timers->emplace_back(); | |
| 354 timer = &timers->back(); | |
| 355 } | |
| 356 | |
| 357 timer_queued = | |
| 358 timer->StartOneShotTimer(std::move(task), milliseconds); | |
| 359 if (!timer_queued) { | |
| 360 // No more multimedia timers can be queued. | |
| 361 // Detach the task and fall back on SetTimer. | |
| 362 task = timer->Cancel(); | |
| 363 } | |
| 364 } | |
| 365 | |
| 366 // When we fail to use multimedia timers, we fall back on the more | |
| 367 // coarse SetTimer/WM_TIMER approach. | |
| 368 if (!timer_queued) { | |
| 369 UINT_PTR timer_id = ::SetTimer(nullptr, 0, milliseconds, nullptr); | |
| 370 delayed_tasks->insert(std::make_pair(timer_id, task.release())); | |
| 371 } | 323 } |
| 372 break; | 324 break; |
| 373 } | 325 } |
| 374 case WM_TIMER: { | 326 case WM_TIMER: { |
| 327 RTC_DCHECK_EQ(timer_id_, msg.wParam); |
| 375 ::KillTimer(nullptr, msg.wParam); | 328 ::KillTimer(nullptr, msg.wParam); |
| 376 auto found = delayed_tasks->find(msg.wParam); | 329 timer_id_ = 0; |
| 377 RTC_DCHECK(found != delayed_tasks->end()); | 330 RunDueTasks(); |
| 378 if (!found->second->Run()) | 331 ScheduleNextTimer(); |
| 379 found->second.release(); | |
| 380 delayed_tasks->erase(found); | |
| 381 break; | 332 break; |
| 382 } | 333 } |
| 383 default: | 334 default: |
| 384 RTC_NOTREACHED(); | 335 RTC_NOTREACHED(); |
| 385 break; | 336 break; |
| 386 } | 337 } |
| 387 } else { | 338 } else { |
| 388 ::TranslateMessage(&msg); | 339 ::TranslateMessage(&msg); |
| 389 ::DispatchMessage(&msg); | 340 ::DispatchMessage(&msg); |
| 390 } | 341 } |
| 391 } | 342 } |
| 392 return msg.message != WM_QUIT; | 343 return msg.message != WM_QUIT; |
| 393 } | 344 } |
| 394 | 345 |
| 346 void TaskQueue::ThreadState::RunDueTasks() { |
| 347 RTC_DCHECK(!timer_tasks_.empty()); |
| 348 auto now = GetTick(); |
| 349 do { |
| 350 const auto& top = timer_tasks_.top(); |
| 351 if (top.due_time() > now) |
| 352 break; |
| 353 top.Run(); |
| 354 timer_tasks_.pop(); |
| 355 } while (!timer_tasks_.empty()); |
| 356 } |
| 357 |
| 358 void TaskQueue::ThreadState::ScheduleNextTimer() { |
| 359 RTC_DCHECK_EQ(timer_id_, 0); |
| 360 if (timer_tasks_.empty()) |
| 361 return; |
| 362 |
| 363 const auto& next_task = timer_tasks_.top(); |
| 364 int64_t delay_ms = std::max(0ll, next_task.due_time() - GetTick()); |
| 365 uint32_t milliseconds = rtc::dchecked_cast<uint32_t>(delay_ms); |
| 366 if (!timer_.StartOneShotTimer(milliseconds)) |
| 367 timer_id_ = ::SetTimer(nullptr, 0, milliseconds, nullptr); |
| 368 } |
| 369 |
| 370 void TaskQueue::ThreadState::CancelTimers() { |
| 371 timer_.Cancel(); |
| 372 if (timer_id_) { |
| 373 ::KillTimer(nullptr, timer_id_); |
| 374 timer_id_ = 0; |
| 375 } |
| 376 } |
| 377 |
| 395 } // namespace rtc | 378 } // namespace rtc |
| OLD | NEW |