blob: 7f627f829dbd873a184c034c07706d5b21536883 [file] [log] [blame]
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001/*
2 * Copyright (C) 2011 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
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Mathias Agopian841cde52012-03-01 15:44:37 -080021#define ATRACE_TAG ATRACE_TAG_GRAPHICS
22
Lloyd Pique46a46b32018-01-31 19:01:18 -080023#include <pthread.h>
24#include <sched.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080025#include <sys/types.h>
Dominik Laskowskid9e4de62019-01-21 14:23:01 -080026
Lloyd Pique46a46b32018-01-31 19:01:18 -080027#include <chrono>
28#include <cstdint>
Dominik Laskowskid9e4de62019-01-21 14:23:01 -080029#include <optional>
30#include <type_traits>
Ady Abraham011f8ba2022-11-22 15:09:07 -080031#include <utility>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080032
Yiwei Zhang5434a782018-12-05 18:06:32 -080033#include <android-base/stringprintf.h>
34
Ady Abraham0bb6a472020-10-12 10:22:13 -070035#include <binder/IPCThreadState.h>
36
Mathias Agopiana4cb35a2012-08-20 20:07:34 -070037#include <cutils/compiler.h>
Lloyd Pique46a46b32018-01-31 19:01:18 -080038#include <cutils/sched_policy.h>
Mathias Agopiana4cb35a2012-08-20 20:07:34 -070039
Mathias Agopiand0566bc2011-11-17 17:49:17 -080040#include <gui/DisplayEventReceiver.h>
Ady Abraham07d03c42023-09-27 19:15:08 -070041#include <gui/SchedulingPolicy.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080042
43#include <utils/Errors.h>
Mathias Agopian841cde52012-03-01 15:44:37 -080044#include <utils/Trace.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080045
Rachel Lee0655a912023-04-20 19:54:18 -070046#include <scheduler/VsyncConfig.h>
Marin Shalamanov23c44202020-12-22 19:09:20 +010047#include "DisplayHardware/DisplayMode.h"
Ady Abrahamd6d80162023-10-23 12:57:41 -070048#include "FlagManager.h"
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -070049#include "FrameTimeline.h"
Ady Abraham011f8ba2022-11-22 15:09:07 -080050#include "VSyncDispatch.h"
51#include "VSyncTracker.h"
Marin Shalamanov23c44202020-12-22 19:09:20 +010052
53#include "EventThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Ady Abraham62f216c2020-10-13 19:07:23 -070055#undef LOG_TAG
56#define LOG_TAG "EventThread"
57
Lloyd Pique46a46b32018-01-31 19:01:18 -080058using namespace std::chrono_literals;
Mathias Agopiand0566bc2011-11-17 17:49:17 -080059
Lloyd Pique46a46b32018-01-31 19:01:18 -080060namespace android {
61
Dominik Laskowskid9e4de62019-01-21 14:23:01 -080062using base::StringAppendF;
63using base::StringPrintf;
64
65namespace {
66
67auto vsyncPeriod(VSyncRequest request) {
68 return static_cast<std::underlying_type_t<VSyncRequest>>(request);
69}
70
71std::string toString(VSyncRequest request) {
72 switch (request) {
73 case VSyncRequest::None:
74 return "VSyncRequest::None";
75 case VSyncRequest::Single:
76 return "VSyncRequest::Single";
Tim Murrayb5daa912020-09-09 21:29:13 +000077 case VSyncRequest::SingleSuppressCallback:
78 return "VSyncRequest::SingleSuppressCallback";
Dominik Laskowskid9e4de62019-01-21 14:23:01 -080079 default:
80 return StringPrintf("VSyncRequest::Periodic{period=%d}", vsyncPeriod(request));
81 }
82}
83
84std::string toString(const EventThreadConnection& connection) {
85 return StringPrintf("Connection{%p, %s}", &connection,
86 toString(connection.vsyncRequest).c_str());
87}
88
89std::string toString(const DisplayEventReceiver::Event& event) {
90 switch (event.header.type) {
91 case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
Marin Shalamanova524a092020-07-27 21:39:55 +020092 return StringPrintf("Hotplug{displayId=%s, %s}",
93 to_string(event.header.displayId).c_str(),
Dominik Laskowskid9e4de62019-01-21 14:23:01 -080094 event.hotplug.connected ? "connected" : "disconnected");
95 case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
Rachel Leeb9c5a772022-02-04 21:17:37 -080096 return StringPrintf("VSync{displayId=%s, count=%u, expectedPresentationTime=%" PRId64
97 "}",
Marin Shalamanova524a092020-07-27 21:39:55 +020098 to_string(event.header.displayId).c_str(), event.vsync.count,
Rachel Leeb9c5a772022-02-04 21:17:37 -080099 event.vsync.vsyncData.preferredExpectedPresentationTime());
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100100 case DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE:
101 return StringPrintf("ModeChanged{displayId=%s, modeId=%u}",
102 to_string(event.header.displayId).c_str(), event.modeChange.modeId);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800103 default:
104 return "Event{}";
105 }
106}
107
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800108DisplayEventReceiver::Event makeHotplug(PhysicalDisplayId displayId, nsecs_t timestamp,
109 bool connected) {
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800110 DisplayEventReceiver::Event event;
111 event.header = {DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG, displayId, timestamp};
112 event.hotplug.connected = connected;
113 return event;
114}
115
Brian Johnson5dcd75d2023-08-15 09:36:37 -0700116DisplayEventReceiver::Event makeHotplugError(nsecs_t timestamp, int32_t connectionError) {
117 DisplayEventReceiver::Event event;
118 PhysicalDisplayId unusedDisplayId;
119 event.header = {DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG, unusedDisplayId, timestamp};
120 event.hotplug.connected = false;
121 event.hotplug.connectionError = connectionError;
122 return event;
123}
124
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800125DisplayEventReceiver::Event makeVSync(PhysicalDisplayId displayId, nsecs_t timestamp,
Rachel Leeb9c5a772022-02-04 21:17:37 -0800126 uint32_t count, nsecs_t expectedPresentationTime,
Rachel Lee0d943202022-02-01 23:29:41 -0800127 nsecs_t deadlineTimestamp) {
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800128 DisplayEventReceiver::Event event;
129 event.header = {DisplayEventReceiver::DISPLAY_EVENT_VSYNC, displayId, timestamp};
130 event.vsync.count = count;
Rachel Leeb9c5a772022-02-04 21:17:37 -0800131 event.vsync.vsyncData.preferredFrameTimelineIndex = 0;
132 // Temporarily store the current vsync information in frameTimelines[0], marked as
133 // platform-preferred. When the event is dispatched later, the frame interval at that time is
134 // used with this information to generate multiple frame timeline choices.
135 event.vsync.vsyncData.frameTimelines[0] = {.vsyncId = FrameTimelineInfo::INVALID_VSYNC_ID,
136 .deadlineTimestamp = deadlineTimestamp,
137 .expectedPresentationTime =
138 expectedPresentationTime};
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800139 return event;
140}
141
Ady Abraham67434eb2022-12-01 17:48:12 -0800142DisplayEventReceiver::Event makeModeChanged(const scheduler::FrameRateMode& mode) {
Ady Abraham447052e2019-02-13 16:07:27 -0800143 DisplayEventReceiver::Event event;
Ady Abraham67434eb2022-12-01 17:48:12 -0800144 event.header = {DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE,
145 mode.modePtr->getPhysicalDisplayId(), systemTime()};
146 event.modeChange.modeId = mode.modePtr->getId().value();
147 event.modeChange.vsyncPeriod = mode.fps.getPeriodNsecs();
Ady Abraham447052e2019-02-13 16:07:27 -0800148 return event;
149}
150
Ady Abraham62f216c2020-10-13 19:07:23 -0700151DisplayEventReceiver::Event makeFrameRateOverrideEvent(PhysicalDisplayId displayId,
152 FrameRateOverride frameRateOverride) {
153 return DisplayEventReceiver::Event{
154 .header =
155 DisplayEventReceiver::Event::Header{
156 .type = DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE,
157 .displayId = displayId,
158 .timestamp = systemTime(),
159 },
160 .frameRateOverride = frameRateOverride,
161 };
162}
163
164DisplayEventReceiver::Event makeFrameRateOverrideFlushEvent(PhysicalDisplayId displayId) {
165 return DisplayEventReceiver::Event{
166 .header = DisplayEventReceiver::Event::Header{
167 .type = DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH,
168 .displayId = displayId,
169 .timestamp = systemTime(),
170 }};
171}
172
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800173} // namespace
Lloyd Pique46a46b32018-01-31 19:01:18 -0800174
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700175EventThreadConnection::EventThreadConnection(EventThread* eventThread, uid_t callingUid,
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700176 EventRegistrationFlags eventRegistration)
Ady Abrahamf2851612023-09-25 17:19:00 -0700177 : mOwnerUid(callingUid),
Ady Abraham62f216c2020-10-13 19:07:23 -0700178 mEventRegistration(eventRegistration),
Dominik Laskowskif654d572018-12-20 11:03:06 -0800179 mEventThread(eventThread),
180 mChannel(gui::BitTube::DefaultSize) {}
Ana Krulec85c39af2018-12-26 17:29:57 -0800181
182EventThreadConnection::~EventThreadConnection() {
183 // do nothing here -- clean-up will happen automatically
184 // when the main thread wakes up
185}
186
187void EventThreadConnection::onFirstRef() {
188 // NOTE: mEventThread doesn't hold a strong reference on us
Ady Abrahamd11bade2022-08-01 16:18:03 -0700189 mEventThread->registerDisplayEventConnection(sp<EventThreadConnection>::fromExisting(this));
Ana Krulec85c39af2018-12-26 17:29:57 -0800190}
191
Huihong Luo6fac5232021-11-22 16:05:23 -0800192binder::Status EventThreadConnection::stealReceiveChannel(gui::BitTube* outChannel) {
Ady Abraham899e8cd2022-06-06 15:16:06 -0700193 std::scoped_lock lock(mLock);
194 if (mChannel.initCheck() != NO_ERROR) {
195 return binder::Status::fromStatusT(NAME_NOT_FOUND);
196 }
197
Ana Krulec85c39af2018-12-26 17:29:57 -0800198 outChannel->setReceiveFd(mChannel.moveReceiveFd());
Alec Mouri967d5d72020-08-05 12:50:03 -0700199 outChannel->setSendFd(base::unique_fd(dup(mChannel.getSendFd())));
Huihong Luo6fac5232021-11-22 16:05:23 -0800200 return binder::Status::ok();
Ana Krulec85c39af2018-12-26 17:29:57 -0800201}
202
Huihong Luo6fac5232021-11-22 16:05:23 -0800203binder::Status EventThreadConnection::setVsyncRate(int rate) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700204 mEventThread->setVsyncRate(static_cast<uint32_t>(rate),
205 sp<EventThreadConnection>::fromExisting(this));
Huihong Luo6fac5232021-11-22 16:05:23 -0800206 return binder::Status::ok();
Ana Krulec85c39af2018-12-26 17:29:57 -0800207}
208
Huihong Luo6fac5232021-11-22 16:05:23 -0800209binder::Status EventThreadConnection::requestNextVsync() {
Rachel Leeef2e21f2022-02-01 14:51:34 -0800210 ATRACE_CALL();
Ady Abrahamd11bade2022-08-01 16:18:03 -0700211 mEventThread->requestNextVsync(sp<EventThreadConnection>::fromExisting(this));
Huihong Luo6fac5232021-11-22 16:05:23 -0800212 return binder::Status::ok();
Ana Krulec85c39af2018-12-26 17:29:57 -0800213}
214
Rachel Leeb9c5a772022-02-04 21:17:37 -0800215binder::Status EventThreadConnection::getLatestVsyncEventData(
216 ParcelableVsyncEventData* outVsyncEventData) {
Rachel Leeef2e21f2022-02-01 14:51:34 -0800217 ATRACE_CALL();
Ady Abrahamd11bade2022-08-01 16:18:03 -0700218 outVsyncEventData->vsync =
219 mEventThread->getLatestVsyncEventData(sp<EventThreadConnection>::fromExisting(this));
Rachel Leeef2e21f2022-02-01 14:51:34 -0800220 return binder::Status::ok();
221}
222
Ady Abraham07d03c42023-09-27 19:15:08 -0700223binder::Status EventThreadConnection::getSchedulingPolicy(gui::SchedulingPolicy* outPolicy) {
224 return gui::getSchedulingPolicy(outPolicy);
225}
226
Ana Krulec85c39af2018-12-26 17:29:57 -0800227status_t EventThreadConnection::postEvent(const DisplayEventReceiver::Event& event) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700228 constexpr auto toStatus = [](ssize_t size) {
229 return size < 0 ? status_t(size) : status_t(NO_ERROR);
230 };
231
232 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE ||
233 event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH) {
234 mPendingEvents.emplace_back(event);
235 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE) {
236 return status_t(NO_ERROR);
237 }
238
239 auto size = DisplayEventReceiver::sendEvents(&mChannel, mPendingEvents.data(),
240 mPendingEvents.size());
241 mPendingEvents.clear();
242 return toStatus(size);
243 }
244
245 auto size = DisplayEventReceiver::sendEvents(&mChannel, &event, 1);
246 return toStatus(size);
Ana Krulec85c39af2018-12-26 17:29:57 -0800247}
248
249// ---------------------------------------------------------------------------
250
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800251EventThread::~EventThread() = default;
252
253namespace impl {
254
Leon Scroggins III67388622023-02-06 20:36:20 -0500255EventThread::EventThread(const char* name, std::shared_ptr<scheduler::VsyncSchedule> vsyncSchedule,
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700256 android::frametimeline::TokenManager* tokenManager,
Ady Abrahamf2851612023-09-25 17:19:00 -0700257 IEventThreadCallback& callback, std::chrono::nanoseconds workDuration,
Ady Abraham011f8ba2022-11-22 15:09:07 -0800258 std::chrono::nanoseconds readyDuration)
259 : mThreadName(name),
260 mVsyncTracer(base::StringPrintf("VSYNC-%s", name), 0),
261 mWorkDuration(base::StringPrintf("VsyncWorkDuration-%s", name), workDuration),
262 mReadyDuration(readyDuration),
Leon Scroggins III67388622023-02-06 20:36:20 -0500263 mVsyncSchedule(std::move(vsyncSchedule)),
264 mVsyncRegistration(mVsyncSchedule->getDispatch(), createDispatchCallback(), name),
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700265 mTokenManager(tokenManager),
Ady Abrahamf2851612023-09-25 17:19:00 -0700266 mCallback(callback) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800267 mThread = std::thread([this]() NO_THREAD_SAFETY_ANALYSIS {
268 std::unique_lock<std::mutex> lock(mMutex);
269 threadMain(lock);
270 });
Lloyd Pique46a46b32018-01-31 19:01:18 -0800271
Dominik Laskowski6505f792019-09-18 11:10:05 -0700272 pthread_setname_np(mThread.native_handle(), mThreadName);
Lloyd Pique46a46b32018-01-31 19:01:18 -0800273
274 pid_t tid = pthread_gettid_np(mThread.native_handle());
275
276 // Use SCHED_FIFO to minimize jitter
277 constexpr int EVENT_THREAD_PRIORITY = 2;
278 struct sched_param param = {0};
279 param.sched_priority = EVENT_THREAD_PRIORITY;
280 if (pthread_setschedparam(mThread.native_handle(), SCHED_FIFO, &param) != 0) {
281 ALOGE("Couldn't set SCHED_FIFO for EventThread");
282 }
283
284 set_sched_policy(tid, SP_FOREGROUND);
285}
286
287EventThread::~EventThread() {
288 {
289 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski029cc122019-01-23 19:52:06 -0800290 mState = State::Quit;
Lloyd Pique46a46b32018-01-31 19:01:18 -0800291 mCondition.notify_all();
292 }
293 mThread.join();
Ruchi Kandoief472ec2014-04-02 12:50:06 -0700294}
295
Ady Abraham9c53ee72020-07-22 21:16:18 -0700296void EventThread::setDuration(std::chrono::nanoseconds workDuration,
297 std::chrono::nanoseconds readyDuration) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800298 std::lock_guard<std::mutex> lock(mMutex);
Ady Abraham011f8ba2022-11-22 15:09:07 -0800299 mWorkDuration = workDuration;
300 mReadyDuration = readyDuration;
301
302 mVsyncRegistration.update({.workDuration = mWorkDuration.get().count(),
303 .readyDuration = mReadyDuration.count(),
304 .earliestVsync = mLastVsyncCallbackTime.ns()});
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700305}
306
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700307sp<EventThreadConnection> EventThread::createEventConnection(
Ady Abrahamf2851612023-09-25 17:19:00 -0700308 EventRegistrationFlags eventRegistration) const {
Ady Abraham07d03c42023-09-27 19:15:08 -0700309 auto connection = sp<EventThreadConnection>::make(const_cast<EventThread*>(this),
310 IPCThreadState::self()->getCallingUid(),
311 eventRegistration);
Ady Abrahamd6d80162023-10-23 12:57:41 -0700312 if (FlagManager::getInstance().misc1()) {
Ady Abraham07d03c42023-09-27 19:15:08 -0700313 const int policy = SCHED_FIFO;
314 connection->setMinSchedulerPolicy(policy, sched_get_priority_min(policy));
315 }
316 return connection;
Mathias Agopian8aedd472012-01-24 16:39:14 -0800317}
318
Ana Krulec85c39af2018-12-26 17:29:57 -0800319status_t EventThread::registerDisplayEventConnection(const sp<EventThreadConnection>& connection) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800320 std::lock_guard<std::mutex> lock(mMutex);
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700321
322 // this should never happen
323 auto it = std::find(mDisplayEventConnections.cbegin(),
324 mDisplayEventConnections.cend(), connection);
325 if (it != mDisplayEventConnections.cend()) {
326 ALOGW("DisplayEventConnection %p already exists", connection.get());
327 mCondition.notify_all();
328 return ALREADY_EXISTS;
329 }
330
331 mDisplayEventConnections.push_back(connection);
Lloyd Pique46a46b32018-01-31 19:01:18 -0800332 mCondition.notify_all();
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800333 return NO_ERROR;
334}
335
Ana Krulec85c39af2018-12-26 17:29:57 -0800336void EventThread::removeDisplayEventConnectionLocked(const wp<EventThreadConnection>& connection) {
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700337 auto it = std::find(mDisplayEventConnections.cbegin(),
338 mDisplayEventConnections.cend(), connection);
339 if (it != mDisplayEventConnections.cend()) {
340 mDisplayEventConnections.erase(it);
341 }
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800342}
343
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800344void EventThread::setVsyncRate(uint32_t rate, const sp<EventThreadConnection>& connection) {
345 if (static_cast<std::underlying_type_t<VSyncRequest>>(rate) < 0) {
346 return;
347 }
348
349 std::lock_guard<std::mutex> lock(mMutex);
350
351 const auto request = rate == 0 ? VSyncRequest::None : static_cast<VSyncRequest>(rate);
352 if (connection->vsyncRequest != request) {
353 connection->vsyncRequest = request;
354 mCondition.notify_all();
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800355 }
356}
357
Ady Abraham8532d012019-05-08 14:50:56 -0700358void EventThread::requestNextVsync(const sp<EventThreadConnection>& connection) {
Ady Abrahamf2851612023-09-25 17:19:00 -0700359 mCallback.resync();
Tim Murray4a4e4a22016-04-19 16:29:23 +0000360
Ana Krulec7d1d6832018-12-27 11:10:09 -0800361 std::lock_guard<std::mutex> lock(mMutex);
362
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800363 if (connection->vsyncRequest == VSyncRequest::None) {
364 connection->vsyncRequest = VSyncRequest::Single;
Lloyd Pique46a46b32018-01-31 19:01:18 -0800365 mCondition.notify_all();
Tim Murrayb5daa912020-09-09 21:29:13 +0000366 } else if (connection->vsyncRequest == VSyncRequest::SingleSuppressCallback) {
367 connection->vsyncRequest = VSyncRequest::Single;
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800368 }
Mathias Agopian23748662011-12-05 14:33:34 -0800369}
370
Rachel Leeef2e21f2022-02-01 14:51:34 -0800371VsyncEventData EventThread::getLatestVsyncEventData(
372 const sp<EventThreadConnection>& connection) const {
Rachel Leeb5223cf2022-03-14 14:39:27 -0700373 // Resync so that the vsync is accurate with hardware. getLatestVsyncEventData is an alternate
374 // way to get vsync data (instead of posting callbacks to Choreographer).
Ady Abrahamf2851612023-09-25 17:19:00 -0700375 mCallback.resync();
Rachel Leeb5223cf2022-03-14 14:39:27 -0700376
Rachel Leeef2e21f2022-02-01 14:51:34 -0800377 VsyncEventData vsyncEventData;
Ady Abrahamf2851612023-09-25 17:19:00 -0700378 const Period frameInterval = mCallback.getVsyncPeriod(connection->mOwnerUid);
379 vsyncEventData.frameInterval = frameInterval.ns();
Ady Abraham011f8ba2022-11-22 15:09:07 -0800380 const auto [presentTime, deadline] = [&]() -> std::pair<nsecs_t, nsecs_t> {
Rachel Leeb9c5a772022-02-04 21:17:37 -0800381 std::lock_guard<std::mutex> lock(mMutex);
Leon Scroggins III67388622023-02-06 20:36:20 -0500382 const auto vsyncTime = mVsyncSchedule->getTracker().nextAnticipatedVSyncTimeFrom(
Ady Abraham011f8ba2022-11-22 15:09:07 -0800383 systemTime() + mWorkDuration.get().count() + mReadyDuration.count());
384 return {vsyncTime, vsyncTime - mReadyDuration.count()};
385 }();
Ady Abrahamf2851612023-09-25 17:19:00 -0700386 generateFrameTimeline(vsyncEventData, frameInterval.ns(), systemTime(SYSTEM_TIME_MONOTONIC),
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500387 presentTime, deadline);
Rachel Leeef2e21f2022-02-01 14:51:34 -0800388 return vsyncEventData;
389}
390
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500391void EventThread::enableSyntheticVsync(bool enable) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800392 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500393 if (!mVSyncState || mVSyncState->synthetic == enable) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800394 return;
Mathias Agopian22ffb112012-04-10 21:04:02 -0700395 }
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800396
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500397 mVSyncState->synthetic = enable;
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800398 mCondition.notify_all();
Mathias Agopian22ffb112012-04-10 21:04:02 -0700399}
400
Ady Abraham011f8ba2022-11-22 15:09:07 -0800401void EventThread::onVsync(nsecs_t vsyncTime, nsecs_t wakeupTime, nsecs_t readyTime) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800402 std::lock_guard<std::mutex> lock(mMutex);
Ady Abraham011f8ba2022-11-22 15:09:07 -0800403 mLastVsyncCallbackTime = TimePoint::fromNs(vsyncTime);
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800404
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800405 LOG_FATAL_IF(!mVSyncState);
Ady Abraham011f8ba2022-11-22 15:09:07 -0800406 mVsyncTracer = (mVsyncTracer + 1) % 2;
407 mPendingEvents.push_back(makeVSync(mVSyncState->displayId, wakeupTime, ++mVSyncState->count,
408 vsyncTime, readyTime));
Lloyd Pique46a46b32018-01-31 19:01:18 -0800409 mCondition.notify_all();
Mathias Agopian3eb38cb2012-04-03 22:09:52 -0700410}
411
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800412void EventThread::onHotplugReceived(PhysicalDisplayId displayId, bool connected) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800413 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -0700414
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800415 mPendingEvents.push_back(makeHotplug(displayId, systemTime(), connected));
Dominik Laskowski00a6fa22018-06-06 16:42:02 -0700416 mCondition.notify_all();
Mathias Agopian148994e2012-09-19 17:31:36 -0700417}
418
Brian Johnson5dcd75d2023-08-15 09:36:37 -0700419void EventThread::onHotplugConnectionError(int32_t errorCode) {
420 std::lock_guard<std::mutex> lock(mMutex);
421
422 mPendingEvents.push_back(makeHotplugError(systemTime(), errorCode));
423 mCondition.notify_all();
424}
425
Ady Abraham67434eb2022-12-01 17:48:12 -0800426void EventThread::onModeChanged(const scheduler::FrameRateMode& mode) {
Ady Abraham447052e2019-02-13 16:07:27 -0800427 std::lock_guard<std::mutex> lock(mMutex);
428
Ady Abraham690f4612021-07-01 23:24:03 -0700429 mPendingEvents.push_back(makeModeChanged(mode));
Ady Abraham447052e2019-02-13 16:07:27 -0800430 mCondition.notify_all();
431}
432
Ady Abraham62f216c2020-10-13 19:07:23 -0700433void EventThread::onFrameRateOverridesChanged(PhysicalDisplayId displayId,
434 std::vector<FrameRateOverride> overrides) {
435 std::lock_guard<std::mutex> lock(mMutex);
436
437 for (auto frameRateOverride : overrides) {
438 mPendingEvents.push_back(makeFrameRateOverrideEvent(displayId, frameRateOverride));
439 }
440 mPendingEvents.push_back(makeFrameRateOverrideFlushEvent(displayId));
441
442 mCondition.notify_all();
443}
444
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800445void EventThread::threadMain(std::unique_lock<std::mutex>& lock) {
446 DisplayEventConsumers consumers;
447
Dominik Laskowski029cc122019-01-23 19:52:06 -0800448 while (mState != State::Quit) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800449 std::optional<DisplayEventReceiver::Event> event;
Mathias Agopian3eb38cb2012-04-03 22:09:52 -0700450
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800451 // Determine next event to dispatch.
452 if (!mPendingEvents.empty()) {
453 event = mPendingEvents.front();
454 mPendingEvents.pop_front();
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800455
Huihong Luoab8ffef2022-08-18 13:02:26 -0700456 if (event->header.type == DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG) {
Brian Johnson5dcd75d2023-08-15 09:36:37 -0700457 if (event->hotplug.connectionError == 0) {
458 if (event->hotplug.connected && !mVSyncState) {
459 mVSyncState.emplace(event->header.displayId);
460 } else if (!event->hotplug.connected && mVSyncState &&
461 mVSyncState->displayId == event->header.displayId) {
462 mVSyncState.reset();
463 }
464 } else {
465 // Ignore vsync stuff on an error.
Huihong Luoab8ffef2022-08-18 13:02:26 -0700466 }
Dominik Laskowski029cc122019-01-23 19:52:06 -0800467 }
Mathias Agopianff28e202012-09-20 23:24:19 -0700468 }
469
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800470 bool vsyncRequested = false;
Mathias Agopian148994e2012-09-19 17:31:36 -0700471
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800472 // Find connections that should consume this event.
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700473 auto it = mDisplayEventConnections.begin();
474 while (it != mDisplayEventConnections.end()) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800475 if (const auto connection = it->promote()) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800476 if (event && shouldConsumeEvent(*event, connection)) {
477 consumers.push_back(connection);
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700478 }
Mathias Agopianb4d18ed2012-09-20 23:14:05 -0700479
Ady Abraham011f8ba2022-11-22 15:09:07 -0800480 vsyncRequested |= connection->vsyncRequest != VSyncRequest::None;
481
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700482 ++it;
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700483 } else {
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700484 it = mDisplayEventConnections.erase(it);
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700485 }
486 }
487
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800488 if (!consumers.empty()) {
489 dispatchEvent(*event, consumers);
490 consumers.clear();
491 }
492
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800493 if (mVSyncState && vsyncRequested) {
Ady Abraham011f8ba2022-11-22 15:09:07 -0800494 mState = mVSyncState->synthetic ? State::SyntheticVSync : State::VSync;
Dominik Laskowski029cc122019-01-23 19:52:06 -0800495 } else {
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800496 ALOGW_IF(!mVSyncState, "Ignoring VSYNC request while display is disconnected");
Ady Abraham011f8ba2022-11-22 15:09:07 -0800497 mState = State::Idle;
Dominik Laskowski029cc122019-01-23 19:52:06 -0800498 }
499
Ady Abraham011f8ba2022-11-22 15:09:07 -0800500 if (mState == State::VSync) {
501 const auto scheduleResult =
502 mVsyncRegistration.schedule({.workDuration = mWorkDuration.get().count(),
503 .readyDuration = mReadyDuration.count(),
504 .earliestVsync = mLastVsyncCallbackTime.ns()});
505 LOG_ALWAYS_FATAL_IF(!scheduleResult, "Error scheduling callback");
506 } else {
507 mVsyncRegistration.cancel();
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700508 }
509
Ady Abraham011f8ba2022-11-22 15:09:07 -0800510 if (!mPendingEvents.empty()) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800511 continue;
512 }
513
514 // Wait for event or client registration/request.
Dominik Laskowski029cc122019-01-23 19:52:06 -0800515 if (mState == State::Idle) {
516 mCondition.wait(lock);
517 } else {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800518 // Generate a fake VSYNC after a long timeout in case the driver stalls. When the
519 // display is off, keep feeding clients at 60 Hz.
Ady Abraham5facfb12020-04-22 15:18:31 -0700520 const std::chrono::nanoseconds timeout =
521 mState == State::SyntheticVSync ? 16ms : 1000ms;
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800522 if (mCondition.wait_for(lock, timeout) == std::cv_status::timeout) {
Ady Abraham5e7371c2020-03-24 14:47:24 -0700523 if (mState == State::VSync) {
524 ALOGW("Faking VSYNC due to driver stall for thread %s", mThreadName);
Ady Abraham5e7371c2020-03-24 14:47:24 -0700525 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800526
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800527 LOG_FATAL_IF(!mVSyncState);
Ady Abraham5facfb12020-04-22 15:18:31 -0700528 const auto now = systemTime(SYSTEM_TIME_MONOTONIC);
Ady Abraham8cb21882020-08-26 18:22:05 -0700529 const auto deadlineTimestamp = now + timeout.count();
530 const auto expectedVSyncTime = deadlineTimestamp + timeout.count();
Ady Abraham5facfb12020-04-22 15:18:31 -0700531 mPendingEvents.push_back(makeVSync(mVSyncState->displayId, now,
Ady Abraham8cb21882020-08-26 18:22:05 -0700532 ++mVSyncState->count, expectedVSyncTime,
Rachel Lee0d943202022-02-01 23:29:41 -0800533 deadlineTimestamp));
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700534 }
535 }
Lloyd Pique46a46b32018-01-31 19:01:18 -0800536 }
Ady Abraham011f8ba2022-11-22 15:09:07 -0800537 // cancel any pending vsync event before exiting
538 mVsyncRegistration.cancel();
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800539}
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700540
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800541bool EventThread::shouldConsumeEvent(const DisplayEventReceiver::Event& event,
542 const sp<EventThreadConnection>& connection) const {
Leon Scroggins IIIed66a352023-03-23 17:55:43 -0400543 const auto throttleVsync = [&]() REQUIRES(mMutex) {
Leon Scroggins III31d41412022-11-18 16:42:53 -0500544 const auto& vsyncData = event.vsync.vsyncData;
Rachel Lee2248f522023-01-27 16:45:23 -0800545 if (connection->frameRate.isValid()) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500546 return !mVsyncSchedule->getTracker()
Rachel Lee2248f522023-01-27 16:45:23 -0800547 .isVSyncInPhase(vsyncData.preferredExpectedPresentationTime(),
548 connection->frameRate);
549 }
550
Ady Abrahamf2851612023-09-25 17:19:00 -0700551 const auto expectedPresentTime =
552 TimePoint::fromNs(event.vsync.vsyncData.preferredExpectedPresentationTime());
553 return mCallback.throttleVsync(expectedPresentTime, connection->mOwnerUid);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700554 };
555
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800556 switch (event.header.type) {
557 case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
558 return true;
559
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100560 case DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE: {
Ady Abraham62f216c2020-10-13 19:07:23 -0700561 return connection->mEventRegistration.test(
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700562 gui::ISurfaceComposer::EventRegistration::modeChanged);
Alec Mouri60aee1c2019-10-28 16:18:59 -0700563 }
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700564
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800565 case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
566 switch (connection->vsyncRequest) {
567 case VSyncRequest::None:
568 return false;
Tim Murrayb5daa912020-09-09 21:29:13 +0000569 case VSyncRequest::SingleSuppressCallback:
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800570 connection->vsyncRequest = VSyncRequest::None;
Tim Murrayb5daa912020-09-09 21:29:13 +0000571 return false;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700572 case VSyncRequest::Single: {
573 if (throttleVsync()) {
574 return false;
575 }
Tim Murrayb5daa912020-09-09 21:29:13 +0000576 connection->vsyncRequest = VSyncRequest::SingleSuppressCallback;
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800577 return true;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700578 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800579 case VSyncRequest::Periodic:
Ady Abraham0bb6a472020-10-12 10:22:13 -0700580 if (throttleVsync()) {
581 return false;
582 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800583 return true;
584 default:
Ady Abraham0bb6a472020-10-12 10:22:13 -0700585 // We don't throttle vsync if the app set a vsync request rate
586 // since there is no easy way to do that and this is a very
587 // rare case
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800588 return event.vsync.count % vsyncPeriod(connection->vsyncRequest) == 0;
589 }
590
Ady Abraham62f216c2020-10-13 19:07:23 -0700591 case DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE:
592 [[fallthrough]];
593 case DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH:
594 return connection->mEventRegistration.test(
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700595 gui::ISurfaceComposer::EventRegistration::frameRateOverride);
Ady Abraham62f216c2020-10-13 19:07:23 -0700596
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800597 default:
598 return false;
599 }
600}
601
Rachel Lee8d0c6102021-11-03 22:00:25 +0000602int64_t EventThread::generateToken(nsecs_t timestamp, nsecs_t deadlineTimestamp,
Rachel Leeb9c5a772022-02-04 21:17:37 -0800603 nsecs_t expectedPresentationTime) const {
Rachel Lee3f028662021-11-04 19:32:24 +0000604 if (mTokenManager != nullptr) {
605 return mTokenManager->generateTokenForPredictions(
Rachel Leeb9c5a772022-02-04 21:17:37 -0800606 {timestamp, deadlineTimestamp, expectedPresentationTime});
Rachel Lee3f028662021-11-04 19:32:24 +0000607 }
608 return FrameTimelineInfo::INVALID_VSYNC_ID;
609}
610
Rachel Leeb9c5a772022-02-04 21:17:37 -0800611void EventThread::generateFrameTimeline(VsyncEventData& outVsyncEventData, nsecs_t frameInterval,
612 nsecs_t timestamp,
613 nsecs_t preferredExpectedPresentationTime,
614 nsecs_t preferredDeadlineTimestamp) const {
Rachel Lee0655a912023-04-20 19:54:18 -0700615 uint32_t currentIndex = 0;
Rachel Lee3f028662021-11-04 19:32:24 +0000616 // Add 1 to ensure the preferredFrameTimelineIndex entry (when multiplier == 0) is included.
Rachel Lee40aef422023-04-25 14:35:47 -0700617 for (int64_t multiplier = -VsyncEventData::kFrameTimelinesCapacity + 1;
618 currentIndex < VsyncEventData::kFrameTimelinesCapacity; multiplier++) {
Rachel Leeb9c5a772022-02-04 21:17:37 -0800619 nsecs_t deadlineTimestamp = preferredDeadlineTimestamp + multiplier * frameInterval;
Rachel Lee0655a912023-04-20 19:54:18 -0700620 // Valid possible frame timelines must have future values, so find a later frame timeline.
621 if (deadlineTimestamp <= timestamp) {
622 continue;
Rachel Lee3f028662021-11-04 19:32:24 +0000623 }
Rachel Lee0655a912023-04-20 19:54:18 -0700624
625 nsecs_t expectedPresentationTime =
626 preferredExpectedPresentationTime + multiplier * frameInterval;
627 if (expectedPresentationTime >= preferredExpectedPresentationTime +
628 scheduler::VsyncConfig::kEarlyLatchMaxThreshold.count()) {
Rachel Leeafb6b502023-05-12 15:53:05 -0700629 if (currentIndex == 0) {
630 ALOGW("%s: Expected present time is too far in the future but no timelines are "
631 "valid. preferred EPT=%" PRId64 ", Calculated EPT=%" PRId64
632 ", multiplier=%" PRId64 ", frameInterval=%" PRId64 ", threshold=%" PRId64,
633 __func__, preferredExpectedPresentationTime, expectedPresentationTime,
634 multiplier, frameInterval,
635 static_cast<int64_t>(
636 scheduler::VsyncConfig::kEarlyLatchMaxThreshold.count()));
637 }
Rachel Lee0655a912023-04-20 19:54:18 -0700638 break;
639 }
640
641 if (multiplier == 0) {
642 outVsyncEventData.preferredFrameTimelineIndex = currentIndex;
643 }
644
645 outVsyncEventData.frameTimelines[currentIndex] =
646 {.vsyncId = generateToken(timestamp, deadlineTimestamp, expectedPresentationTime),
647 .deadlineTimestamp = deadlineTimestamp,
648 .expectedPresentationTime = expectedPresentationTime};
649 currentIndex++;
Rachel Lee3f028662021-11-04 19:32:24 +0000650 }
Rachel Leeafb6b502023-05-12 15:53:05 -0700651
652 if (currentIndex == 0) {
653 ALOGW("%s: No timelines are valid. preferred EPT=%" PRId64 ", frameInterval=%" PRId64
654 ", threshold=%" PRId64,
655 __func__, preferredExpectedPresentationTime, frameInterval,
656 static_cast<int64_t>(scheduler::VsyncConfig::kEarlyLatchMaxThreshold.count()));
657 outVsyncEventData.frameTimelines[currentIndex] =
658 {.vsyncId = generateToken(timestamp, preferredDeadlineTimestamp,
659 preferredExpectedPresentationTime),
660 .deadlineTimestamp = preferredDeadlineTimestamp,
661 .expectedPresentationTime = preferredExpectedPresentationTime};
662 currentIndex++;
663 }
664
Rachel Lee0655a912023-04-20 19:54:18 -0700665 outVsyncEventData.frameTimelinesLength = currentIndex;
Rachel Lee3f028662021-11-04 19:32:24 +0000666}
667
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800668void EventThread::dispatchEvent(const DisplayEventReceiver::Event& event,
669 const DisplayEventConsumers& consumers) {
670 for (const auto& consumer : consumers) {
Jorim Jaggic0086af2021-02-12 18:18:11 +0100671 DisplayEventReceiver::Event copy = event;
672 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_VSYNC) {
Ady Abrahamf2851612023-09-25 17:19:00 -0700673 const Period frameInterval = mCallback.getVsyncPeriod(consumer->mOwnerUid);
674 copy.vsync.vsyncData.frameInterval = frameInterval.ns();
675 generateFrameTimeline(copy.vsync.vsyncData, frameInterval.ns(), copy.header.timestamp,
Rachel Leeb9c5a772022-02-04 21:17:37 -0800676 event.vsync.vsyncData.preferredExpectedPresentationTime(),
677 event.vsync.vsyncData.preferredDeadlineTimestamp());
Jorim Jaggic0086af2021-02-12 18:18:11 +0100678 }
679 switch (consumer->postEvent(copy)) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800680 case NO_ERROR:
681 break;
682
683 case -EAGAIN:
684 // TODO: Try again if pipe is full.
685 ALOGW("Failed dispatching %s for %s", toString(event).c_str(),
686 toString(*consumer).c_str());
687 break;
688
689 default:
690 // Treat EPIPE and other errors as fatal.
691 removeDisplayEventConnectionLocked(consumer);
692 }
693 }
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700694}
695
Yiwei Zhang5434a782018-12-05 18:06:32 -0800696void EventThread::dump(std::string& result) const {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800697 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800698
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800699 StringAppendF(&result, "%s: state=%s VSyncState=", mThreadName, toCString(mState));
700 if (mVSyncState) {
Marin Shalamanova524a092020-07-27 21:39:55 +0200701 StringAppendF(&result, "{displayId=%s, count=%u%s}\n",
702 to_string(mVSyncState->displayId).c_str(), mVSyncState->count,
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800703 mVSyncState->synthetic ? ", synthetic" : "");
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800704 } else {
705 StringAppendF(&result, "none\n");
706 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800707
Ady Abraham011f8ba2022-11-22 15:09:07 -0800708 const auto relativeLastCallTime =
709 ticks<std::milli, float>(mLastVsyncCallbackTime - TimePoint::now());
710 StringAppendF(&result, "mWorkDuration=%.2f mReadyDuration=%.2f last vsync time ",
711 mWorkDuration.get().count() / 1e6f, mReadyDuration.count() / 1e6f);
712 StringAppendF(&result, "%.2fms relative to now\n", relativeLastCallTime);
713
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800714 StringAppendF(&result, " pending events (count=%zu):\n", mPendingEvents.size());
715 for (const auto& event : mPendingEvents) {
716 StringAppendF(&result, " %s\n", toString(event).c_str());
Mathias Agopiane2c4f4e2012-04-10 18:25:31 -0700717 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800718
719 StringAppendF(&result, " connections (count=%zu):\n", mDisplayEventConnections.size());
720 for (const auto& ptr : mDisplayEventConnections) {
721 if (const auto connection = ptr.promote()) {
722 StringAppendF(&result, " %s\n", toString(*connection).c_str());
723 }
724 }
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400725 result += '\n';
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800726}
727
Dominik Laskowski029cc122019-01-23 19:52:06 -0800728const char* EventThread::toCString(State state) {
729 switch (state) {
730 case State::Idle:
731 return "Idle";
732 case State::Quit:
733 return "Quit";
734 case State::SyntheticVSync:
735 return "SyntheticVSync";
736 case State::VSync:
737 return "VSync";
738 }
739}
740
Leon Scroggins III67388622023-02-06 20:36:20 -0500741void EventThread::onNewVsyncSchedule(std::shared_ptr<scheduler::VsyncSchedule> schedule) {
Leon Scroggins IIIb2253602023-04-19 17:04:04 -0400742 // Hold onto the old registration until after releasing the mutex to avoid deadlock.
743 scheduler::VSyncCallbackRegistration oldRegistration =
744 onNewVsyncScheduleInternal(std::move(schedule));
745}
746
747scheduler::VSyncCallbackRegistration EventThread::onNewVsyncScheduleInternal(
748 std::shared_ptr<scheduler::VsyncSchedule> schedule) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500749 std::lock_guard<std::mutex> lock(mMutex);
750 const bool reschedule = mVsyncRegistration.cancel() == scheduler::CancelResult::Cancelled;
751 mVsyncSchedule = std::move(schedule);
Leon Scroggins IIIb2253602023-04-19 17:04:04 -0400752 auto oldRegistration =
753 std::exchange(mVsyncRegistration,
754 scheduler::VSyncCallbackRegistration(mVsyncSchedule->getDispatch(),
755 createDispatchCallback(),
756 mThreadName));
Leon Scroggins III67388622023-02-06 20:36:20 -0500757 if (reschedule) {
758 mVsyncRegistration.schedule({.workDuration = mWorkDuration.get().count(),
759 .readyDuration = mReadyDuration.count(),
760 .earliestVsync = mLastVsyncCallbackTime.ns()});
761 }
Leon Scroggins IIIb2253602023-04-19 17:04:04 -0400762 return oldRegistration;
Leon Scroggins III67388622023-02-06 20:36:20 -0500763}
764
765scheduler::VSyncDispatch::Callback EventThread::createDispatchCallback() {
766 return [this](nsecs_t vsyncTime, nsecs_t wakeupTime, nsecs_t readyTime) {
767 onVsync(vsyncTime, wakeupTime, readyTime);
768 };
769}
770
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800771} // namespace impl
Lloyd Pique46a46b32018-01-31 19:01:18 -0800772} // namespace android
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800773
774// TODO(b/129481165): remove the #pragma below and fix conversion issues
775#pragma clang diagnostic pop // ignored "-Wconversion"