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/FrameTime.h>
23 #include <scheduler/Timer.h>
24
25 #include "Scheduler/VSyncDispatchTimerQueue.h"
26 #include "Scheduler/VSyncTracker.h"
27
28 using namespace testing;
29 using namespace std::literals;
30
31 namespace android::scheduler {
32
33 template <typename Rep, typename Per>
toNs(std::chrono::duration<Rep,Per> const & tp)34 constexpr nsecs_t toNs(std::chrono::duration<Rep, Per> const& tp) {
35 return std::chrono::duration_cast<std::chrono::nanoseconds>(tp).count();
36 }
37
38 class StubTracker : public VSyncTracker {
39 public:
StubTracker(nsecs_t period)40 StubTracker(nsecs_t period) : mPeriod(period) {}
41
addVsyncTimestamp(nsecs_t)42 bool addVsyncTimestamp(nsecs_t) final { return true; }
43
currentPeriod() const44 nsecs_t currentPeriod() const final {
45 std::lock_guard lock(mMutex);
46 return mPeriod;
47 }
48
minFramePeriod() const49 Period minFramePeriod() const final { return Period::fromNs(currentPeriod()); }
resetModel()50 void resetModel() final {}
needsMoreSamples() const51 bool needsMoreSamples() const final { return false; }
isVSyncInPhase(nsecs_t,Fps)52 bool isVSyncInPhase(nsecs_t, Fps) final { return false; }
setDisplayModePtr(ftl::NonNull<DisplayModePtr>)53 void setDisplayModePtr(ftl::NonNull<DisplayModePtr>) final {}
setRenderRate(Fps,bool)54 void setRenderRate(Fps, bool) final {}
onFrameBegin(TimePoint,scheduler::FrameTime)55 void onFrameBegin(TimePoint, scheduler::FrameTime) final {}
onFrameMissed(TimePoint)56 void onFrameMissed(TimePoint) final {}
dump(std::string &) const57 void dump(std::string&) const final {}
isCurrentMode(const ftl::NonNull<DisplayModePtr> &) const58 bool isCurrentMode(const ftl::NonNull<DisplayModePtr>&) const final { return false; };
59
60 protected:
61 std::mutex mutable mMutex;
62 nsecs_t mPeriod;
63 };
64
65 class FixedRateIdealStubTracker : public StubTracker {
66 public:
FixedRateIdealStubTracker()67 FixedRateIdealStubTracker() : StubTracker{toNs(3ms)} {}
68
nextAnticipatedVSyncTimeFrom(nsecs_t timePoint,std::optional<nsecs_t>)69 nsecs_t nextAnticipatedVSyncTimeFrom(nsecs_t timePoint, std::optional<nsecs_t>) final {
70 auto const floor = timePoint % mPeriod;
71 if (floor == 0) {
72 return timePoint;
73 }
74 return timePoint - floor + mPeriod;
75 }
76 };
77
78 class VRRStubTracker : public StubTracker {
79 public:
VRRStubTracker(nsecs_t period)80 VRRStubTracker(nsecs_t period) : StubTracker(period) {}
81
nextAnticipatedVSyncTimeFrom(nsecs_t time_point,std::optional<nsecs_t>)82 nsecs_t nextAnticipatedVSyncTimeFrom(nsecs_t time_point, std::optional<nsecs_t>) final {
83 std::lock_guard lock(mMutex);
84 auto const normalized_to_base = time_point - mBase;
85 auto const floor = (normalized_to_base) % mPeriod;
86 if (floor == 0) {
87 return time_point;
88 }
89 return normalized_to_base - floor + mPeriod + mBase;
90 }
91
set_interval(nsecs_t interval,nsecs_t last_known)92 void set_interval(nsecs_t interval, nsecs_t last_known) {
93 std::lock_guard lock(mMutex);
94 mPeriod = interval;
95 mBase = last_known;
96 }
97
98 private:
99 nsecs_t mBase = 0;
100 };
101
102 struct VSyncDispatchRealtimeTest : testing::Test {
103 static nsecs_t constexpr mDispatchGroupThreshold = toNs(100us);
104 static nsecs_t constexpr mVsyncMoveThreshold = toNs(500us);
105 static size_t constexpr mIterations = 20;
106 };
107
108 class RepeatingCallbackReceiver {
109 public:
RepeatingCallbackReceiver(std::shared_ptr<VSyncDispatch> dispatch,nsecs_t workload,nsecs_t readyDuration)110 RepeatingCallbackReceiver(std::shared_ptr<VSyncDispatch> dispatch, nsecs_t workload,
111 nsecs_t readyDuration)
112 : mWorkload(workload),
113 mReadyDuration(readyDuration),
114 mCallback(
115 dispatch, [&](auto time, auto, auto) { callback_called(time); }, "repeat0") {}
116
repeatedly_schedule(size_t iterations,std::function<void (nsecs_t)> const & onEachFrame)117 void repeatedly_schedule(size_t iterations, std::function<void(nsecs_t)> const& onEachFrame) {
118 mCallbackTimes.reserve(iterations);
119 mCallback.schedule(
120 {.workDuration = mWorkload,
121 .readyDuration = mReadyDuration,
122 .lastVsync = systemTime(SYSTEM_TIME_MONOTONIC) + mWorkload + mReadyDuration});
123
124 for (auto i = 0u; i < iterations - 1; i++) {
125 std::unique_lock lock(mMutex);
126 mCv.wait(lock, [&] { return mCalled; });
127 mCalled = false;
128 auto last = mLastTarget;
129 lock.unlock();
130
131 onEachFrame(last);
132
133 mCallback.schedule({.workDuration = mWorkload,
134 .readyDuration = mReadyDuration,
135 .lastVsync = last + mWorkload + mReadyDuration});
136 }
137
138 // wait for the last callback.
139 std::unique_lock lock(mMutex);
140 mCv.wait(lock, [&] { return mCalled; });
141 }
142
with_callback_times(std::function<void (std::vector<nsecs_t> const &)> const & fn) const143 void with_callback_times(std::function<void(std::vector<nsecs_t> const&)> const& fn) const {
144 fn(mCallbackTimes);
145 }
146
147 private:
callback_called(nsecs_t time)148 void callback_called(nsecs_t time) {
149 std::lock_guard lock(mMutex);
150 mCallbackTimes.push_back(time);
151 mCalled = true;
152 mLastTarget = time;
153 mCv.notify_all();
154 }
155
156 nsecs_t const mWorkload;
157 nsecs_t const mReadyDuration;
158 VSyncCallbackRegistration mCallback;
159
160 std::mutex mMutex;
161 std::condition_variable mCv;
162 bool mCalled = false;
163 nsecs_t mLastTarget = 0;
164 std::vector<nsecs_t> mCallbackTimes;
165 };
166
TEST_F(VSyncDispatchRealtimeTest,triple_alarm)167 TEST_F(VSyncDispatchRealtimeTest, triple_alarm) {
168 auto tracker = std::make_shared<FixedRateIdealStubTracker>();
169 auto dispatch =
170 std::make_shared<VSyncDispatchTimerQueue>(std::make_unique<Timer>(), tracker,
171 mDispatchGroupThreshold, mVsyncMoveThreshold);
172
173 static size_t constexpr num_clients = 3;
174 std::array<RepeatingCallbackReceiver, num_clients>
175 cb_receiver{RepeatingCallbackReceiver(dispatch, toNs(1500us), toNs(2500us)),
176 RepeatingCallbackReceiver(dispatch, toNs(0h), toNs(0h)),
177 RepeatingCallbackReceiver(dispatch, toNs(1ms), toNs(3ms))};
178
179 auto const on_each_frame = [](nsecs_t) {};
180 std::array<std::thread, num_clients> threads{
181 std::thread([&] { cb_receiver[0].repeatedly_schedule(mIterations, on_each_frame); }),
182 std::thread([&] { cb_receiver[1].repeatedly_schedule(mIterations, on_each_frame); }),
183 std::thread([&] { cb_receiver[2].repeatedly_schedule(mIterations, on_each_frame); }),
184 };
185
186 for (auto it = threads.rbegin(); it != threads.rend(); it++) {
187 it->join();
188 }
189
190 for (auto const& cbs : cb_receiver) {
191 cbs.with_callback_times([](auto times) { EXPECT_THAT(times.size(), Eq(mIterations)); });
192 }
193 }
194
195 // starts at 333hz, slides down to 43hz
TEST_F(VSyncDispatchRealtimeTest,vascillating_vrr)196 TEST_F(VSyncDispatchRealtimeTest, vascillating_vrr) {
197 auto next_vsync_interval = toNs(3ms);
198 auto tracker = std::make_shared<VRRStubTracker>(next_vsync_interval);
199 auto dispatch =
200 std::make_shared<VSyncDispatchTimerQueue>(std::make_unique<Timer>(), tracker,
201 mDispatchGroupThreshold, mVsyncMoveThreshold);
202
203 RepeatingCallbackReceiver cb_receiver(dispatch, toNs(1ms), toNs(5ms));
204
205 auto const on_each_frame = [&](nsecs_t last_known) {
206 tracker->set_interval(next_vsync_interval += toNs(1ms), last_known);
207 };
208
209 std::thread eventThread([&] { cb_receiver.repeatedly_schedule(mIterations, on_each_frame); });
210 eventThread.join();
211
212 cb_receiver.with_callback_times([](auto times) { EXPECT_THAT(times.size(), Eq(mIterations)); });
213 }
214
215 // starts at 333hz, jumps to 200hz at frame 10
TEST_F(VSyncDispatchRealtimeTest,fixed_jump)216 TEST_F(VSyncDispatchRealtimeTest, fixed_jump) {
217 auto tracker = std::make_shared<VRRStubTracker>(toNs(3ms));
218 auto dispatch =
219 std::make_shared<VSyncDispatchTimerQueue>(std::make_unique<Timer>(), tracker,
220 mDispatchGroupThreshold, mVsyncMoveThreshold);
221
222 RepeatingCallbackReceiver cb_receiver(dispatch, toNs(1ms), toNs(5ms));
223
224 auto jump_frame_counter = 0u;
225 auto constexpr jump_frame_at = 10u;
226 auto const on_each_frame = [&](nsecs_t last_known) {
227 if (jump_frame_counter++ == jump_frame_at) {
228 tracker->set_interval(toNs(5ms), last_known);
229 }
230 };
231 std::thread eventThread([&] { cb_receiver.repeatedly_schedule(mIterations, on_each_frame); });
232 eventThread.join();
233
234 cb_receiver.with_callback_times([](auto times) { EXPECT_THAT(times.size(), Eq(mIterations)); });
235 }
236 } // namespace android::scheduler
237