blob: 3bdce8d089c3b2499c267fc1ba25788ff58fa7a2 [file] [log] [blame]
Sebastian Jansson0d617cc2019-03-22 15:22:16 +01001/*
2 * Copyright 2019 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 "test/time_controller/simulated_time_controller.h"
11
12#include <algorithm>
13#include <deque>
14#include <list>
Mirko Bonadei317a1f02019-09-17 17:06:18 +020015#include <memory>
Sebastian Jansson0d617cc2019-03-22 15:22:16 +010016#include <string>
17#include <thread>
18#include <vector>
19
Sebastian Jansson0d617cc2019-03-22 15:22:16 +010020#include "absl/strings/string_view.h"
Sebastian Jansson53cd9e22020-01-13 10:33:19 +010021#include "test/time_controller/simulated_process_thread.h"
22#include "test/time_controller/simulated_task_queue.h"
Sebastian Jansson0d617cc2019-03-22 15:22:16 +010023
24namespace webrtc {
Sebastian Jansson7b6add32019-03-29 10:34:26 +010025namespace {
26// Helper function to remove from a std container by value.
27template <class C>
Sebastian Jansson53cd9e22020-01-13 10:33:19 +010028bool RemoveByValue(C* vec, typename C::value_type val) {
29 auto it = std::find(vec->begin(), vec->end(), val);
30 if (it == vec->end())
Sebastian Jansson7b6add32019-03-29 10:34:26 +010031 return false;
Sebastian Jansson53cd9e22020-01-13 10:33:19 +010032 vec->erase(it);
Sebastian Jansson7b6add32019-03-29 10:34:26 +010033 return true;
34}
35} // namespace
Sebastian Jansson0d617cc2019-03-22 15:22:16 +010036
37namespace sim_time_impl {
Sebastian Jansson7b6add32019-03-29 10:34:26 +010038
Sebastian Jansson0d617cc2019-03-22 15:22:16 +010039SimulatedTimeControllerImpl::SimulatedTimeControllerImpl(Timestamp start_time)
40 : thread_id_(rtc::CurrentThreadId()), current_time_(start_time) {}
41
42SimulatedTimeControllerImpl::~SimulatedTimeControllerImpl() = default;
43
44std::unique_ptr<TaskQueueBase, TaskQueueDeleter>
45SimulatedTimeControllerImpl::CreateTaskQueue(
46 absl::string_view name,
47 TaskQueueFactory::Priority priority) const {
48 // TODO(srte): Remove the const cast when the interface is made mutable.
49 auto mutable_this = const_cast<SimulatedTimeControllerImpl*>(this);
Sebastian Jansson53cd9e22020-01-13 10:33:19 +010050 auto task_queue = std::unique_ptr<SimulatedTaskQueue, TaskQueueDeleter>(
51 new SimulatedTaskQueue(mutable_this, name));
Sebastian Jansson0d617cc2019-03-22 15:22:16 +010052 rtc::CritScope lock(&mutable_this->lock_);
Sebastian Jansson7b6add32019-03-29 10:34:26 +010053 mutable_this->runners_.push_back(task_queue.get());
Sebastian Jansson0d617cc2019-03-22 15:22:16 +010054 return task_queue;
55}
56
57std::unique_ptr<ProcessThread> SimulatedTimeControllerImpl::CreateProcessThread(
58 const char* thread_name) {
59 rtc::CritScope lock(&lock_);
60 auto process_thread =
Sebastian Jansson53cd9e22020-01-13 10:33:19 +010061 std::make_unique<SimulatedProcessThread>(this, thread_name);
Sebastian Jansson7b6add32019-03-29 10:34:26 +010062 runners_.push_back(process_thread.get());
Sebastian Jansson0d617cc2019-03-22 15:22:16 +010063 return process_thread;
64}
65
Sebastian Jansson0d617cc2019-03-22 15:22:16 +010066void SimulatedTimeControllerImpl::YieldExecution() {
67 if (rtc::CurrentThreadId() == thread_id_) {
Sebastian Jansson7b6add32019-03-29 10:34:26 +010068 TaskQueueBase* yielding_from = TaskQueueBase::Current();
69 // Since we might continue execution on a process thread, we should reset
70 // the thread local task queue reference. This ensures that thread checkers
71 // won't think we are executing on the yielding task queue. It also ensure
72 // that TaskQueueBase::Current() won't return the yielding task queue.
Sebastian Jansson53cd9e22020-01-13 10:33:19 +010073 TokenTaskQueue::CurrentTaskQueueSetter reset_queue(nullptr);
Sebastian Jansson0d617cc2019-03-22 15:22:16 +010074 // When we yield, we don't want to risk executing further tasks on the
75 // currently executing task queue. If there's a ready task that also yields,
76 // it's added to this set as well and only tasks on the remaining task
77 // queues are executed.
Sebastian Jansson7b6add32019-03-29 10:34:26 +010078 auto inserted = yielded_.insert(yielding_from);
Sebastian Jansson0d617cc2019-03-22 15:22:16 +010079 RTC_DCHECK(inserted.second);
80 RunReadyRunners();
81 yielded_.erase(inserted.first);
82 }
83}
84
85void SimulatedTimeControllerImpl::RunReadyRunners() {
Sebastian Jansson1b408232019-04-12 15:39:38 +020086 rtc::CritScope lock(&lock_);
Sebastian Jansson7b6add32019-03-29 10:34:26 +010087 RTC_DCHECK_EQ(rtc::CurrentThreadId(), thread_id_);
Sebastian Jansson0d617cc2019-03-22 15:22:16 +010088 Timestamp current_time = CurrentTime();
Sebastian Jansson1b408232019-04-12 15:39:38 +020089 // Clearing |ready_runners_| in case this is a recursive call:
90 // RunReadyRunners -> Run -> Event::Wait -> Yield ->RunReadyRunners
91 ready_runners_.clear();
92
Sebastian Jansson0d617cc2019-03-22 15:22:16 +010093 // We repeat until we have no ready left to handle tasks posted by ready
94 // runners.
95 while (true) {
Sebastian Jansson76540812019-04-11 17:48:30 +020096 for (auto* runner : runners_) {
Sebastian Jansson53cd9e22020-01-13 10:33:19 +010097 if (yielded_.find(runner->GetAsTaskQueue()) == yielded_.end() &&
Sebastian Jansson76540812019-04-11 17:48:30 +020098 runner->GetNextRunTime() <= current_time) {
99 ready_runners_.push_back(runner);
100 }
101 }
102 if (ready_runners_.empty())
Sebastian Jansson53cd9e22020-01-13 10:33:19 +0100103 break;
Sebastian Jansson76540812019-04-11 17:48:30 +0200104 while (!ready_runners_.empty()) {
105 auto* runner = ready_runners_.front();
106 ready_runners_.pop_front();
Sebastian Jansson53cd9e22020-01-13 10:33:19 +0100107 // Note that the RunReady function might indirectly cause a call to
Sebastian Jansson76540812019-04-11 17:48:30 +0200108 // Unregister() which will recursively grab |lock_| again to remove items
109 // from |ready_runners_|.
Sebastian Jansson53cd9e22020-01-13 10:33:19 +0100110 runner->RunReady(current_time);
Sebastian Jansson0d617cc2019-03-22 15:22:16 +0100111 }
112 }
113}
114
115Timestamp SimulatedTimeControllerImpl::CurrentTime() const {
116 rtc::CritScope lock(&time_lock_);
117 return current_time_;
118}
119
120Timestamp SimulatedTimeControllerImpl::NextRunTime() const {
121 Timestamp current_time = CurrentTime();
122 Timestamp next_time = Timestamp::PlusInfinity();
123 rtc::CritScope lock(&lock_);
124 for (auto* runner : runners_) {
125 Timestamp next_run_time = runner->GetNextRunTime();
126 if (next_run_time <= current_time)
127 return current_time;
128 next_time = std::min(next_time, next_run_time);
129 }
130 return next_time;
131}
132
133void SimulatedTimeControllerImpl::AdvanceTime(Timestamp target_time) {
134 rtc::CritScope time_lock(&time_lock_);
Sebastian Jansson5a000162019-04-12 11:21:32 +0200135 RTC_DCHECK_GE(target_time, current_time_);
Sebastian Jansson0d617cc2019-03-22 15:22:16 +0100136 current_time_ = target_time;
137}
138
139void SimulatedTimeControllerImpl::Unregister(SimulatedSequenceRunner* runner) {
140 rtc::CritScope lock(&lock_);
Sebastian Jansson53cd9e22020-01-13 10:33:19 +0100141 bool removed = RemoveByValue(&runners_, runner);
Sebastian Jansson7b6add32019-03-29 10:34:26 +0100142 RTC_CHECK(removed);
Sebastian Jansson53cd9e22020-01-13 10:33:19 +0100143 RemoveByValue(&ready_runners_, runner);
Sebastian Jansson0d617cc2019-03-22 15:22:16 +0100144}
Sebastian Jansson0d617cc2019-03-22 15:22:16 +0100145} // namespace sim_time_impl
146
147GlobalSimulatedTimeController::GlobalSimulatedTimeController(
148 Timestamp start_time)
Sebastian Jansson340af972019-12-04 10:07:48 +0100149 : sim_clock_(start_time.us()), impl_(start_time), yield_policy_(&impl_) {
Sebastian Janssond624c392019-04-17 10:36:03 +0200150 global_clock_.SetTime(start_time);
Sebastian Jansson0d617cc2019-03-22 15:22:16 +0100151}
152
153GlobalSimulatedTimeController::~GlobalSimulatedTimeController() = default;
154
155Clock* GlobalSimulatedTimeController::GetClock() {
156 return &sim_clock_;
157}
158
159TaskQueueFactory* GlobalSimulatedTimeController::GetTaskQueueFactory() {
160 return &impl_;
161}
162
163std::unique_ptr<ProcessThread>
164GlobalSimulatedTimeController::CreateProcessThread(const char* thread_name) {
165 return impl_.CreateProcessThread(thread_name);
166}
167
Markus Handell486cc552019-12-03 14:37:28 +0100168void GlobalSimulatedTimeController::AdvanceTime(TimeDelta duration) {
Sebastian Jansson0d617cc2019-03-22 15:22:16 +0100169 rtc::ScopedYieldPolicy yield_policy(&impl_);
170 Timestamp current_time = impl_.CurrentTime();
171 Timestamp target_time = current_time + duration;
172 RTC_DCHECK_EQ(current_time.us(), rtc::TimeMicros());
173 while (current_time < target_time) {
174 impl_.RunReadyRunners();
175 Timestamp next_time = std::min(impl_.NextRunTime(), target_time);
176 impl_.AdvanceTime(next_time);
177 auto delta = next_time - current_time;
178 current_time = next_time;
179 sim_clock_.AdvanceTimeMicroseconds(delta.us());
Sebastian Janssond624c392019-04-17 10:36:03 +0200180 global_clock_.AdvanceTime(delta);
Sebastian Jansson0d617cc2019-03-22 15:22:16 +0100181 }
philipeld5727482020-01-03 14:43:10 +0100182 // After time has been simulated up until |target_time| we also need to run
183 // tasks meant to be executed at |target_time|.
184 impl_.RunReadyRunners();
Sebastian Jansson0d617cc2019-03-22 15:22:16 +0100185}
186
Sebastian Jansson0d617cc2019-03-22 15:22:16 +0100187} // namespace webrtc