1 /*
2 * Copyright 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <thread>
18
19 #include <gmock/gmock.h>
20 #include <gtest/gtest.h>
21
22 #include <scheduler/Timer.h>
23
24 #include "Scheduler/VSyncDispatchTimerQueue.h"
25 #include "Scheduler/VSyncTracker.h"
26
27 using namespace testing;
28 using namespace std::literals;
29
30 namespace android::scheduler {
31
32 template <typename Rep, typename Per>
toNs(std::chrono::duration<Rep,Per> const & tp)33 constexpr nsecs_t toNs(std::chrono::duration<Rep, Per> const& tp) {
34 return std::chrono::duration_cast<std::chrono::nanoseconds>(tp).count();
35 }
36
37 class StubTracker : public VSyncTracker {
38 public:
StubTracker(nsecs_t period)39 StubTracker(nsecs_t period) : mPeriod(period) {}
40
addVsyncTimestamp(nsecs_t)41 bool addVsyncTimestamp(nsecs_t) final { return true; }
42
currentPeriod() const43 nsecs_t currentPeriod() const final {
44 std::lock_guard lock(mMutex);
45 return mPeriod;
46 }
47
minFramePeriod() const48 Period minFramePeriod() const final { return Period::fromNs(currentPeriod()); }
resetModel()49 void resetModel() final {}
needsMoreSamples() const50 bool needsMoreSamples() const final { return false; }
isVSyncInPhase(nsecs_t,Fps)51 bool isVSyncInPhase(nsecs_t, Fps) final { return false; }
setDisplayModePtr(ftl::NonNull<DisplayModePtr>)52 void setDisplayModePtr(ftl::NonNull<DisplayModePtr>) final {}
setRenderRate(Fps,bool)53 void setRenderRate(Fps, bool) final {}
onFrameBegin(TimePoint,TimePoint)54 void onFrameBegin(TimePoint, TimePoint) final {}
onFrameMissed(TimePoint)55 void onFrameMissed(TimePoint) final {}
dump(std::string &) const56 void dump(std::string&) const final {}
isCurrentMode(const ftl::NonNull<DisplayModePtr> &) const57 bool isCurrentMode(const ftl::NonNull<DisplayModePtr>&) const final { return false; };
58
59 protected:
60 std::mutex mutable mMutex;
61 nsecs_t mPeriod;
62 };
63
64 class FixedRateIdealStubTracker : public StubTracker {
65 public:
FixedRateIdealStubTracker()66 FixedRateIdealStubTracker() : StubTracker{toNs(3ms)} {}
67
nextAnticipatedVSyncTimeFrom(nsecs_t timePoint,std::optional<nsecs_t>)68 nsecs_t nextAnticipatedVSyncTimeFrom(nsecs_t timePoint, std::optional<nsecs_t>) final {
69 auto const floor = timePoint % mPeriod;
70 if (floor == 0) {
71 return timePoint;
72 }
73 return timePoint - floor + mPeriod;
74 }
75 };
76
77 class VRRStubTracker : public StubTracker {
78 public:
VRRStubTracker(nsecs_t period)79 VRRStubTracker(nsecs_t period) : StubTracker(period) {}
80
nextAnticipatedVSyncTimeFrom(nsecs_t time_point,std::optional<nsecs_t>)81 nsecs_t nextAnticipatedVSyncTimeFrom(nsecs_t time_point, std::optional<nsecs_t>) final {
82 std::lock_guard lock(mMutex);
83 auto const normalized_to_base = time_point - mBase;
84 auto const floor = (normalized_to_base) % mPeriod;
85 if (floor == 0) {
86 return time_point;
87 }
88 return normalized_to_base - floor + mPeriod + mBase;
89 }
90
set_interval(nsecs_t interval,nsecs_t last_known)91 void set_interval(nsecs_t interval, nsecs_t last_known) {
92 std::lock_guard lock(mMutex);
93 mPeriod = interval;
94 mBase = last_known;
95 }
96
97 private:
98 nsecs_t mBase = 0;
99 };
100
101 struct VSyncDispatchRealtimeTest : testing::Test {
102 static nsecs_t constexpr mDispatchGroupThreshold = toNs(100us);
103 static nsecs_t constexpr mVsyncMoveThreshold = toNs(500us);
104 static size_t constexpr mIterations = 20;
105 };
106
107 class RepeatingCallbackReceiver {
108 public:
RepeatingCallbackReceiver(std::shared_ptr<VSyncDispatch> dispatch,nsecs_t workload,nsecs_t readyDuration)109 RepeatingCallbackReceiver(std::shared_ptr<VSyncDispatch> dispatch, nsecs_t workload,
110 nsecs_t readyDuration)
111 : mWorkload(workload),
112 mReadyDuration(readyDuration),
113 mCallback(
114 dispatch, [&](auto time, auto, auto) { callback_called(time); }, "repeat0") {}
115
repeatedly_schedule(size_t iterations,std::function<void (nsecs_t)> const & onEachFrame)116 void repeatedly_schedule(size_t iterations, std::function<void(nsecs_t)> const& onEachFrame) {
117 mCallbackTimes.reserve(iterations);
118 mCallback.schedule(
119 {.workDuration = mWorkload,
120 .readyDuration = mReadyDuration,
121 .lastVsync = systemTime(SYSTEM_TIME_MONOTONIC) + mWorkload + mReadyDuration});
122
123 for (auto i = 0u; i < iterations - 1; i++) {
124 std::unique_lock lock(mMutex);
125 mCv.wait(lock, [&] { return mCalled; });
126 mCalled = false;
127 auto last = mLastTarget;
128 lock.unlock();
129
130 onEachFrame(last);
131
132 mCallback.schedule({.workDuration = mWorkload,
133 .readyDuration = mReadyDuration,
134 .lastVsync = last + mWorkload + mReadyDuration});
135 }
136
137 // wait for the last callback.
138 std::unique_lock lock(mMutex);
139 mCv.wait(lock, [&] { return mCalled; });
140 }
141
with_callback_times(std::function<void (std::vector<nsecs_t> const &)> const & fn) const142 void with_callback_times(std::function<void(std::vector<nsecs_t> const&)> const& fn) const {
143 fn(mCallbackTimes);
144 }
145
146 private:
callback_called(nsecs_t time)147 void callback_called(nsecs_t time) {
148 std::lock_guard lock(mMutex);
149 mCallbackTimes.push_back(time);
150 mCalled = true;
151 mLastTarget = time;
152 mCv.notify_all();
153 }
154
155 nsecs_t const mWorkload;
156 nsecs_t const mReadyDuration;
157 VSyncCallbackRegistration mCallback;
158
159 std::mutex mMutex;
160 std::condition_variable mCv;
161 bool mCalled = false;
162 nsecs_t mLastTarget = 0;
163 std::vector<nsecs_t> mCallbackTimes;
164 };
165
TEST_F(VSyncDispatchRealtimeTest,triple_alarm)166 TEST_F(VSyncDispatchRealtimeTest, triple_alarm) {
167 auto tracker = std::make_shared<FixedRateIdealStubTracker>();
168 auto dispatch =
169 std::make_shared<VSyncDispatchTimerQueue>(std::make_unique<Timer>(), tracker,
170 mDispatchGroupThreshold, mVsyncMoveThreshold);
171
172 static size_t constexpr num_clients = 3;
173 std::array<RepeatingCallbackReceiver, num_clients>
174 cb_receiver{RepeatingCallbackReceiver(dispatch, toNs(1500us), toNs(2500us)),
175 RepeatingCallbackReceiver(dispatch, toNs(0h), toNs(0h)),
176 RepeatingCallbackReceiver(dispatch, toNs(1ms), toNs(3ms))};
177
178 auto const on_each_frame = [](nsecs_t) {};
179 std::array<std::thread, num_clients> threads{
180 std::thread([&] { cb_receiver[0].repeatedly_schedule(mIterations, on_each_frame); }),
181 std::thread([&] { cb_receiver[1].repeatedly_schedule(mIterations, on_each_frame); }),
182 std::thread([&] { cb_receiver[2].repeatedly_schedule(mIterations, on_each_frame); }),
183 };
184
185 for (auto it = threads.rbegin(); it != threads.rend(); it++) {
186 it->join();
187 }
188
189 for (auto const& cbs : cb_receiver) {
190 cbs.with_callback_times([](auto times) { EXPECT_THAT(times.size(), Eq(mIterations)); });
191 }
192 }
193
194 // starts at 333hz, slides down to 43hz
TEST_F(VSyncDispatchRealtimeTest,vascillating_vrr)195 TEST_F(VSyncDispatchRealtimeTest, vascillating_vrr) {
196 auto next_vsync_interval = toNs(3ms);
197 auto tracker = std::make_shared<VRRStubTracker>(next_vsync_interval);
198 auto dispatch =
199 std::make_shared<VSyncDispatchTimerQueue>(std::make_unique<Timer>(), tracker,
200 mDispatchGroupThreshold, mVsyncMoveThreshold);
201
202 RepeatingCallbackReceiver cb_receiver(dispatch, toNs(1ms), toNs(5ms));
203
204 auto const on_each_frame = [&](nsecs_t last_known) {
205 tracker->set_interval(next_vsync_interval += toNs(1ms), last_known);
206 };
207
208 std::thread eventThread([&] { cb_receiver.repeatedly_schedule(mIterations, on_each_frame); });
209 eventThread.join();
210
211 cb_receiver.with_callback_times([](auto times) { EXPECT_THAT(times.size(), Eq(mIterations)); });
212 }
213
214 // starts at 333hz, jumps to 200hz at frame 10
TEST_F(VSyncDispatchRealtimeTest,fixed_jump)215 TEST_F(VSyncDispatchRealtimeTest, fixed_jump) {
216 auto tracker = std::make_shared<VRRStubTracker>(toNs(3ms));
217 auto dispatch =
218 std::make_shared<VSyncDispatchTimerQueue>(std::make_unique<Timer>(), tracker,
219 mDispatchGroupThreshold, mVsyncMoveThreshold);
220
221 RepeatingCallbackReceiver cb_receiver(dispatch, toNs(1ms), toNs(5ms));
222
223 auto jump_frame_counter = 0u;
224 auto constexpr jump_frame_at = 10u;
225 auto const on_each_frame = [&](nsecs_t last_known) {
226 if (jump_frame_counter++ == jump_frame_at) {
227 tracker->set_interval(toNs(5ms), last_known);
228 }
229 };
230 std::thread eventThread([&] { cb_receiver.repeatedly_schedule(mIterations, on_each_frame); });
231 eventThread.join();
232
233 cb_receiver.with_callback_times([](auto times) { EXPECT_THAT(times.size(), Eq(mIterations)); });
234 }
235 } // namespace android::scheduler
236