blob: b63e8c835bf1b07e03a8a67eeadc539b5432d7aa [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>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080031
Yiwei Zhang5434a782018-12-05 18:06:32 -080032#include <android-base/stringprintf.h>
33
Ady Abraham0bb6a472020-10-12 10:22:13 -070034#include <binder/IPCThreadState.h>
35
Mathias Agopiana4cb35a2012-08-20 20:07:34 -070036#include <cutils/compiler.h>
Lloyd Pique46a46b32018-01-31 19:01:18 -080037#include <cutils/sched_policy.h>
Mathias Agopiana4cb35a2012-08-20 20:07:34 -070038
Mathias Agopiand0566bc2011-11-17 17:49:17 -080039#include <gui/DisplayEventReceiver.h>
40
41#include <utils/Errors.h>
Mathias Agopian841cde52012-03-01 15:44:37 -080042#include <utils/Trace.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080043
Mathias Agopiand0566bc2011-11-17 17:49:17 -080044#include "EventThread.h"
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -070045#include "FrameTimeline.h"
Ady Abraham2139f732019-11-13 18:56:40 -080046#include "HwcStrongTypes.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080047
Ady Abraham62f216c2020-10-13 19:07:23 -070048#undef LOG_TAG
49#define LOG_TAG "EventThread"
50
Lloyd Pique46a46b32018-01-31 19:01:18 -080051using namespace std::chrono_literals;
Mathias Agopiand0566bc2011-11-17 17:49:17 -080052
Lloyd Pique46a46b32018-01-31 19:01:18 -080053namespace android {
54
Dominik Laskowskid9e4de62019-01-21 14:23:01 -080055using base::StringAppendF;
56using base::StringPrintf;
57
58namespace {
59
60auto vsyncPeriod(VSyncRequest request) {
61 return static_cast<std::underlying_type_t<VSyncRequest>>(request);
62}
63
64std::string toString(VSyncRequest request) {
65 switch (request) {
66 case VSyncRequest::None:
67 return "VSyncRequest::None";
68 case VSyncRequest::Single:
69 return "VSyncRequest::Single";
Tim Murrayb5daa912020-09-09 21:29:13 +000070 case VSyncRequest::SingleSuppressCallback:
71 return "VSyncRequest::SingleSuppressCallback";
Dominik Laskowskid9e4de62019-01-21 14:23:01 -080072 default:
73 return StringPrintf("VSyncRequest::Periodic{period=%d}", vsyncPeriod(request));
74 }
75}
76
77std::string toString(const EventThreadConnection& connection) {
78 return StringPrintf("Connection{%p, %s}", &connection,
79 toString(connection.vsyncRequest).c_str());
80}
81
82std::string toString(const DisplayEventReceiver::Event& event) {
83 switch (event.header.type) {
84 case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
Marin Shalamanova524a092020-07-27 21:39:55 +020085 return StringPrintf("Hotplug{displayId=%s, %s}",
86 to_string(event.header.displayId).c_str(),
Dominik Laskowskid9e4de62019-01-21 14:23:01 -080087 event.hotplug.connected ? "connected" : "disconnected");
88 case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
Marin Shalamanova524a092020-07-27 21:39:55 +020089 return StringPrintf("VSync{displayId=%s, count=%u, expectedVSyncTimestamp=%" PRId64 "}",
90 to_string(event.header.displayId).c_str(), event.vsync.count,
Ady Abraham5facfb12020-04-22 15:18:31 -070091 event.vsync.expectedVSyncTimestamp);
Ady Abraham0f4a1b12019-06-04 16:04:04 -070092 case DisplayEventReceiver::DISPLAY_EVENT_CONFIG_CHANGED:
Marin Shalamanova524a092020-07-27 21:39:55 +020093 return StringPrintf("ConfigChanged{displayId=%s, configId=%u}",
94 to_string(event.header.displayId).c_str(), event.config.configId);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -080095 default:
96 return "Event{}";
97 }
98}
99
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800100DisplayEventReceiver::Event makeHotplug(PhysicalDisplayId displayId, nsecs_t timestamp,
101 bool connected) {
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800102 DisplayEventReceiver::Event event;
103 event.header = {DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG, displayId, timestamp};
104 event.hotplug.connected = connected;
105 return event;
106}
107
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800108DisplayEventReceiver::Event makeVSync(PhysicalDisplayId displayId, nsecs_t timestamp,
Ady Abraham8cb21882020-08-26 18:22:05 -0700109 uint32_t count, nsecs_t expectedVSyncTimestamp,
Ady Abraham74e17562020-08-24 18:18:19 -0700110 nsecs_t deadlineTimestamp, int64_t vsyncId) {
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800111 DisplayEventReceiver::Event event;
112 event.header = {DisplayEventReceiver::DISPLAY_EVENT_VSYNC, displayId, timestamp};
113 event.vsync.count = count;
Ady Abraham5facfb12020-04-22 15:18:31 -0700114 event.vsync.expectedVSyncTimestamp = expectedVSyncTimestamp;
Ady Abraham8cb21882020-08-26 18:22:05 -0700115 event.vsync.deadlineTimestamp = deadlineTimestamp;
Ady Abraham74e17562020-08-24 18:18:19 -0700116 event.vsync.vsyncId = vsyncId;
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800117 return event;
118}
119
Ady Abraham2139f732019-11-13 18:56:40 -0800120DisplayEventReceiver::Event makeConfigChanged(PhysicalDisplayId displayId,
Alec Mouri60aee1c2019-10-28 16:18:59 -0700121 HwcConfigIndexType configId, nsecs_t vsyncPeriod) {
Ady Abraham447052e2019-02-13 16:07:27 -0800122 DisplayEventReceiver::Event event;
123 event.header = {DisplayEventReceiver::DISPLAY_EVENT_CONFIG_CHANGED, displayId, systemTime()};
Ady Abraham2139f732019-11-13 18:56:40 -0800124 event.config.configId = configId.value();
Alec Mouri60aee1c2019-10-28 16:18:59 -0700125 event.config.vsyncPeriod = vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -0800126 return event;
127}
128
Ady Abraham62f216c2020-10-13 19:07:23 -0700129DisplayEventReceiver::Event makeFrameRateOverrideEvent(PhysicalDisplayId displayId,
130 FrameRateOverride frameRateOverride) {
131 return DisplayEventReceiver::Event{
132 .header =
133 DisplayEventReceiver::Event::Header{
134 .type = DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE,
135 .displayId = displayId,
136 .timestamp = systemTime(),
137 },
138 .frameRateOverride = frameRateOverride,
139 };
140}
141
142DisplayEventReceiver::Event makeFrameRateOverrideFlushEvent(PhysicalDisplayId displayId) {
143 return DisplayEventReceiver::Event{
144 .header = DisplayEventReceiver::Event::Header{
145 .type = DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH,
146 .displayId = displayId,
147 .timestamp = systemTime(),
148 }};
149}
150
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800151} // namespace
Lloyd Pique46a46b32018-01-31 19:01:18 -0800152
Ady Abraham62f216c2020-10-13 19:07:23 -0700153EventThreadConnection::EventThreadConnection(
154 EventThread* eventThread, uid_t callingUid, ResyncCallback resyncCallback,
155 ISurfaceComposer::EventRegistrationFlags eventRegistration)
Dominik Laskowskif654d572018-12-20 11:03:06 -0800156 : resyncCallback(std::move(resyncCallback)),
Ady Abraham0bb6a472020-10-12 10:22:13 -0700157 mOwnerUid(callingUid),
Ady Abraham62f216c2020-10-13 19:07:23 -0700158 mEventRegistration(eventRegistration),
Dominik Laskowskif654d572018-12-20 11:03:06 -0800159 mEventThread(eventThread),
160 mChannel(gui::BitTube::DefaultSize) {}
Ana Krulec85c39af2018-12-26 17:29:57 -0800161
162EventThreadConnection::~EventThreadConnection() {
163 // do nothing here -- clean-up will happen automatically
164 // when the main thread wakes up
165}
166
167void EventThreadConnection::onFirstRef() {
168 // NOTE: mEventThread doesn't hold a strong reference on us
169 mEventThread->registerDisplayEventConnection(this);
170}
171
172status_t EventThreadConnection::stealReceiveChannel(gui::BitTube* outChannel) {
173 outChannel->setReceiveFd(mChannel.moveReceiveFd());
Alec Mouri967d5d72020-08-05 12:50:03 -0700174 outChannel->setSendFd(base::unique_fd(dup(mChannel.getSendFd())));
Ana Krulec85c39af2018-12-26 17:29:57 -0800175 return NO_ERROR;
176}
177
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800178status_t EventThreadConnection::setVsyncRate(uint32_t rate) {
179 mEventThread->setVsyncRate(rate, this);
Ana Krulec85c39af2018-12-26 17:29:57 -0800180 return NO_ERROR;
181}
182
183void EventThreadConnection::requestNextVsync() {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800184 ATRACE_NAME("requestNextVsync");
Ady Abraham8532d012019-05-08 14:50:56 -0700185 mEventThread->requestNextVsync(this);
Ana Krulec85c39af2018-12-26 17:29:57 -0800186}
187
188status_t EventThreadConnection::postEvent(const DisplayEventReceiver::Event& event) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700189 constexpr auto toStatus = [](ssize_t size) {
190 return size < 0 ? status_t(size) : status_t(NO_ERROR);
191 };
192
193 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE ||
194 event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH) {
195 mPendingEvents.emplace_back(event);
196 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE) {
197 return status_t(NO_ERROR);
198 }
199
200 auto size = DisplayEventReceiver::sendEvents(&mChannel, mPendingEvents.data(),
201 mPendingEvents.size());
202 mPendingEvents.clear();
203 return toStatus(size);
204 }
205
206 auto size = DisplayEventReceiver::sendEvents(&mChannel, &event, 1);
207 return toStatus(size);
Ana Krulec85c39af2018-12-26 17:29:57 -0800208}
209
210// ---------------------------------------------------------------------------
211
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800212EventThread::~EventThread() = default;
213
214namespace impl {
215
Dominik Laskowski6505f792019-09-18 11:10:05 -0700216EventThread::EventThread(std::unique_ptr<VSyncSource> vsyncSource,
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700217 android::frametimeline::TokenManager* tokenManager,
Ady Abraham0bb6a472020-10-12 10:22:13 -0700218 InterceptVSyncsCallback interceptVSyncsCallback,
219 ThrottleVsyncCallback throttleVsyncCallback)
Dominik Laskowski6505f792019-09-18 11:10:05 -0700220 : mVSyncSource(std::move(vsyncSource)),
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700221 mTokenManager(tokenManager),
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800222 mInterceptVSyncsCallback(std::move(interceptVSyncsCallback)),
Ady Abraham0bb6a472020-10-12 10:22:13 -0700223 mThrottleVsyncCallback(std::move(throttleVsyncCallback)),
Dominik Laskowski6505f792019-09-18 11:10:05 -0700224 mThreadName(mVSyncSource->getName()) {
Dominik Laskowski029cc122019-01-23 19:52:06 -0800225 mVSyncSource->setCallback(this);
Lloyd Pique46a46b32018-01-31 19:01:18 -0800226
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800227 mThread = std::thread([this]() NO_THREAD_SAFETY_ANALYSIS {
228 std::unique_lock<std::mutex> lock(mMutex);
229 threadMain(lock);
230 });
Lloyd Pique46a46b32018-01-31 19:01:18 -0800231
Dominik Laskowski6505f792019-09-18 11:10:05 -0700232 pthread_setname_np(mThread.native_handle(), mThreadName);
Lloyd Pique46a46b32018-01-31 19:01:18 -0800233
234 pid_t tid = pthread_gettid_np(mThread.native_handle());
235
236 // Use SCHED_FIFO to minimize jitter
237 constexpr int EVENT_THREAD_PRIORITY = 2;
238 struct sched_param param = {0};
239 param.sched_priority = EVENT_THREAD_PRIORITY;
240 if (pthread_setschedparam(mThread.native_handle(), SCHED_FIFO, &param) != 0) {
241 ALOGE("Couldn't set SCHED_FIFO for EventThread");
242 }
243
244 set_sched_policy(tid, SP_FOREGROUND);
245}
246
247EventThread::~EventThread() {
Dominik Laskowski029cc122019-01-23 19:52:06 -0800248 mVSyncSource->setCallback(nullptr);
249
Lloyd Pique46a46b32018-01-31 19:01:18 -0800250 {
251 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski029cc122019-01-23 19:52:06 -0800252 mState = State::Quit;
Lloyd Pique46a46b32018-01-31 19:01:18 -0800253 mCondition.notify_all();
254 }
255 mThread.join();
Ruchi Kandoief472ec2014-04-02 12:50:06 -0700256}
257
Ady Abraham9c53ee72020-07-22 21:16:18 -0700258void EventThread::setDuration(std::chrono::nanoseconds workDuration,
259 std::chrono::nanoseconds readyDuration) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800260 std::lock_guard<std::mutex> lock(mMutex);
Ady Abraham9c53ee72020-07-22 21:16:18 -0700261 mVSyncSource->setDuration(workDuration, readyDuration);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700262}
263
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700264sp<EventThreadConnection> EventThread::createEventConnection(
Ady Abraham62f216c2020-10-13 19:07:23 -0700265 ResyncCallback resyncCallback,
266 ISurfaceComposer::EventRegistrationFlags eventRegistration) const {
Ady Abraham0bb6a472020-10-12 10:22:13 -0700267 return new EventThreadConnection(const_cast<EventThread*>(this),
268 IPCThreadState::self()->getCallingUid(),
Ady Abraham62f216c2020-10-13 19:07:23 -0700269 std::move(resyncCallback), eventRegistration);
Mathias Agopian8aedd472012-01-24 16:39:14 -0800270}
271
Ana Krulec85c39af2018-12-26 17:29:57 -0800272status_t EventThread::registerDisplayEventConnection(const sp<EventThreadConnection>& connection) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800273 std::lock_guard<std::mutex> lock(mMutex);
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700274
275 // this should never happen
276 auto it = std::find(mDisplayEventConnections.cbegin(),
277 mDisplayEventConnections.cend(), connection);
278 if (it != mDisplayEventConnections.cend()) {
279 ALOGW("DisplayEventConnection %p already exists", connection.get());
280 mCondition.notify_all();
281 return ALREADY_EXISTS;
282 }
283
284 mDisplayEventConnections.push_back(connection);
Lloyd Pique46a46b32018-01-31 19:01:18 -0800285 mCondition.notify_all();
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800286 return NO_ERROR;
287}
288
Ana Krulec85c39af2018-12-26 17:29:57 -0800289void EventThread::removeDisplayEventConnectionLocked(const wp<EventThreadConnection>& connection) {
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700290 auto it = std::find(mDisplayEventConnections.cbegin(),
291 mDisplayEventConnections.cend(), connection);
292 if (it != mDisplayEventConnections.cend()) {
293 mDisplayEventConnections.erase(it);
294 }
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800295}
296
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800297void EventThread::setVsyncRate(uint32_t rate, const sp<EventThreadConnection>& connection) {
298 if (static_cast<std::underlying_type_t<VSyncRequest>>(rate) < 0) {
299 return;
300 }
301
302 std::lock_guard<std::mutex> lock(mMutex);
303
304 const auto request = rate == 0 ? VSyncRequest::None : static_cast<VSyncRequest>(rate);
305 if (connection->vsyncRequest != request) {
306 connection->vsyncRequest = request;
307 mCondition.notify_all();
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800308 }
309}
310
Ady Abraham8532d012019-05-08 14:50:56 -0700311void EventThread::requestNextVsync(const sp<EventThreadConnection>& connection) {
Dominik Laskowskif654d572018-12-20 11:03:06 -0800312 if (connection->resyncCallback) {
313 connection->resyncCallback();
Lloyd Pique24b0a482018-03-09 18:52:26 -0800314 }
Tim Murray4a4e4a22016-04-19 16:29:23 +0000315
Ana Krulec7d1d6832018-12-27 11:10:09 -0800316 std::lock_guard<std::mutex> lock(mMutex);
317
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800318 if (connection->vsyncRequest == VSyncRequest::None) {
319 connection->vsyncRequest = VSyncRequest::Single;
Lloyd Pique46a46b32018-01-31 19:01:18 -0800320 mCondition.notify_all();
Tim Murrayb5daa912020-09-09 21:29:13 +0000321 } else if (connection->vsyncRequest == VSyncRequest::SingleSuppressCallback) {
322 connection->vsyncRequest = VSyncRequest::Single;
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800323 }
Mathias Agopian23748662011-12-05 14:33:34 -0800324}
325
Mathias Agopian22ffb112012-04-10 21:04:02 -0700326void EventThread::onScreenReleased() {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800327 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800328 if (!mVSyncState || mVSyncState->synthetic) {
329 return;
Mathias Agopian22ffb112012-04-10 21:04:02 -0700330 }
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800331
332 mVSyncState->synthetic = true;
333 mCondition.notify_all();
Mathias Agopian22ffb112012-04-10 21:04:02 -0700334}
335
336void EventThread::onScreenAcquired() {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800337 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800338 if (!mVSyncState || !mVSyncState->synthetic) {
339 return;
Mathias Agopian7d886472012-06-14 23:39:35 -0700340 }
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800341
342 mVSyncState->synthetic = false;
343 mCondition.notify_all();
Mathias Agopian22ffb112012-04-10 21:04:02 -0700344}
345
Ady Abraham9c53ee72020-07-22 21:16:18 -0700346void EventThread::onVSyncEvent(nsecs_t timestamp, nsecs_t expectedVSyncTimestamp,
Ady Abraham8cb21882020-08-26 18:22:05 -0700347 nsecs_t deadlineTimestamp) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800348 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800349
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800350 LOG_FATAL_IF(!mVSyncState);
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700351 const int64_t vsyncId = [&] {
352 if (mTokenManager != nullptr) {
353 return mTokenManager->generateTokenForPredictions(
354 {timestamp, deadlineTimestamp, expectedVSyncTimestamp});
355 }
356 return static_cast<int64_t>(0);
357 }();
358
Ady Abraham5facfb12020-04-22 15:18:31 -0700359 mPendingEvents.push_back(makeVSync(mVSyncState->displayId, timestamp, ++mVSyncState->count,
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700360 expectedVSyncTimestamp, deadlineTimestamp, vsyncId));
Lloyd Pique46a46b32018-01-31 19:01:18 -0800361 mCondition.notify_all();
Mathias Agopian3eb38cb2012-04-03 22:09:52 -0700362}
363
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800364void EventThread::onHotplugReceived(PhysicalDisplayId displayId, bool connected) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800365 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -0700366
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800367 mPendingEvents.push_back(makeHotplug(displayId, systemTime(), connected));
Dominik Laskowski00a6fa22018-06-06 16:42:02 -0700368 mCondition.notify_all();
Mathias Agopian148994e2012-09-19 17:31:36 -0700369}
370
Alec Mouri60aee1c2019-10-28 16:18:59 -0700371void EventThread::onConfigChanged(PhysicalDisplayId displayId, HwcConfigIndexType configId,
372 nsecs_t vsyncPeriod) {
Ady Abraham447052e2019-02-13 16:07:27 -0800373 std::lock_guard<std::mutex> lock(mMutex);
374
Alec Mouri60aee1c2019-10-28 16:18:59 -0700375 mPendingEvents.push_back(makeConfigChanged(displayId, configId, vsyncPeriod));
Ady Abraham447052e2019-02-13 16:07:27 -0800376 mCondition.notify_all();
377}
378
Ady Abraham62f216c2020-10-13 19:07:23 -0700379void EventThread::onFrameRateOverridesChanged(PhysicalDisplayId displayId,
380 std::vector<FrameRateOverride> overrides) {
381 std::lock_guard<std::mutex> lock(mMutex);
382
383 for (auto frameRateOverride : overrides) {
384 mPendingEvents.push_back(makeFrameRateOverrideEvent(displayId, frameRateOverride));
385 }
386 mPendingEvents.push_back(makeFrameRateOverrideFlushEvent(displayId));
387
388 mCondition.notify_all();
389}
390
Alec Mouri717bcb62020-02-10 17:07:19 -0800391size_t EventThread::getEventThreadConnectionCount() {
392 std::lock_guard<std::mutex> lock(mMutex);
393 return mDisplayEventConnections.size();
394}
395
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800396void EventThread::threadMain(std::unique_lock<std::mutex>& lock) {
397 DisplayEventConsumers consumers;
398
Dominik Laskowski029cc122019-01-23 19:52:06 -0800399 while (mState != State::Quit) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800400 std::optional<DisplayEventReceiver::Event> event;
Mathias Agopian3eb38cb2012-04-03 22:09:52 -0700401
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800402 // Determine next event to dispatch.
403 if (!mPendingEvents.empty()) {
404 event = mPendingEvents.front();
405 mPendingEvents.pop_front();
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800406
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800407 switch (event->header.type) {
408 case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
409 if (event->hotplug.connected && !mVSyncState) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800410 mVSyncState.emplace(event->header.displayId);
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800411 } else if (!event->hotplug.connected && mVSyncState &&
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800412 mVSyncState->displayId == event->header.displayId) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800413 mVSyncState.reset();
414 }
415 break;
416
417 case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
418 if (mInterceptVSyncsCallback) {
419 mInterceptVSyncsCallback(event->header.timestamp);
420 }
421 break;
Dominik Laskowski029cc122019-01-23 19:52:06 -0800422 }
Mathias Agopianff28e202012-09-20 23:24:19 -0700423 }
424
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800425 bool vsyncRequested = false;
Mathias Agopian148994e2012-09-19 17:31:36 -0700426
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800427 // Find connections that should consume this event.
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700428 auto it = mDisplayEventConnections.begin();
429 while (it != mDisplayEventConnections.end()) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800430 if (const auto connection = it->promote()) {
431 vsyncRequested |= connection->vsyncRequest != VSyncRequest::None;
432
433 if (event && shouldConsumeEvent(*event, connection)) {
434 consumers.push_back(connection);
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700435 }
Mathias Agopianb4d18ed2012-09-20 23:14:05 -0700436
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700437 ++it;
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700438 } else {
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700439 it = mDisplayEventConnections.erase(it);
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700440 }
441 }
442
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800443 if (!consumers.empty()) {
444 dispatchEvent(*event, consumers);
445 consumers.clear();
446 }
447
Dominik Laskowski029cc122019-01-23 19:52:06 -0800448 State nextState;
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800449 if (mVSyncState && vsyncRequested) {
450 nextState = mVSyncState->synthetic ? State::SyntheticVSync : State::VSync;
Dominik Laskowski029cc122019-01-23 19:52:06 -0800451 } else {
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800452 ALOGW_IF(!mVSyncState, "Ignoring VSYNC request while display is disconnected");
Dominik Laskowski029cc122019-01-23 19:52:06 -0800453 nextState = State::Idle;
454 }
455
456 if (mState != nextState) {
457 if (mState == State::VSync) {
458 mVSyncSource->setVSyncEnabled(false);
459 } else if (nextState == State::VSync) {
460 mVSyncSource->setVSyncEnabled(true);
461 }
462
463 mState = nextState;
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700464 }
465
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800466 if (event) {
467 continue;
468 }
469
470 // Wait for event or client registration/request.
Dominik Laskowski029cc122019-01-23 19:52:06 -0800471 if (mState == State::Idle) {
472 mCondition.wait(lock);
473 } else {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800474 // Generate a fake VSYNC after a long timeout in case the driver stalls. When the
475 // display is off, keep feeding clients at 60 Hz.
Ady Abraham5facfb12020-04-22 15:18:31 -0700476 const std::chrono::nanoseconds timeout =
477 mState == State::SyntheticVSync ? 16ms : 1000ms;
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800478 if (mCondition.wait_for(lock, timeout) == std::cv_status::timeout) {
Ady Abraham5e7371c2020-03-24 14:47:24 -0700479 if (mState == State::VSync) {
480 ALOGW("Faking VSYNC due to driver stall for thread %s", mThreadName);
481 std::string debugInfo = "VsyncSource debug info:\n";
482 mVSyncSource->dump(debugInfo);
Ady Abraham75398722020-04-07 14:08:45 -0700483 // Log the debug info line-by-line to avoid logcat overflow
484 auto pos = debugInfo.find('\n');
485 while (pos != std::string::npos) {
486 ALOGW("%s", debugInfo.substr(0, pos).c_str());
487 debugInfo = debugInfo.substr(pos + 1);
488 pos = debugInfo.find('\n');
489 }
Ady Abraham5e7371c2020-03-24 14:47:24 -0700490 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800491
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800492 LOG_FATAL_IF(!mVSyncState);
Ady Abraham5facfb12020-04-22 15:18:31 -0700493 const auto now = systemTime(SYSTEM_TIME_MONOTONIC);
Ady Abraham8cb21882020-08-26 18:22:05 -0700494 const auto deadlineTimestamp = now + timeout.count();
495 const auto expectedVSyncTime = deadlineTimestamp + timeout.count();
Ady Abraham74e17562020-08-24 18:18:19 -0700496 // TODO(b/162890590): use TokenManager to populate vsyncId
Ady Abraham5facfb12020-04-22 15:18:31 -0700497 mPendingEvents.push_back(makeVSync(mVSyncState->displayId, now,
Ady Abraham8cb21882020-08-26 18:22:05 -0700498 ++mVSyncState->count, expectedVSyncTime,
Ady Abraham74e17562020-08-24 18:18:19 -0700499 deadlineTimestamp, /*vsyncId=*/0));
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700500 }
501 }
Lloyd Pique46a46b32018-01-31 19:01:18 -0800502 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800503}
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700504
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800505bool EventThread::shouldConsumeEvent(const DisplayEventReceiver::Event& event,
506 const sp<EventThreadConnection>& connection) const {
Ady Abraham0bb6a472020-10-12 10:22:13 -0700507 const auto throttleVsync = [&] {
508 return mThrottleVsyncCallback &&
509 mThrottleVsyncCallback(event.vsync.expectedVSyncTimestamp, connection->mOwnerUid);
510 };
511
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800512 switch (event.header.type) {
513 case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
514 return true;
515
Alec Mouri60aee1c2019-10-28 16:18:59 -0700516 case DisplayEventReceiver::DISPLAY_EVENT_CONFIG_CHANGED: {
Ady Abraham62f216c2020-10-13 19:07:23 -0700517 return connection->mEventRegistration.test(
518 ISurfaceComposer::EventRegistration::configChanged);
Alec Mouri60aee1c2019-10-28 16:18:59 -0700519 }
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700520
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800521 case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
522 switch (connection->vsyncRequest) {
523 case VSyncRequest::None:
524 return false;
Tim Murrayb5daa912020-09-09 21:29:13 +0000525 case VSyncRequest::SingleSuppressCallback:
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800526 connection->vsyncRequest = VSyncRequest::None;
Tim Murrayb5daa912020-09-09 21:29:13 +0000527 return false;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700528 case VSyncRequest::Single: {
529 if (throttleVsync()) {
530 return false;
531 }
Tim Murrayb5daa912020-09-09 21:29:13 +0000532 connection->vsyncRequest = VSyncRequest::SingleSuppressCallback;
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800533 return true;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700534 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800535 case VSyncRequest::Periodic:
Ady Abraham0bb6a472020-10-12 10:22:13 -0700536 if (throttleVsync()) {
537 return false;
538 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800539 return true;
540 default:
Ady Abraham0bb6a472020-10-12 10:22:13 -0700541 // We don't throttle vsync if the app set a vsync request rate
542 // since there is no easy way to do that and this is a very
543 // rare case
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800544 return event.vsync.count % vsyncPeriod(connection->vsyncRequest) == 0;
545 }
546
Ady Abraham62f216c2020-10-13 19:07:23 -0700547 case DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE:
548 [[fallthrough]];
549 case DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH:
550 return connection->mEventRegistration.test(
551 ISurfaceComposer::EventRegistration::frameRateOverride);
552
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800553 default:
554 return false;
555 }
556}
557
558void EventThread::dispatchEvent(const DisplayEventReceiver::Event& event,
559 const DisplayEventConsumers& consumers) {
560 for (const auto& consumer : consumers) {
561 switch (consumer->postEvent(event)) {
562 case NO_ERROR:
563 break;
564
565 case -EAGAIN:
566 // TODO: Try again if pipe is full.
567 ALOGW("Failed dispatching %s for %s", toString(event).c_str(),
568 toString(*consumer).c_str());
569 break;
570
571 default:
572 // Treat EPIPE and other errors as fatal.
573 removeDisplayEventConnectionLocked(consumer);
574 }
575 }
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700576}
577
Yiwei Zhang5434a782018-12-05 18:06:32 -0800578void EventThread::dump(std::string& result) const {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800579 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800580
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800581 StringAppendF(&result, "%s: state=%s VSyncState=", mThreadName, toCString(mState));
582 if (mVSyncState) {
Marin Shalamanova524a092020-07-27 21:39:55 +0200583 StringAppendF(&result, "{displayId=%s, count=%u%s}\n",
584 to_string(mVSyncState->displayId).c_str(), mVSyncState->count,
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800585 mVSyncState->synthetic ? ", synthetic" : "");
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800586 } else {
587 StringAppendF(&result, "none\n");
588 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800589
590 StringAppendF(&result, " pending events (count=%zu):\n", mPendingEvents.size());
591 for (const auto& event : mPendingEvents) {
592 StringAppendF(&result, " %s\n", toString(event).c_str());
Mathias Agopiane2c4f4e2012-04-10 18:25:31 -0700593 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800594
595 StringAppendF(&result, " connections (count=%zu):\n", mDisplayEventConnections.size());
596 for (const auto& ptr : mDisplayEventConnections) {
597 if (const auto connection = ptr.promote()) {
598 StringAppendF(&result, " %s\n", toString(*connection).c_str());
599 }
600 }
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800601}
602
Dominik Laskowski029cc122019-01-23 19:52:06 -0800603const char* EventThread::toCString(State state) {
604 switch (state) {
605 case State::Idle:
606 return "Idle";
607 case State::Quit:
608 return "Quit";
609 case State::SyntheticVSync:
610 return "SyntheticVSync";
611 case State::VSync:
612 return "VSync";
613 }
614}
615
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800616} // namespace impl
Lloyd Pique46a46b32018-01-31 19:01:18 -0800617} // namespace android
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800618
619// TODO(b/129481165): remove the #pragma below and fix conversion issues
620#pragma clang diagnostic pop // ignored "-Wconversion"