blob: edab7ecee1c1a94632f648685ddf6a6b0b6f55a2 [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>
41
42#include <utils/Errors.h>
Mathias Agopian841cde52012-03-01 15:44:37 -080043#include <utils/Trace.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080044
Rachel Lee0655a912023-04-20 19:54:18 -070045#include <scheduler/VsyncConfig.h>
Marin Shalamanov23c44202020-12-22 19:09:20 +010046#include "DisplayHardware/DisplayMode.h"
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -070047#include "FrameTimeline.h"
Ady Abraham011f8ba2022-11-22 15:09:07 -080048#include "VSyncDispatch.h"
49#include "VSyncTracker.h"
Marin Shalamanov23c44202020-12-22 19:09:20 +010050
51#include "EventThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080052
Ady Abraham62f216c2020-10-13 19:07:23 -070053#undef LOG_TAG
54#define LOG_TAG "EventThread"
55
Lloyd Pique46a46b32018-01-31 19:01:18 -080056using namespace std::chrono_literals;
Mathias Agopiand0566bc2011-11-17 17:49:17 -080057
Lloyd Pique46a46b32018-01-31 19:01:18 -080058namespace android {
59
Dominik Laskowskid9e4de62019-01-21 14:23:01 -080060using base::StringAppendF;
61using base::StringPrintf;
62
63namespace {
64
65auto vsyncPeriod(VSyncRequest request) {
66 return static_cast<std::underlying_type_t<VSyncRequest>>(request);
67}
68
69std::string toString(VSyncRequest request) {
70 switch (request) {
71 case VSyncRequest::None:
72 return "VSyncRequest::None";
73 case VSyncRequest::Single:
74 return "VSyncRequest::Single";
Tim Murrayb5daa912020-09-09 21:29:13 +000075 case VSyncRequest::SingleSuppressCallback:
76 return "VSyncRequest::SingleSuppressCallback";
Dominik Laskowskid9e4de62019-01-21 14:23:01 -080077 default:
78 return StringPrintf("VSyncRequest::Periodic{period=%d}", vsyncPeriod(request));
79 }
80}
81
82std::string toString(const EventThreadConnection& connection) {
83 return StringPrintf("Connection{%p, %s}", &connection,
84 toString(connection.vsyncRequest).c_str());
85}
86
87std::string toString(const DisplayEventReceiver::Event& event) {
88 switch (event.header.type) {
89 case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
Marin Shalamanova524a092020-07-27 21:39:55 +020090 return StringPrintf("Hotplug{displayId=%s, %s}",
91 to_string(event.header.displayId).c_str(),
Dominik Laskowskid9e4de62019-01-21 14:23:01 -080092 event.hotplug.connected ? "connected" : "disconnected");
93 case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
Rachel Leeb9c5a772022-02-04 21:17:37 -080094 return StringPrintf("VSync{displayId=%s, count=%u, expectedPresentationTime=%" PRId64
95 "}",
Marin Shalamanova524a092020-07-27 21:39:55 +020096 to_string(event.header.displayId).c_str(), event.vsync.count,
Rachel Leeb9c5a772022-02-04 21:17:37 -080097 event.vsync.vsyncData.preferredExpectedPresentationTime());
Marin Shalamanova7fe3042021-01-29 21:02:08 +010098 case DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE:
99 return StringPrintf("ModeChanged{displayId=%s, modeId=%u}",
100 to_string(event.header.displayId).c_str(), event.modeChange.modeId);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800101 default:
102 return "Event{}";
103 }
104}
105
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800106DisplayEventReceiver::Event makeHotplug(PhysicalDisplayId displayId, nsecs_t timestamp,
107 bool connected) {
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800108 DisplayEventReceiver::Event event;
109 event.header = {DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG, displayId, timestamp};
110 event.hotplug.connected = connected;
111 return event;
112}
113
Brian Johnson5dcd75d2023-08-15 09:36:37 -0700114DisplayEventReceiver::Event makeHotplugError(nsecs_t timestamp, int32_t connectionError) {
115 DisplayEventReceiver::Event event;
116 PhysicalDisplayId unusedDisplayId;
117 event.header = {DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG, unusedDisplayId, timestamp};
118 event.hotplug.connected = false;
119 event.hotplug.connectionError = connectionError;
120 return event;
121}
122
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800123DisplayEventReceiver::Event makeVSync(PhysicalDisplayId displayId, nsecs_t timestamp,
Rachel Leeb9c5a772022-02-04 21:17:37 -0800124 uint32_t count, nsecs_t expectedPresentationTime,
Rachel Lee0d943202022-02-01 23:29:41 -0800125 nsecs_t deadlineTimestamp) {
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800126 DisplayEventReceiver::Event event;
127 event.header = {DisplayEventReceiver::DISPLAY_EVENT_VSYNC, displayId, timestamp};
128 event.vsync.count = count;
Rachel Leeb9c5a772022-02-04 21:17:37 -0800129 event.vsync.vsyncData.preferredFrameTimelineIndex = 0;
130 // Temporarily store the current vsync information in frameTimelines[0], marked as
131 // platform-preferred. When the event is dispatched later, the frame interval at that time is
132 // used with this information to generate multiple frame timeline choices.
133 event.vsync.vsyncData.frameTimelines[0] = {.vsyncId = FrameTimelineInfo::INVALID_VSYNC_ID,
134 .deadlineTimestamp = deadlineTimestamp,
135 .expectedPresentationTime =
136 expectedPresentationTime};
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800137 return event;
138}
139
Ady Abraham67434eb2022-12-01 17:48:12 -0800140DisplayEventReceiver::Event makeModeChanged(const scheduler::FrameRateMode& mode) {
Ady Abraham447052e2019-02-13 16:07:27 -0800141 DisplayEventReceiver::Event event;
Ady Abraham67434eb2022-12-01 17:48:12 -0800142 event.header = {DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE,
143 mode.modePtr->getPhysicalDisplayId(), systemTime()};
144 event.modeChange.modeId = mode.modePtr->getId().value();
145 event.modeChange.vsyncPeriod = mode.fps.getPeriodNsecs();
Ady Abraham447052e2019-02-13 16:07:27 -0800146 return event;
147}
148
Ady Abraham62f216c2020-10-13 19:07:23 -0700149DisplayEventReceiver::Event makeFrameRateOverrideEvent(PhysicalDisplayId displayId,
150 FrameRateOverride frameRateOverride) {
151 return DisplayEventReceiver::Event{
152 .header =
153 DisplayEventReceiver::Event::Header{
154 .type = DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE,
155 .displayId = displayId,
156 .timestamp = systemTime(),
157 },
158 .frameRateOverride = frameRateOverride,
159 };
160}
161
162DisplayEventReceiver::Event makeFrameRateOverrideFlushEvent(PhysicalDisplayId displayId) {
163 return DisplayEventReceiver::Event{
164 .header = DisplayEventReceiver::Event::Header{
165 .type = DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH,
166 .displayId = displayId,
167 .timestamp = systemTime(),
168 }};
169}
170
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800171} // namespace
Lloyd Pique46a46b32018-01-31 19:01:18 -0800172
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700173EventThreadConnection::EventThreadConnection(EventThread* eventThread, uid_t callingUid,
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700174 EventRegistrationFlags eventRegistration)
Ady Abrahamf2851612023-09-25 17:19:00 -0700175 : mOwnerUid(callingUid),
Ady Abraham62f216c2020-10-13 19:07:23 -0700176 mEventRegistration(eventRegistration),
Dominik Laskowskif654d572018-12-20 11:03:06 -0800177 mEventThread(eventThread),
178 mChannel(gui::BitTube::DefaultSize) {}
Ana Krulec85c39af2018-12-26 17:29:57 -0800179
180EventThreadConnection::~EventThreadConnection() {
181 // do nothing here -- clean-up will happen automatically
182 // when the main thread wakes up
183}
184
185void EventThreadConnection::onFirstRef() {
186 // NOTE: mEventThread doesn't hold a strong reference on us
Ady Abrahamd11bade2022-08-01 16:18:03 -0700187 mEventThread->registerDisplayEventConnection(sp<EventThreadConnection>::fromExisting(this));
Ana Krulec85c39af2018-12-26 17:29:57 -0800188}
189
Huihong Luo6fac5232021-11-22 16:05:23 -0800190binder::Status EventThreadConnection::stealReceiveChannel(gui::BitTube* outChannel) {
Ady Abraham899e8cd2022-06-06 15:16:06 -0700191 std::scoped_lock lock(mLock);
192 if (mChannel.initCheck() != NO_ERROR) {
193 return binder::Status::fromStatusT(NAME_NOT_FOUND);
194 }
195
Ana Krulec85c39af2018-12-26 17:29:57 -0800196 outChannel->setReceiveFd(mChannel.moveReceiveFd());
Alec Mouri967d5d72020-08-05 12:50:03 -0700197 outChannel->setSendFd(base::unique_fd(dup(mChannel.getSendFd())));
Huihong Luo6fac5232021-11-22 16:05:23 -0800198 return binder::Status::ok();
Ana Krulec85c39af2018-12-26 17:29:57 -0800199}
200
Huihong Luo6fac5232021-11-22 16:05:23 -0800201binder::Status EventThreadConnection::setVsyncRate(int rate) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700202 mEventThread->setVsyncRate(static_cast<uint32_t>(rate),
203 sp<EventThreadConnection>::fromExisting(this));
Huihong Luo6fac5232021-11-22 16:05:23 -0800204 return binder::Status::ok();
Ana Krulec85c39af2018-12-26 17:29:57 -0800205}
206
Huihong Luo6fac5232021-11-22 16:05:23 -0800207binder::Status EventThreadConnection::requestNextVsync() {
Rachel Leeef2e21f2022-02-01 14:51:34 -0800208 ATRACE_CALL();
Ady Abrahamd11bade2022-08-01 16:18:03 -0700209 mEventThread->requestNextVsync(sp<EventThreadConnection>::fromExisting(this));
Huihong Luo6fac5232021-11-22 16:05:23 -0800210 return binder::Status::ok();
Ana Krulec85c39af2018-12-26 17:29:57 -0800211}
212
Rachel Leeb9c5a772022-02-04 21:17:37 -0800213binder::Status EventThreadConnection::getLatestVsyncEventData(
214 ParcelableVsyncEventData* outVsyncEventData) {
Rachel Leeef2e21f2022-02-01 14:51:34 -0800215 ATRACE_CALL();
Ady Abrahamd11bade2022-08-01 16:18:03 -0700216 outVsyncEventData->vsync =
217 mEventThread->getLatestVsyncEventData(sp<EventThreadConnection>::fromExisting(this));
Rachel Leeef2e21f2022-02-01 14:51:34 -0800218 return binder::Status::ok();
219}
220
Ana Krulec85c39af2018-12-26 17:29:57 -0800221status_t EventThreadConnection::postEvent(const DisplayEventReceiver::Event& event) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700222 constexpr auto toStatus = [](ssize_t size) {
223 return size < 0 ? status_t(size) : status_t(NO_ERROR);
224 };
225
226 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE ||
227 event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH) {
228 mPendingEvents.emplace_back(event);
229 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE) {
230 return status_t(NO_ERROR);
231 }
232
233 auto size = DisplayEventReceiver::sendEvents(&mChannel, mPendingEvents.data(),
234 mPendingEvents.size());
235 mPendingEvents.clear();
236 return toStatus(size);
237 }
238
239 auto size = DisplayEventReceiver::sendEvents(&mChannel, &event, 1);
240 return toStatus(size);
Ana Krulec85c39af2018-12-26 17:29:57 -0800241}
242
243// ---------------------------------------------------------------------------
244
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800245EventThread::~EventThread() = default;
246
247namespace impl {
248
Leon Scroggins III67388622023-02-06 20:36:20 -0500249EventThread::EventThread(const char* name, std::shared_ptr<scheduler::VsyncSchedule> vsyncSchedule,
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700250 android::frametimeline::TokenManager* tokenManager,
Ady Abrahamf2851612023-09-25 17:19:00 -0700251 IEventThreadCallback& callback, std::chrono::nanoseconds workDuration,
Ady Abraham011f8ba2022-11-22 15:09:07 -0800252 std::chrono::nanoseconds readyDuration)
253 : mThreadName(name),
254 mVsyncTracer(base::StringPrintf("VSYNC-%s", name), 0),
255 mWorkDuration(base::StringPrintf("VsyncWorkDuration-%s", name), workDuration),
256 mReadyDuration(readyDuration),
Leon Scroggins III67388622023-02-06 20:36:20 -0500257 mVsyncSchedule(std::move(vsyncSchedule)),
258 mVsyncRegistration(mVsyncSchedule->getDispatch(), createDispatchCallback(), name),
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700259 mTokenManager(tokenManager),
Ady Abrahamf2851612023-09-25 17:19:00 -0700260 mCallback(callback) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800261 mThread = std::thread([this]() NO_THREAD_SAFETY_ANALYSIS {
262 std::unique_lock<std::mutex> lock(mMutex);
263 threadMain(lock);
264 });
Lloyd Pique46a46b32018-01-31 19:01:18 -0800265
Dominik Laskowski6505f792019-09-18 11:10:05 -0700266 pthread_setname_np(mThread.native_handle(), mThreadName);
Lloyd Pique46a46b32018-01-31 19:01:18 -0800267
268 pid_t tid = pthread_gettid_np(mThread.native_handle());
269
270 // Use SCHED_FIFO to minimize jitter
271 constexpr int EVENT_THREAD_PRIORITY = 2;
272 struct sched_param param = {0};
273 param.sched_priority = EVENT_THREAD_PRIORITY;
274 if (pthread_setschedparam(mThread.native_handle(), SCHED_FIFO, &param) != 0) {
275 ALOGE("Couldn't set SCHED_FIFO for EventThread");
276 }
277
278 set_sched_policy(tid, SP_FOREGROUND);
279}
280
281EventThread::~EventThread() {
282 {
283 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski029cc122019-01-23 19:52:06 -0800284 mState = State::Quit;
Lloyd Pique46a46b32018-01-31 19:01:18 -0800285 mCondition.notify_all();
286 }
287 mThread.join();
Ruchi Kandoief472ec2014-04-02 12:50:06 -0700288}
289
Ady Abraham9c53ee72020-07-22 21:16:18 -0700290void EventThread::setDuration(std::chrono::nanoseconds workDuration,
291 std::chrono::nanoseconds readyDuration) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800292 std::lock_guard<std::mutex> lock(mMutex);
Ady Abraham011f8ba2022-11-22 15:09:07 -0800293 mWorkDuration = workDuration;
294 mReadyDuration = readyDuration;
295
296 mVsyncRegistration.update({.workDuration = mWorkDuration.get().count(),
297 .readyDuration = mReadyDuration.count(),
298 .earliestVsync = mLastVsyncCallbackTime.ns()});
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700299}
300
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700301sp<EventThreadConnection> EventThread::createEventConnection(
Ady Abrahamf2851612023-09-25 17:19:00 -0700302 EventRegistrationFlags eventRegistration) const {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700303 return sp<EventThreadConnection>::make(const_cast<EventThread*>(this),
304 IPCThreadState::self()->getCallingUid(),
Ady Abrahamf2851612023-09-25 17:19:00 -0700305 eventRegistration);
Mathias Agopian8aedd472012-01-24 16:39:14 -0800306}
307
Ana Krulec85c39af2018-12-26 17:29:57 -0800308status_t EventThread::registerDisplayEventConnection(const sp<EventThreadConnection>& connection) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800309 std::lock_guard<std::mutex> lock(mMutex);
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700310
311 // this should never happen
312 auto it = std::find(mDisplayEventConnections.cbegin(),
313 mDisplayEventConnections.cend(), connection);
314 if (it != mDisplayEventConnections.cend()) {
315 ALOGW("DisplayEventConnection %p already exists", connection.get());
316 mCondition.notify_all();
317 return ALREADY_EXISTS;
318 }
319
320 mDisplayEventConnections.push_back(connection);
Lloyd Pique46a46b32018-01-31 19:01:18 -0800321 mCondition.notify_all();
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800322 return NO_ERROR;
323}
324
Ana Krulec85c39af2018-12-26 17:29:57 -0800325void EventThread::removeDisplayEventConnectionLocked(const wp<EventThreadConnection>& connection) {
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700326 auto it = std::find(mDisplayEventConnections.cbegin(),
327 mDisplayEventConnections.cend(), connection);
328 if (it != mDisplayEventConnections.cend()) {
329 mDisplayEventConnections.erase(it);
330 }
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800331}
332
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800333void EventThread::setVsyncRate(uint32_t rate, const sp<EventThreadConnection>& connection) {
334 if (static_cast<std::underlying_type_t<VSyncRequest>>(rate) < 0) {
335 return;
336 }
337
338 std::lock_guard<std::mutex> lock(mMutex);
339
340 const auto request = rate == 0 ? VSyncRequest::None : static_cast<VSyncRequest>(rate);
341 if (connection->vsyncRequest != request) {
342 connection->vsyncRequest = request;
343 mCondition.notify_all();
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800344 }
345}
346
Ady Abraham8532d012019-05-08 14:50:56 -0700347void EventThread::requestNextVsync(const sp<EventThreadConnection>& connection) {
Ady Abrahamf2851612023-09-25 17:19:00 -0700348 mCallback.resync();
Tim Murray4a4e4a22016-04-19 16:29:23 +0000349
Ana Krulec7d1d6832018-12-27 11:10:09 -0800350 std::lock_guard<std::mutex> lock(mMutex);
351
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800352 if (connection->vsyncRequest == VSyncRequest::None) {
353 connection->vsyncRequest = VSyncRequest::Single;
Lloyd Pique46a46b32018-01-31 19:01:18 -0800354 mCondition.notify_all();
Tim Murrayb5daa912020-09-09 21:29:13 +0000355 } else if (connection->vsyncRequest == VSyncRequest::SingleSuppressCallback) {
356 connection->vsyncRequest = VSyncRequest::Single;
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800357 }
Mathias Agopian23748662011-12-05 14:33:34 -0800358}
359
Rachel Leeef2e21f2022-02-01 14:51:34 -0800360VsyncEventData EventThread::getLatestVsyncEventData(
361 const sp<EventThreadConnection>& connection) const {
Rachel Leeb5223cf2022-03-14 14:39:27 -0700362 // Resync so that the vsync is accurate with hardware. getLatestVsyncEventData is an alternate
363 // way to get vsync data (instead of posting callbacks to Choreographer).
Ady Abrahamf2851612023-09-25 17:19:00 -0700364 mCallback.resync();
Rachel Leeb5223cf2022-03-14 14:39:27 -0700365
Rachel Leeef2e21f2022-02-01 14:51:34 -0800366 VsyncEventData vsyncEventData;
Ady Abrahamf2851612023-09-25 17:19:00 -0700367 const Period frameInterval = mCallback.getVsyncPeriod(connection->mOwnerUid);
368 vsyncEventData.frameInterval = frameInterval.ns();
Ady Abraham011f8ba2022-11-22 15:09:07 -0800369 const auto [presentTime, deadline] = [&]() -> std::pair<nsecs_t, nsecs_t> {
Rachel Leeb9c5a772022-02-04 21:17:37 -0800370 std::lock_guard<std::mutex> lock(mMutex);
Leon Scroggins III67388622023-02-06 20:36:20 -0500371 const auto vsyncTime = mVsyncSchedule->getTracker().nextAnticipatedVSyncTimeFrom(
Ady Abraham011f8ba2022-11-22 15:09:07 -0800372 systemTime() + mWorkDuration.get().count() + mReadyDuration.count());
373 return {vsyncTime, vsyncTime - mReadyDuration.count()};
374 }();
Ady Abrahamf2851612023-09-25 17:19:00 -0700375 generateFrameTimeline(vsyncEventData, frameInterval.ns(), systemTime(SYSTEM_TIME_MONOTONIC),
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500376 presentTime, deadline);
Rachel Leeef2e21f2022-02-01 14:51:34 -0800377 return vsyncEventData;
378}
379
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500380void EventThread::enableSyntheticVsync(bool enable) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800381 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500382 if (!mVSyncState || mVSyncState->synthetic == enable) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800383 return;
Mathias Agopian22ffb112012-04-10 21:04:02 -0700384 }
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800385
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500386 mVSyncState->synthetic = enable;
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800387 mCondition.notify_all();
Mathias Agopian22ffb112012-04-10 21:04:02 -0700388}
389
Ady Abraham011f8ba2022-11-22 15:09:07 -0800390void EventThread::onVsync(nsecs_t vsyncTime, nsecs_t wakeupTime, nsecs_t readyTime) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800391 std::lock_guard<std::mutex> lock(mMutex);
Ady Abraham011f8ba2022-11-22 15:09:07 -0800392 mLastVsyncCallbackTime = TimePoint::fromNs(vsyncTime);
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800393
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800394 LOG_FATAL_IF(!mVSyncState);
Ady Abraham011f8ba2022-11-22 15:09:07 -0800395 mVsyncTracer = (mVsyncTracer + 1) % 2;
396 mPendingEvents.push_back(makeVSync(mVSyncState->displayId, wakeupTime, ++mVSyncState->count,
397 vsyncTime, readyTime));
Lloyd Pique46a46b32018-01-31 19:01:18 -0800398 mCondition.notify_all();
Mathias Agopian3eb38cb2012-04-03 22:09:52 -0700399}
400
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800401void EventThread::onHotplugReceived(PhysicalDisplayId displayId, bool connected) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800402 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -0700403
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800404 mPendingEvents.push_back(makeHotplug(displayId, systemTime(), connected));
Dominik Laskowski00a6fa22018-06-06 16:42:02 -0700405 mCondition.notify_all();
Mathias Agopian148994e2012-09-19 17:31:36 -0700406}
407
Brian Johnson5dcd75d2023-08-15 09:36:37 -0700408void EventThread::onHotplugConnectionError(int32_t errorCode) {
409 std::lock_guard<std::mutex> lock(mMutex);
410
411 mPendingEvents.push_back(makeHotplugError(systemTime(), errorCode));
412 mCondition.notify_all();
413}
414
Ady Abraham67434eb2022-12-01 17:48:12 -0800415void EventThread::onModeChanged(const scheduler::FrameRateMode& mode) {
Ady Abraham447052e2019-02-13 16:07:27 -0800416 std::lock_guard<std::mutex> lock(mMutex);
417
Ady Abraham690f4612021-07-01 23:24:03 -0700418 mPendingEvents.push_back(makeModeChanged(mode));
Ady Abraham447052e2019-02-13 16:07:27 -0800419 mCondition.notify_all();
420}
421
Ady Abraham62f216c2020-10-13 19:07:23 -0700422void EventThread::onFrameRateOverridesChanged(PhysicalDisplayId displayId,
423 std::vector<FrameRateOverride> overrides) {
424 std::lock_guard<std::mutex> lock(mMutex);
425
426 for (auto frameRateOverride : overrides) {
427 mPendingEvents.push_back(makeFrameRateOverrideEvent(displayId, frameRateOverride));
428 }
429 mPendingEvents.push_back(makeFrameRateOverrideFlushEvent(displayId));
430
431 mCondition.notify_all();
432}
433
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800434void EventThread::threadMain(std::unique_lock<std::mutex>& lock) {
435 DisplayEventConsumers consumers;
436
Dominik Laskowski029cc122019-01-23 19:52:06 -0800437 while (mState != State::Quit) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800438 std::optional<DisplayEventReceiver::Event> event;
Mathias Agopian3eb38cb2012-04-03 22:09:52 -0700439
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800440 // Determine next event to dispatch.
441 if (!mPendingEvents.empty()) {
442 event = mPendingEvents.front();
443 mPendingEvents.pop_front();
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800444
Huihong Luoab8ffef2022-08-18 13:02:26 -0700445 if (event->header.type == DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG) {
Brian Johnson5dcd75d2023-08-15 09:36:37 -0700446 if (event->hotplug.connectionError == 0) {
447 if (event->hotplug.connected && !mVSyncState) {
448 mVSyncState.emplace(event->header.displayId);
449 } else if (!event->hotplug.connected && mVSyncState &&
450 mVSyncState->displayId == event->header.displayId) {
451 mVSyncState.reset();
452 }
453 } else {
454 // Ignore vsync stuff on an error.
Huihong Luoab8ffef2022-08-18 13:02:26 -0700455 }
Dominik Laskowski029cc122019-01-23 19:52:06 -0800456 }
Mathias Agopianff28e202012-09-20 23:24:19 -0700457 }
458
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800459 bool vsyncRequested = false;
Mathias Agopian148994e2012-09-19 17:31:36 -0700460
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800461 // Find connections that should consume this event.
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700462 auto it = mDisplayEventConnections.begin();
463 while (it != mDisplayEventConnections.end()) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800464 if (const auto connection = it->promote()) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800465 if (event && shouldConsumeEvent(*event, connection)) {
466 consumers.push_back(connection);
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700467 }
Mathias Agopianb4d18ed2012-09-20 23:14:05 -0700468
Ady Abraham011f8ba2022-11-22 15:09:07 -0800469 vsyncRequested |= connection->vsyncRequest != VSyncRequest::None;
470
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700471 ++it;
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700472 } else {
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700473 it = mDisplayEventConnections.erase(it);
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700474 }
475 }
476
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800477 if (!consumers.empty()) {
478 dispatchEvent(*event, consumers);
479 consumers.clear();
480 }
481
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800482 if (mVSyncState && vsyncRequested) {
Ady Abraham011f8ba2022-11-22 15:09:07 -0800483 mState = mVSyncState->synthetic ? State::SyntheticVSync : State::VSync;
Dominik Laskowski029cc122019-01-23 19:52:06 -0800484 } else {
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800485 ALOGW_IF(!mVSyncState, "Ignoring VSYNC request while display is disconnected");
Ady Abraham011f8ba2022-11-22 15:09:07 -0800486 mState = State::Idle;
Dominik Laskowski029cc122019-01-23 19:52:06 -0800487 }
488
Ady Abraham011f8ba2022-11-22 15:09:07 -0800489 if (mState == State::VSync) {
490 const auto scheduleResult =
491 mVsyncRegistration.schedule({.workDuration = mWorkDuration.get().count(),
492 .readyDuration = mReadyDuration.count(),
493 .earliestVsync = mLastVsyncCallbackTime.ns()});
494 LOG_ALWAYS_FATAL_IF(!scheduleResult, "Error scheduling callback");
495 } else {
496 mVsyncRegistration.cancel();
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700497 }
498
Ady Abraham011f8ba2022-11-22 15:09:07 -0800499 if (!mPendingEvents.empty()) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800500 continue;
501 }
502
503 // Wait for event or client registration/request.
Dominik Laskowski029cc122019-01-23 19:52:06 -0800504 if (mState == State::Idle) {
505 mCondition.wait(lock);
506 } else {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800507 // Generate a fake VSYNC after a long timeout in case the driver stalls. When the
508 // display is off, keep feeding clients at 60 Hz.
Ady Abraham5facfb12020-04-22 15:18:31 -0700509 const std::chrono::nanoseconds timeout =
510 mState == State::SyntheticVSync ? 16ms : 1000ms;
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800511 if (mCondition.wait_for(lock, timeout) == std::cv_status::timeout) {
Ady Abraham5e7371c2020-03-24 14:47:24 -0700512 if (mState == State::VSync) {
513 ALOGW("Faking VSYNC due to driver stall for thread %s", mThreadName);
Ady Abraham5e7371c2020-03-24 14:47:24 -0700514 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800515
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800516 LOG_FATAL_IF(!mVSyncState);
Ady Abraham5facfb12020-04-22 15:18:31 -0700517 const auto now = systemTime(SYSTEM_TIME_MONOTONIC);
Ady Abraham8cb21882020-08-26 18:22:05 -0700518 const auto deadlineTimestamp = now + timeout.count();
519 const auto expectedVSyncTime = deadlineTimestamp + timeout.count();
Ady Abraham5facfb12020-04-22 15:18:31 -0700520 mPendingEvents.push_back(makeVSync(mVSyncState->displayId, now,
Ady Abraham8cb21882020-08-26 18:22:05 -0700521 ++mVSyncState->count, expectedVSyncTime,
Rachel Lee0d943202022-02-01 23:29:41 -0800522 deadlineTimestamp));
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700523 }
524 }
Lloyd Pique46a46b32018-01-31 19:01:18 -0800525 }
Ady Abraham011f8ba2022-11-22 15:09:07 -0800526 // cancel any pending vsync event before exiting
527 mVsyncRegistration.cancel();
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800528}
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700529
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800530bool EventThread::shouldConsumeEvent(const DisplayEventReceiver::Event& event,
531 const sp<EventThreadConnection>& connection) const {
Leon Scroggins IIIed66a352023-03-23 17:55:43 -0400532 const auto throttleVsync = [&]() REQUIRES(mMutex) {
Leon Scroggins III31d41412022-11-18 16:42:53 -0500533 const auto& vsyncData = event.vsync.vsyncData;
Rachel Lee2248f522023-01-27 16:45:23 -0800534 if (connection->frameRate.isValid()) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500535 return !mVsyncSchedule->getTracker()
Rachel Lee2248f522023-01-27 16:45:23 -0800536 .isVSyncInPhase(vsyncData.preferredExpectedPresentationTime(),
537 connection->frameRate);
538 }
539
Ady Abrahamf2851612023-09-25 17:19:00 -0700540 const auto expectedPresentTime =
541 TimePoint::fromNs(event.vsync.vsyncData.preferredExpectedPresentationTime());
542 return mCallback.throttleVsync(expectedPresentTime, connection->mOwnerUid);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700543 };
544
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800545 switch (event.header.type) {
546 case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
547 return true;
548
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100549 case DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE: {
Ady Abraham62f216c2020-10-13 19:07:23 -0700550 return connection->mEventRegistration.test(
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700551 gui::ISurfaceComposer::EventRegistration::modeChanged);
Alec Mouri60aee1c2019-10-28 16:18:59 -0700552 }
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700553
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800554 case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
555 switch (connection->vsyncRequest) {
556 case VSyncRequest::None:
557 return false;
Tim Murrayb5daa912020-09-09 21:29:13 +0000558 case VSyncRequest::SingleSuppressCallback:
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800559 connection->vsyncRequest = VSyncRequest::None;
Tim Murrayb5daa912020-09-09 21:29:13 +0000560 return false;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700561 case VSyncRequest::Single: {
562 if (throttleVsync()) {
563 return false;
564 }
Tim Murrayb5daa912020-09-09 21:29:13 +0000565 connection->vsyncRequest = VSyncRequest::SingleSuppressCallback;
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800566 return true;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700567 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800568 case VSyncRequest::Periodic:
Ady Abraham0bb6a472020-10-12 10:22:13 -0700569 if (throttleVsync()) {
570 return false;
571 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800572 return true;
573 default:
Ady Abraham0bb6a472020-10-12 10:22:13 -0700574 // We don't throttle vsync if the app set a vsync request rate
575 // since there is no easy way to do that and this is a very
576 // rare case
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800577 return event.vsync.count % vsyncPeriod(connection->vsyncRequest) == 0;
578 }
579
Ady Abraham62f216c2020-10-13 19:07:23 -0700580 case DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE:
581 [[fallthrough]];
582 case DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH:
583 return connection->mEventRegistration.test(
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700584 gui::ISurfaceComposer::EventRegistration::frameRateOverride);
Ady Abraham62f216c2020-10-13 19:07:23 -0700585
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800586 default:
587 return false;
588 }
589}
590
Rachel Lee8d0c6102021-11-03 22:00:25 +0000591int64_t EventThread::generateToken(nsecs_t timestamp, nsecs_t deadlineTimestamp,
Rachel Leeb9c5a772022-02-04 21:17:37 -0800592 nsecs_t expectedPresentationTime) const {
Rachel Lee3f028662021-11-04 19:32:24 +0000593 if (mTokenManager != nullptr) {
594 return mTokenManager->generateTokenForPredictions(
Rachel Leeb9c5a772022-02-04 21:17:37 -0800595 {timestamp, deadlineTimestamp, expectedPresentationTime});
Rachel Lee3f028662021-11-04 19:32:24 +0000596 }
597 return FrameTimelineInfo::INVALID_VSYNC_ID;
598}
599
Rachel Leeb9c5a772022-02-04 21:17:37 -0800600void EventThread::generateFrameTimeline(VsyncEventData& outVsyncEventData, nsecs_t frameInterval,
601 nsecs_t timestamp,
602 nsecs_t preferredExpectedPresentationTime,
603 nsecs_t preferredDeadlineTimestamp) const {
Rachel Lee0655a912023-04-20 19:54:18 -0700604 uint32_t currentIndex = 0;
Rachel Lee3f028662021-11-04 19:32:24 +0000605 // Add 1 to ensure the preferredFrameTimelineIndex entry (when multiplier == 0) is included.
Rachel Lee40aef422023-04-25 14:35:47 -0700606 for (int64_t multiplier = -VsyncEventData::kFrameTimelinesCapacity + 1;
607 currentIndex < VsyncEventData::kFrameTimelinesCapacity; multiplier++) {
Rachel Leeb9c5a772022-02-04 21:17:37 -0800608 nsecs_t deadlineTimestamp = preferredDeadlineTimestamp + multiplier * frameInterval;
Rachel Lee0655a912023-04-20 19:54:18 -0700609 // Valid possible frame timelines must have future values, so find a later frame timeline.
610 if (deadlineTimestamp <= timestamp) {
611 continue;
Rachel Lee3f028662021-11-04 19:32:24 +0000612 }
Rachel Lee0655a912023-04-20 19:54:18 -0700613
614 nsecs_t expectedPresentationTime =
615 preferredExpectedPresentationTime + multiplier * frameInterval;
616 if (expectedPresentationTime >= preferredExpectedPresentationTime +
617 scheduler::VsyncConfig::kEarlyLatchMaxThreshold.count()) {
Rachel Leeafb6b502023-05-12 15:53:05 -0700618 if (currentIndex == 0) {
619 ALOGW("%s: Expected present time is too far in the future but no timelines are "
620 "valid. preferred EPT=%" PRId64 ", Calculated EPT=%" PRId64
621 ", multiplier=%" PRId64 ", frameInterval=%" PRId64 ", threshold=%" PRId64,
622 __func__, preferredExpectedPresentationTime, expectedPresentationTime,
623 multiplier, frameInterval,
624 static_cast<int64_t>(
625 scheduler::VsyncConfig::kEarlyLatchMaxThreshold.count()));
626 }
Rachel Lee0655a912023-04-20 19:54:18 -0700627 break;
628 }
629
630 if (multiplier == 0) {
631 outVsyncEventData.preferredFrameTimelineIndex = currentIndex;
632 }
633
634 outVsyncEventData.frameTimelines[currentIndex] =
635 {.vsyncId = generateToken(timestamp, deadlineTimestamp, expectedPresentationTime),
636 .deadlineTimestamp = deadlineTimestamp,
637 .expectedPresentationTime = expectedPresentationTime};
638 currentIndex++;
Rachel Lee3f028662021-11-04 19:32:24 +0000639 }
Rachel Leeafb6b502023-05-12 15:53:05 -0700640
641 if (currentIndex == 0) {
642 ALOGW("%s: No timelines are valid. preferred EPT=%" PRId64 ", frameInterval=%" PRId64
643 ", threshold=%" PRId64,
644 __func__, preferredExpectedPresentationTime, frameInterval,
645 static_cast<int64_t>(scheduler::VsyncConfig::kEarlyLatchMaxThreshold.count()));
646 outVsyncEventData.frameTimelines[currentIndex] =
647 {.vsyncId = generateToken(timestamp, preferredDeadlineTimestamp,
648 preferredExpectedPresentationTime),
649 .deadlineTimestamp = preferredDeadlineTimestamp,
650 .expectedPresentationTime = preferredExpectedPresentationTime};
651 currentIndex++;
652 }
653
Rachel Lee0655a912023-04-20 19:54:18 -0700654 outVsyncEventData.frameTimelinesLength = currentIndex;
Rachel Lee3f028662021-11-04 19:32:24 +0000655}
656
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800657void EventThread::dispatchEvent(const DisplayEventReceiver::Event& event,
658 const DisplayEventConsumers& consumers) {
659 for (const auto& consumer : consumers) {
Jorim Jaggic0086af2021-02-12 18:18:11 +0100660 DisplayEventReceiver::Event copy = event;
661 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_VSYNC) {
Ady Abrahamf2851612023-09-25 17:19:00 -0700662 const Period frameInterval = mCallback.getVsyncPeriod(consumer->mOwnerUid);
663 copy.vsync.vsyncData.frameInterval = frameInterval.ns();
664 generateFrameTimeline(copy.vsync.vsyncData, frameInterval.ns(), copy.header.timestamp,
Rachel Leeb9c5a772022-02-04 21:17:37 -0800665 event.vsync.vsyncData.preferredExpectedPresentationTime(),
666 event.vsync.vsyncData.preferredDeadlineTimestamp());
Jorim Jaggic0086af2021-02-12 18:18:11 +0100667 }
668 switch (consumer->postEvent(copy)) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800669 case NO_ERROR:
670 break;
671
672 case -EAGAIN:
673 // TODO: Try again if pipe is full.
674 ALOGW("Failed dispatching %s for %s", toString(event).c_str(),
675 toString(*consumer).c_str());
676 break;
677
678 default:
679 // Treat EPIPE and other errors as fatal.
680 removeDisplayEventConnectionLocked(consumer);
681 }
682 }
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700683}
684
Yiwei Zhang5434a782018-12-05 18:06:32 -0800685void EventThread::dump(std::string& result) const {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800686 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800687
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800688 StringAppendF(&result, "%s: state=%s VSyncState=", mThreadName, toCString(mState));
689 if (mVSyncState) {
Marin Shalamanova524a092020-07-27 21:39:55 +0200690 StringAppendF(&result, "{displayId=%s, count=%u%s}\n",
691 to_string(mVSyncState->displayId).c_str(), mVSyncState->count,
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800692 mVSyncState->synthetic ? ", synthetic" : "");
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800693 } else {
694 StringAppendF(&result, "none\n");
695 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800696
Ady Abraham011f8ba2022-11-22 15:09:07 -0800697 const auto relativeLastCallTime =
698 ticks<std::milli, float>(mLastVsyncCallbackTime - TimePoint::now());
699 StringAppendF(&result, "mWorkDuration=%.2f mReadyDuration=%.2f last vsync time ",
700 mWorkDuration.get().count() / 1e6f, mReadyDuration.count() / 1e6f);
701 StringAppendF(&result, "%.2fms relative to now\n", relativeLastCallTime);
702
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800703 StringAppendF(&result, " pending events (count=%zu):\n", mPendingEvents.size());
704 for (const auto& event : mPendingEvents) {
705 StringAppendF(&result, " %s\n", toString(event).c_str());
Mathias Agopiane2c4f4e2012-04-10 18:25:31 -0700706 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800707
708 StringAppendF(&result, " connections (count=%zu):\n", mDisplayEventConnections.size());
709 for (const auto& ptr : mDisplayEventConnections) {
710 if (const auto connection = ptr.promote()) {
711 StringAppendF(&result, " %s\n", toString(*connection).c_str());
712 }
713 }
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400714 result += '\n';
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800715}
716
Dominik Laskowski029cc122019-01-23 19:52:06 -0800717const char* EventThread::toCString(State state) {
718 switch (state) {
719 case State::Idle:
720 return "Idle";
721 case State::Quit:
722 return "Quit";
723 case State::SyntheticVSync:
724 return "SyntheticVSync";
725 case State::VSync:
726 return "VSync";
727 }
728}
729
Leon Scroggins III67388622023-02-06 20:36:20 -0500730void EventThread::onNewVsyncSchedule(std::shared_ptr<scheduler::VsyncSchedule> schedule) {
Leon Scroggins IIIb2253602023-04-19 17:04:04 -0400731 // Hold onto the old registration until after releasing the mutex to avoid deadlock.
732 scheduler::VSyncCallbackRegistration oldRegistration =
733 onNewVsyncScheduleInternal(std::move(schedule));
734}
735
736scheduler::VSyncCallbackRegistration EventThread::onNewVsyncScheduleInternal(
737 std::shared_ptr<scheduler::VsyncSchedule> schedule) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500738 std::lock_guard<std::mutex> lock(mMutex);
739 const bool reschedule = mVsyncRegistration.cancel() == scheduler::CancelResult::Cancelled;
740 mVsyncSchedule = std::move(schedule);
Leon Scroggins IIIb2253602023-04-19 17:04:04 -0400741 auto oldRegistration =
742 std::exchange(mVsyncRegistration,
743 scheduler::VSyncCallbackRegistration(mVsyncSchedule->getDispatch(),
744 createDispatchCallback(),
745 mThreadName));
Leon Scroggins III67388622023-02-06 20:36:20 -0500746 if (reschedule) {
747 mVsyncRegistration.schedule({.workDuration = mWorkDuration.get().count(),
748 .readyDuration = mReadyDuration.count(),
749 .earliestVsync = mLastVsyncCallbackTime.ns()});
750 }
Leon Scroggins IIIb2253602023-04-19 17:04:04 -0400751 return oldRegistration;
Leon Scroggins III67388622023-02-06 20:36:20 -0500752}
753
754scheduler::VSyncDispatch::Callback EventThread::createDispatchCallback() {
755 return [this](nsecs_t vsyncTime, nsecs_t wakeupTime, nsecs_t readyTime) {
756 onVsync(vsyncTime, wakeupTime, readyTime);
757 };
758}
759
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800760} // namespace impl
Lloyd Pique46a46b32018-01-31 19:01:18 -0800761} // namespace android
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800762
763// TODO(b/129481165): remove the #pragma below and fix conversion issues
764#pragma clang diagnostic pop // ignored "-Wconversion"