You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

412 lines
12 KiB

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