blob: 24d387a49800a7365dddd8f50a23f20c130a7ec0 [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>
Vishnu Nairbe0ad902024-06-27 23:38:43 +000036#include <common/trace.h>
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>
44
Alec Mouri9b133ca2023-11-14 19:00:01 +000045#include <common/FlagManager.h>
Rachel Lee0655a912023-04-20 19:54:18 -070046#include <scheduler/VsyncConfig.h>
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -070047#include "FrameTimeline.h"
Ady Abraham011f8ba2022-11-22 15:09:07 -080048#include "VSyncDispatch.h"
Marin Shalamanov23c44202020-12-22 19:09:20 +010049
50#include "EventThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080051
Ady Abraham62f216c2020-10-13 19:07:23 -070052#undef LOG_TAG
53#define LOG_TAG "EventThread"
54
Lloyd Pique46a46b32018-01-31 19:01:18 -080055using namespace std::chrono_literals;
Mathias Agopiand0566bc2011-11-17 17:49:17 -080056
Lloyd Pique46a46b32018-01-31 19:01:18 -080057namespace android {
58
Dominik Laskowskid9e4de62019-01-21 14:23:01 -080059using base::StringAppendF;
60using base::StringPrintf;
61
62namespace {
63
64auto vsyncPeriod(VSyncRequest request) {
65 return static_cast<std::underlying_type_t<VSyncRequest>>(request);
66}
67
68std::string toString(VSyncRequest request) {
69 switch (request) {
70 case VSyncRequest::None:
71 return "VSyncRequest::None";
72 case VSyncRequest::Single:
73 return "VSyncRequest::Single";
Tim Murrayb5daa912020-09-09 21:29:13 +000074 case VSyncRequest::SingleSuppressCallback:
75 return "VSyncRequest::SingleSuppressCallback";
Dominik Laskowskid9e4de62019-01-21 14:23:01 -080076 default:
77 return StringPrintf("VSyncRequest::Periodic{period=%d}", vsyncPeriod(request));
78 }
79}
80
81std::string toString(const EventThreadConnection& connection) {
82 return StringPrintf("Connection{%p, %s}", &connection,
83 toString(connection.vsyncRequest).c_str());
84}
85
86std::string toString(const DisplayEventReceiver::Event& event) {
87 switch (event.header.type) {
88 case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
Marin Shalamanova524a092020-07-27 21:39:55 +020089 return StringPrintf("Hotplug{displayId=%s, %s}",
90 to_string(event.header.displayId).c_str(),
Dominik Laskowskid9e4de62019-01-21 14:23:01 -080091 event.hotplug.connected ? "connected" : "disconnected");
92 case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
Rachel Leeb9c5a772022-02-04 21:17:37 -080093 return StringPrintf("VSync{displayId=%s, count=%u, expectedPresentationTime=%" PRId64
94 "}",
Marin Shalamanova524a092020-07-27 21:39:55 +020095 to_string(event.header.displayId).c_str(), event.vsync.count,
Rachel Leeb9c5a772022-02-04 21:17:37 -080096 event.vsync.vsyncData.preferredExpectedPresentationTime());
Marin Shalamanova7fe3042021-01-29 21:02:08 +010097 case DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE:
98 return StringPrintf("ModeChanged{displayId=%s, modeId=%u}",
99 to_string(event.header.displayId).c_str(), event.modeChange.modeId);
Huihong Luo9ebb7a72023-06-27 17:01:50 -0700100 case DisplayEventReceiver::DISPLAY_EVENT_HDCP_LEVELS_CHANGE:
101 return StringPrintf("HdcpLevelsChange{displayId=%s, connectedLevel=%d, maxLevel=%d}",
102 to_string(event.header.displayId).c_str(),
103 event.hdcpLevelsChange.connectedLevel,
104 event.hdcpLevelsChange.maxLevel);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800105 default:
106 return "Event{}";
107 }
108}
109
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800110DisplayEventReceiver::Event makeHotplug(PhysicalDisplayId displayId, nsecs_t timestamp,
111 bool connected) {
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800112 DisplayEventReceiver::Event event;
113 event.header = {DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG, displayId, timestamp};
114 event.hotplug.connected = connected;
115 return event;
116}
117
Brian Johnson5dcd75d2023-08-15 09:36:37 -0700118DisplayEventReceiver::Event makeHotplugError(nsecs_t timestamp, int32_t connectionError) {
119 DisplayEventReceiver::Event event;
120 PhysicalDisplayId unusedDisplayId;
121 event.header = {DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG, unusedDisplayId, timestamp};
122 event.hotplug.connected = false;
123 event.hotplug.connectionError = connectionError;
124 return event;
125}
126
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800127DisplayEventReceiver::Event makeVSync(PhysicalDisplayId displayId, nsecs_t timestamp,
Rachel Leeb9c5a772022-02-04 21:17:37 -0800128 uint32_t count, nsecs_t expectedPresentationTime,
Rachel Lee0d943202022-02-01 23:29:41 -0800129 nsecs_t deadlineTimestamp) {
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800130 DisplayEventReceiver::Event event;
131 event.header = {DisplayEventReceiver::DISPLAY_EVENT_VSYNC, displayId, timestamp};
132 event.vsync.count = count;
Rachel Leeb9c5a772022-02-04 21:17:37 -0800133 event.vsync.vsyncData.preferredFrameTimelineIndex = 0;
134 // Temporarily store the current vsync information in frameTimelines[0], marked as
135 // platform-preferred. When the event is dispatched later, the frame interval at that time is
136 // used with this information to generate multiple frame timeline choices.
137 event.vsync.vsyncData.frameTimelines[0] = {.vsyncId = FrameTimelineInfo::INVALID_VSYNC_ID,
138 .deadlineTimestamp = deadlineTimestamp,
139 .expectedPresentationTime =
140 expectedPresentationTime};
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800141 return event;
142}
143
Ady Abraham67434eb2022-12-01 17:48:12 -0800144DisplayEventReceiver::Event makeModeChanged(const scheduler::FrameRateMode& mode) {
Ady Abraham447052e2019-02-13 16:07:27 -0800145 DisplayEventReceiver::Event event;
Ady Abraham67434eb2022-12-01 17:48:12 -0800146 event.header = {DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE,
147 mode.modePtr->getPhysicalDisplayId(), systemTime()};
Dominik Laskowski43baf902023-11-17 18:13:11 -0500148 event.modeChange.modeId = ftl::to_underlying(mode.modePtr->getId());
Ady Abraham67434eb2022-12-01 17:48:12 -0800149 event.modeChange.vsyncPeriod = mode.fps.getPeriodNsecs();
Ady Abraham447052e2019-02-13 16:07:27 -0800150 return event;
151}
152
Ady Abraham62f216c2020-10-13 19:07:23 -0700153DisplayEventReceiver::Event makeFrameRateOverrideEvent(PhysicalDisplayId displayId,
154 FrameRateOverride frameRateOverride) {
155 return DisplayEventReceiver::Event{
156 .header =
157 DisplayEventReceiver::Event::Header{
158 .type = DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE,
159 .displayId = displayId,
160 .timestamp = systemTime(),
161 },
162 .frameRateOverride = frameRateOverride,
163 };
164}
165
166DisplayEventReceiver::Event makeFrameRateOverrideFlushEvent(PhysicalDisplayId displayId) {
167 return DisplayEventReceiver::Event{
168 .header = DisplayEventReceiver::Event::Header{
169 .type = DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH,
170 .displayId = displayId,
171 .timestamp = systemTime(),
172 }};
173}
174
Huihong Luo9ebb7a72023-06-27 17:01:50 -0700175DisplayEventReceiver::Event makeHdcpLevelsChange(PhysicalDisplayId displayId,
176 int32_t connectedLevel, int32_t maxLevel) {
177 return DisplayEventReceiver::Event{
178 .header =
179 DisplayEventReceiver::Event::Header{
180 .type = DisplayEventReceiver::DISPLAY_EVENT_HDCP_LEVELS_CHANGE,
181 .displayId = displayId,
182 .timestamp = systemTime(),
183 },
184 .hdcpLevelsChange.connectedLevel = connectedLevel,
185 .hdcpLevelsChange.maxLevel = maxLevel,
186 };
187}
188
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800189} // namespace
Lloyd Pique46a46b32018-01-31 19:01:18 -0800190
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700191EventThreadConnection::EventThreadConnection(EventThread* eventThread, uid_t callingUid,
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700192 EventRegistrationFlags eventRegistration)
Ady Abrahamf2851612023-09-25 17:19:00 -0700193 : mOwnerUid(callingUid),
Ady Abraham62f216c2020-10-13 19:07:23 -0700194 mEventRegistration(eventRegistration),
Dominik Laskowskif654d572018-12-20 11:03:06 -0800195 mEventThread(eventThread),
196 mChannel(gui::BitTube::DefaultSize) {}
Ana Krulec85c39af2018-12-26 17:29:57 -0800197
198EventThreadConnection::~EventThreadConnection() {
199 // do nothing here -- clean-up will happen automatically
200 // when the main thread wakes up
201}
202
203void EventThreadConnection::onFirstRef() {
204 // NOTE: mEventThread doesn't hold a strong reference on us
Ady Abrahamd11bade2022-08-01 16:18:03 -0700205 mEventThread->registerDisplayEventConnection(sp<EventThreadConnection>::fromExisting(this));
Ana Krulec85c39af2018-12-26 17:29:57 -0800206}
207
Huihong Luo6fac5232021-11-22 16:05:23 -0800208binder::Status EventThreadConnection::stealReceiveChannel(gui::BitTube* outChannel) {
Ady Abraham899e8cd2022-06-06 15:16:06 -0700209 std::scoped_lock lock(mLock);
210 if (mChannel.initCheck() != NO_ERROR) {
211 return binder::Status::fromStatusT(NAME_NOT_FOUND);
212 }
213
Ana Krulec85c39af2018-12-26 17:29:57 -0800214 outChannel->setReceiveFd(mChannel.moveReceiveFd());
Alec Mouri967d5d72020-08-05 12:50:03 -0700215 outChannel->setSendFd(base::unique_fd(dup(mChannel.getSendFd())));
Huihong Luo6fac5232021-11-22 16:05:23 -0800216 return binder::Status::ok();
Ana Krulec85c39af2018-12-26 17:29:57 -0800217}
218
Huihong Luo6fac5232021-11-22 16:05:23 -0800219binder::Status EventThreadConnection::setVsyncRate(int rate) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700220 mEventThread->setVsyncRate(static_cast<uint32_t>(rate),
221 sp<EventThreadConnection>::fromExisting(this));
Huihong Luo6fac5232021-11-22 16:05:23 -0800222 return binder::Status::ok();
Ana Krulec85c39af2018-12-26 17:29:57 -0800223}
224
Huihong Luo6fac5232021-11-22 16:05:23 -0800225binder::Status EventThreadConnection::requestNextVsync() {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000226 SFTRACE_CALL();
Ady Abrahamd11bade2022-08-01 16:18:03 -0700227 mEventThread->requestNextVsync(sp<EventThreadConnection>::fromExisting(this));
Huihong Luo6fac5232021-11-22 16:05:23 -0800228 return binder::Status::ok();
Ana Krulec85c39af2018-12-26 17:29:57 -0800229}
230
Rachel Leeb9c5a772022-02-04 21:17:37 -0800231binder::Status EventThreadConnection::getLatestVsyncEventData(
232 ParcelableVsyncEventData* outVsyncEventData) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000233 SFTRACE_CALL();
Ady Abrahamd11bade2022-08-01 16:18:03 -0700234 outVsyncEventData->vsync =
Ady Abraham40ec5842024-04-04 13:22:38 -0700235 mEventThread->getLatestVsyncEventData(sp<EventThreadConnection>::fromExisting(this),
236 systemTime());
Rachel Leeef2e21f2022-02-01 14:51:34 -0800237 return binder::Status::ok();
238}
239
Ady Abraham07d03c42023-09-27 19:15:08 -0700240binder::Status EventThreadConnection::getSchedulingPolicy(gui::SchedulingPolicy* outPolicy) {
241 return gui::getSchedulingPolicy(outPolicy);
242}
243
Ana Krulec85c39af2018-12-26 17:29:57 -0800244status_t EventThreadConnection::postEvent(const DisplayEventReceiver::Event& event) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700245 constexpr auto toStatus = [](ssize_t size) {
246 return size < 0 ? status_t(size) : status_t(NO_ERROR);
247 };
248
249 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE ||
250 event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH) {
251 mPendingEvents.emplace_back(event);
252 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE) {
253 return status_t(NO_ERROR);
254 }
255
256 auto size = DisplayEventReceiver::sendEvents(&mChannel, mPendingEvents.data(),
257 mPendingEvents.size());
258 mPendingEvents.clear();
259 return toStatus(size);
260 }
261
262 auto size = DisplayEventReceiver::sendEvents(&mChannel, &event, 1);
263 return toStatus(size);
Ana Krulec85c39af2018-12-26 17:29:57 -0800264}
265
266// ---------------------------------------------------------------------------
267
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800268EventThread::~EventThread() = default;
269
270namespace impl {
271
Leon Scroggins III67388622023-02-06 20:36:20 -0500272EventThread::EventThread(const char* name, std::shared_ptr<scheduler::VsyncSchedule> vsyncSchedule,
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700273 android::frametimeline::TokenManager* tokenManager,
Ady Abrahamf2851612023-09-25 17:19:00 -0700274 IEventThreadCallback& callback, std::chrono::nanoseconds workDuration,
Ady Abraham011f8ba2022-11-22 15:09:07 -0800275 std::chrono::nanoseconds readyDuration)
276 : mThreadName(name),
277 mVsyncTracer(base::StringPrintf("VSYNC-%s", name), 0),
278 mWorkDuration(base::StringPrintf("VsyncWorkDuration-%s", name), workDuration),
279 mReadyDuration(readyDuration),
Leon Scroggins III67388622023-02-06 20:36:20 -0500280 mVsyncSchedule(std::move(vsyncSchedule)),
281 mVsyncRegistration(mVsyncSchedule->getDispatch(), createDispatchCallback(), name),
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700282 mTokenManager(tokenManager),
Ady Abrahamf2851612023-09-25 17:19:00 -0700283 mCallback(callback) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800284 mThread = std::thread([this]() NO_THREAD_SAFETY_ANALYSIS {
285 std::unique_lock<std::mutex> lock(mMutex);
286 threadMain(lock);
287 });
Lloyd Pique46a46b32018-01-31 19:01:18 -0800288
Dominik Laskowski6505f792019-09-18 11:10:05 -0700289 pthread_setname_np(mThread.native_handle(), mThreadName);
Lloyd Pique46a46b32018-01-31 19:01:18 -0800290
291 pid_t tid = pthread_gettid_np(mThread.native_handle());
292
293 // Use SCHED_FIFO to minimize jitter
294 constexpr int EVENT_THREAD_PRIORITY = 2;
295 struct sched_param param = {0};
296 param.sched_priority = EVENT_THREAD_PRIORITY;
297 if (pthread_setschedparam(mThread.native_handle(), SCHED_FIFO, &param) != 0) {
298 ALOGE("Couldn't set SCHED_FIFO for EventThread");
299 }
300
301 set_sched_policy(tid, SP_FOREGROUND);
302}
303
304EventThread::~EventThread() {
305 {
306 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski029cc122019-01-23 19:52:06 -0800307 mState = State::Quit;
Lloyd Pique46a46b32018-01-31 19:01:18 -0800308 mCondition.notify_all();
309 }
310 mThread.join();
Ruchi Kandoief472ec2014-04-02 12:50:06 -0700311}
312
Ady Abraham9c53ee72020-07-22 21:16:18 -0700313void EventThread::setDuration(std::chrono::nanoseconds workDuration,
314 std::chrono::nanoseconds readyDuration) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800315 std::lock_guard<std::mutex> lock(mMutex);
Ady Abraham011f8ba2022-11-22 15:09:07 -0800316 mWorkDuration = workDuration;
317 mReadyDuration = readyDuration;
318
319 mVsyncRegistration.update({.workDuration = mWorkDuration.get().count(),
320 .readyDuration = mReadyDuration.count(),
ramindani92ab9872024-07-26 15:09:37 -0700321 .lastVsync = mLastVsyncCallbackTime.ns(),
322 .committedVsyncOpt = mLastCommittedVsyncTime.ns()});
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700323}
324
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700325sp<EventThreadConnection> EventThread::createEventConnection(
Ady Abrahamf2851612023-09-25 17:19:00 -0700326 EventRegistrationFlags eventRegistration) const {
Ady Abraham07d03c42023-09-27 19:15:08 -0700327 auto connection = sp<EventThreadConnection>::make(const_cast<EventThread*>(this),
328 IPCThreadState::self()->getCallingUid(),
329 eventRegistration);
Ady Abrahamd6d80162023-10-23 12:57:41 -0700330 if (FlagManager::getInstance().misc1()) {
Ady Abraham07d03c42023-09-27 19:15:08 -0700331 const int policy = SCHED_FIFO;
332 connection->setMinSchedulerPolicy(policy, sched_get_priority_min(policy));
333 }
334 return connection;
Mathias Agopian8aedd472012-01-24 16:39:14 -0800335}
336
Ana Krulec85c39af2018-12-26 17:29:57 -0800337status_t EventThread::registerDisplayEventConnection(const sp<EventThreadConnection>& connection) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800338 std::lock_guard<std::mutex> lock(mMutex);
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700339
340 // this should never happen
341 auto it = std::find(mDisplayEventConnections.cbegin(),
342 mDisplayEventConnections.cend(), connection);
343 if (it != mDisplayEventConnections.cend()) {
344 ALOGW("DisplayEventConnection %p already exists", connection.get());
345 mCondition.notify_all();
346 return ALREADY_EXISTS;
347 }
348
349 mDisplayEventConnections.push_back(connection);
Lloyd Pique46a46b32018-01-31 19:01:18 -0800350 mCondition.notify_all();
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800351 return NO_ERROR;
352}
353
Ana Krulec85c39af2018-12-26 17:29:57 -0800354void EventThread::removeDisplayEventConnectionLocked(const wp<EventThreadConnection>& connection) {
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700355 auto it = std::find(mDisplayEventConnections.cbegin(),
356 mDisplayEventConnections.cend(), connection);
357 if (it != mDisplayEventConnections.cend()) {
358 mDisplayEventConnections.erase(it);
359 }
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800360}
361
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800362void EventThread::setVsyncRate(uint32_t rate, const sp<EventThreadConnection>& connection) {
363 if (static_cast<std::underlying_type_t<VSyncRequest>>(rate) < 0) {
364 return;
365 }
366
367 std::lock_guard<std::mutex> lock(mMutex);
368
369 const auto request = rate == 0 ? VSyncRequest::None : static_cast<VSyncRequest>(rate);
370 if (connection->vsyncRequest != request) {
371 connection->vsyncRequest = request;
372 mCondition.notify_all();
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800373 }
374}
375
Ady Abraham8532d012019-05-08 14:50:56 -0700376void EventThread::requestNextVsync(const sp<EventThreadConnection>& connection) {
Ady Abrahamf2851612023-09-25 17:19:00 -0700377 mCallback.resync();
Tim Murray4a4e4a22016-04-19 16:29:23 +0000378
Ana Krulec7d1d6832018-12-27 11:10:09 -0800379 std::lock_guard<std::mutex> lock(mMutex);
380
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800381 if (connection->vsyncRequest == VSyncRequest::None) {
382 connection->vsyncRequest = VSyncRequest::Single;
Lloyd Pique46a46b32018-01-31 19:01:18 -0800383 mCondition.notify_all();
Tim Murrayb5daa912020-09-09 21:29:13 +0000384 } else if (connection->vsyncRequest == VSyncRequest::SingleSuppressCallback) {
385 connection->vsyncRequest = VSyncRequest::Single;
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800386 }
Mathias Agopian23748662011-12-05 14:33:34 -0800387}
388
Ady Abraham40ec5842024-04-04 13:22:38 -0700389VsyncEventData EventThread::getLatestVsyncEventData(const sp<EventThreadConnection>& connection,
390 nsecs_t now) const {
Rachel Leeb5223cf2022-03-14 14:39:27 -0700391 // Resync so that the vsync is accurate with hardware. getLatestVsyncEventData is an alternate
392 // way to get vsync data (instead of posting callbacks to Choreographer).
Ady Abrahamf2851612023-09-25 17:19:00 -0700393 mCallback.resync();
Rachel Leeb5223cf2022-03-14 14:39:27 -0700394
Rachel Leeef2e21f2022-02-01 14:51:34 -0800395 VsyncEventData vsyncEventData;
Ady Abrahamf2851612023-09-25 17:19:00 -0700396 const Period frameInterval = mCallback.getVsyncPeriod(connection->mOwnerUid);
397 vsyncEventData.frameInterval = frameInterval.ns();
Ady Abraham011f8ba2022-11-22 15:09:07 -0800398 const auto [presentTime, deadline] = [&]() -> std::pair<nsecs_t, nsecs_t> {
Rachel Leeb9c5a772022-02-04 21:17:37 -0800399 std::lock_guard<std::mutex> lock(mMutex);
Leon Scroggins III67388622023-02-06 20:36:20 -0500400 const auto vsyncTime = mVsyncSchedule->getTracker().nextAnticipatedVSyncTimeFrom(
Ady Abraham40ec5842024-04-04 13:22:38 -0700401 now + mWorkDuration.get().count() + mReadyDuration.count());
Ady Abraham011f8ba2022-11-22 15:09:07 -0800402 return {vsyncTime, vsyncTime - mReadyDuration.count()};
403 }();
Ady Abraham40ec5842024-04-04 13:22:38 -0700404 generateFrameTimeline(vsyncEventData, frameInterval.ns(), now, presentTime, deadline);
ramindaniae645822024-01-11 10:57:29 -0800405 if (FlagManager::getInstance().vrr_config()) {
406 mCallback.onExpectedPresentTimePosted(TimePoint::fromNs(presentTime));
407 }
Rachel Leeef2e21f2022-02-01 14:51:34 -0800408 return vsyncEventData;
409}
410
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500411void EventThread::enableSyntheticVsync(bool enable) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800412 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500413 if (!mVSyncState || mVSyncState->synthetic == enable) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800414 return;
Mathias Agopian22ffb112012-04-10 21:04:02 -0700415 }
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800416
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500417 mVSyncState->synthetic = enable;
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800418 mCondition.notify_all();
Mathias Agopian22ffb112012-04-10 21:04:02 -0700419}
420
Ady Abraham011f8ba2022-11-22 15:09:07 -0800421void EventThread::onVsync(nsecs_t vsyncTime, nsecs_t wakeupTime, nsecs_t readyTime) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800422 std::lock_guard<std::mutex> lock(mMutex);
Ady Abraham011f8ba2022-11-22 15:09:07 -0800423 mLastVsyncCallbackTime = TimePoint::fromNs(vsyncTime);
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800424
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800425 LOG_FATAL_IF(!mVSyncState);
Ady Abraham011f8ba2022-11-22 15:09:07 -0800426 mVsyncTracer = (mVsyncTracer + 1) % 2;
Ben Widawsky59954c42024-09-16 14:52:59 -0700427 mPendingEvents.push_back(makeVSync(mVsyncSchedule->getPhysicalDisplayId(), wakeupTime,
428 ++mVSyncState->count, vsyncTime, readyTime));
Lloyd Pique46a46b32018-01-31 19:01:18 -0800429 mCondition.notify_all();
Mathias Agopian3eb38cb2012-04-03 22:09:52 -0700430}
431
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800432void EventThread::onHotplugReceived(PhysicalDisplayId displayId, bool connected) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800433 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -0700434
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800435 mPendingEvents.push_back(makeHotplug(displayId, systemTime(), connected));
Dominik Laskowski00a6fa22018-06-06 16:42:02 -0700436 mCondition.notify_all();
Mathias Agopian148994e2012-09-19 17:31:36 -0700437}
438
Brian Johnson5dcd75d2023-08-15 09:36:37 -0700439void EventThread::onHotplugConnectionError(int32_t errorCode) {
440 std::lock_guard<std::mutex> lock(mMutex);
441
442 mPendingEvents.push_back(makeHotplugError(systemTime(), errorCode));
443 mCondition.notify_all();
444}
445
Ady Abraham67434eb2022-12-01 17:48:12 -0800446void EventThread::onModeChanged(const scheduler::FrameRateMode& mode) {
Ady Abraham447052e2019-02-13 16:07:27 -0800447 std::lock_guard<std::mutex> lock(mMutex);
448
Ady Abraham690f4612021-07-01 23:24:03 -0700449 mPendingEvents.push_back(makeModeChanged(mode));
Ady Abraham447052e2019-02-13 16:07:27 -0800450 mCondition.notify_all();
451}
452
Ady Abraham62f216c2020-10-13 19:07:23 -0700453void EventThread::onFrameRateOverridesChanged(PhysicalDisplayId displayId,
454 std::vector<FrameRateOverride> overrides) {
455 std::lock_guard<std::mutex> lock(mMutex);
456
457 for (auto frameRateOverride : overrides) {
458 mPendingEvents.push_back(makeFrameRateOverrideEvent(displayId, frameRateOverride));
459 }
460 mPendingEvents.push_back(makeFrameRateOverrideFlushEvent(displayId));
461
462 mCondition.notify_all();
463}
464
Huihong Luo9ebb7a72023-06-27 17:01:50 -0700465void EventThread::onHdcpLevelsChanged(PhysicalDisplayId displayId, int32_t connectedLevel,
466 int32_t maxLevel) {
467 std::lock_guard<std::mutex> lock(mMutex);
468
469 mPendingEvents.push_back(makeHdcpLevelsChange(displayId, connectedLevel, maxLevel));
470 mCondition.notify_all();
471}
472
Melody Hsue524dd92024-08-27 22:27:29 +0000473// Merge lists of buffer stuffed Uids
474void EventThread::addBufferStuffedUids(BufferStuffingMap bufferStuffedUids) {
475 std::lock_guard<std::mutex> lock(mMutex);
476 for (auto& [uid, count] : bufferStuffedUids) {
477 mBufferStuffedUids.emplace_or_replace(uid, count);
478 }
479}
480
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800481void EventThread::threadMain(std::unique_lock<std::mutex>& lock) {
482 DisplayEventConsumers consumers;
483
Dominik Laskowski029cc122019-01-23 19:52:06 -0800484 while (mState != State::Quit) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800485 std::optional<DisplayEventReceiver::Event> event;
Mathias Agopian3eb38cb2012-04-03 22:09:52 -0700486
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800487 // Determine next event to dispatch.
488 if (!mPendingEvents.empty()) {
489 event = mPendingEvents.front();
490 mPendingEvents.pop_front();
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800491
Huihong Luoab8ffef2022-08-18 13:02:26 -0700492 if (event->header.type == DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG) {
Brian Johnson5dcd75d2023-08-15 09:36:37 -0700493 if (event->hotplug.connectionError == 0) {
494 if (event->hotplug.connected && !mVSyncState) {
Ben Widawsky59954c42024-09-16 14:52:59 -0700495 mVSyncState.emplace();
496 } else if (!event->hotplug.connected &&
497 mVsyncSchedule->getPhysicalDisplayId() == event->header.displayId) {
Brian Johnson5dcd75d2023-08-15 09:36:37 -0700498 mVSyncState.reset();
499 }
500 } else {
501 // Ignore vsync stuff on an error.
Huihong Luoab8ffef2022-08-18 13:02:26 -0700502 }
Dominik Laskowski029cc122019-01-23 19:52:06 -0800503 }
Mathias Agopianff28e202012-09-20 23:24:19 -0700504 }
505
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800506 bool vsyncRequested = false;
Mathias Agopian148994e2012-09-19 17:31:36 -0700507
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800508 // Find connections that should consume this event.
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700509 auto it = mDisplayEventConnections.begin();
510 while (it != mDisplayEventConnections.end()) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800511 if (const auto connection = it->promote()) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800512 if (event && shouldConsumeEvent(*event, connection)) {
513 consumers.push_back(connection);
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700514 }
Mathias Agopianb4d18ed2012-09-20 23:14:05 -0700515
Ady Abraham011f8ba2022-11-22 15:09:07 -0800516 vsyncRequested |= connection->vsyncRequest != VSyncRequest::None;
517
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700518 ++it;
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700519 } else {
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700520 it = mDisplayEventConnections.erase(it);
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700521 }
522 }
523
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800524 if (!consumers.empty()) {
525 dispatchEvent(*event, consumers);
526 consumers.clear();
527 }
528
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800529 if (mVSyncState && vsyncRequested) {
Ady Abraham011f8ba2022-11-22 15:09:07 -0800530 mState = mVSyncState->synthetic ? State::SyntheticVSync : State::VSync;
Dominik Laskowski029cc122019-01-23 19:52:06 -0800531 } else {
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800532 ALOGW_IF(!mVSyncState, "Ignoring VSYNC request while display is disconnected");
Ady Abraham011f8ba2022-11-22 15:09:07 -0800533 mState = State::Idle;
Dominik Laskowski029cc122019-01-23 19:52:06 -0800534 }
535
Ady Abraham011f8ba2022-11-22 15:09:07 -0800536 if (mState == State::VSync) {
ramindani92ab9872024-07-26 15:09:37 -0700537 const auto scheduleResult = mVsyncRegistration.schedule(
538 {.workDuration = mWorkDuration.get().count(),
539 .readyDuration = mReadyDuration.count(),
540 .lastVsync = mLastVsyncCallbackTime.ns(),
541 .committedVsyncOpt = mLastCommittedVsyncTime.ns()});
Ady Abraham011f8ba2022-11-22 15:09:07 -0800542 LOG_ALWAYS_FATAL_IF(!scheduleResult, "Error scheduling callback");
543 } else {
544 mVsyncRegistration.cancel();
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700545 }
546
Ady Abraham011f8ba2022-11-22 15:09:07 -0800547 if (!mPendingEvents.empty()) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800548 continue;
549 }
550
551 // Wait for event or client registration/request.
Dominik Laskowski029cc122019-01-23 19:52:06 -0800552 if (mState == State::Idle) {
553 mCondition.wait(lock);
554 } else {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800555 // Generate a fake VSYNC after a long timeout in case the driver stalls. When the
556 // display is off, keep feeding clients at 60 Hz.
Ady Abraham5facfb12020-04-22 15:18:31 -0700557 const std::chrono::nanoseconds timeout =
558 mState == State::SyntheticVSync ? 16ms : 1000ms;
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800559 if (mCondition.wait_for(lock, timeout) == std::cv_status::timeout) {
Ady Abraham5e7371c2020-03-24 14:47:24 -0700560 if (mState == State::VSync) {
561 ALOGW("Faking VSYNC due to driver stall for thread %s", mThreadName);
Ady Abraham5e7371c2020-03-24 14:47:24 -0700562 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800563
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800564 LOG_FATAL_IF(!mVSyncState);
Ady Abraham5facfb12020-04-22 15:18:31 -0700565 const auto now = systemTime(SYSTEM_TIME_MONOTONIC);
Ady Abraham8cb21882020-08-26 18:22:05 -0700566 const auto deadlineTimestamp = now + timeout.count();
567 const auto expectedVSyncTime = deadlineTimestamp + timeout.count();
Ben Widawsky59954c42024-09-16 14:52:59 -0700568 mPendingEvents.push_back(makeVSync(mVsyncSchedule->getPhysicalDisplayId(), now,
Ady Abraham8cb21882020-08-26 18:22:05 -0700569 ++mVSyncState->count, expectedVSyncTime,
Rachel Lee0d943202022-02-01 23:29:41 -0800570 deadlineTimestamp));
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700571 }
572 }
Lloyd Pique46a46b32018-01-31 19:01:18 -0800573 }
Ady Abraham011f8ba2022-11-22 15:09:07 -0800574 // cancel any pending vsync event before exiting
575 mVsyncRegistration.cancel();
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800576}
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700577
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800578bool EventThread::shouldConsumeEvent(const DisplayEventReceiver::Event& event,
579 const sp<EventThreadConnection>& connection) const {
Leon Scroggins IIIed66a352023-03-23 17:55:43 -0400580 const auto throttleVsync = [&]() REQUIRES(mMutex) {
Leon Scroggins III31d41412022-11-18 16:42:53 -0500581 const auto& vsyncData = event.vsync.vsyncData;
Rachel Lee2248f522023-01-27 16:45:23 -0800582 if (connection->frameRate.isValid()) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500583 return !mVsyncSchedule->getTracker()
Rachel Lee2248f522023-01-27 16:45:23 -0800584 .isVSyncInPhase(vsyncData.preferredExpectedPresentationTime(),
585 connection->frameRate);
586 }
587
Ady Abrahamf2851612023-09-25 17:19:00 -0700588 const auto expectedPresentTime =
589 TimePoint::fromNs(event.vsync.vsyncData.preferredExpectedPresentationTime());
590 return mCallback.throttleVsync(expectedPresentTime, connection->mOwnerUid);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700591 };
592
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800593 switch (event.header.type) {
594 case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
595 return true;
596
Huihong Luocac92162023-12-21 13:52:42 -0800597 case DisplayEventReceiver::DISPLAY_EVENT_HDCP_LEVELS_CHANGE:
598 return true;
599
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100600 case DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE: {
Ady Abraham62f216c2020-10-13 19:07:23 -0700601 return connection->mEventRegistration.test(
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700602 gui::ISurfaceComposer::EventRegistration::modeChanged);
Alec Mouri60aee1c2019-10-28 16:18:59 -0700603 }
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700604
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800605 case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
606 switch (connection->vsyncRequest) {
607 case VSyncRequest::None:
608 return false;
Tim Murrayb5daa912020-09-09 21:29:13 +0000609 case VSyncRequest::SingleSuppressCallback:
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800610 connection->vsyncRequest = VSyncRequest::None;
Tim Murrayb5daa912020-09-09 21:29:13 +0000611 return false;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700612 case VSyncRequest::Single: {
613 if (throttleVsync()) {
614 return false;
615 }
Tim Murrayb5daa912020-09-09 21:29:13 +0000616 connection->vsyncRequest = VSyncRequest::SingleSuppressCallback;
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800617 return true;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700618 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800619 case VSyncRequest::Periodic:
Ady Abraham0bb6a472020-10-12 10:22:13 -0700620 if (throttleVsync()) {
621 return false;
622 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800623 return true;
624 default:
Ady Abraham0bb6a472020-10-12 10:22:13 -0700625 // We don't throttle vsync if the app set a vsync request rate
626 // since there is no easy way to do that and this is a very
627 // rare case
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800628 return event.vsync.count % vsyncPeriod(connection->vsyncRequest) == 0;
629 }
630
Ady Abraham62f216c2020-10-13 19:07:23 -0700631 case DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE:
632 [[fallthrough]];
633 case DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH:
634 return connection->mEventRegistration.test(
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700635 gui::ISurfaceComposer::EventRegistration::frameRateOverride);
Ady Abraham62f216c2020-10-13 19:07:23 -0700636
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800637 default:
638 return false;
639 }
640}
641
Rachel Lee8d0c6102021-11-03 22:00:25 +0000642int64_t EventThread::generateToken(nsecs_t timestamp, nsecs_t deadlineTimestamp,
Rachel Leeb9c5a772022-02-04 21:17:37 -0800643 nsecs_t expectedPresentationTime) const {
Rachel Lee3f028662021-11-04 19:32:24 +0000644 if (mTokenManager != nullptr) {
645 return mTokenManager->generateTokenForPredictions(
Rachel Leeb9c5a772022-02-04 21:17:37 -0800646 {timestamp, deadlineTimestamp, expectedPresentationTime});
Rachel Lee3f028662021-11-04 19:32:24 +0000647 }
648 return FrameTimelineInfo::INVALID_VSYNC_ID;
649}
650
Rachel Leeb9c5a772022-02-04 21:17:37 -0800651void EventThread::generateFrameTimeline(VsyncEventData& outVsyncEventData, nsecs_t frameInterval,
652 nsecs_t timestamp,
653 nsecs_t preferredExpectedPresentationTime,
654 nsecs_t preferredDeadlineTimestamp) const {
Rachel Lee0655a912023-04-20 19:54:18 -0700655 uint32_t currentIndex = 0;
Rachel Lee3f028662021-11-04 19:32:24 +0000656 // Add 1 to ensure the preferredFrameTimelineIndex entry (when multiplier == 0) is included.
Rachel Lee40aef422023-04-25 14:35:47 -0700657 for (int64_t multiplier = -VsyncEventData::kFrameTimelinesCapacity + 1;
658 currentIndex < VsyncEventData::kFrameTimelinesCapacity; multiplier++) {
Rachel Leeb9c5a772022-02-04 21:17:37 -0800659 nsecs_t deadlineTimestamp = preferredDeadlineTimestamp + multiplier * frameInterval;
Rachel Lee0655a912023-04-20 19:54:18 -0700660 // Valid possible frame timelines must have future values, so find a later frame timeline.
661 if (deadlineTimestamp <= timestamp) {
662 continue;
Rachel Lee3f028662021-11-04 19:32:24 +0000663 }
Rachel Lee0655a912023-04-20 19:54:18 -0700664
665 nsecs_t expectedPresentationTime =
666 preferredExpectedPresentationTime + multiplier * frameInterval;
667 if (expectedPresentationTime >= preferredExpectedPresentationTime +
668 scheduler::VsyncConfig::kEarlyLatchMaxThreshold.count()) {
Rachel Leeafb6b502023-05-12 15:53:05 -0700669 if (currentIndex == 0) {
670 ALOGW("%s: Expected present time is too far in the future but no timelines are "
671 "valid. preferred EPT=%" PRId64 ", Calculated EPT=%" PRId64
672 ", multiplier=%" PRId64 ", frameInterval=%" PRId64 ", threshold=%" PRId64,
673 __func__, preferredExpectedPresentationTime, expectedPresentationTime,
674 multiplier, frameInterval,
675 static_cast<int64_t>(
676 scheduler::VsyncConfig::kEarlyLatchMaxThreshold.count()));
677 }
Rachel Lee0655a912023-04-20 19:54:18 -0700678 break;
679 }
680
681 if (multiplier == 0) {
682 outVsyncEventData.preferredFrameTimelineIndex = currentIndex;
683 }
684
685 outVsyncEventData.frameTimelines[currentIndex] =
686 {.vsyncId = generateToken(timestamp, deadlineTimestamp, expectedPresentationTime),
687 .deadlineTimestamp = deadlineTimestamp,
688 .expectedPresentationTime = expectedPresentationTime};
689 currentIndex++;
Rachel Lee3f028662021-11-04 19:32:24 +0000690 }
Rachel Leeafb6b502023-05-12 15:53:05 -0700691
692 if (currentIndex == 0) {
693 ALOGW("%s: No timelines are valid. preferred EPT=%" PRId64 ", frameInterval=%" PRId64
694 ", threshold=%" PRId64,
695 __func__, preferredExpectedPresentationTime, frameInterval,
696 static_cast<int64_t>(scheduler::VsyncConfig::kEarlyLatchMaxThreshold.count()));
697 outVsyncEventData.frameTimelines[currentIndex] =
698 {.vsyncId = generateToken(timestamp, preferredDeadlineTimestamp,
699 preferredExpectedPresentationTime),
700 .deadlineTimestamp = preferredDeadlineTimestamp,
701 .expectedPresentationTime = preferredExpectedPresentationTime};
702 currentIndex++;
703 }
704
Rachel Lee0655a912023-04-20 19:54:18 -0700705 outVsyncEventData.frameTimelinesLength = currentIndex;
Rachel Lee3f028662021-11-04 19:32:24 +0000706}
707
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800708void EventThread::dispatchEvent(const DisplayEventReceiver::Event& event,
709 const DisplayEventConsumers& consumers) {
Melody Hsue524dd92024-08-27 22:27:29 +0000710 // List of Uids that have been sent vsync data with queued buffer count.
711 // Used to keep track of which Uids can be removed from the map of
712 // buffer stuffed clients.
713 ftl::SmallVector<uid_t, 10> uidsPostedQueuedBuffers;
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800714 for (const auto& consumer : consumers) {
Jorim Jaggic0086af2021-02-12 18:18:11 +0100715 DisplayEventReceiver::Event copy = event;
716 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_VSYNC) {
Ady Abrahamf2851612023-09-25 17:19:00 -0700717 const Period frameInterval = mCallback.getVsyncPeriod(consumer->mOwnerUid);
718 copy.vsync.vsyncData.frameInterval = frameInterval.ns();
719 generateFrameTimeline(copy.vsync.vsyncData, frameInterval.ns(), copy.header.timestamp,
Rachel Leeb9c5a772022-02-04 21:17:37 -0800720 event.vsync.vsyncData.preferredExpectedPresentationTime(),
721 event.vsync.vsyncData.preferredDeadlineTimestamp());
Jorim Jaggic0086af2021-02-12 18:18:11 +0100722 }
Melody Hsue524dd92024-08-27 22:27:29 +0000723 auto it = mBufferStuffedUids.find(consumer->mOwnerUid);
724 if (it != mBufferStuffedUids.end()) {
725 copy.vsync.vsyncData.numberQueuedBuffers = it->second;
726 uidsPostedQueuedBuffers.emplace_back(consumer->mOwnerUid);
727 } else {
728 copy.vsync.vsyncData.numberQueuedBuffers = 0;
729 }
Jorim Jaggic0086af2021-02-12 18:18:11 +0100730 switch (consumer->postEvent(copy)) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800731 case NO_ERROR:
732 break;
733
734 case -EAGAIN:
735 // TODO: Try again if pipe is full.
736 ALOGW("Failed dispatching %s for %s", toString(event).c_str(),
737 toString(*consumer).c_str());
738 break;
739
740 default:
741 // Treat EPIPE and other errors as fatal.
742 removeDisplayEventConnectionLocked(consumer);
743 }
744 }
Melody Hsue524dd92024-08-27 22:27:29 +0000745 // The clients that have already received the queued buffer count
746 // can be removed from the buffer stuffed Uid list to avoid
747 // being sent duplicate messages.
748 for (auto uid : uidsPostedQueuedBuffers) {
749 mBufferStuffedUids.erase(uid);
750 }
ramindaniae645822024-01-11 10:57:29 -0800751 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_VSYNC &&
752 FlagManager::getInstance().vrr_config()) {
ramindani92ab9872024-07-26 15:09:37 -0700753 mLastCommittedVsyncTime =
754 TimePoint::fromNs(event.vsync.vsyncData.preferredExpectedPresentationTime());
755 mCallback.onExpectedPresentTimePosted(mLastCommittedVsyncTime);
ramindaniae645822024-01-11 10:57:29 -0800756 }
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700757}
758
Yiwei Zhang5434a782018-12-05 18:06:32 -0800759void EventThread::dump(std::string& result) const {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800760 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800761
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800762 StringAppendF(&result, "%s: state=%s VSyncState=", mThreadName, toCString(mState));
763 if (mVSyncState) {
Marin Shalamanova524a092020-07-27 21:39:55 +0200764 StringAppendF(&result, "{displayId=%s, count=%u%s}\n",
Ben Widawsky59954c42024-09-16 14:52:59 -0700765 to_string(mVsyncSchedule->getPhysicalDisplayId()).c_str(), mVSyncState->count,
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800766 mVSyncState->synthetic ? ", synthetic" : "");
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800767 } else {
768 StringAppendF(&result, "none\n");
769 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800770
Ady Abraham011f8ba2022-11-22 15:09:07 -0800771 const auto relativeLastCallTime =
772 ticks<std::milli, float>(mLastVsyncCallbackTime - TimePoint::now());
ramindani92ab9872024-07-26 15:09:37 -0700773 const auto relativeLastCommittedTime =
774 ticks<std::milli, float>(mLastCommittedVsyncTime - TimePoint::now());
Ady Abraham011f8ba2022-11-22 15:09:07 -0800775 StringAppendF(&result, "mWorkDuration=%.2f mReadyDuration=%.2f last vsync time ",
776 mWorkDuration.get().count() / 1e6f, mReadyDuration.count() / 1e6f);
777 StringAppendF(&result, "%.2fms relative to now\n", relativeLastCallTime);
ramindani92ab9872024-07-26 15:09:37 -0700778 StringAppendF(&result, " with vsync committed at %.2fms", relativeLastCommittedTime);
Ady Abraham011f8ba2022-11-22 15:09:07 -0800779
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800780 StringAppendF(&result, " pending events (count=%zu):\n", mPendingEvents.size());
781 for (const auto& event : mPendingEvents) {
782 StringAppendF(&result, " %s\n", toString(event).c_str());
Mathias Agopiane2c4f4e2012-04-10 18:25:31 -0700783 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800784
785 StringAppendF(&result, " connections (count=%zu):\n", mDisplayEventConnections.size());
786 for (const auto& ptr : mDisplayEventConnections) {
787 if (const auto connection = ptr.promote()) {
788 StringAppendF(&result, " %s\n", toString(*connection).c_str());
789 }
790 }
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400791 result += '\n';
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800792}
793
Dominik Laskowski029cc122019-01-23 19:52:06 -0800794const char* EventThread::toCString(State state) {
795 switch (state) {
796 case State::Idle:
797 return "Idle";
798 case State::Quit:
799 return "Quit";
800 case State::SyntheticVSync:
801 return "SyntheticVSync";
802 case State::VSync:
803 return "VSync";
804 }
805}
806
Leon Scroggins III67388622023-02-06 20:36:20 -0500807void EventThread::onNewVsyncSchedule(std::shared_ptr<scheduler::VsyncSchedule> schedule) {
Leon Scroggins IIIb2253602023-04-19 17:04:04 -0400808 // Hold onto the old registration until after releasing the mutex to avoid deadlock.
809 scheduler::VSyncCallbackRegistration oldRegistration =
810 onNewVsyncScheduleInternal(std::move(schedule));
811}
812
813scheduler::VSyncCallbackRegistration EventThread::onNewVsyncScheduleInternal(
814 std::shared_ptr<scheduler::VsyncSchedule> schedule) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500815 std::lock_guard<std::mutex> lock(mMutex);
816 const bool reschedule = mVsyncRegistration.cancel() == scheduler::CancelResult::Cancelled;
817 mVsyncSchedule = std::move(schedule);
Leon Scroggins IIIb2253602023-04-19 17:04:04 -0400818 auto oldRegistration =
819 std::exchange(mVsyncRegistration,
820 scheduler::VSyncCallbackRegistration(mVsyncSchedule->getDispatch(),
821 createDispatchCallback(),
822 mThreadName));
Leon Scroggins III67388622023-02-06 20:36:20 -0500823 if (reschedule) {
824 mVsyncRegistration.schedule({.workDuration = mWorkDuration.get().count(),
825 .readyDuration = mReadyDuration.count(),
ramindani92ab9872024-07-26 15:09:37 -0700826 .lastVsync = mLastVsyncCallbackTime.ns(),
827 .committedVsyncOpt = mLastCommittedVsyncTime.ns()});
Leon Scroggins III67388622023-02-06 20:36:20 -0500828 }
Leon Scroggins IIIb2253602023-04-19 17:04:04 -0400829 return oldRegistration;
Leon Scroggins III67388622023-02-06 20:36:20 -0500830}
831
832scheduler::VSyncDispatch::Callback EventThread::createDispatchCallback() {
833 return [this](nsecs_t vsyncTime, nsecs_t wakeupTime, nsecs_t readyTime) {
834 onVsync(vsyncTime, wakeupTime, readyTime);
835 };
836}
837
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800838} // namespace impl
Lloyd Pique46a46b32018-01-31 19:01:18 -0800839} // namespace android
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800840
841// TODO(b/129481165): remove the #pragma below and fix conversion issues
842#pragma clang diagnostic pop // ignored "-Wconversion"