blob: 9a55c944248634150da057efbf3de81acabb974a [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"
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -070048#include "FrameTimeline.h"
Ady Abraham011f8ba2022-11-22 15:09:07 -080049#include "VSyncDispatch.h"
50#include "VSyncTracker.h"
Marin Shalamanov23c44202020-12-22 19:09:20 +010051
52#include "EventThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Ady Abraham62f216c2020-10-13 19:07:23 -070054#undef LOG_TAG
55#define LOG_TAG "EventThread"
56
Lloyd Pique46a46b32018-01-31 19:01:18 -080057using namespace std::chrono_literals;
Mathias Agopiand0566bc2011-11-17 17:49:17 -080058
Lloyd Pique46a46b32018-01-31 19:01:18 -080059namespace android {
60
Dominik Laskowskid9e4de62019-01-21 14:23:01 -080061using base::StringAppendF;
62using base::StringPrintf;
63
64namespace {
65
66auto vsyncPeriod(VSyncRequest request) {
67 return static_cast<std::underlying_type_t<VSyncRequest>>(request);
68}
69
70std::string toString(VSyncRequest request) {
71 switch (request) {
72 case VSyncRequest::None:
73 return "VSyncRequest::None";
74 case VSyncRequest::Single:
75 return "VSyncRequest::Single";
Tim Murrayb5daa912020-09-09 21:29:13 +000076 case VSyncRequest::SingleSuppressCallback:
77 return "VSyncRequest::SingleSuppressCallback";
Dominik Laskowskid9e4de62019-01-21 14:23:01 -080078 default:
79 return StringPrintf("VSyncRequest::Periodic{period=%d}", vsyncPeriod(request));
80 }
81}
82
83std::string toString(const EventThreadConnection& connection) {
84 return StringPrintf("Connection{%p, %s}", &connection,
85 toString(connection.vsyncRequest).c_str());
86}
87
88std::string toString(const DisplayEventReceiver::Event& event) {
89 switch (event.header.type) {
90 case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
Marin Shalamanova524a092020-07-27 21:39:55 +020091 return StringPrintf("Hotplug{displayId=%s, %s}",
92 to_string(event.header.displayId).c_str(),
Dominik Laskowskid9e4de62019-01-21 14:23:01 -080093 event.hotplug.connected ? "connected" : "disconnected");
94 case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
Rachel Leeb9c5a772022-02-04 21:17:37 -080095 return StringPrintf("VSync{displayId=%s, count=%u, expectedPresentationTime=%" PRId64
96 "}",
Marin Shalamanova524a092020-07-27 21:39:55 +020097 to_string(event.header.displayId).c_str(), event.vsync.count,
Rachel Leeb9c5a772022-02-04 21:17:37 -080098 event.vsync.vsyncData.preferredExpectedPresentationTime());
Marin Shalamanova7fe3042021-01-29 21:02:08 +010099 case DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE:
100 return StringPrintf("ModeChanged{displayId=%s, modeId=%u}",
101 to_string(event.header.displayId).c_str(), event.modeChange.modeId);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800102 default:
103 return "Event{}";
104 }
105}
106
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800107DisplayEventReceiver::Event makeHotplug(PhysicalDisplayId displayId, nsecs_t timestamp,
108 bool connected) {
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800109 DisplayEventReceiver::Event event;
110 event.header = {DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG, displayId, timestamp};
111 event.hotplug.connected = connected;
112 return event;
113}
114
Brian Johnson5dcd75d2023-08-15 09:36:37 -0700115DisplayEventReceiver::Event makeHotplugError(nsecs_t timestamp, int32_t connectionError) {
116 DisplayEventReceiver::Event event;
117 PhysicalDisplayId unusedDisplayId;
118 event.header = {DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG, unusedDisplayId, timestamp};
119 event.hotplug.connected = false;
120 event.hotplug.connectionError = connectionError;
121 return event;
122}
123
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800124DisplayEventReceiver::Event makeVSync(PhysicalDisplayId displayId, nsecs_t timestamp,
Rachel Leeb9c5a772022-02-04 21:17:37 -0800125 uint32_t count, nsecs_t expectedPresentationTime,
Rachel Lee0d943202022-02-01 23:29:41 -0800126 nsecs_t deadlineTimestamp) {
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800127 DisplayEventReceiver::Event event;
128 event.header = {DisplayEventReceiver::DISPLAY_EVENT_VSYNC, displayId, timestamp};
129 event.vsync.count = count;
Rachel Leeb9c5a772022-02-04 21:17:37 -0800130 event.vsync.vsyncData.preferredFrameTimelineIndex = 0;
131 // Temporarily store the current vsync information in frameTimelines[0], marked as
132 // platform-preferred. When the event is dispatched later, the frame interval at that time is
133 // used with this information to generate multiple frame timeline choices.
134 event.vsync.vsyncData.frameTimelines[0] = {.vsyncId = FrameTimelineInfo::INVALID_VSYNC_ID,
135 .deadlineTimestamp = deadlineTimestamp,
136 .expectedPresentationTime =
137 expectedPresentationTime};
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800138 return event;
139}
140
Ady Abraham67434eb2022-12-01 17:48:12 -0800141DisplayEventReceiver::Event makeModeChanged(const scheduler::FrameRateMode& mode) {
Ady Abraham447052e2019-02-13 16:07:27 -0800142 DisplayEventReceiver::Event event;
Ady Abraham67434eb2022-12-01 17:48:12 -0800143 event.header = {DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE,
144 mode.modePtr->getPhysicalDisplayId(), systemTime()};
145 event.modeChange.modeId = mode.modePtr->getId().value();
146 event.modeChange.vsyncPeriod = mode.fps.getPeriodNsecs();
Ady Abraham447052e2019-02-13 16:07:27 -0800147 return event;
148}
149
Ady Abraham62f216c2020-10-13 19:07:23 -0700150DisplayEventReceiver::Event makeFrameRateOverrideEvent(PhysicalDisplayId displayId,
151 FrameRateOverride frameRateOverride) {
152 return DisplayEventReceiver::Event{
153 .header =
154 DisplayEventReceiver::Event::Header{
155 .type = DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE,
156 .displayId = displayId,
157 .timestamp = systemTime(),
158 },
159 .frameRateOverride = frameRateOverride,
160 };
161}
162
163DisplayEventReceiver::Event makeFrameRateOverrideFlushEvent(PhysicalDisplayId displayId) {
164 return DisplayEventReceiver::Event{
165 .header = DisplayEventReceiver::Event::Header{
166 .type = DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH,
167 .displayId = displayId,
168 .timestamp = systemTime(),
169 }};
170}
171
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800172} // namespace
Lloyd Pique46a46b32018-01-31 19:01:18 -0800173
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700174EventThreadConnection::EventThreadConnection(EventThread* eventThread, uid_t callingUid,
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700175 EventRegistrationFlags eventRegistration)
Ady Abrahamf2851612023-09-25 17:19:00 -0700176 : mOwnerUid(callingUid),
Ady Abraham62f216c2020-10-13 19:07:23 -0700177 mEventRegistration(eventRegistration),
Dominik Laskowskif654d572018-12-20 11:03:06 -0800178 mEventThread(eventThread),
179 mChannel(gui::BitTube::DefaultSize) {}
Ana Krulec85c39af2018-12-26 17:29:57 -0800180
181EventThreadConnection::~EventThreadConnection() {
182 // do nothing here -- clean-up will happen automatically
183 // when the main thread wakes up
184}
185
186void EventThreadConnection::onFirstRef() {
187 // NOTE: mEventThread doesn't hold a strong reference on us
Ady Abrahamd11bade2022-08-01 16:18:03 -0700188 mEventThread->registerDisplayEventConnection(sp<EventThreadConnection>::fromExisting(this));
Ana Krulec85c39af2018-12-26 17:29:57 -0800189}
190
Huihong Luo6fac5232021-11-22 16:05:23 -0800191binder::Status EventThreadConnection::stealReceiveChannel(gui::BitTube* outChannel) {
Ady Abraham899e8cd2022-06-06 15:16:06 -0700192 std::scoped_lock lock(mLock);
193 if (mChannel.initCheck() != NO_ERROR) {
194 return binder::Status::fromStatusT(NAME_NOT_FOUND);
195 }
196
Ana Krulec85c39af2018-12-26 17:29:57 -0800197 outChannel->setReceiveFd(mChannel.moveReceiveFd());
Alec Mouri967d5d72020-08-05 12:50:03 -0700198 outChannel->setSendFd(base::unique_fd(dup(mChannel.getSendFd())));
Huihong Luo6fac5232021-11-22 16:05:23 -0800199 return binder::Status::ok();
Ana Krulec85c39af2018-12-26 17:29:57 -0800200}
201
Huihong Luo6fac5232021-11-22 16:05:23 -0800202binder::Status EventThreadConnection::setVsyncRate(int rate) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700203 mEventThread->setVsyncRate(static_cast<uint32_t>(rate),
204 sp<EventThreadConnection>::fromExisting(this));
Huihong Luo6fac5232021-11-22 16:05:23 -0800205 return binder::Status::ok();
Ana Krulec85c39af2018-12-26 17:29:57 -0800206}
207
Huihong Luo6fac5232021-11-22 16:05:23 -0800208binder::Status EventThreadConnection::requestNextVsync() {
Rachel Leeef2e21f2022-02-01 14:51:34 -0800209 ATRACE_CALL();
Ady Abrahamd11bade2022-08-01 16:18:03 -0700210 mEventThread->requestNextVsync(sp<EventThreadConnection>::fromExisting(this));
Huihong Luo6fac5232021-11-22 16:05:23 -0800211 return binder::Status::ok();
Ana Krulec85c39af2018-12-26 17:29:57 -0800212}
213
Rachel Leeb9c5a772022-02-04 21:17:37 -0800214binder::Status EventThreadConnection::getLatestVsyncEventData(
215 ParcelableVsyncEventData* outVsyncEventData) {
Rachel Leeef2e21f2022-02-01 14:51:34 -0800216 ATRACE_CALL();
Ady Abrahamd11bade2022-08-01 16:18:03 -0700217 outVsyncEventData->vsync =
218 mEventThread->getLatestVsyncEventData(sp<EventThreadConnection>::fromExisting(this));
Rachel Leeef2e21f2022-02-01 14:51:34 -0800219 return binder::Status::ok();
220}
221
Ady Abraham07d03c42023-09-27 19:15:08 -0700222binder::Status EventThreadConnection::getSchedulingPolicy(gui::SchedulingPolicy* outPolicy) {
223 return gui::getSchedulingPolicy(outPolicy);
224}
225
Ana Krulec85c39af2018-12-26 17:29:57 -0800226status_t EventThreadConnection::postEvent(const DisplayEventReceiver::Event& event) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700227 constexpr auto toStatus = [](ssize_t size) {
228 return size < 0 ? status_t(size) : status_t(NO_ERROR);
229 };
230
231 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE ||
232 event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH) {
233 mPendingEvents.emplace_back(event);
234 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE) {
235 return status_t(NO_ERROR);
236 }
237
238 auto size = DisplayEventReceiver::sendEvents(&mChannel, mPendingEvents.data(),
239 mPendingEvents.size());
240 mPendingEvents.clear();
241 return toStatus(size);
242 }
243
244 auto size = DisplayEventReceiver::sendEvents(&mChannel, &event, 1);
245 return toStatus(size);
Ana Krulec85c39af2018-12-26 17:29:57 -0800246}
247
248// ---------------------------------------------------------------------------
249
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800250EventThread::~EventThread() = default;
251
252namespace impl {
253
Leon Scroggins III67388622023-02-06 20:36:20 -0500254EventThread::EventThread(const char* name, std::shared_ptr<scheduler::VsyncSchedule> vsyncSchedule,
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700255 android::frametimeline::TokenManager* tokenManager,
Ady Abrahamf2851612023-09-25 17:19:00 -0700256 IEventThreadCallback& callback, std::chrono::nanoseconds workDuration,
Ady Abraham011f8ba2022-11-22 15:09:07 -0800257 std::chrono::nanoseconds readyDuration)
258 : mThreadName(name),
259 mVsyncTracer(base::StringPrintf("VSYNC-%s", name), 0),
260 mWorkDuration(base::StringPrintf("VsyncWorkDuration-%s", name), workDuration),
261 mReadyDuration(readyDuration),
Leon Scroggins III67388622023-02-06 20:36:20 -0500262 mVsyncSchedule(std::move(vsyncSchedule)),
263 mVsyncRegistration(mVsyncSchedule->getDispatch(), createDispatchCallback(), name),
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700264 mTokenManager(tokenManager),
Ady Abrahamf2851612023-09-25 17:19:00 -0700265 mCallback(callback) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800266 mThread = std::thread([this]() NO_THREAD_SAFETY_ANALYSIS {
267 std::unique_lock<std::mutex> lock(mMutex);
268 threadMain(lock);
269 });
Lloyd Pique46a46b32018-01-31 19:01:18 -0800270
Dominik Laskowski6505f792019-09-18 11:10:05 -0700271 pthread_setname_np(mThread.native_handle(), mThreadName);
Lloyd Pique46a46b32018-01-31 19:01:18 -0800272
273 pid_t tid = pthread_gettid_np(mThread.native_handle());
274
275 // Use SCHED_FIFO to minimize jitter
276 constexpr int EVENT_THREAD_PRIORITY = 2;
277 struct sched_param param = {0};
278 param.sched_priority = EVENT_THREAD_PRIORITY;
279 if (pthread_setschedparam(mThread.native_handle(), SCHED_FIFO, &param) != 0) {
280 ALOGE("Couldn't set SCHED_FIFO for EventThread");
281 }
282
283 set_sched_policy(tid, SP_FOREGROUND);
284}
285
286EventThread::~EventThread() {
287 {
288 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski029cc122019-01-23 19:52:06 -0800289 mState = State::Quit;
Lloyd Pique46a46b32018-01-31 19:01:18 -0800290 mCondition.notify_all();
291 }
292 mThread.join();
Ruchi Kandoief472ec2014-04-02 12:50:06 -0700293}
294
Ady Abraham9c53ee72020-07-22 21:16:18 -0700295void EventThread::setDuration(std::chrono::nanoseconds workDuration,
296 std::chrono::nanoseconds readyDuration) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800297 std::lock_guard<std::mutex> lock(mMutex);
Ady Abraham011f8ba2022-11-22 15:09:07 -0800298 mWorkDuration = workDuration;
299 mReadyDuration = readyDuration;
300
301 mVsyncRegistration.update({.workDuration = mWorkDuration.get().count(),
302 .readyDuration = mReadyDuration.count(),
303 .earliestVsync = mLastVsyncCallbackTime.ns()});
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700304}
305
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700306sp<EventThreadConnection> EventThread::createEventConnection(
Ady Abrahamf2851612023-09-25 17:19:00 -0700307 EventRegistrationFlags eventRegistration) const {
Ady Abraham07d03c42023-09-27 19:15:08 -0700308 auto connection = sp<EventThreadConnection>::make(const_cast<EventThread*>(this),
309 IPCThreadState::self()->getCallingUid(),
310 eventRegistration);
311 if (flags::misc1()) {
312 const int policy = SCHED_FIFO;
313 connection->setMinSchedulerPolicy(policy, sched_get_priority_min(policy));
314 }
315 return connection;
Mathias Agopian8aedd472012-01-24 16:39:14 -0800316}
317
Ana Krulec85c39af2018-12-26 17:29:57 -0800318status_t EventThread::registerDisplayEventConnection(const sp<EventThreadConnection>& connection) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800319 std::lock_guard<std::mutex> lock(mMutex);
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700320
321 // this should never happen
322 auto it = std::find(mDisplayEventConnections.cbegin(),
323 mDisplayEventConnections.cend(), connection);
324 if (it != mDisplayEventConnections.cend()) {
325 ALOGW("DisplayEventConnection %p already exists", connection.get());
326 mCondition.notify_all();
327 return ALREADY_EXISTS;
328 }
329
330 mDisplayEventConnections.push_back(connection);
Lloyd Pique46a46b32018-01-31 19:01:18 -0800331 mCondition.notify_all();
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800332 return NO_ERROR;
333}
334
Ana Krulec85c39af2018-12-26 17:29:57 -0800335void EventThread::removeDisplayEventConnectionLocked(const wp<EventThreadConnection>& connection) {
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700336 auto it = std::find(mDisplayEventConnections.cbegin(),
337 mDisplayEventConnections.cend(), connection);
338 if (it != mDisplayEventConnections.cend()) {
339 mDisplayEventConnections.erase(it);
340 }
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800341}
342
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800343void EventThread::setVsyncRate(uint32_t rate, const sp<EventThreadConnection>& connection) {
344 if (static_cast<std::underlying_type_t<VSyncRequest>>(rate) < 0) {
345 return;
346 }
347
348 std::lock_guard<std::mutex> lock(mMutex);
349
350 const auto request = rate == 0 ? VSyncRequest::None : static_cast<VSyncRequest>(rate);
351 if (connection->vsyncRequest != request) {
352 connection->vsyncRequest = request;
353 mCondition.notify_all();
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800354 }
355}
356
Ady Abraham8532d012019-05-08 14:50:56 -0700357void EventThread::requestNextVsync(const sp<EventThreadConnection>& connection) {
Ady Abrahamf2851612023-09-25 17:19:00 -0700358 mCallback.resync();
Tim Murray4a4e4a22016-04-19 16:29:23 +0000359
Ana Krulec7d1d6832018-12-27 11:10:09 -0800360 std::lock_guard<std::mutex> lock(mMutex);
361
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800362 if (connection->vsyncRequest == VSyncRequest::None) {
363 connection->vsyncRequest = VSyncRequest::Single;
Lloyd Pique46a46b32018-01-31 19:01:18 -0800364 mCondition.notify_all();
Tim Murrayb5daa912020-09-09 21:29:13 +0000365 } else if (connection->vsyncRequest == VSyncRequest::SingleSuppressCallback) {
366 connection->vsyncRequest = VSyncRequest::Single;
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800367 }
Mathias Agopian23748662011-12-05 14:33:34 -0800368}
369
Rachel Leeef2e21f2022-02-01 14:51:34 -0800370VsyncEventData EventThread::getLatestVsyncEventData(
371 const sp<EventThreadConnection>& connection) const {
Rachel Leeb5223cf2022-03-14 14:39:27 -0700372 // Resync so that the vsync is accurate with hardware. getLatestVsyncEventData is an alternate
373 // way to get vsync data (instead of posting callbacks to Choreographer).
Ady Abrahamf2851612023-09-25 17:19:00 -0700374 mCallback.resync();
Rachel Leeb5223cf2022-03-14 14:39:27 -0700375
Rachel Leeef2e21f2022-02-01 14:51:34 -0800376 VsyncEventData vsyncEventData;
Ady Abrahamf2851612023-09-25 17:19:00 -0700377 const Period frameInterval = mCallback.getVsyncPeriod(connection->mOwnerUid);
378 vsyncEventData.frameInterval = frameInterval.ns();
Ady Abraham011f8ba2022-11-22 15:09:07 -0800379 const auto [presentTime, deadline] = [&]() -> std::pair<nsecs_t, nsecs_t> {
Rachel Leeb9c5a772022-02-04 21:17:37 -0800380 std::lock_guard<std::mutex> lock(mMutex);
Leon Scroggins III67388622023-02-06 20:36:20 -0500381 const auto vsyncTime = mVsyncSchedule->getTracker().nextAnticipatedVSyncTimeFrom(
Ady Abraham011f8ba2022-11-22 15:09:07 -0800382 systemTime() + mWorkDuration.get().count() + mReadyDuration.count());
383 return {vsyncTime, vsyncTime - mReadyDuration.count()};
384 }();
Ady Abrahamf2851612023-09-25 17:19:00 -0700385 generateFrameTimeline(vsyncEventData, frameInterval.ns(), systemTime(SYSTEM_TIME_MONOTONIC),
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500386 presentTime, deadline);
Rachel Leeef2e21f2022-02-01 14:51:34 -0800387 return vsyncEventData;
388}
389
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500390void EventThread::enableSyntheticVsync(bool enable) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800391 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500392 if (!mVSyncState || mVSyncState->synthetic == enable) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800393 return;
Mathias Agopian22ffb112012-04-10 21:04:02 -0700394 }
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800395
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500396 mVSyncState->synthetic = enable;
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800397 mCondition.notify_all();
Mathias Agopian22ffb112012-04-10 21:04:02 -0700398}
399
Ady Abraham011f8ba2022-11-22 15:09:07 -0800400void EventThread::onVsync(nsecs_t vsyncTime, nsecs_t wakeupTime, nsecs_t readyTime) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800401 std::lock_guard<std::mutex> lock(mMutex);
Ady Abraham011f8ba2022-11-22 15:09:07 -0800402 mLastVsyncCallbackTime = TimePoint::fromNs(vsyncTime);
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800403
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800404 LOG_FATAL_IF(!mVSyncState);
Ady Abraham011f8ba2022-11-22 15:09:07 -0800405 mVsyncTracer = (mVsyncTracer + 1) % 2;
406 mPendingEvents.push_back(makeVSync(mVSyncState->displayId, wakeupTime, ++mVSyncState->count,
407 vsyncTime, readyTime));
Lloyd Pique46a46b32018-01-31 19:01:18 -0800408 mCondition.notify_all();
Mathias Agopian3eb38cb2012-04-03 22:09:52 -0700409}
410
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800411void EventThread::onHotplugReceived(PhysicalDisplayId displayId, bool connected) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800412 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -0700413
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800414 mPendingEvents.push_back(makeHotplug(displayId, systemTime(), connected));
Dominik Laskowski00a6fa22018-06-06 16:42:02 -0700415 mCondition.notify_all();
Mathias Agopian148994e2012-09-19 17:31:36 -0700416}
417
Brian Johnson5dcd75d2023-08-15 09:36:37 -0700418void EventThread::onHotplugConnectionError(int32_t errorCode) {
419 std::lock_guard<std::mutex> lock(mMutex);
420
421 mPendingEvents.push_back(makeHotplugError(systemTime(), errorCode));
422 mCondition.notify_all();
423}
424
Ady Abraham67434eb2022-12-01 17:48:12 -0800425void EventThread::onModeChanged(const scheduler::FrameRateMode& mode) {
Ady Abraham447052e2019-02-13 16:07:27 -0800426 std::lock_guard<std::mutex> lock(mMutex);
427
Ady Abraham690f4612021-07-01 23:24:03 -0700428 mPendingEvents.push_back(makeModeChanged(mode));
Ady Abraham447052e2019-02-13 16:07:27 -0800429 mCondition.notify_all();
430}
431
Ady Abraham62f216c2020-10-13 19:07:23 -0700432void EventThread::onFrameRateOverridesChanged(PhysicalDisplayId displayId,
433 std::vector<FrameRateOverride> overrides) {
434 std::lock_guard<std::mutex> lock(mMutex);
435
436 for (auto frameRateOverride : overrides) {
437 mPendingEvents.push_back(makeFrameRateOverrideEvent(displayId, frameRateOverride));
438 }
439 mPendingEvents.push_back(makeFrameRateOverrideFlushEvent(displayId));
440
441 mCondition.notify_all();
442}
443
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800444void EventThread::threadMain(std::unique_lock<std::mutex>& lock) {
445 DisplayEventConsumers consumers;
446
Dominik Laskowski029cc122019-01-23 19:52:06 -0800447 while (mState != State::Quit) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800448 std::optional<DisplayEventReceiver::Event> event;
Mathias Agopian3eb38cb2012-04-03 22:09:52 -0700449
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800450 // Determine next event to dispatch.
451 if (!mPendingEvents.empty()) {
452 event = mPendingEvents.front();
453 mPendingEvents.pop_front();
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800454
Huihong Luoab8ffef2022-08-18 13:02:26 -0700455 if (event->header.type == DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG) {
Brian Johnson5dcd75d2023-08-15 09:36:37 -0700456 if (event->hotplug.connectionError == 0) {
457 if (event->hotplug.connected && !mVSyncState) {
458 mVSyncState.emplace(event->header.displayId);
459 } else if (!event->hotplug.connected && mVSyncState &&
460 mVSyncState->displayId == event->header.displayId) {
461 mVSyncState.reset();
462 }
463 } else {
464 // Ignore vsync stuff on an error.
Huihong Luoab8ffef2022-08-18 13:02:26 -0700465 }
Dominik Laskowski029cc122019-01-23 19:52:06 -0800466 }
Mathias Agopianff28e202012-09-20 23:24:19 -0700467 }
468
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800469 bool vsyncRequested = false;
Mathias Agopian148994e2012-09-19 17:31:36 -0700470
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800471 // Find connections that should consume this event.
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700472 auto it = mDisplayEventConnections.begin();
473 while (it != mDisplayEventConnections.end()) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800474 if (const auto connection = it->promote()) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800475 if (event && shouldConsumeEvent(*event, connection)) {
476 consumers.push_back(connection);
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700477 }
Mathias Agopianb4d18ed2012-09-20 23:14:05 -0700478
Ady Abraham011f8ba2022-11-22 15:09:07 -0800479 vsyncRequested |= connection->vsyncRequest != VSyncRequest::None;
480
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700481 ++it;
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700482 } else {
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700483 it = mDisplayEventConnections.erase(it);
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700484 }
485 }
486
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800487 if (!consumers.empty()) {
488 dispatchEvent(*event, consumers);
489 consumers.clear();
490 }
491
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800492 if (mVSyncState && vsyncRequested) {
Ady Abraham011f8ba2022-11-22 15:09:07 -0800493 mState = mVSyncState->synthetic ? State::SyntheticVSync : State::VSync;
Dominik Laskowski029cc122019-01-23 19:52:06 -0800494 } else {
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800495 ALOGW_IF(!mVSyncState, "Ignoring VSYNC request while display is disconnected");
Ady Abraham011f8ba2022-11-22 15:09:07 -0800496 mState = State::Idle;
Dominik Laskowski029cc122019-01-23 19:52:06 -0800497 }
498
Ady Abraham011f8ba2022-11-22 15:09:07 -0800499 if (mState == State::VSync) {
500 const auto scheduleResult =
501 mVsyncRegistration.schedule({.workDuration = mWorkDuration.get().count(),
502 .readyDuration = mReadyDuration.count(),
503 .earliestVsync = mLastVsyncCallbackTime.ns()});
504 LOG_ALWAYS_FATAL_IF(!scheduleResult, "Error scheduling callback");
505 } else {
506 mVsyncRegistration.cancel();
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700507 }
508
Ady Abraham011f8ba2022-11-22 15:09:07 -0800509 if (!mPendingEvents.empty()) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800510 continue;
511 }
512
513 // Wait for event or client registration/request.
Dominik Laskowski029cc122019-01-23 19:52:06 -0800514 if (mState == State::Idle) {
515 mCondition.wait(lock);
516 } else {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800517 // Generate a fake VSYNC after a long timeout in case the driver stalls. When the
518 // display is off, keep feeding clients at 60 Hz.
Ady Abraham5facfb12020-04-22 15:18:31 -0700519 const std::chrono::nanoseconds timeout =
520 mState == State::SyntheticVSync ? 16ms : 1000ms;
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800521 if (mCondition.wait_for(lock, timeout) == std::cv_status::timeout) {
Ady Abraham5e7371c2020-03-24 14:47:24 -0700522 if (mState == State::VSync) {
523 ALOGW("Faking VSYNC due to driver stall for thread %s", mThreadName);
Ady Abraham5e7371c2020-03-24 14:47:24 -0700524 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800525
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800526 LOG_FATAL_IF(!mVSyncState);
Ady Abraham5facfb12020-04-22 15:18:31 -0700527 const auto now = systemTime(SYSTEM_TIME_MONOTONIC);
Ady Abraham8cb21882020-08-26 18:22:05 -0700528 const auto deadlineTimestamp = now + timeout.count();
529 const auto expectedVSyncTime = deadlineTimestamp + timeout.count();
Ady Abraham5facfb12020-04-22 15:18:31 -0700530 mPendingEvents.push_back(makeVSync(mVSyncState->displayId, now,
Ady Abraham8cb21882020-08-26 18:22:05 -0700531 ++mVSyncState->count, expectedVSyncTime,
Rachel Lee0d943202022-02-01 23:29:41 -0800532 deadlineTimestamp));
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700533 }
534 }
Lloyd Pique46a46b32018-01-31 19:01:18 -0800535 }
Ady Abraham011f8ba2022-11-22 15:09:07 -0800536 // cancel any pending vsync event before exiting
537 mVsyncRegistration.cancel();
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800538}
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700539
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800540bool EventThread::shouldConsumeEvent(const DisplayEventReceiver::Event& event,
541 const sp<EventThreadConnection>& connection) const {
Leon Scroggins IIIed66a352023-03-23 17:55:43 -0400542 const auto throttleVsync = [&]() REQUIRES(mMutex) {
Leon Scroggins III31d41412022-11-18 16:42:53 -0500543 const auto& vsyncData = event.vsync.vsyncData;
Rachel Lee2248f522023-01-27 16:45:23 -0800544 if (connection->frameRate.isValid()) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500545 return !mVsyncSchedule->getTracker()
Rachel Lee2248f522023-01-27 16:45:23 -0800546 .isVSyncInPhase(vsyncData.preferredExpectedPresentationTime(),
547 connection->frameRate);
548 }
549
Ady Abrahamf2851612023-09-25 17:19:00 -0700550 const auto expectedPresentTime =
551 TimePoint::fromNs(event.vsync.vsyncData.preferredExpectedPresentationTime());
552 return mCallback.throttleVsync(expectedPresentTime, connection->mOwnerUid);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700553 };
554
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800555 switch (event.header.type) {
556 case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
557 return true;
558
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100559 case DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE: {
Ady Abraham62f216c2020-10-13 19:07:23 -0700560 return connection->mEventRegistration.test(
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700561 gui::ISurfaceComposer::EventRegistration::modeChanged);
Alec Mouri60aee1c2019-10-28 16:18:59 -0700562 }
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700563
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800564 case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
565 switch (connection->vsyncRequest) {
566 case VSyncRequest::None:
567 return false;
Tim Murrayb5daa912020-09-09 21:29:13 +0000568 case VSyncRequest::SingleSuppressCallback:
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800569 connection->vsyncRequest = VSyncRequest::None;
Tim Murrayb5daa912020-09-09 21:29:13 +0000570 return false;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700571 case VSyncRequest::Single: {
572 if (throttleVsync()) {
573 return false;
574 }
Tim Murrayb5daa912020-09-09 21:29:13 +0000575 connection->vsyncRequest = VSyncRequest::SingleSuppressCallback;
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800576 return true;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700577 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800578 case VSyncRequest::Periodic:
Ady Abraham0bb6a472020-10-12 10:22:13 -0700579 if (throttleVsync()) {
580 return false;
581 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800582 return true;
583 default:
Ady Abraham0bb6a472020-10-12 10:22:13 -0700584 // We don't throttle vsync if the app set a vsync request rate
585 // since there is no easy way to do that and this is a very
586 // rare case
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800587 return event.vsync.count % vsyncPeriod(connection->vsyncRequest) == 0;
588 }
589
Ady Abraham62f216c2020-10-13 19:07:23 -0700590 case DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE:
591 [[fallthrough]];
592 case DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH:
593 return connection->mEventRegistration.test(
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700594 gui::ISurfaceComposer::EventRegistration::frameRateOverride);
Ady Abraham62f216c2020-10-13 19:07:23 -0700595
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800596 default:
597 return false;
598 }
599}
600
Rachel Lee8d0c6102021-11-03 22:00:25 +0000601int64_t EventThread::generateToken(nsecs_t timestamp, nsecs_t deadlineTimestamp,
Rachel Leeb9c5a772022-02-04 21:17:37 -0800602 nsecs_t expectedPresentationTime) const {
Rachel Lee3f028662021-11-04 19:32:24 +0000603 if (mTokenManager != nullptr) {
604 return mTokenManager->generateTokenForPredictions(
Rachel Leeb9c5a772022-02-04 21:17:37 -0800605 {timestamp, deadlineTimestamp, expectedPresentationTime});
Rachel Lee3f028662021-11-04 19:32:24 +0000606 }
607 return FrameTimelineInfo::INVALID_VSYNC_ID;
608}
609
Rachel Leeb9c5a772022-02-04 21:17:37 -0800610void EventThread::generateFrameTimeline(VsyncEventData& outVsyncEventData, nsecs_t frameInterval,
611 nsecs_t timestamp,
612 nsecs_t preferredExpectedPresentationTime,
613 nsecs_t preferredDeadlineTimestamp) const {
Rachel Lee0655a912023-04-20 19:54:18 -0700614 uint32_t currentIndex = 0;
Rachel Lee3f028662021-11-04 19:32:24 +0000615 // Add 1 to ensure the preferredFrameTimelineIndex entry (when multiplier == 0) is included.
Rachel Lee40aef422023-04-25 14:35:47 -0700616 for (int64_t multiplier = -VsyncEventData::kFrameTimelinesCapacity + 1;
617 currentIndex < VsyncEventData::kFrameTimelinesCapacity; multiplier++) {
Rachel Leeb9c5a772022-02-04 21:17:37 -0800618 nsecs_t deadlineTimestamp = preferredDeadlineTimestamp + multiplier * frameInterval;
Rachel Lee0655a912023-04-20 19:54:18 -0700619 // Valid possible frame timelines must have future values, so find a later frame timeline.
620 if (deadlineTimestamp <= timestamp) {
621 continue;
Rachel Lee3f028662021-11-04 19:32:24 +0000622 }
Rachel Lee0655a912023-04-20 19:54:18 -0700623
624 nsecs_t expectedPresentationTime =
625 preferredExpectedPresentationTime + multiplier * frameInterval;
626 if (expectedPresentationTime >= preferredExpectedPresentationTime +
627 scheduler::VsyncConfig::kEarlyLatchMaxThreshold.count()) {
Rachel Leeafb6b502023-05-12 15:53:05 -0700628 if (currentIndex == 0) {
629 ALOGW("%s: Expected present time is too far in the future but no timelines are "
630 "valid. preferred EPT=%" PRId64 ", Calculated EPT=%" PRId64
631 ", multiplier=%" PRId64 ", frameInterval=%" PRId64 ", threshold=%" PRId64,
632 __func__, preferredExpectedPresentationTime, expectedPresentationTime,
633 multiplier, frameInterval,
634 static_cast<int64_t>(
635 scheduler::VsyncConfig::kEarlyLatchMaxThreshold.count()));
636 }
Rachel Lee0655a912023-04-20 19:54:18 -0700637 break;
638 }
639
640 if (multiplier == 0) {
641 outVsyncEventData.preferredFrameTimelineIndex = currentIndex;
642 }
643
644 outVsyncEventData.frameTimelines[currentIndex] =
645 {.vsyncId = generateToken(timestamp, deadlineTimestamp, expectedPresentationTime),
646 .deadlineTimestamp = deadlineTimestamp,
647 .expectedPresentationTime = expectedPresentationTime};
648 currentIndex++;
Rachel Lee3f028662021-11-04 19:32:24 +0000649 }
Rachel Leeafb6b502023-05-12 15:53:05 -0700650
651 if (currentIndex == 0) {
652 ALOGW("%s: No timelines are valid. preferred EPT=%" PRId64 ", frameInterval=%" PRId64
653 ", threshold=%" PRId64,
654 __func__, preferredExpectedPresentationTime, frameInterval,
655 static_cast<int64_t>(scheduler::VsyncConfig::kEarlyLatchMaxThreshold.count()));
656 outVsyncEventData.frameTimelines[currentIndex] =
657 {.vsyncId = generateToken(timestamp, preferredDeadlineTimestamp,
658 preferredExpectedPresentationTime),
659 .deadlineTimestamp = preferredDeadlineTimestamp,
660 .expectedPresentationTime = preferredExpectedPresentationTime};
661 currentIndex++;
662 }
663
Rachel Lee0655a912023-04-20 19:54:18 -0700664 outVsyncEventData.frameTimelinesLength = currentIndex;
Rachel Lee3f028662021-11-04 19:32:24 +0000665}
666
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800667void EventThread::dispatchEvent(const DisplayEventReceiver::Event& event,
668 const DisplayEventConsumers& consumers) {
669 for (const auto& consumer : consumers) {
Jorim Jaggic0086af2021-02-12 18:18:11 +0100670 DisplayEventReceiver::Event copy = event;
671 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_VSYNC) {
Ady Abrahamf2851612023-09-25 17:19:00 -0700672 const Period frameInterval = mCallback.getVsyncPeriod(consumer->mOwnerUid);
673 copy.vsync.vsyncData.frameInterval = frameInterval.ns();
674 generateFrameTimeline(copy.vsync.vsyncData, frameInterval.ns(), copy.header.timestamp,
Rachel Leeb9c5a772022-02-04 21:17:37 -0800675 event.vsync.vsyncData.preferredExpectedPresentationTime(),
676 event.vsync.vsyncData.preferredDeadlineTimestamp());
Jorim Jaggic0086af2021-02-12 18:18:11 +0100677 }
678 switch (consumer->postEvent(copy)) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800679 case NO_ERROR:
680 break;
681
682 case -EAGAIN:
683 // TODO: Try again if pipe is full.
684 ALOGW("Failed dispatching %s for %s", toString(event).c_str(),
685 toString(*consumer).c_str());
686 break;
687
688 default:
689 // Treat EPIPE and other errors as fatal.
690 removeDisplayEventConnectionLocked(consumer);
691 }
692 }
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700693}
694
Yiwei Zhang5434a782018-12-05 18:06:32 -0800695void EventThread::dump(std::string& result) const {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800696 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800697
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800698 StringAppendF(&result, "%s: state=%s VSyncState=", mThreadName, toCString(mState));
699 if (mVSyncState) {
Marin Shalamanova524a092020-07-27 21:39:55 +0200700 StringAppendF(&result, "{displayId=%s, count=%u%s}\n",
701 to_string(mVSyncState->displayId).c_str(), mVSyncState->count,
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800702 mVSyncState->synthetic ? ", synthetic" : "");
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800703 } else {
704 StringAppendF(&result, "none\n");
705 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800706
Ady Abraham011f8ba2022-11-22 15:09:07 -0800707 const auto relativeLastCallTime =
708 ticks<std::milli, float>(mLastVsyncCallbackTime - TimePoint::now());
709 StringAppendF(&result, "mWorkDuration=%.2f mReadyDuration=%.2f last vsync time ",
710 mWorkDuration.get().count() / 1e6f, mReadyDuration.count() / 1e6f);
711 StringAppendF(&result, "%.2fms relative to now\n", relativeLastCallTime);
712
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800713 StringAppendF(&result, " pending events (count=%zu):\n", mPendingEvents.size());
714 for (const auto& event : mPendingEvents) {
715 StringAppendF(&result, " %s\n", toString(event).c_str());
Mathias Agopiane2c4f4e2012-04-10 18:25:31 -0700716 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800717
718 StringAppendF(&result, " connections (count=%zu):\n", mDisplayEventConnections.size());
719 for (const auto& ptr : mDisplayEventConnections) {
720 if (const auto connection = ptr.promote()) {
721 StringAppendF(&result, " %s\n", toString(*connection).c_str());
722 }
723 }
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400724 result += '\n';
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800725}
726
Dominik Laskowski029cc122019-01-23 19:52:06 -0800727const char* EventThread::toCString(State state) {
728 switch (state) {
729 case State::Idle:
730 return "Idle";
731 case State::Quit:
732 return "Quit";
733 case State::SyntheticVSync:
734 return "SyntheticVSync";
735 case State::VSync:
736 return "VSync";
737 }
738}
739
Leon Scroggins III67388622023-02-06 20:36:20 -0500740void EventThread::onNewVsyncSchedule(std::shared_ptr<scheduler::VsyncSchedule> schedule) {
Leon Scroggins IIIb2253602023-04-19 17:04:04 -0400741 // Hold onto the old registration until after releasing the mutex to avoid deadlock.
742 scheduler::VSyncCallbackRegistration oldRegistration =
743 onNewVsyncScheduleInternal(std::move(schedule));
744}
745
746scheduler::VSyncCallbackRegistration EventThread::onNewVsyncScheduleInternal(
747 std::shared_ptr<scheduler::VsyncSchedule> schedule) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500748 std::lock_guard<std::mutex> lock(mMutex);
749 const bool reschedule = mVsyncRegistration.cancel() == scheduler::CancelResult::Cancelled;
750 mVsyncSchedule = std::move(schedule);
Leon Scroggins IIIb2253602023-04-19 17:04:04 -0400751 auto oldRegistration =
752 std::exchange(mVsyncRegistration,
753 scheduler::VSyncCallbackRegistration(mVsyncSchedule->getDispatch(),
754 createDispatchCallback(),
755 mThreadName));
Leon Scroggins III67388622023-02-06 20:36:20 -0500756 if (reschedule) {
757 mVsyncRegistration.schedule({.workDuration = mWorkDuration.get().count(),
758 .readyDuration = mReadyDuration.count(),
759 .earliestVsync = mLastVsyncCallbackTime.ns()});
760 }
Leon Scroggins IIIb2253602023-04-19 17:04:04 -0400761 return oldRegistration;
Leon Scroggins III67388622023-02-06 20:36:20 -0500762}
763
764scheduler::VSyncDispatch::Callback EventThread::createDispatchCallback() {
765 return [this](nsecs_t vsyncTime, nsecs_t wakeupTime, nsecs_t readyTime) {
766 onVsync(vsyncTime, wakeupTime, readyTime);
767 };
768}
769
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800770} // namespace impl
Lloyd Pique46a46b32018-01-31 19:01:18 -0800771} // namespace android
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800772
773// TODO(b/129481165): remove the #pragma below and fix conversion issues
774#pragma clang diagnostic pop // ignored "-Wconversion"