blob: 56be1b1ff74fe17c96afeff165717652f5a59bd5 [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
Alec Mouri9b133ca2023-11-14 19:00:01 +000046#include <common/FlagManager.h>
Rachel Lee0655a912023-04-20 19:54:18 -070047#include <scheduler/VsyncConfig.h>
Marin Shalamanov23c44202020-12-22 19:09:20 +010048#include "DisplayHardware/DisplayMode.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);
Huihong Luo9ebb7a72023-06-27 17:01:50 -0700103 case DisplayEventReceiver::DISPLAY_EVENT_HDCP_LEVELS_CHANGE:
104 return StringPrintf("HdcpLevelsChange{displayId=%s, connectedLevel=%d, maxLevel=%d}",
105 to_string(event.header.displayId).c_str(),
106 event.hdcpLevelsChange.connectedLevel,
107 event.hdcpLevelsChange.maxLevel);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800108 default:
109 return "Event{}";
110 }
111}
112
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800113DisplayEventReceiver::Event makeHotplug(PhysicalDisplayId displayId, nsecs_t timestamp,
114 bool connected) {
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800115 DisplayEventReceiver::Event event;
116 event.header = {DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG, displayId, timestamp};
117 event.hotplug.connected = connected;
118 return event;
119}
120
Brian Johnson5dcd75d2023-08-15 09:36:37 -0700121DisplayEventReceiver::Event makeHotplugError(nsecs_t timestamp, int32_t connectionError) {
122 DisplayEventReceiver::Event event;
123 PhysicalDisplayId unusedDisplayId;
124 event.header = {DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG, unusedDisplayId, timestamp};
125 event.hotplug.connected = false;
126 event.hotplug.connectionError = connectionError;
127 return event;
128}
129
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800130DisplayEventReceiver::Event makeVSync(PhysicalDisplayId displayId, nsecs_t timestamp,
Rachel Leeb9c5a772022-02-04 21:17:37 -0800131 uint32_t count, nsecs_t expectedPresentationTime,
Rachel Lee0d943202022-02-01 23:29:41 -0800132 nsecs_t deadlineTimestamp) {
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800133 DisplayEventReceiver::Event event;
134 event.header = {DisplayEventReceiver::DISPLAY_EVENT_VSYNC, displayId, timestamp};
135 event.vsync.count = count;
Rachel Leeb9c5a772022-02-04 21:17:37 -0800136 event.vsync.vsyncData.preferredFrameTimelineIndex = 0;
137 // Temporarily store the current vsync information in frameTimelines[0], marked as
138 // platform-preferred. When the event is dispatched later, the frame interval at that time is
139 // used with this information to generate multiple frame timeline choices.
140 event.vsync.vsyncData.frameTimelines[0] = {.vsyncId = FrameTimelineInfo::INVALID_VSYNC_ID,
141 .deadlineTimestamp = deadlineTimestamp,
142 .expectedPresentationTime =
143 expectedPresentationTime};
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800144 return event;
145}
146
Ady Abraham67434eb2022-12-01 17:48:12 -0800147DisplayEventReceiver::Event makeModeChanged(const scheduler::FrameRateMode& mode) {
Ady Abraham447052e2019-02-13 16:07:27 -0800148 DisplayEventReceiver::Event event;
Ady Abraham67434eb2022-12-01 17:48:12 -0800149 event.header = {DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE,
150 mode.modePtr->getPhysicalDisplayId(), systemTime()};
151 event.modeChange.modeId = mode.modePtr->getId().value();
152 event.modeChange.vsyncPeriod = mode.fps.getPeriodNsecs();
Ady Abraham447052e2019-02-13 16:07:27 -0800153 return event;
154}
155
Ady Abraham62f216c2020-10-13 19:07:23 -0700156DisplayEventReceiver::Event makeFrameRateOverrideEvent(PhysicalDisplayId displayId,
157 FrameRateOverride frameRateOverride) {
158 return DisplayEventReceiver::Event{
159 .header =
160 DisplayEventReceiver::Event::Header{
161 .type = DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE,
162 .displayId = displayId,
163 .timestamp = systemTime(),
164 },
165 .frameRateOverride = frameRateOverride,
166 };
167}
168
169DisplayEventReceiver::Event makeFrameRateOverrideFlushEvent(PhysicalDisplayId displayId) {
170 return DisplayEventReceiver::Event{
171 .header = DisplayEventReceiver::Event::Header{
172 .type = DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH,
173 .displayId = displayId,
174 .timestamp = systemTime(),
175 }};
176}
177
Huihong Luo9ebb7a72023-06-27 17:01:50 -0700178DisplayEventReceiver::Event makeHdcpLevelsChange(PhysicalDisplayId displayId,
179 int32_t connectedLevel, int32_t maxLevel) {
180 return DisplayEventReceiver::Event{
181 .header =
182 DisplayEventReceiver::Event::Header{
183 .type = DisplayEventReceiver::DISPLAY_EVENT_HDCP_LEVELS_CHANGE,
184 .displayId = displayId,
185 .timestamp = systemTime(),
186 },
187 .hdcpLevelsChange.connectedLevel = connectedLevel,
188 .hdcpLevelsChange.maxLevel = maxLevel,
189 };
190}
191
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800192} // namespace
Lloyd Pique46a46b32018-01-31 19:01:18 -0800193
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700194EventThreadConnection::EventThreadConnection(EventThread* eventThread, uid_t callingUid,
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700195 EventRegistrationFlags eventRegistration)
Ady Abrahamf2851612023-09-25 17:19:00 -0700196 : mOwnerUid(callingUid),
Ady Abraham62f216c2020-10-13 19:07:23 -0700197 mEventRegistration(eventRegistration),
Dominik Laskowskif654d572018-12-20 11:03:06 -0800198 mEventThread(eventThread),
199 mChannel(gui::BitTube::DefaultSize) {}
Ana Krulec85c39af2018-12-26 17:29:57 -0800200
201EventThreadConnection::~EventThreadConnection() {
202 // do nothing here -- clean-up will happen automatically
203 // when the main thread wakes up
204}
205
206void EventThreadConnection::onFirstRef() {
207 // NOTE: mEventThread doesn't hold a strong reference on us
Ady Abrahamd11bade2022-08-01 16:18:03 -0700208 mEventThread->registerDisplayEventConnection(sp<EventThreadConnection>::fromExisting(this));
Ana Krulec85c39af2018-12-26 17:29:57 -0800209}
210
Huihong Luo6fac5232021-11-22 16:05:23 -0800211binder::Status EventThreadConnection::stealReceiveChannel(gui::BitTube* outChannel) {
Ady Abraham899e8cd2022-06-06 15:16:06 -0700212 std::scoped_lock lock(mLock);
213 if (mChannel.initCheck() != NO_ERROR) {
214 return binder::Status::fromStatusT(NAME_NOT_FOUND);
215 }
216
Ana Krulec85c39af2018-12-26 17:29:57 -0800217 outChannel->setReceiveFd(mChannel.moveReceiveFd());
Alec Mouri967d5d72020-08-05 12:50:03 -0700218 outChannel->setSendFd(base::unique_fd(dup(mChannel.getSendFd())));
Huihong Luo6fac5232021-11-22 16:05:23 -0800219 return binder::Status::ok();
Ana Krulec85c39af2018-12-26 17:29:57 -0800220}
221
Huihong Luo6fac5232021-11-22 16:05:23 -0800222binder::Status EventThreadConnection::setVsyncRate(int rate) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700223 mEventThread->setVsyncRate(static_cast<uint32_t>(rate),
224 sp<EventThreadConnection>::fromExisting(this));
Huihong Luo6fac5232021-11-22 16:05:23 -0800225 return binder::Status::ok();
Ana Krulec85c39af2018-12-26 17:29:57 -0800226}
227
Huihong Luo6fac5232021-11-22 16:05:23 -0800228binder::Status EventThreadConnection::requestNextVsync() {
Rachel Leeef2e21f2022-02-01 14:51:34 -0800229 ATRACE_CALL();
Ady Abrahamd11bade2022-08-01 16:18:03 -0700230 mEventThread->requestNextVsync(sp<EventThreadConnection>::fromExisting(this));
Huihong Luo6fac5232021-11-22 16:05:23 -0800231 return binder::Status::ok();
Ana Krulec85c39af2018-12-26 17:29:57 -0800232}
233
Rachel Leeb9c5a772022-02-04 21:17:37 -0800234binder::Status EventThreadConnection::getLatestVsyncEventData(
235 ParcelableVsyncEventData* outVsyncEventData) {
Rachel Leeef2e21f2022-02-01 14:51:34 -0800236 ATRACE_CALL();
Ady Abrahamd11bade2022-08-01 16:18:03 -0700237 outVsyncEventData->vsync =
238 mEventThread->getLatestVsyncEventData(sp<EventThreadConnection>::fromExisting(this));
Rachel Leeef2e21f2022-02-01 14:51:34 -0800239 return binder::Status::ok();
240}
241
Ady Abraham07d03c42023-09-27 19:15:08 -0700242binder::Status EventThreadConnection::getSchedulingPolicy(gui::SchedulingPolicy* outPolicy) {
243 return gui::getSchedulingPolicy(outPolicy);
244}
245
Ana Krulec85c39af2018-12-26 17:29:57 -0800246status_t EventThreadConnection::postEvent(const DisplayEventReceiver::Event& event) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700247 constexpr auto toStatus = [](ssize_t size) {
248 return size < 0 ? status_t(size) : status_t(NO_ERROR);
249 };
250
251 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE ||
252 event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH) {
253 mPendingEvents.emplace_back(event);
254 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE) {
255 return status_t(NO_ERROR);
256 }
257
258 auto size = DisplayEventReceiver::sendEvents(&mChannel, mPendingEvents.data(),
259 mPendingEvents.size());
260 mPendingEvents.clear();
261 return toStatus(size);
262 }
263
264 auto size = DisplayEventReceiver::sendEvents(&mChannel, &event, 1);
265 return toStatus(size);
Ana Krulec85c39af2018-12-26 17:29:57 -0800266}
267
268// ---------------------------------------------------------------------------
269
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800270EventThread::~EventThread() = default;
271
272namespace impl {
273
Leon Scroggins III67388622023-02-06 20:36:20 -0500274EventThread::EventThread(const char* name, std::shared_ptr<scheduler::VsyncSchedule> vsyncSchedule,
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700275 android::frametimeline::TokenManager* tokenManager,
Ady Abrahamf2851612023-09-25 17:19:00 -0700276 IEventThreadCallback& callback, std::chrono::nanoseconds workDuration,
Ady Abraham011f8ba2022-11-22 15:09:07 -0800277 std::chrono::nanoseconds readyDuration)
278 : mThreadName(name),
279 mVsyncTracer(base::StringPrintf("VSYNC-%s", name), 0),
280 mWorkDuration(base::StringPrintf("VsyncWorkDuration-%s", name), workDuration),
281 mReadyDuration(readyDuration),
Leon Scroggins III67388622023-02-06 20:36:20 -0500282 mVsyncSchedule(std::move(vsyncSchedule)),
283 mVsyncRegistration(mVsyncSchedule->getDispatch(), createDispatchCallback(), name),
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700284 mTokenManager(tokenManager),
Ady Abrahamf2851612023-09-25 17:19:00 -0700285 mCallback(callback) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800286 mThread = std::thread([this]() NO_THREAD_SAFETY_ANALYSIS {
287 std::unique_lock<std::mutex> lock(mMutex);
288 threadMain(lock);
289 });
Lloyd Pique46a46b32018-01-31 19:01:18 -0800290
Dominik Laskowski6505f792019-09-18 11:10:05 -0700291 pthread_setname_np(mThread.native_handle(), mThreadName);
Lloyd Pique46a46b32018-01-31 19:01:18 -0800292
293 pid_t tid = pthread_gettid_np(mThread.native_handle());
294
295 // Use SCHED_FIFO to minimize jitter
296 constexpr int EVENT_THREAD_PRIORITY = 2;
297 struct sched_param param = {0};
298 param.sched_priority = EVENT_THREAD_PRIORITY;
299 if (pthread_setschedparam(mThread.native_handle(), SCHED_FIFO, &param) != 0) {
300 ALOGE("Couldn't set SCHED_FIFO for EventThread");
301 }
302
303 set_sched_policy(tid, SP_FOREGROUND);
304}
305
306EventThread::~EventThread() {
307 {
308 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski029cc122019-01-23 19:52:06 -0800309 mState = State::Quit;
Lloyd Pique46a46b32018-01-31 19:01:18 -0800310 mCondition.notify_all();
311 }
312 mThread.join();
Ruchi Kandoief472ec2014-04-02 12:50:06 -0700313}
314
Ady Abraham9c53ee72020-07-22 21:16:18 -0700315void EventThread::setDuration(std::chrono::nanoseconds workDuration,
316 std::chrono::nanoseconds readyDuration) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800317 std::lock_guard<std::mutex> lock(mMutex);
Ady Abraham011f8ba2022-11-22 15:09:07 -0800318 mWorkDuration = workDuration;
319 mReadyDuration = readyDuration;
320
321 mVsyncRegistration.update({.workDuration = mWorkDuration.get().count(),
322 .readyDuration = mReadyDuration.count(),
323 .earliestVsync = mLastVsyncCallbackTime.ns()});
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700324}
325
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700326sp<EventThreadConnection> EventThread::createEventConnection(
Ady Abrahamf2851612023-09-25 17:19:00 -0700327 EventRegistrationFlags eventRegistration) const {
Ady Abraham07d03c42023-09-27 19:15:08 -0700328 auto connection = sp<EventThreadConnection>::make(const_cast<EventThread*>(this),
329 IPCThreadState::self()->getCallingUid(),
330 eventRegistration);
Ady Abrahamd6d80162023-10-23 12:57:41 -0700331 if (FlagManager::getInstance().misc1()) {
Ady Abraham07d03c42023-09-27 19:15:08 -0700332 const int policy = SCHED_FIFO;
333 connection->setMinSchedulerPolicy(policy, sched_get_priority_min(policy));
334 }
335 return connection;
Mathias Agopian8aedd472012-01-24 16:39:14 -0800336}
337
Ana Krulec85c39af2018-12-26 17:29:57 -0800338status_t EventThread::registerDisplayEventConnection(const sp<EventThreadConnection>& connection) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800339 std::lock_guard<std::mutex> lock(mMutex);
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700340
341 // this should never happen
342 auto it = std::find(mDisplayEventConnections.cbegin(),
343 mDisplayEventConnections.cend(), connection);
344 if (it != mDisplayEventConnections.cend()) {
345 ALOGW("DisplayEventConnection %p already exists", connection.get());
346 mCondition.notify_all();
347 return ALREADY_EXISTS;
348 }
349
350 mDisplayEventConnections.push_back(connection);
Lloyd Pique46a46b32018-01-31 19:01:18 -0800351 mCondition.notify_all();
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800352 return NO_ERROR;
353}
354
Ana Krulec85c39af2018-12-26 17:29:57 -0800355void EventThread::removeDisplayEventConnectionLocked(const wp<EventThreadConnection>& connection) {
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700356 auto it = std::find(mDisplayEventConnections.cbegin(),
357 mDisplayEventConnections.cend(), connection);
358 if (it != mDisplayEventConnections.cend()) {
359 mDisplayEventConnections.erase(it);
360 }
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800361}
362
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800363void EventThread::setVsyncRate(uint32_t rate, const sp<EventThreadConnection>& connection) {
364 if (static_cast<std::underlying_type_t<VSyncRequest>>(rate) < 0) {
365 return;
366 }
367
368 std::lock_guard<std::mutex> lock(mMutex);
369
370 const auto request = rate == 0 ? VSyncRequest::None : static_cast<VSyncRequest>(rate);
371 if (connection->vsyncRequest != request) {
372 connection->vsyncRequest = request;
373 mCondition.notify_all();
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800374 }
375}
376
Ady Abraham8532d012019-05-08 14:50:56 -0700377void EventThread::requestNextVsync(const sp<EventThreadConnection>& connection) {
Ady Abrahamf2851612023-09-25 17:19:00 -0700378 mCallback.resync();
Tim Murray4a4e4a22016-04-19 16:29:23 +0000379
Ana Krulec7d1d6832018-12-27 11:10:09 -0800380 std::lock_guard<std::mutex> lock(mMutex);
381
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800382 if (connection->vsyncRequest == VSyncRequest::None) {
383 connection->vsyncRequest = VSyncRequest::Single;
Lloyd Pique46a46b32018-01-31 19:01:18 -0800384 mCondition.notify_all();
Tim Murrayb5daa912020-09-09 21:29:13 +0000385 } else if (connection->vsyncRequest == VSyncRequest::SingleSuppressCallback) {
386 connection->vsyncRequest = VSyncRequest::Single;
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800387 }
Mathias Agopian23748662011-12-05 14:33:34 -0800388}
389
Rachel Leeef2e21f2022-02-01 14:51:34 -0800390VsyncEventData EventThread::getLatestVsyncEventData(
391 const sp<EventThreadConnection>& connection) const {
Rachel Leeb5223cf2022-03-14 14:39:27 -0700392 // Resync so that the vsync is accurate with hardware. getLatestVsyncEventData is an alternate
393 // way to get vsync data (instead of posting callbacks to Choreographer).
Ady Abrahamf2851612023-09-25 17:19:00 -0700394 mCallback.resync();
Rachel Leeb5223cf2022-03-14 14:39:27 -0700395
Rachel Leeef2e21f2022-02-01 14:51:34 -0800396 VsyncEventData vsyncEventData;
Ady Abrahamf2851612023-09-25 17:19:00 -0700397 const Period frameInterval = mCallback.getVsyncPeriod(connection->mOwnerUid);
398 vsyncEventData.frameInterval = frameInterval.ns();
Ady Abraham011f8ba2022-11-22 15:09:07 -0800399 const auto [presentTime, deadline] = [&]() -> std::pair<nsecs_t, nsecs_t> {
Rachel Leeb9c5a772022-02-04 21:17:37 -0800400 std::lock_guard<std::mutex> lock(mMutex);
Leon Scroggins III67388622023-02-06 20:36:20 -0500401 const auto vsyncTime = mVsyncSchedule->getTracker().nextAnticipatedVSyncTimeFrom(
Ady Abraham011f8ba2022-11-22 15:09:07 -0800402 systemTime() + mWorkDuration.get().count() + mReadyDuration.count());
403 return {vsyncTime, vsyncTime - mReadyDuration.count()};
404 }();
Ady Abrahamf2851612023-09-25 17:19:00 -0700405 generateFrameTimeline(vsyncEventData, frameInterval.ns(), systemTime(SYSTEM_TIME_MONOTONIC),
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500406 presentTime, deadline);
Rachel Leeef2e21f2022-02-01 14:51:34 -0800407 return vsyncEventData;
408}
409
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500410void EventThread::enableSyntheticVsync(bool enable) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800411 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500412 if (!mVSyncState || mVSyncState->synthetic == enable) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800413 return;
Mathias Agopian22ffb112012-04-10 21:04:02 -0700414 }
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800415
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500416 mVSyncState->synthetic = enable;
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800417 mCondition.notify_all();
Mathias Agopian22ffb112012-04-10 21:04:02 -0700418}
419
Ady Abraham011f8ba2022-11-22 15:09:07 -0800420void EventThread::onVsync(nsecs_t vsyncTime, nsecs_t wakeupTime, nsecs_t readyTime) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800421 std::lock_guard<std::mutex> lock(mMutex);
Ady Abraham011f8ba2022-11-22 15:09:07 -0800422 mLastVsyncCallbackTime = TimePoint::fromNs(vsyncTime);
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800423
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800424 LOG_FATAL_IF(!mVSyncState);
Ady Abraham011f8ba2022-11-22 15:09:07 -0800425 mVsyncTracer = (mVsyncTracer + 1) % 2;
426 mPendingEvents.push_back(makeVSync(mVSyncState->displayId, wakeupTime, ++mVSyncState->count,
427 vsyncTime, readyTime));
Lloyd Pique46a46b32018-01-31 19:01:18 -0800428 mCondition.notify_all();
Mathias Agopian3eb38cb2012-04-03 22:09:52 -0700429}
430
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800431void EventThread::onHotplugReceived(PhysicalDisplayId displayId, bool connected) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800432 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -0700433
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800434 mPendingEvents.push_back(makeHotplug(displayId, systemTime(), connected));
Dominik Laskowski00a6fa22018-06-06 16:42:02 -0700435 mCondition.notify_all();
Mathias Agopian148994e2012-09-19 17:31:36 -0700436}
437
Brian Johnson5dcd75d2023-08-15 09:36:37 -0700438void EventThread::onHotplugConnectionError(int32_t errorCode) {
439 std::lock_guard<std::mutex> lock(mMutex);
440
441 mPendingEvents.push_back(makeHotplugError(systemTime(), errorCode));
442 mCondition.notify_all();
443}
444
Ady Abraham67434eb2022-12-01 17:48:12 -0800445void EventThread::onModeChanged(const scheduler::FrameRateMode& mode) {
Ady Abraham447052e2019-02-13 16:07:27 -0800446 std::lock_guard<std::mutex> lock(mMutex);
447
Ady Abraham690f4612021-07-01 23:24:03 -0700448 mPendingEvents.push_back(makeModeChanged(mode));
Ady Abraham447052e2019-02-13 16:07:27 -0800449 mCondition.notify_all();
450}
451
Ady Abraham62f216c2020-10-13 19:07:23 -0700452void EventThread::onFrameRateOverridesChanged(PhysicalDisplayId displayId,
453 std::vector<FrameRateOverride> overrides) {
454 std::lock_guard<std::mutex> lock(mMutex);
455
456 for (auto frameRateOverride : overrides) {
457 mPendingEvents.push_back(makeFrameRateOverrideEvent(displayId, frameRateOverride));
458 }
459 mPendingEvents.push_back(makeFrameRateOverrideFlushEvent(displayId));
460
461 mCondition.notify_all();
462}
463
Huihong Luo9ebb7a72023-06-27 17:01:50 -0700464void EventThread::onHdcpLevelsChanged(PhysicalDisplayId displayId, int32_t connectedLevel,
465 int32_t maxLevel) {
466 std::lock_guard<std::mutex> lock(mMutex);
467
468 mPendingEvents.push_back(makeHdcpLevelsChange(displayId, connectedLevel, maxLevel));
469 mCondition.notify_all();
470}
471
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800472void EventThread::threadMain(std::unique_lock<std::mutex>& lock) {
473 DisplayEventConsumers consumers;
474
Dominik Laskowski029cc122019-01-23 19:52:06 -0800475 while (mState != State::Quit) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800476 std::optional<DisplayEventReceiver::Event> event;
Mathias Agopian3eb38cb2012-04-03 22:09:52 -0700477
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800478 // Determine next event to dispatch.
479 if (!mPendingEvents.empty()) {
480 event = mPendingEvents.front();
481 mPendingEvents.pop_front();
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800482
Huihong Luoab8ffef2022-08-18 13:02:26 -0700483 if (event->header.type == DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG) {
Brian Johnson5dcd75d2023-08-15 09:36:37 -0700484 if (event->hotplug.connectionError == 0) {
485 if (event->hotplug.connected && !mVSyncState) {
486 mVSyncState.emplace(event->header.displayId);
487 } else if (!event->hotplug.connected && mVSyncState &&
488 mVSyncState->displayId == event->header.displayId) {
489 mVSyncState.reset();
490 }
491 } else {
492 // Ignore vsync stuff on an error.
Huihong Luoab8ffef2022-08-18 13:02:26 -0700493 }
Dominik Laskowski029cc122019-01-23 19:52:06 -0800494 }
Mathias Agopianff28e202012-09-20 23:24:19 -0700495 }
496
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800497 bool vsyncRequested = false;
Mathias Agopian148994e2012-09-19 17:31:36 -0700498
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800499 // Find connections that should consume this event.
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700500 auto it = mDisplayEventConnections.begin();
501 while (it != mDisplayEventConnections.end()) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800502 if (const auto connection = it->promote()) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800503 if (event && shouldConsumeEvent(*event, connection)) {
504 consumers.push_back(connection);
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700505 }
Mathias Agopianb4d18ed2012-09-20 23:14:05 -0700506
Ady Abraham011f8ba2022-11-22 15:09:07 -0800507 vsyncRequested |= connection->vsyncRequest != VSyncRequest::None;
508
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700509 ++it;
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700510 } else {
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700511 it = mDisplayEventConnections.erase(it);
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700512 }
513 }
514
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800515 if (!consumers.empty()) {
516 dispatchEvent(*event, consumers);
517 consumers.clear();
518 }
519
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800520 if (mVSyncState && vsyncRequested) {
Ady Abraham011f8ba2022-11-22 15:09:07 -0800521 mState = mVSyncState->synthetic ? State::SyntheticVSync : State::VSync;
Dominik Laskowski029cc122019-01-23 19:52:06 -0800522 } else {
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800523 ALOGW_IF(!mVSyncState, "Ignoring VSYNC request while display is disconnected");
Ady Abraham011f8ba2022-11-22 15:09:07 -0800524 mState = State::Idle;
Dominik Laskowski029cc122019-01-23 19:52:06 -0800525 }
526
Ady Abraham011f8ba2022-11-22 15:09:07 -0800527 if (mState == State::VSync) {
528 const auto scheduleResult =
529 mVsyncRegistration.schedule({.workDuration = mWorkDuration.get().count(),
530 .readyDuration = mReadyDuration.count(),
531 .earliestVsync = mLastVsyncCallbackTime.ns()});
532 LOG_ALWAYS_FATAL_IF(!scheduleResult, "Error scheduling callback");
533 } else {
534 mVsyncRegistration.cancel();
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700535 }
536
Ady Abraham011f8ba2022-11-22 15:09:07 -0800537 if (!mPendingEvents.empty()) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800538 continue;
539 }
540
541 // Wait for event or client registration/request.
Dominik Laskowski029cc122019-01-23 19:52:06 -0800542 if (mState == State::Idle) {
543 mCondition.wait(lock);
544 } else {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800545 // Generate a fake VSYNC after a long timeout in case the driver stalls. When the
546 // display is off, keep feeding clients at 60 Hz.
Ady Abraham5facfb12020-04-22 15:18:31 -0700547 const std::chrono::nanoseconds timeout =
548 mState == State::SyntheticVSync ? 16ms : 1000ms;
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800549 if (mCondition.wait_for(lock, timeout) == std::cv_status::timeout) {
Ady Abraham5e7371c2020-03-24 14:47:24 -0700550 if (mState == State::VSync) {
551 ALOGW("Faking VSYNC due to driver stall for thread %s", mThreadName);
Ady Abraham5e7371c2020-03-24 14:47:24 -0700552 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800553
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800554 LOG_FATAL_IF(!mVSyncState);
Ady Abraham5facfb12020-04-22 15:18:31 -0700555 const auto now = systemTime(SYSTEM_TIME_MONOTONIC);
Ady Abraham8cb21882020-08-26 18:22:05 -0700556 const auto deadlineTimestamp = now + timeout.count();
557 const auto expectedVSyncTime = deadlineTimestamp + timeout.count();
Ady Abraham5facfb12020-04-22 15:18:31 -0700558 mPendingEvents.push_back(makeVSync(mVSyncState->displayId, now,
Ady Abraham8cb21882020-08-26 18:22:05 -0700559 ++mVSyncState->count, expectedVSyncTime,
Rachel Lee0d943202022-02-01 23:29:41 -0800560 deadlineTimestamp));
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700561 }
562 }
Lloyd Pique46a46b32018-01-31 19:01:18 -0800563 }
Ady Abraham011f8ba2022-11-22 15:09:07 -0800564 // cancel any pending vsync event before exiting
565 mVsyncRegistration.cancel();
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800566}
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700567
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800568bool EventThread::shouldConsumeEvent(const DisplayEventReceiver::Event& event,
569 const sp<EventThreadConnection>& connection) const {
Leon Scroggins IIIed66a352023-03-23 17:55:43 -0400570 const auto throttleVsync = [&]() REQUIRES(mMutex) {
Leon Scroggins III31d41412022-11-18 16:42:53 -0500571 const auto& vsyncData = event.vsync.vsyncData;
Rachel Lee2248f522023-01-27 16:45:23 -0800572 if (connection->frameRate.isValid()) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500573 return !mVsyncSchedule->getTracker()
Rachel Lee2248f522023-01-27 16:45:23 -0800574 .isVSyncInPhase(vsyncData.preferredExpectedPresentationTime(),
575 connection->frameRate);
576 }
577
Ady Abrahamf2851612023-09-25 17:19:00 -0700578 const auto expectedPresentTime =
579 TimePoint::fromNs(event.vsync.vsyncData.preferredExpectedPresentationTime());
580 return mCallback.throttleVsync(expectedPresentTime, connection->mOwnerUid);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700581 };
582
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800583 switch (event.header.type) {
584 case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
585 return true;
586
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100587 case DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE: {
Ady Abraham62f216c2020-10-13 19:07:23 -0700588 return connection->mEventRegistration.test(
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700589 gui::ISurfaceComposer::EventRegistration::modeChanged);
Alec Mouri60aee1c2019-10-28 16:18:59 -0700590 }
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700591
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800592 case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
593 switch (connection->vsyncRequest) {
594 case VSyncRequest::None:
595 return false;
Tim Murrayb5daa912020-09-09 21:29:13 +0000596 case VSyncRequest::SingleSuppressCallback:
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800597 connection->vsyncRequest = VSyncRequest::None;
Tim Murrayb5daa912020-09-09 21:29:13 +0000598 return false;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700599 case VSyncRequest::Single: {
600 if (throttleVsync()) {
601 return false;
602 }
Tim Murrayb5daa912020-09-09 21:29:13 +0000603 connection->vsyncRequest = VSyncRequest::SingleSuppressCallback;
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800604 return true;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700605 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800606 case VSyncRequest::Periodic:
Ady Abraham0bb6a472020-10-12 10:22:13 -0700607 if (throttleVsync()) {
608 return false;
609 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800610 return true;
611 default:
Ady Abraham0bb6a472020-10-12 10:22:13 -0700612 // We don't throttle vsync if the app set a vsync request rate
613 // since there is no easy way to do that and this is a very
614 // rare case
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800615 return event.vsync.count % vsyncPeriod(connection->vsyncRequest) == 0;
616 }
617
Ady Abraham62f216c2020-10-13 19:07:23 -0700618 case DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE:
619 [[fallthrough]];
620 case DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH:
621 return connection->mEventRegistration.test(
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700622 gui::ISurfaceComposer::EventRegistration::frameRateOverride);
Ady Abraham62f216c2020-10-13 19:07:23 -0700623
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800624 default:
625 return false;
626 }
627}
628
Rachel Lee8d0c6102021-11-03 22:00:25 +0000629int64_t EventThread::generateToken(nsecs_t timestamp, nsecs_t deadlineTimestamp,
Rachel Leeb9c5a772022-02-04 21:17:37 -0800630 nsecs_t expectedPresentationTime) const {
Rachel Lee3f028662021-11-04 19:32:24 +0000631 if (mTokenManager != nullptr) {
632 return mTokenManager->generateTokenForPredictions(
Rachel Leeb9c5a772022-02-04 21:17:37 -0800633 {timestamp, deadlineTimestamp, expectedPresentationTime});
Rachel Lee3f028662021-11-04 19:32:24 +0000634 }
635 return FrameTimelineInfo::INVALID_VSYNC_ID;
636}
637
Rachel Leeb9c5a772022-02-04 21:17:37 -0800638void EventThread::generateFrameTimeline(VsyncEventData& outVsyncEventData, nsecs_t frameInterval,
639 nsecs_t timestamp,
640 nsecs_t preferredExpectedPresentationTime,
641 nsecs_t preferredDeadlineTimestamp) const {
Rachel Lee0655a912023-04-20 19:54:18 -0700642 uint32_t currentIndex = 0;
Rachel Lee3f028662021-11-04 19:32:24 +0000643 // Add 1 to ensure the preferredFrameTimelineIndex entry (when multiplier == 0) is included.
Rachel Lee40aef422023-04-25 14:35:47 -0700644 for (int64_t multiplier = -VsyncEventData::kFrameTimelinesCapacity + 1;
645 currentIndex < VsyncEventData::kFrameTimelinesCapacity; multiplier++) {
Rachel Leeb9c5a772022-02-04 21:17:37 -0800646 nsecs_t deadlineTimestamp = preferredDeadlineTimestamp + multiplier * frameInterval;
Rachel Lee0655a912023-04-20 19:54:18 -0700647 // Valid possible frame timelines must have future values, so find a later frame timeline.
648 if (deadlineTimestamp <= timestamp) {
649 continue;
Rachel Lee3f028662021-11-04 19:32:24 +0000650 }
Rachel Lee0655a912023-04-20 19:54:18 -0700651
652 nsecs_t expectedPresentationTime =
653 preferredExpectedPresentationTime + multiplier * frameInterval;
654 if (expectedPresentationTime >= preferredExpectedPresentationTime +
655 scheduler::VsyncConfig::kEarlyLatchMaxThreshold.count()) {
Rachel Leeafb6b502023-05-12 15:53:05 -0700656 if (currentIndex == 0) {
657 ALOGW("%s: Expected present time is too far in the future but no timelines are "
658 "valid. preferred EPT=%" PRId64 ", Calculated EPT=%" PRId64
659 ", multiplier=%" PRId64 ", frameInterval=%" PRId64 ", threshold=%" PRId64,
660 __func__, preferredExpectedPresentationTime, expectedPresentationTime,
661 multiplier, frameInterval,
662 static_cast<int64_t>(
663 scheduler::VsyncConfig::kEarlyLatchMaxThreshold.count()));
664 }
Rachel Lee0655a912023-04-20 19:54:18 -0700665 break;
666 }
667
668 if (multiplier == 0) {
669 outVsyncEventData.preferredFrameTimelineIndex = currentIndex;
670 }
671
672 outVsyncEventData.frameTimelines[currentIndex] =
673 {.vsyncId = generateToken(timestamp, deadlineTimestamp, expectedPresentationTime),
674 .deadlineTimestamp = deadlineTimestamp,
675 .expectedPresentationTime = expectedPresentationTime};
676 currentIndex++;
Rachel Lee3f028662021-11-04 19:32:24 +0000677 }
Rachel Leeafb6b502023-05-12 15:53:05 -0700678
679 if (currentIndex == 0) {
680 ALOGW("%s: No timelines are valid. preferred EPT=%" PRId64 ", frameInterval=%" PRId64
681 ", threshold=%" PRId64,
682 __func__, preferredExpectedPresentationTime, frameInterval,
683 static_cast<int64_t>(scheduler::VsyncConfig::kEarlyLatchMaxThreshold.count()));
684 outVsyncEventData.frameTimelines[currentIndex] =
685 {.vsyncId = generateToken(timestamp, preferredDeadlineTimestamp,
686 preferredExpectedPresentationTime),
687 .deadlineTimestamp = preferredDeadlineTimestamp,
688 .expectedPresentationTime = preferredExpectedPresentationTime};
689 currentIndex++;
690 }
691
Rachel Lee0655a912023-04-20 19:54:18 -0700692 outVsyncEventData.frameTimelinesLength = currentIndex;
Rachel Lee3f028662021-11-04 19:32:24 +0000693}
694
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800695void EventThread::dispatchEvent(const DisplayEventReceiver::Event& event,
696 const DisplayEventConsumers& consumers) {
697 for (const auto& consumer : consumers) {
Jorim Jaggic0086af2021-02-12 18:18:11 +0100698 DisplayEventReceiver::Event copy = event;
699 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_VSYNC) {
Ady Abrahamf2851612023-09-25 17:19:00 -0700700 const Period frameInterval = mCallback.getVsyncPeriod(consumer->mOwnerUid);
701 copy.vsync.vsyncData.frameInterval = frameInterval.ns();
702 generateFrameTimeline(copy.vsync.vsyncData, frameInterval.ns(), copy.header.timestamp,
Rachel Leeb9c5a772022-02-04 21:17:37 -0800703 event.vsync.vsyncData.preferredExpectedPresentationTime(),
704 event.vsync.vsyncData.preferredDeadlineTimestamp());
Jorim Jaggic0086af2021-02-12 18:18:11 +0100705 }
706 switch (consumer->postEvent(copy)) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800707 case NO_ERROR:
708 break;
709
710 case -EAGAIN:
711 // TODO: Try again if pipe is full.
712 ALOGW("Failed dispatching %s for %s", toString(event).c_str(),
713 toString(*consumer).c_str());
714 break;
715
716 default:
717 // Treat EPIPE and other errors as fatal.
718 removeDisplayEventConnectionLocked(consumer);
719 }
720 }
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700721}
722
Yiwei Zhang5434a782018-12-05 18:06:32 -0800723void EventThread::dump(std::string& result) const {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800724 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800725
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800726 StringAppendF(&result, "%s: state=%s VSyncState=", mThreadName, toCString(mState));
727 if (mVSyncState) {
Marin Shalamanova524a092020-07-27 21:39:55 +0200728 StringAppendF(&result, "{displayId=%s, count=%u%s}\n",
729 to_string(mVSyncState->displayId).c_str(), mVSyncState->count,
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800730 mVSyncState->synthetic ? ", synthetic" : "");
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800731 } else {
732 StringAppendF(&result, "none\n");
733 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800734
Ady Abraham011f8ba2022-11-22 15:09:07 -0800735 const auto relativeLastCallTime =
736 ticks<std::milli, float>(mLastVsyncCallbackTime - TimePoint::now());
737 StringAppendF(&result, "mWorkDuration=%.2f mReadyDuration=%.2f last vsync time ",
738 mWorkDuration.get().count() / 1e6f, mReadyDuration.count() / 1e6f);
739 StringAppendF(&result, "%.2fms relative to now\n", relativeLastCallTime);
740
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800741 StringAppendF(&result, " pending events (count=%zu):\n", mPendingEvents.size());
742 for (const auto& event : mPendingEvents) {
743 StringAppendF(&result, " %s\n", toString(event).c_str());
Mathias Agopiane2c4f4e2012-04-10 18:25:31 -0700744 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800745
746 StringAppendF(&result, " connections (count=%zu):\n", mDisplayEventConnections.size());
747 for (const auto& ptr : mDisplayEventConnections) {
748 if (const auto connection = ptr.promote()) {
749 StringAppendF(&result, " %s\n", toString(*connection).c_str());
750 }
751 }
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400752 result += '\n';
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800753}
754
Dominik Laskowski029cc122019-01-23 19:52:06 -0800755const char* EventThread::toCString(State state) {
756 switch (state) {
757 case State::Idle:
758 return "Idle";
759 case State::Quit:
760 return "Quit";
761 case State::SyntheticVSync:
762 return "SyntheticVSync";
763 case State::VSync:
764 return "VSync";
765 }
766}
767
Leon Scroggins III67388622023-02-06 20:36:20 -0500768void EventThread::onNewVsyncSchedule(std::shared_ptr<scheduler::VsyncSchedule> schedule) {
Leon Scroggins IIIb2253602023-04-19 17:04:04 -0400769 // Hold onto the old registration until after releasing the mutex to avoid deadlock.
770 scheduler::VSyncCallbackRegistration oldRegistration =
771 onNewVsyncScheduleInternal(std::move(schedule));
772}
773
774scheduler::VSyncCallbackRegistration EventThread::onNewVsyncScheduleInternal(
775 std::shared_ptr<scheduler::VsyncSchedule> schedule) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500776 std::lock_guard<std::mutex> lock(mMutex);
777 const bool reschedule = mVsyncRegistration.cancel() == scheduler::CancelResult::Cancelled;
778 mVsyncSchedule = std::move(schedule);
Leon Scroggins IIIb2253602023-04-19 17:04:04 -0400779 auto oldRegistration =
780 std::exchange(mVsyncRegistration,
781 scheduler::VSyncCallbackRegistration(mVsyncSchedule->getDispatch(),
782 createDispatchCallback(),
783 mThreadName));
Leon Scroggins III67388622023-02-06 20:36:20 -0500784 if (reschedule) {
785 mVsyncRegistration.schedule({.workDuration = mWorkDuration.get().count(),
786 .readyDuration = mReadyDuration.count(),
787 .earliestVsync = mLastVsyncCallbackTime.ns()});
788 }
Leon Scroggins IIIb2253602023-04-19 17:04:04 -0400789 return oldRegistration;
Leon Scroggins III67388622023-02-06 20:36:20 -0500790}
791
792scheduler::VSyncDispatch::Callback EventThread::createDispatchCallback() {
793 return [this](nsecs_t vsyncTime, nsecs_t wakeupTime, nsecs_t readyTime) {
794 onVsync(vsyncTime, wakeupTime, readyTime);
795 };
796}
797
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800798} // namespace impl
Lloyd Pique46a46b32018-01-31 19:01:18 -0800799} // namespace android
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800800
801// TODO(b/129481165): remove the #pragma below and fix conversion issues
802#pragma clang diagnostic pop // ignored "-Wconversion"