blob: c6d716081824ade8081616013ee7a16d8b48e583 [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>
Manasi Navare5ef1fa12024-11-07 23:49:46 +000046#include <scheduler/FrameRateMode.h>
Rachel Lee0655a912023-04-20 19:54:18 -070047#include <scheduler/VsyncConfig.h>
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -070048#include "FrameTimeline.h"
Ady Abraham011f8ba2022-11-22 15:09:07 -080049#include "VSyncDispatch.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);
Huihong Luo9ebb7a72023-06-27 17:01:50 -0700101 case DisplayEventReceiver::DISPLAY_EVENT_HDCP_LEVELS_CHANGE:
102 return StringPrintf("HdcpLevelsChange{displayId=%s, connectedLevel=%d, maxLevel=%d}",
103 to_string(event.header.displayId).c_str(),
104 event.hdcpLevelsChange.connectedLevel,
105 event.hdcpLevelsChange.maxLevel);
Manasi Navare5ef1fa12024-11-07 23:49:46 +0000106 case DisplayEventReceiver::DISPLAY_EVENT_MODE_REJECTION:
107 return StringPrintf("ModeRejected{displayId=%s, modeId=%u}",
108 to_string(event.header.displayId).c_str(),
109 event.modeRejection.modeId);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800110 default:
111 return "Event{}";
112 }
113}
114
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800115DisplayEventReceiver::Event makeHotplug(PhysicalDisplayId displayId, nsecs_t timestamp,
116 bool connected) {
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800117 DisplayEventReceiver::Event event;
118 event.header = {DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG, displayId, timestamp};
119 event.hotplug.connected = connected;
120 return event;
121}
122
Brian Johnson5dcd75d2023-08-15 09:36:37 -0700123DisplayEventReceiver::Event makeHotplugError(nsecs_t timestamp, int32_t connectionError) {
124 DisplayEventReceiver::Event event;
125 PhysicalDisplayId unusedDisplayId;
126 event.header = {DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG, unusedDisplayId, timestamp};
127 event.hotplug.connected = false;
128 event.hotplug.connectionError = connectionError;
129 return event;
130}
131
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800132DisplayEventReceiver::Event makeVSync(PhysicalDisplayId displayId, nsecs_t timestamp,
Rachel Leeb9c5a772022-02-04 21:17:37 -0800133 uint32_t count, nsecs_t expectedPresentationTime,
Rachel Lee0d943202022-02-01 23:29:41 -0800134 nsecs_t deadlineTimestamp) {
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800135 DisplayEventReceiver::Event event;
136 event.header = {DisplayEventReceiver::DISPLAY_EVENT_VSYNC, displayId, timestamp};
137 event.vsync.count = count;
Rachel Leeb9c5a772022-02-04 21:17:37 -0800138 event.vsync.vsyncData.preferredFrameTimelineIndex = 0;
139 // Temporarily store the current vsync information in frameTimelines[0], marked as
140 // platform-preferred. When the event is dispatched later, the frame interval at that time is
141 // used with this information to generate multiple frame timeline choices.
142 event.vsync.vsyncData.frameTimelines[0] = {.vsyncId = FrameTimelineInfo::INVALID_VSYNC_ID,
143 .deadlineTimestamp = deadlineTimestamp,
144 .expectedPresentationTime =
145 expectedPresentationTime};
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800146 return event;
147}
148
Ady Abraham67434eb2022-12-01 17:48:12 -0800149DisplayEventReceiver::Event makeModeChanged(const scheduler::FrameRateMode& mode) {
Ady Abraham447052e2019-02-13 16:07:27 -0800150 DisplayEventReceiver::Event event;
Ady Abraham67434eb2022-12-01 17:48:12 -0800151 event.header = {DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE,
152 mode.modePtr->getPhysicalDisplayId(), systemTime()};
Dominik Laskowski43baf902023-11-17 18:13:11 -0500153 event.modeChange.modeId = ftl::to_underlying(mode.modePtr->getId());
Ady Abraham67434eb2022-12-01 17:48:12 -0800154 event.modeChange.vsyncPeriod = mode.fps.getPeriodNsecs();
Ady Abraham447052e2019-02-13 16:07:27 -0800155 return event;
156}
157
Ady Abraham62f216c2020-10-13 19:07:23 -0700158DisplayEventReceiver::Event makeFrameRateOverrideEvent(PhysicalDisplayId displayId,
159 FrameRateOverride frameRateOverride) {
160 return DisplayEventReceiver::Event{
161 .header =
162 DisplayEventReceiver::Event::Header{
163 .type = DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE,
164 .displayId = displayId,
165 .timestamp = systemTime(),
166 },
167 .frameRateOverride = frameRateOverride,
168 };
169}
170
171DisplayEventReceiver::Event makeFrameRateOverrideFlushEvent(PhysicalDisplayId displayId) {
172 return DisplayEventReceiver::Event{
173 .header = DisplayEventReceiver::Event::Header{
174 .type = DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH,
175 .displayId = displayId,
176 .timestamp = systemTime(),
177 }};
178}
179
Huihong Luo9ebb7a72023-06-27 17:01:50 -0700180DisplayEventReceiver::Event makeHdcpLevelsChange(PhysicalDisplayId displayId,
181 int32_t connectedLevel, int32_t maxLevel) {
182 return DisplayEventReceiver::Event{
183 .header =
184 DisplayEventReceiver::Event::Header{
185 .type = DisplayEventReceiver::DISPLAY_EVENT_HDCP_LEVELS_CHANGE,
186 .displayId = displayId,
187 .timestamp = systemTime(),
188 },
189 .hdcpLevelsChange.connectedLevel = connectedLevel,
190 .hdcpLevelsChange.maxLevel = maxLevel,
191 };
192}
193
Manasi Navare5ef1fa12024-11-07 23:49:46 +0000194DisplayEventReceiver::Event makeModeRejection(PhysicalDisplayId displayId, DisplayModeId modeId) {
195 return DisplayEventReceiver::Event{
196 .header =
197 DisplayEventReceiver::Event::Header{
198 .type = DisplayEventReceiver::DISPLAY_EVENT_MODE_REJECTION,
199 .displayId = displayId,
200 .timestamp = systemTime(),
201 },
202 .modeRejection.modeId = ftl::to_underlying(modeId),
203 };
204}
205
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800206} // namespace
Lloyd Pique46a46b32018-01-31 19:01:18 -0800207
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700208EventThreadConnection::EventThreadConnection(EventThread* eventThread, uid_t callingUid,
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700209 EventRegistrationFlags eventRegistration)
Ady Abrahamf2851612023-09-25 17:19:00 -0700210 : mOwnerUid(callingUid),
Ady Abraham62f216c2020-10-13 19:07:23 -0700211 mEventRegistration(eventRegistration),
Dominik Laskowskif654d572018-12-20 11:03:06 -0800212 mEventThread(eventThread),
213 mChannel(gui::BitTube::DefaultSize) {}
Ana Krulec85c39af2018-12-26 17:29:57 -0800214
215EventThreadConnection::~EventThreadConnection() {
216 // do nothing here -- clean-up will happen automatically
217 // when the main thread wakes up
218}
219
220void EventThreadConnection::onFirstRef() {
221 // NOTE: mEventThread doesn't hold a strong reference on us
Ady Abrahamd11bade2022-08-01 16:18:03 -0700222 mEventThread->registerDisplayEventConnection(sp<EventThreadConnection>::fromExisting(this));
Ana Krulec85c39af2018-12-26 17:29:57 -0800223}
224
Huihong Luo6fac5232021-11-22 16:05:23 -0800225binder::Status EventThreadConnection::stealReceiveChannel(gui::BitTube* outChannel) {
Ady Abraham899e8cd2022-06-06 15:16:06 -0700226 std::scoped_lock lock(mLock);
227 if (mChannel.initCheck() != NO_ERROR) {
228 return binder::Status::fromStatusT(NAME_NOT_FOUND);
229 }
230
Ana Krulec85c39af2018-12-26 17:29:57 -0800231 outChannel->setReceiveFd(mChannel.moveReceiveFd());
Alec Mouri967d5d72020-08-05 12:50:03 -0700232 outChannel->setSendFd(base::unique_fd(dup(mChannel.getSendFd())));
Huihong Luo6fac5232021-11-22 16:05:23 -0800233 return binder::Status::ok();
Ana Krulec85c39af2018-12-26 17:29:57 -0800234}
235
Huihong Luo6fac5232021-11-22 16:05:23 -0800236binder::Status EventThreadConnection::setVsyncRate(int rate) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700237 mEventThread->setVsyncRate(static_cast<uint32_t>(rate),
238 sp<EventThreadConnection>::fromExisting(this));
Huihong Luo6fac5232021-11-22 16:05:23 -0800239 return binder::Status::ok();
Ana Krulec85c39af2018-12-26 17:29:57 -0800240}
241
Huihong Luo6fac5232021-11-22 16:05:23 -0800242binder::Status EventThreadConnection::requestNextVsync() {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000243 SFTRACE_CALL();
Ady Abrahamd11bade2022-08-01 16:18:03 -0700244 mEventThread->requestNextVsync(sp<EventThreadConnection>::fromExisting(this));
Huihong Luo6fac5232021-11-22 16:05:23 -0800245 return binder::Status::ok();
Ana Krulec85c39af2018-12-26 17:29:57 -0800246}
247
Rachel Leeb9c5a772022-02-04 21:17:37 -0800248binder::Status EventThreadConnection::getLatestVsyncEventData(
249 ParcelableVsyncEventData* outVsyncEventData) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000250 SFTRACE_CALL();
Ady Abrahamd11bade2022-08-01 16:18:03 -0700251 outVsyncEventData->vsync =
Ady Abraham40ec5842024-04-04 13:22:38 -0700252 mEventThread->getLatestVsyncEventData(sp<EventThreadConnection>::fromExisting(this),
253 systemTime());
Rachel Leeef2e21f2022-02-01 14:51:34 -0800254 return binder::Status::ok();
255}
256
Ady Abraham07d03c42023-09-27 19:15:08 -0700257binder::Status EventThreadConnection::getSchedulingPolicy(gui::SchedulingPolicy* outPolicy) {
258 return gui::getSchedulingPolicy(outPolicy);
259}
260
Ana Krulec85c39af2018-12-26 17:29:57 -0800261status_t EventThreadConnection::postEvent(const DisplayEventReceiver::Event& event) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700262 constexpr auto toStatus = [](ssize_t size) {
263 return size < 0 ? status_t(size) : status_t(NO_ERROR);
264 };
265
266 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE ||
267 event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH) {
268 mPendingEvents.emplace_back(event);
269 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE) {
270 return status_t(NO_ERROR);
271 }
272
273 auto size = DisplayEventReceiver::sendEvents(&mChannel, mPendingEvents.data(),
274 mPendingEvents.size());
275 mPendingEvents.clear();
276 return toStatus(size);
277 }
278
279 auto size = DisplayEventReceiver::sendEvents(&mChannel, &event, 1);
280 return toStatus(size);
Ana Krulec85c39af2018-12-26 17:29:57 -0800281}
282
283// ---------------------------------------------------------------------------
284
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800285EventThread::~EventThread() = default;
286
287namespace impl {
288
Leon Scroggins III67388622023-02-06 20:36:20 -0500289EventThread::EventThread(const char* name, std::shared_ptr<scheduler::VsyncSchedule> vsyncSchedule,
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700290 android::frametimeline::TokenManager* tokenManager,
Ady Abrahamf2851612023-09-25 17:19:00 -0700291 IEventThreadCallback& callback, std::chrono::nanoseconds workDuration,
Ady Abraham011f8ba2022-11-22 15:09:07 -0800292 std::chrono::nanoseconds readyDuration)
293 : mThreadName(name),
294 mVsyncTracer(base::StringPrintf("VSYNC-%s", name), 0),
295 mWorkDuration(base::StringPrintf("VsyncWorkDuration-%s", name), workDuration),
296 mReadyDuration(readyDuration),
Leon Scroggins III67388622023-02-06 20:36:20 -0500297 mVsyncSchedule(std::move(vsyncSchedule)),
298 mVsyncRegistration(mVsyncSchedule->getDispatch(), createDispatchCallback(), name),
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700299 mTokenManager(tokenManager),
Ady Abrahamf2851612023-09-25 17:19:00 -0700300 mCallback(callback) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800301 mThread = std::thread([this]() NO_THREAD_SAFETY_ANALYSIS {
302 std::unique_lock<std::mutex> lock(mMutex);
303 threadMain(lock);
304 });
Lloyd Pique46a46b32018-01-31 19:01:18 -0800305
Dominik Laskowski6505f792019-09-18 11:10:05 -0700306 pthread_setname_np(mThread.native_handle(), mThreadName);
Lloyd Pique46a46b32018-01-31 19:01:18 -0800307
308 pid_t tid = pthread_gettid_np(mThread.native_handle());
309
310 // Use SCHED_FIFO to minimize jitter
311 constexpr int EVENT_THREAD_PRIORITY = 2;
312 struct sched_param param = {0};
313 param.sched_priority = EVENT_THREAD_PRIORITY;
314 if (pthread_setschedparam(mThread.native_handle(), SCHED_FIFO, &param) != 0) {
315 ALOGE("Couldn't set SCHED_FIFO for EventThread");
316 }
317
318 set_sched_policy(tid, SP_FOREGROUND);
319}
320
321EventThread::~EventThread() {
322 {
323 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski029cc122019-01-23 19:52:06 -0800324 mState = State::Quit;
Lloyd Pique46a46b32018-01-31 19:01:18 -0800325 mCondition.notify_all();
326 }
327 mThread.join();
Ruchi Kandoief472ec2014-04-02 12:50:06 -0700328}
329
Ady Abraham9c53ee72020-07-22 21:16:18 -0700330void EventThread::setDuration(std::chrono::nanoseconds workDuration,
331 std::chrono::nanoseconds readyDuration) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800332 std::lock_guard<std::mutex> lock(mMutex);
Ady Abraham011f8ba2022-11-22 15:09:07 -0800333 mWorkDuration = workDuration;
334 mReadyDuration = readyDuration;
335
336 mVsyncRegistration.update({.workDuration = mWorkDuration.get().count(),
337 .readyDuration = mReadyDuration.count(),
ramindani92ab9872024-07-26 15:09:37 -0700338 .lastVsync = mLastVsyncCallbackTime.ns(),
339 .committedVsyncOpt = mLastCommittedVsyncTime.ns()});
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700340}
341
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700342sp<EventThreadConnection> EventThread::createEventConnection(
Ady Abrahamf2851612023-09-25 17:19:00 -0700343 EventRegistrationFlags eventRegistration) const {
Ady Abraham07d03c42023-09-27 19:15:08 -0700344 auto connection = sp<EventThreadConnection>::make(const_cast<EventThread*>(this),
345 IPCThreadState::self()->getCallingUid(),
346 eventRegistration);
Ady Abrahamd6d80162023-10-23 12:57:41 -0700347 if (FlagManager::getInstance().misc1()) {
Ady Abraham07d03c42023-09-27 19:15:08 -0700348 const int policy = SCHED_FIFO;
349 connection->setMinSchedulerPolicy(policy, sched_get_priority_min(policy));
350 }
351 return connection;
Mathias Agopian8aedd472012-01-24 16:39:14 -0800352}
353
Ana Krulec85c39af2018-12-26 17:29:57 -0800354status_t EventThread::registerDisplayEventConnection(const sp<EventThreadConnection>& connection) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800355 std::lock_guard<std::mutex> lock(mMutex);
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700356
357 // this should never happen
358 auto it = std::find(mDisplayEventConnections.cbegin(),
359 mDisplayEventConnections.cend(), connection);
360 if (it != mDisplayEventConnections.cend()) {
361 ALOGW("DisplayEventConnection %p already exists", connection.get());
362 mCondition.notify_all();
363 return ALREADY_EXISTS;
364 }
365
366 mDisplayEventConnections.push_back(connection);
Lloyd Pique46a46b32018-01-31 19:01:18 -0800367 mCondition.notify_all();
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800368 return NO_ERROR;
369}
370
Ana Krulec85c39af2018-12-26 17:29:57 -0800371void EventThread::removeDisplayEventConnectionLocked(const wp<EventThreadConnection>& connection) {
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700372 auto it = std::find(mDisplayEventConnections.cbegin(),
373 mDisplayEventConnections.cend(), connection);
374 if (it != mDisplayEventConnections.cend()) {
375 mDisplayEventConnections.erase(it);
376 }
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800377}
378
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800379void EventThread::setVsyncRate(uint32_t rate, const sp<EventThreadConnection>& connection) {
380 if (static_cast<std::underlying_type_t<VSyncRequest>>(rate) < 0) {
381 return;
382 }
383
384 std::lock_guard<std::mutex> lock(mMutex);
385
386 const auto request = rate == 0 ? VSyncRequest::None : static_cast<VSyncRequest>(rate);
387 if (connection->vsyncRequest != request) {
388 connection->vsyncRequest = request;
389 mCondition.notify_all();
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800390 }
391}
392
Ady Abraham8532d012019-05-08 14:50:56 -0700393void EventThread::requestNextVsync(const sp<EventThreadConnection>& connection) {
Ady Abrahamf2851612023-09-25 17:19:00 -0700394 mCallback.resync();
Tim Murray4a4e4a22016-04-19 16:29:23 +0000395
Ana Krulec7d1d6832018-12-27 11:10:09 -0800396 std::lock_guard<std::mutex> lock(mMutex);
397
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800398 if (connection->vsyncRequest == VSyncRequest::None) {
399 connection->vsyncRequest = VSyncRequest::Single;
Lloyd Pique46a46b32018-01-31 19:01:18 -0800400 mCondition.notify_all();
Tim Murrayb5daa912020-09-09 21:29:13 +0000401 } else if (connection->vsyncRequest == VSyncRequest::SingleSuppressCallback) {
402 connection->vsyncRequest = VSyncRequest::Single;
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800403 }
Mathias Agopian23748662011-12-05 14:33:34 -0800404}
405
Ady Abraham40ec5842024-04-04 13:22:38 -0700406VsyncEventData EventThread::getLatestVsyncEventData(const sp<EventThreadConnection>& connection,
407 nsecs_t now) const {
Rachel Leeb5223cf2022-03-14 14:39:27 -0700408 // Resync so that the vsync is accurate with hardware. getLatestVsyncEventData is an alternate
409 // way to get vsync data (instead of posting callbacks to Choreographer).
Ady Abrahamf2851612023-09-25 17:19:00 -0700410 mCallback.resync();
Rachel Leeb5223cf2022-03-14 14:39:27 -0700411
Rachel Leeef2e21f2022-02-01 14:51:34 -0800412 VsyncEventData vsyncEventData;
Ady Abrahamf2851612023-09-25 17:19:00 -0700413 const Period frameInterval = mCallback.getVsyncPeriod(connection->mOwnerUid);
414 vsyncEventData.frameInterval = frameInterval.ns();
Ady Abraham011f8ba2022-11-22 15:09:07 -0800415 const auto [presentTime, deadline] = [&]() -> std::pair<nsecs_t, nsecs_t> {
Rachel Leeb9c5a772022-02-04 21:17:37 -0800416 std::lock_guard<std::mutex> lock(mMutex);
Leon Scroggins III67388622023-02-06 20:36:20 -0500417 const auto vsyncTime = mVsyncSchedule->getTracker().nextAnticipatedVSyncTimeFrom(
Ady Abraham40ec5842024-04-04 13:22:38 -0700418 now + mWorkDuration.get().count() + mReadyDuration.count());
Ady Abraham011f8ba2022-11-22 15:09:07 -0800419 return {vsyncTime, vsyncTime - mReadyDuration.count()};
420 }();
Ady Abraham40ec5842024-04-04 13:22:38 -0700421 generateFrameTimeline(vsyncEventData, frameInterval.ns(), now, presentTime, deadline);
ramindaniae645822024-01-11 10:57:29 -0800422 if (FlagManager::getInstance().vrr_config()) {
423 mCallback.onExpectedPresentTimePosted(TimePoint::fromNs(presentTime));
424 }
Rachel Leeef2e21f2022-02-01 14:51:34 -0800425 return vsyncEventData;
426}
427
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500428void EventThread::enableSyntheticVsync(bool enable) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800429 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500430 if (!mVSyncState || mVSyncState->synthetic == enable) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800431 return;
Mathias Agopian22ffb112012-04-10 21:04:02 -0700432 }
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800433
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500434 mVSyncState->synthetic = enable;
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800435 mCondition.notify_all();
Mathias Agopian22ffb112012-04-10 21:04:02 -0700436}
437
Ady Abraham8e3e2ea2024-10-31 15:52:31 -0700438void EventThread::omitVsyncDispatching(bool omitted) {
439 std::lock_guard<std::mutex> lock(mMutex);
440 if (!mVSyncState || mVSyncState->omitted == omitted) {
441 return;
442 }
443
444 mVSyncState->omitted = omitted;
445 mCondition.notify_all();
446}
447
Ady Abraham011f8ba2022-11-22 15:09:07 -0800448void EventThread::onVsync(nsecs_t vsyncTime, nsecs_t wakeupTime, nsecs_t readyTime) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800449 std::lock_guard<std::mutex> lock(mMutex);
Ady Abraham011f8ba2022-11-22 15:09:07 -0800450 mLastVsyncCallbackTime = TimePoint::fromNs(vsyncTime);
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800451
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800452 LOG_FATAL_IF(!mVSyncState);
Ady Abraham011f8ba2022-11-22 15:09:07 -0800453 mVsyncTracer = (mVsyncTracer + 1) % 2;
Ben Widawsky59954c42024-09-16 14:52:59 -0700454 mPendingEvents.push_back(makeVSync(mVsyncSchedule->getPhysicalDisplayId(), wakeupTime,
455 ++mVSyncState->count, vsyncTime, readyTime));
Lloyd Pique46a46b32018-01-31 19:01:18 -0800456 mCondition.notify_all();
Mathias Agopian3eb38cb2012-04-03 22:09:52 -0700457}
458
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800459void EventThread::onHotplugReceived(PhysicalDisplayId displayId, bool connected) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800460 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -0700461
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800462 mPendingEvents.push_back(makeHotplug(displayId, systemTime(), connected));
Dominik Laskowski00a6fa22018-06-06 16:42:02 -0700463 mCondition.notify_all();
Mathias Agopian148994e2012-09-19 17:31:36 -0700464}
465
Brian Johnson5dcd75d2023-08-15 09:36:37 -0700466void EventThread::onHotplugConnectionError(int32_t errorCode) {
467 std::lock_guard<std::mutex> lock(mMutex);
468
469 mPendingEvents.push_back(makeHotplugError(systemTime(), errorCode));
470 mCondition.notify_all();
471}
472
Ady Abraham67434eb2022-12-01 17:48:12 -0800473void EventThread::onModeChanged(const scheduler::FrameRateMode& mode) {
Ady Abraham447052e2019-02-13 16:07:27 -0800474 std::lock_guard<std::mutex> lock(mMutex);
475
Ady Abraham690f4612021-07-01 23:24:03 -0700476 mPendingEvents.push_back(makeModeChanged(mode));
Ady Abraham447052e2019-02-13 16:07:27 -0800477 mCondition.notify_all();
478}
479
Ady Abraham62f216c2020-10-13 19:07:23 -0700480void EventThread::onFrameRateOverridesChanged(PhysicalDisplayId displayId,
481 std::vector<FrameRateOverride> overrides) {
482 std::lock_guard<std::mutex> lock(mMutex);
483
484 for (auto frameRateOverride : overrides) {
485 mPendingEvents.push_back(makeFrameRateOverrideEvent(displayId, frameRateOverride));
486 }
487 mPendingEvents.push_back(makeFrameRateOverrideFlushEvent(displayId));
488
489 mCondition.notify_all();
490}
491
Huihong Luo9ebb7a72023-06-27 17:01:50 -0700492void EventThread::onHdcpLevelsChanged(PhysicalDisplayId displayId, int32_t connectedLevel,
493 int32_t maxLevel) {
494 std::lock_guard<std::mutex> lock(mMutex);
495
496 mPendingEvents.push_back(makeHdcpLevelsChange(displayId, connectedLevel, maxLevel));
497 mCondition.notify_all();
498}
499
Manasi Navare5ef1fa12024-11-07 23:49:46 +0000500void EventThread::onModeRejected(PhysicalDisplayId displayId, DisplayModeId modeId) {
501 std::lock_guard<std::mutex> lock(mMutex);
502
503 mPendingEvents.push_back(makeModeRejection(displayId, modeId));
504 mCondition.notify_all();
505}
506
Melody Hsue524dd92024-08-27 22:27:29 +0000507// Merge lists of buffer stuffed Uids
508void EventThread::addBufferStuffedUids(BufferStuffingMap bufferStuffedUids) {
509 std::lock_guard<std::mutex> lock(mMutex);
510 for (auto& [uid, count] : bufferStuffedUids) {
511 mBufferStuffedUids.emplace_or_replace(uid, count);
512 }
513}
514
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800515void EventThread::threadMain(std::unique_lock<std::mutex>& lock) {
516 DisplayEventConsumers consumers;
517
Dominik Laskowski029cc122019-01-23 19:52:06 -0800518 while (mState != State::Quit) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800519 std::optional<DisplayEventReceiver::Event> event;
Mathias Agopian3eb38cb2012-04-03 22:09:52 -0700520
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800521 // Determine next event to dispatch.
522 if (!mPendingEvents.empty()) {
523 event = mPendingEvents.front();
524 mPendingEvents.pop_front();
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800525
Huihong Luoab8ffef2022-08-18 13:02:26 -0700526 if (event->header.type == DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG) {
Brian Johnson5dcd75d2023-08-15 09:36:37 -0700527 if (event->hotplug.connectionError == 0) {
528 if (event->hotplug.connected && !mVSyncState) {
Ben Widawsky59954c42024-09-16 14:52:59 -0700529 mVSyncState.emplace();
530 } else if (!event->hotplug.connected &&
531 mVsyncSchedule->getPhysicalDisplayId() == event->header.displayId) {
Brian Johnson5dcd75d2023-08-15 09:36:37 -0700532 mVSyncState.reset();
533 }
534 } else {
535 // Ignore vsync stuff on an error.
Huihong Luoab8ffef2022-08-18 13:02:26 -0700536 }
Dominik Laskowski029cc122019-01-23 19:52:06 -0800537 }
Mathias Agopianff28e202012-09-20 23:24:19 -0700538 }
539
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800540 bool vsyncRequested = false;
Mathias Agopian148994e2012-09-19 17:31:36 -0700541
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800542 // Find connections that should consume this event.
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700543 auto it = mDisplayEventConnections.begin();
544 while (it != mDisplayEventConnections.end()) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800545 if (const auto connection = it->promote()) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800546 if (event && shouldConsumeEvent(*event, connection)) {
547 consumers.push_back(connection);
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700548 }
Mathias Agopianb4d18ed2012-09-20 23:14:05 -0700549
Ady Abraham011f8ba2022-11-22 15:09:07 -0800550 vsyncRequested |= connection->vsyncRequest != VSyncRequest::None;
551
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700552 ++it;
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700553 } else {
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700554 it = mDisplayEventConnections.erase(it);
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700555 }
556 }
557
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800558 if (!consumers.empty()) {
559 dispatchEvent(*event, consumers);
560 consumers.clear();
561 }
562
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800563 if (mVSyncState && vsyncRequested) {
Ady Abraham8e3e2ea2024-10-31 15:52:31 -0700564 const bool vsyncOmitted =
565 FlagManager::getInstance().no_vsyncs_on_screen_off() && mVSyncState->omitted;
566 if (vsyncOmitted) {
567 mState = State::Idle;
568 SFTRACE_INT("VsyncPendingScreenOn", 1);
569 } else {
570 mState = mVSyncState->synthetic ? State::SyntheticVSync : State::VSync;
571 if (FlagManager::getInstance().no_vsyncs_on_screen_off()) {
572 SFTRACE_INT("VsyncPendingScreenOn", 0);
573 }
574 }
Dominik Laskowski029cc122019-01-23 19:52:06 -0800575 } else {
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800576 ALOGW_IF(!mVSyncState, "Ignoring VSYNC request while display is disconnected");
Ady Abraham011f8ba2022-11-22 15:09:07 -0800577 mState = State::Idle;
Dominik Laskowski029cc122019-01-23 19:52:06 -0800578 }
579
Ady Abraham011f8ba2022-11-22 15:09:07 -0800580 if (mState == State::VSync) {
ramindani92ab9872024-07-26 15:09:37 -0700581 const auto scheduleResult = mVsyncRegistration.schedule(
582 {.workDuration = mWorkDuration.get().count(),
583 .readyDuration = mReadyDuration.count(),
584 .lastVsync = mLastVsyncCallbackTime.ns(),
585 .committedVsyncOpt = mLastCommittedVsyncTime.ns()});
Ady Abraham011f8ba2022-11-22 15:09:07 -0800586 LOG_ALWAYS_FATAL_IF(!scheduleResult, "Error scheduling callback");
587 } else {
588 mVsyncRegistration.cancel();
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700589 }
590
Ady Abraham011f8ba2022-11-22 15:09:07 -0800591 if (!mPendingEvents.empty()) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800592 continue;
593 }
594
595 // Wait for event or client registration/request.
Dominik Laskowski029cc122019-01-23 19:52:06 -0800596 if (mState == State::Idle) {
597 mCondition.wait(lock);
598 } else {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800599 // Generate a fake VSYNC after a long timeout in case the driver stalls. When the
600 // display is off, keep feeding clients at 60 Hz.
Ady Abraham5facfb12020-04-22 15:18:31 -0700601 const std::chrono::nanoseconds timeout =
602 mState == State::SyntheticVSync ? 16ms : 1000ms;
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800603 if (mCondition.wait_for(lock, timeout) == std::cv_status::timeout) {
Ady Abraham5e7371c2020-03-24 14:47:24 -0700604 if (mState == State::VSync) {
605 ALOGW("Faking VSYNC due to driver stall for thread %s", mThreadName);
Ady Abraham5e7371c2020-03-24 14:47:24 -0700606 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800607
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800608 LOG_FATAL_IF(!mVSyncState);
Ady Abraham5facfb12020-04-22 15:18:31 -0700609 const auto now = systemTime(SYSTEM_TIME_MONOTONIC);
Ady Abraham8cb21882020-08-26 18:22:05 -0700610 const auto deadlineTimestamp = now + timeout.count();
611 const auto expectedVSyncTime = deadlineTimestamp + timeout.count();
Ben Widawsky59954c42024-09-16 14:52:59 -0700612 mPendingEvents.push_back(makeVSync(mVsyncSchedule->getPhysicalDisplayId(), now,
Ady Abraham8cb21882020-08-26 18:22:05 -0700613 ++mVSyncState->count, expectedVSyncTime,
Rachel Lee0d943202022-02-01 23:29:41 -0800614 deadlineTimestamp));
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700615 }
616 }
Lloyd Pique46a46b32018-01-31 19:01:18 -0800617 }
Ady Abraham011f8ba2022-11-22 15:09:07 -0800618 // cancel any pending vsync event before exiting
619 mVsyncRegistration.cancel();
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800620}
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700621
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800622bool EventThread::shouldConsumeEvent(const DisplayEventReceiver::Event& event,
623 const sp<EventThreadConnection>& connection) const {
Leon Scroggins IIIed66a352023-03-23 17:55:43 -0400624 const auto throttleVsync = [&]() REQUIRES(mMutex) {
Leon Scroggins III31d41412022-11-18 16:42:53 -0500625 const auto& vsyncData = event.vsync.vsyncData;
Rachel Lee2248f522023-01-27 16:45:23 -0800626 if (connection->frameRate.isValid()) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500627 return !mVsyncSchedule->getTracker()
Rachel Lee2248f522023-01-27 16:45:23 -0800628 .isVSyncInPhase(vsyncData.preferredExpectedPresentationTime(),
629 connection->frameRate);
630 }
631
Ady Abrahamf2851612023-09-25 17:19:00 -0700632 const auto expectedPresentTime =
633 TimePoint::fromNs(event.vsync.vsyncData.preferredExpectedPresentationTime());
634 return mCallback.throttleVsync(expectedPresentTime, connection->mOwnerUid);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700635 };
636
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800637 switch (event.header.type) {
638 case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
639 return true;
640
Huihong Luocac92162023-12-21 13:52:42 -0800641 case DisplayEventReceiver::DISPLAY_EVENT_HDCP_LEVELS_CHANGE:
642 return true;
643
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100644 case DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE: {
Ady Abraham62f216c2020-10-13 19:07:23 -0700645 return connection->mEventRegistration.test(
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700646 gui::ISurfaceComposer::EventRegistration::modeChanged);
Alec Mouri60aee1c2019-10-28 16:18:59 -0700647 }
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700648
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800649 case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
650 switch (connection->vsyncRequest) {
651 case VSyncRequest::None:
652 return false;
Tim Murrayb5daa912020-09-09 21:29:13 +0000653 case VSyncRequest::SingleSuppressCallback:
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800654 connection->vsyncRequest = VSyncRequest::None;
Tim Murrayb5daa912020-09-09 21:29:13 +0000655 return false;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700656 case VSyncRequest::Single: {
657 if (throttleVsync()) {
658 return false;
659 }
Tim Murrayb5daa912020-09-09 21:29:13 +0000660 connection->vsyncRequest = VSyncRequest::SingleSuppressCallback;
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800661 return true;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700662 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800663 case VSyncRequest::Periodic:
Ady Abraham0bb6a472020-10-12 10:22:13 -0700664 if (throttleVsync()) {
665 return false;
666 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800667 return true;
668 default:
Ady Abraham0bb6a472020-10-12 10:22:13 -0700669 // We don't throttle vsync if the app set a vsync request rate
670 // since there is no easy way to do that and this is a very
671 // rare case
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800672 return event.vsync.count % vsyncPeriod(connection->vsyncRequest) == 0;
673 }
674
Ady Abraham62f216c2020-10-13 19:07:23 -0700675 case DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE:
676 [[fallthrough]];
677 case DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH:
678 return connection->mEventRegistration.test(
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700679 gui::ISurfaceComposer::EventRegistration::frameRateOverride);
Ady Abraham62f216c2020-10-13 19:07:23 -0700680
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800681 default:
682 return false;
683 }
684}
685
Rachel Lee8d0c6102021-11-03 22:00:25 +0000686int64_t EventThread::generateToken(nsecs_t timestamp, nsecs_t deadlineTimestamp,
Rachel Leeb9c5a772022-02-04 21:17:37 -0800687 nsecs_t expectedPresentationTime) const {
Rachel Lee3f028662021-11-04 19:32:24 +0000688 if (mTokenManager != nullptr) {
689 return mTokenManager->generateTokenForPredictions(
Rachel Leeb9c5a772022-02-04 21:17:37 -0800690 {timestamp, deadlineTimestamp, expectedPresentationTime});
Rachel Lee3f028662021-11-04 19:32:24 +0000691 }
692 return FrameTimelineInfo::INVALID_VSYNC_ID;
693}
694
Rachel Leeb9c5a772022-02-04 21:17:37 -0800695void EventThread::generateFrameTimeline(VsyncEventData& outVsyncEventData, nsecs_t frameInterval,
696 nsecs_t timestamp,
697 nsecs_t preferredExpectedPresentationTime,
698 nsecs_t preferredDeadlineTimestamp) const {
Rachel Lee0655a912023-04-20 19:54:18 -0700699 uint32_t currentIndex = 0;
Rachel Lee3f028662021-11-04 19:32:24 +0000700 // Add 1 to ensure the preferredFrameTimelineIndex entry (when multiplier == 0) is included.
Rachel Lee40aef422023-04-25 14:35:47 -0700701 for (int64_t multiplier = -VsyncEventData::kFrameTimelinesCapacity + 1;
702 currentIndex < VsyncEventData::kFrameTimelinesCapacity; multiplier++) {
Rachel Leeb9c5a772022-02-04 21:17:37 -0800703 nsecs_t deadlineTimestamp = preferredDeadlineTimestamp + multiplier * frameInterval;
Rachel Lee0655a912023-04-20 19:54:18 -0700704 // Valid possible frame timelines must have future values, so find a later frame timeline.
705 if (deadlineTimestamp <= timestamp) {
706 continue;
Rachel Lee3f028662021-11-04 19:32:24 +0000707 }
Rachel Lee0655a912023-04-20 19:54:18 -0700708
709 nsecs_t expectedPresentationTime =
710 preferredExpectedPresentationTime + multiplier * frameInterval;
711 if (expectedPresentationTime >= preferredExpectedPresentationTime +
712 scheduler::VsyncConfig::kEarlyLatchMaxThreshold.count()) {
Rachel Leeafb6b502023-05-12 15:53:05 -0700713 if (currentIndex == 0) {
714 ALOGW("%s: Expected present time is too far in the future but no timelines are "
715 "valid. preferred EPT=%" PRId64 ", Calculated EPT=%" PRId64
716 ", multiplier=%" PRId64 ", frameInterval=%" PRId64 ", threshold=%" PRId64,
717 __func__, preferredExpectedPresentationTime, expectedPresentationTime,
718 multiplier, frameInterval,
719 static_cast<int64_t>(
720 scheduler::VsyncConfig::kEarlyLatchMaxThreshold.count()));
721 }
Rachel Lee0655a912023-04-20 19:54:18 -0700722 break;
723 }
724
725 if (multiplier == 0) {
726 outVsyncEventData.preferredFrameTimelineIndex = currentIndex;
727 }
728
729 outVsyncEventData.frameTimelines[currentIndex] =
730 {.vsyncId = generateToken(timestamp, deadlineTimestamp, expectedPresentationTime),
731 .deadlineTimestamp = deadlineTimestamp,
732 .expectedPresentationTime = expectedPresentationTime};
733 currentIndex++;
Rachel Lee3f028662021-11-04 19:32:24 +0000734 }
Rachel Leeafb6b502023-05-12 15:53:05 -0700735
736 if (currentIndex == 0) {
737 ALOGW("%s: No timelines are valid. preferred EPT=%" PRId64 ", frameInterval=%" PRId64
738 ", threshold=%" PRId64,
739 __func__, preferredExpectedPresentationTime, frameInterval,
740 static_cast<int64_t>(scheduler::VsyncConfig::kEarlyLatchMaxThreshold.count()));
741 outVsyncEventData.frameTimelines[currentIndex] =
742 {.vsyncId = generateToken(timestamp, preferredDeadlineTimestamp,
743 preferredExpectedPresentationTime),
744 .deadlineTimestamp = preferredDeadlineTimestamp,
745 .expectedPresentationTime = preferredExpectedPresentationTime};
746 currentIndex++;
747 }
748
Rachel Lee0655a912023-04-20 19:54:18 -0700749 outVsyncEventData.frameTimelinesLength = currentIndex;
Rachel Lee3f028662021-11-04 19:32:24 +0000750}
751
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800752void EventThread::dispatchEvent(const DisplayEventReceiver::Event& event,
753 const DisplayEventConsumers& consumers) {
Melody Hsue524dd92024-08-27 22:27:29 +0000754 // List of Uids that have been sent vsync data with queued buffer count.
755 // Used to keep track of which Uids can be removed from the map of
756 // buffer stuffed clients.
757 ftl::SmallVector<uid_t, 10> uidsPostedQueuedBuffers;
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800758 for (const auto& consumer : consumers) {
Jorim Jaggic0086af2021-02-12 18:18:11 +0100759 DisplayEventReceiver::Event copy = event;
760 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_VSYNC) {
Ady Abrahamf2851612023-09-25 17:19:00 -0700761 const Period frameInterval = mCallback.getVsyncPeriod(consumer->mOwnerUid);
762 copy.vsync.vsyncData.frameInterval = frameInterval.ns();
763 generateFrameTimeline(copy.vsync.vsyncData, frameInterval.ns(), copy.header.timestamp,
Rachel Leeb9c5a772022-02-04 21:17:37 -0800764 event.vsync.vsyncData.preferredExpectedPresentationTime(),
765 event.vsync.vsyncData.preferredDeadlineTimestamp());
Jorim Jaggic0086af2021-02-12 18:18:11 +0100766 }
Melody Hsue524dd92024-08-27 22:27:29 +0000767 auto it = mBufferStuffedUids.find(consumer->mOwnerUid);
768 if (it != mBufferStuffedUids.end()) {
769 copy.vsync.vsyncData.numberQueuedBuffers = it->second;
770 uidsPostedQueuedBuffers.emplace_back(consumer->mOwnerUid);
771 } else {
772 copy.vsync.vsyncData.numberQueuedBuffers = 0;
773 }
Jorim Jaggic0086af2021-02-12 18:18:11 +0100774 switch (consumer->postEvent(copy)) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800775 case NO_ERROR:
776 break;
777
778 case -EAGAIN:
779 // TODO: Try again if pipe is full.
780 ALOGW("Failed dispatching %s for %s", toString(event).c_str(),
781 toString(*consumer).c_str());
782 break;
783
784 default:
785 // Treat EPIPE and other errors as fatal.
786 removeDisplayEventConnectionLocked(consumer);
787 }
788 }
Melody Hsue524dd92024-08-27 22:27:29 +0000789 // The clients that have already received the queued buffer count
790 // can be removed from the buffer stuffed Uid list to avoid
791 // being sent duplicate messages.
792 for (auto uid : uidsPostedQueuedBuffers) {
793 mBufferStuffedUids.erase(uid);
794 }
ramindaniae645822024-01-11 10:57:29 -0800795 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_VSYNC &&
796 FlagManager::getInstance().vrr_config()) {
ramindani92ab9872024-07-26 15:09:37 -0700797 mLastCommittedVsyncTime =
798 TimePoint::fromNs(event.vsync.vsyncData.preferredExpectedPresentationTime());
799 mCallback.onExpectedPresentTimePosted(mLastCommittedVsyncTime);
ramindaniae645822024-01-11 10:57:29 -0800800 }
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700801}
802
Yiwei Zhang5434a782018-12-05 18:06:32 -0800803void EventThread::dump(std::string& result) const {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800804 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800805
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800806 StringAppendF(&result, "%s: state=%s VSyncState=", mThreadName, toCString(mState));
807 if (mVSyncState) {
Marin Shalamanova524a092020-07-27 21:39:55 +0200808 StringAppendF(&result, "{displayId=%s, count=%u%s}\n",
Ben Widawsky59954c42024-09-16 14:52:59 -0700809 to_string(mVsyncSchedule->getPhysicalDisplayId()).c_str(), mVSyncState->count,
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800810 mVSyncState->synthetic ? ", synthetic" : "");
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800811 } else {
812 StringAppendF(&result, "none\n");
813 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800814
Ady Abraham011f8ba2022-11-22 15:09:07 -0800815 const auto relativeLastCallTime =
816 ticks<std::milli, float>(mLastVsyncCallbackTime - TimePoint::now());
ramindani92ab9872024-07-26 15:09:37 -0700817 const auto relativeLastCommittedTime =
818 ticks<std::milli, float>(mLastCommittedVsyncTime - TimePoint::now());
Ady Abraham011f8ba2022-11-22 15:09:07 -0800819 StringAppendF(&result, "mWorkDuration=%.2f mReadyDuration=%.2f last vsync time ",
820 mWorkDuration.get().count() / 1e6f, mReadyDuration.count() / 1e6f);
821 StringAppendF(&result, "%.2fms relative to now\n", relativeLastCallTime);
ramindani92ab9872024-07-26 15:09:37 -0700822 StringAppendF(&result, " with vsync committed at %.2fms", relativeLastCommittedTime);
Ady Abraham011f8ba2022-11-22 15:09:07 -0800823
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800824 StringAppendF(&result, " pending events (count=%zu):\n", mPendingEvents.size());
825 for (const auto& event : mPendingEvents) {
826 StringAppendF(&result, " %s\n", toString(event).c_str());
Mathias Agopiane2c4f4e2012-04-10 18:25:31 -0700827 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800828
829 StringAppendF(&result, " connections (count=%zu):\n", mDisplayEventConnections.size());
830 for (const auto& ptr : mDisplayEventConnections) {
831 if (const auto connection = ptr.promote()) {
832 StringAppendF(&result, " %s\n", toString(*connection).c_str());
833 }
834 }
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400835 result += '\n';
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800836}
837
Dominik Laskowski029cc122019-01-23 19:52:06 -0800838const char* EventThread::toCString(State state) {
839 switch (state) {
840 case State::Idle:
841 return "Idle";
842 case State::Quit:
843 return "Quit";
844 case State::SyntheticVSync:
845 return "SyntheticVSync";
846 case State::VSync:
847 return "VSync";
848 }
849}
850
Leon Scroggins III67388622023-02-06 20:36:20 -0500851void EventThread::onNewVsyncSchedule(std::shared_ptr<scheduler::VsyncSchedule> schedule) {
Leon Scroggins IIIb2253602023-04-19 17:04:04 -0400852 // Hold onto the old registration until after releasing the mutex to avoid deadlock.
853 scheduler::VSyncCallbackRegistration oldRegistration =
854 onNewVsyncScheduleInternal(std::move(schedule));
855}
856
857scheduler::VSyncCallbackRegistration EventThread::onNewVsyncScheduleInternal(
858 std::shared_ptr<scheduler::VsyncSchedule> schedule) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500859 std::lock_guard<std::mutex> lock(mMutex);
860 const bool reschedule = mVsyncRegistration.cancel() == scheduler::CancelResult::Cancelled;
861 mVsyncSchedule = std::move(schedule);
Leon Scroggins IIIb2253602023-04-19 17:04:04 -0400862 auto oldRegistration =
863 std::exchange(mVsyncRegistration,
864 scheduler::VSyncCallbackRegistration(mVsyncSchedule->getDispatch(),
865 createDispatchCallback(),
866 mThreadName));
Leon Scroggins III67388622023-02-06 20:36:20 -0500867 if (reschedule) {
868 mVsyncRegistration.schedule({.workDuration = mWorkDuration.get().count(),
869 .readyDuration = mReadyDuration.count(),
ramindani92ab9872024-07-26 15:09:37 -0700870 .lastVsync = mLastVsyncCallbackTime.ns(),
871 .committedVsyncOpt = mLastCommittedVsyncTime.ns()});
Leon Scroggins III67388622023-02-06 20:36:20 -0500872 }
Leon Scroggins IIIb2253602023-04-19 17:04:04 -0400873 return oldRegistration;
Leon Scroggins III67388622023-02-06 20:36:20 -0500874}
875
876scheduler::VSyncDispatch::Callback EventThread::createDispatchCallback() {
877 return [this](nsecs_t vsyncTime, nsecs_t wakeupTime, nsecs_t readyTime) {
878 onVsync(vsyncTime, wakeupTime, readyTime);
879 };
880}
881
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800882} // namespace impl
Lloyd Pique46a46b32018-01-31 19:01:18 -0800883} // namespace android
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800884
885// TODO(b/129481165): remove the #pragma below and fix conversion issues
886#pragma clang diagnostic pop // ignored "-Wconversion"