blob: bfe9b4a3bb7b7363f5dfa61ee7a2398087a31d4d [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
Marin Shalamanov23c44202020-12-22 19:09:20 +010044#include "DisplayHardware/DisplayMode.h"
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -070045#include "FrameTimeline.h"
Marin Shalamanov23c44202020-12-22 19:09:20 +010046
47#include "EventThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080048
Ady Abraham62f216c2020-10-13 19:07:23 -070049#undef LOG_TAG
50#define LOG_TAG "EventThread"
51
Lloyd Pique46a46b32018-01-31 19:01:18 -080052using namespace std::chrono_literals;
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Lloyd Pique46a46b32018-01-31 19:01:18 -080054namespace android {
55
Dominik Laskowskid9e4de62019-01-21 14:23:01 -080056using base::StringAppendF;
57using base::StringPrintf;
58
59namespace {
60
61auto vsyncPeriod(VSyncRequest request) {
62 return static_cast<std::underlying_type_t<VSyncRequest>>(request);
63}
64
65std::string toString(VSyncRequest request) {
66 switch (request) {
67 case VSyncRequest::None:
68 return "VSyncRequest::None";
69 case VSyncRequest::Single:
70 return "VSyncRequest::Single";
Tim Murrayb5daa912020-09-09 21:29:13 +000071 case VSyncRequest::SingleSuppressCallback:
72 return "VSyncRequest::SingleSuppressCallback";
Dominik Laskowskid9e4de62019-01-21 14:23:01 -080073 default:
74 return StringPrintf("VSyncRequest::Periodic{period=%d}", vsyncPeriod(request));
75 }
76}
77
78std::string toString(const EventThreadConnection& connection) {
79 return StringPrintf("Connection{%p, %s}", &connection,
80 toString(connection.vsyncRequest).c_str());
81}
82
83std::string toString(const DisplayEventReceiver::Event& event) {
84 switch (event.header.type) {
85 case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
Marin Shalamanova524a092020-07-27 21:39:55 +020086 return StringPrintf("Hotplug{displayId=%s, %s}",
87 to_string(event.header.displayId).c_str(),
Dominik Laskowskid9e4de62019-01-21 14:23:01 -080088 event.hotplug.connected ? "connected" : "disconnected");
89 case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
Marin Shalamanova524a092020-07-27 21:39:55 +020090 return StringPrintf("VSync{displayId=%s, count=%u, expectedVSyncTimestamp=%" PRId64 "}",
91 to_string(event.header.displayId).c_str(), event.vsync.count,
Ady Abraham5facfb12020-04-22 15:18:31 -070092 event.vsync.expectedVSyncTimestamp);
Marin Shalamanova7fe3042021-01-29 21:02:08 +010093 case DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE:
94 return StringPrintf("ModeChanged{displayId=%s, modeId=%u}",
95 to_string(event.header.displayId).c_str(), event.modeChange.modeId);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -080096 default:
97 return "Event{}";
98 }
99}
100
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800101DisplayEventReceiver::Event makeHotplug(PhysicalDisplayId displayId, nsecs_t timestamp,
102 bool connected) {
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800103 DisplayEventReceiver::Event event;
104 event.header = {DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG, displayId, timestamp};
105 event.hotplug.connected = connected;
106 return event;
107}
108
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800109DisplayEventReceiver::Event makeVSync(PhysicalDisplayId displayId, nsecs_t timestamp,
Ady Abraham8cb21882020-08-26 18:22:05 -0700110 uint32_t count, nsecs_t expectedVSyncTimestamp,
Ady Abraham74e17562020-08-24 18:18:19 -0700111 nsecs_t deadlineTimestamp, int64_t vsyncId) {
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800112 DisplayEventReceiver::Event event;
113 event.header = {DisplayEventReceiver::DISPLAY_EVENT_VSYNC, displayId, timestamp};
114 event.vsync.count = count;
Ady Abraham5facfb12020-04-22 15:18:31 -0700115 event.vsync.expectedVSyncTimestamp = expectedVSyncTimestamp;
Ady Abraham8cb21882020-08-26 18:22:05 -0700116 event.vsync.deadlineTimestamp = deadlineTimestamp;
Ady Abraham74e17562020-08-24 18:18:19 -0700117 event.vsync.vsyncId = vsyncId;
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800118 return event;
119}
120
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100121DisplayEventReceiver::Event makeModeChanged(PhysicalDisplayId displayId, DisplayModeId modeId,
122 nsecs_t vsyncPeriod) {
Ady Abraham447052e2019-02-13 16:07:27 -0800123 DisplayEventReceiver::Event event;
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100124 event.header = {DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE, displayId, systemTime()};
125 event.modeChange.modeId = modeId.value();
126 event.modeChange.vsyncPeriod = vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -0800127 return event;
128}
129
Ady Abraham62f216c2020-10-13 19:07:23 -0700130DisplayEventReceiver::Event makeFrameRateOverrideEvent(PhysicalDisplayId displayId,
131 FrameRateOverride frameRateOverride) {
132 return DisplayEventReceiver::Event{
133 .header =
134 DisplayEventReceiver::Event::Header{
135 .type = DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE,
136 .displayId = displayId,
137 .timestamp = systemTime(),
138 },
139 .frameRateOverride = frameRateOverride,
140 };
141}
142
143DisplayEventReceiver::Event makeFrameRateOverrideFlushEvent(PhysicalDisplayId displayId) {
144 return DisplayEventReceiver::Event{
145 .header = DisplayEventReceiver::Event::Header{
146 .type = DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH,
147 .displayId = displayId,
148 .timestamp = systemTime(),
149 }};
150}
151
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800152} // namespace
Lloyd Pique46a46b32018-01-31 19:01:18 -0800153
Ady Abraham62f216c2020-10-13 19:07:23 -0700154EventThreadConnection::EventThreadConnection(
155 EventThread* eventThread, uid_t callingUid, ResyncCallback resyncCallback,
156 ISurfaceComposer::EventRegistrationFlags eventRegistration)
Dominik Laskowskif654d572018-12-20 11:03:06 -0800157 : resyncCallback(std::move(resyncCallback)),
Ady Abraham0bb6a472020-10-12 10:22:13 -0700158 mOwnerUid(callingUid),
Ady Abraham62f216c2020-10-13 19:07:23 -0700159 mEventRegistration(eventRegistration),
Dominik Laskowskif654d572018-12-20 11:03:06 -0800160 mEventThread(eventThread),
161 mChannel(gui::BitTube::DefaultSize) {}
Ana Krulec85c39af2018-12-26 17:29:57 -0800162
163EventThreadConnection::~EventThreadConnection() {
164 // do nothing here -- clean-up will happen automatically
165 // when the main thread wakes up
166}
167
168void EventThreadConnection::onFirstRef() {
169 // NOTE: mEventThread doesn't hold a strong reference on us
170 mEventThread->registerDisplayEventConnection(this);
171}
172
173status_t EventThreadConnection::stealReceiveChannel(gui::BitTube* outChannel) {
174 outChannel->setReceiveFd(mChannel.moveReceiveFd());
Alec Mouri967d5d72020-08-05 12:50:03 -0700175 outChannel->setSendFd(base::unique_fd(dup(mChannel.getSendFd())));
Ana Krulec85c39af2018-12-26 17:29:57 -0800176 return NO_ERROR;
177}
178
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800179status_t EventThreadConnection::setVsyncRate(uint32_t rate) {
180 mEventThread->setVsyncRate(rate, this);
Ana Krulec85c39af2018-12-26 17:29:57 -0800181 return NO_ERROR;
182}
183
184void EventThreadConnection::requestNextVsync() {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800185 ATRACE_NAME("requestNextVsync");
Ady Abraham8532d012019-05-08 14:50:56 -0700186 mEventThread->requestNextVsync(this);
Ana Krulec85c39af2018-12-26 17:29:57 -0800187}
188
189status_t EventThreadConnection::postEvent(const DisplayEventReceiver::Event& event) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700190 constexpr auto toStatus = [](ssize_t size) {
191 return size < 0 ? status_t(size) : status_t(NO_ERROR);
192 };
193
194 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE ||
195 event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH) {
196 mPendingEvents.emplace_back(event);
197 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE) {
198 return status_t(NO_ERROR);
199 }
200
201 auto size = DisplayEventReceiver::sendEvents(&mChannel, mPendingEvents.data(),
202 mPendingEvents.size());
203 mPendingEvents.clear();
204 return toStatus(size);
205 }
206
207 auto size = DisplayEventReceiver::sendEvents(&mChannel, &event, 1);
208 return toStatus(size);
Ana Krulec85c39af2018-12-26 17:29:57 -0800209}
210
211// ---------------------------------------------------------------------------
212
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800213EventThread::~EventThread() = default;
214
215namespace impl {
216
Dominik Laskowski6505f792019-09-18 11:10:05 -0700217EventThread::EventThread(std::unique_ptr<VSyncSource> vsyncSource,
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700218 android::frametimeline::TokenManager* tokenManager,
Ady Abraham0bb6a472020-10-12 10:22:13 -0700219 InterceptVSyncsCallback interceptVSyncsCallback,
220 ThrottleVsyncCallback throttleVsyncCallback)
Dominik Laskowski6505f792019-09-18 11:10:05 -0700221 : mVSyncSource(std::move(vsyncSource)),
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700222 mTokenManager(tokenManager),
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800223 mInterceptVSyncsCallback(std::move(interceptVSyncsCallback)),
Ady Abraham0bb6a472020-10-12 10:22:13 -0700224 mThrottleVsyncCallback(std::move(throttleVsyncCallback)),
Dominik Laskowski6505f792019-09-18 11:10:05 -0700225 mThreadName(mVSyncSource->getName()) {
Dominik Laskowski029cc122019-01-23 19:52:06 -0800226 mVSyncSource->setCallback(this);
Lloyd Pique46a46b32018-01-31 19:01:18 -0800227
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800228 mThread = std::thread([this]() NO_THREAD_SAFETY_ANALYSIS {
229 std::unique_lock<std::mutex> lock(mMutex);
230 threadMain(lock);
231 });
Lloyd Pique46a46b32018-01-31 19:01:18 -0800232
Dominik Laskowski6505f792019-09-18 11:10:05 -0700233 pthread_setname_np(mThread.native_handle(), mThreadName);
Lloyd Pique46a46b32018-01-31 19:01:18 -0800234
235 pid_t tid = pthread_gettid_np(mThread.native_handle());
236
237 // Use SCHED_FIFO to minimize jitter
238 constexpr int EVENT_THREAD_PRIORITY = 2;
239 struct sched_param param = {0};
240 param.sched_priority = EVENT_THREAD_PRIORITY;
241 if (pthread_setschedparam(mThread.native_handle(), SCHED_FIFO, &param) != 0) {
242 ALOGE("Couldn't set SCHED_FIFO for EventThread");
243 }
244
245 set_sched_policy(tid, SP_FOREGROUND);
246}
247
248EventThread::~EventThread() {
Dominik Laskowski029cc122019-01-23 19:52:06 -0800249 mVSyncSource->setCallback(nullptr);
250
Lloyd Pique46a46b32018-01-31 19:01:18 -0800251 {
252 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski029cc122019-01-23 19:52:06 -0800253 mState = State::Quit;
Lloyd Pique46a46b32018-01-31 19:01:18 -0800254 mCondition.notify_all();
255 }
256 mThread.join();
Ruchi Kandoief472ec2014-04-02 12:50:06 -0700257}
258
Ady Abraham9c53ee72020-07-22 21:16:18 -0700259void EventThread::setDuration(std::chrono::nanoseconds workDuration,
260 std::chrono::nanoseconds readyDuration) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800261 std::lock_guard<std::mutex> lock(mMutex);
Ady Abraham9c53ee72020-07-22 21:16:18 -0700262 mVSyncSource->setDuration(workDuration, readyDuration);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700263}
264
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700265sp<EventThreadConnection> EventThread::createEventConnection(
Ady Abraham62f216c2020-10-13 19:07:23 -0700266 ResyncCallback resyncCallback,
267 ISurfaceComposer::EventRegistrationFlags eventRegistration) const {
Ady Abraham0bb6a472020-10-12 10:22:13 -0700268 return new EventThreadConnection(const_cast<EventThread*>(this),
269 IPCThreadState::self()->getCallingUid(),
Ady Abraham62f216c2020-10-13 19:07:23 -0700270 std::move(resyncCallback), eventRegistration);
Mathias Agopian8aedd472012-01-24 16:39:14 -0800271}
272
Ana Krulec85c39af2018-12-26 17:29:57 -0800273status_t EventThread::registerDisplayEventConnection(const sp<EventThreadConnection>& connection) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800274 std::lock_guard<std::mutex> lock(mMutex);
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700275
276 // this should never happen
277 auto it = std::find(mDisplayEventConnections.cbegin(),
278 mDisplayEventConnections.cend(), connection);
279 if (it != mDisplayEventConnections.cend()) {
280 ALOGW("DisplayEventConnection %p already exists", connection.get());
281 mCondition.notify_all();
282 return ALREADY_EXISTS;
283 }
284
285 mDisplayEventConnections.push_back(connection);
Lloyd Pique46a46b32018-01-31 19:01:18 -0800286 mCondition.notify_all();
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800287 return NO_ERROR;
288}
289
Ana Krulec85c39af2018-12-26 17:29:57 -0800290void EventThread::removeDisplayEventConnectionLocked(const wp<EventThreadConnection>& connection) {
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700291 auto it = std::find(mDisplayEventConnections.cbegin(),
292 mDisplayEventConnections.cend(), connection);
293 if (it != mDisplayEventConnections.cend()) {
294 mDisplayEventConnections.erase(it);
295 }
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800296}
297
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800298void EventThread::setVsyncRate(uint32_t rate, const sp<EventThreadConnection>& connection) {
299 if (static_cast<std::underlying_type_t<VSyncRequest>>(rate) < 0) {
300 return;
301 }
302
303 std::lock_guard<std::mutex> lock(mMutex);
304
305 const auto request = rate == 0 ? VSyncRequest::None : static_cast<VSyncRequest>(rate);
Ady Abraham98178752020-12-21 19:14:30 -0800306 if (request != VSyncRequest::None && connection->resyncCallback) {
307 connection->resyncCallback();
308 }
309
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800310 if (connection->vsyncRequest != request) {
311 connection->vsyncRequest = request;
312 mCondition.notify_all();
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800313 }
314}
315
Ady Abraham8532d012019-05-08 14:50:56 -0700316void EventThread::requestNextVsync(const sp<EventThreadConnection>& connection) {
Dominik Laskowskif654d572018-12-20 11:03:06 -0800317 if (connection->resyncCallback) {
318 connection->resyncCallback();
Lloyd Pique24b0a482018-03-09 18:52:26 -0800319 }
Tim Murray4a4e4a22016-04-19 16:29:23 +0000320
Ana Krulec7d1d6832018-12-27 11:10:09 -0800321 std::lock_guard<std::mutex> lock(mMutex);
322
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800323 if (connection->vsyncRequest == VSyncRequest::None) {
324 connection->vsyncRequest = VSyncRequest::Single;
Lloyd Pique46a46b32018-01-31 19:01:18 -0800325 mCondition.notify_all();
Tim Murrayb5daa912020-09-09 21:29:13 +0000326 } else if (connection->vsyncRequest == VSyncRequest::SingleSuppressCallback) {
327 connection->vsyncRequest = VSyncRequest::Single;
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800328 }
Mathias Agopian23748662011-12-05 14:33:34 -0800329}
330
Mathias Agopian22ffb112012-04-10 21:04:02 -0700331void EventThread::onScreenReleased() {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800332 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800333 if (!mVSyncState || mVSyncState->synthetic) {
334 return;
Mathias Agopian22ffb112012-04-10 21:04:02 -0700335 }
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800336
337 mVSyncState->synthetic = true;
338 mCondition.notify_all();
Mathias Agopian22ffb112012-04-10 21:04:02 -0700339}
340
341void EventThread::onScreenAcquired() {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800342 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800343 if (!mVSyncState || !mVSyncState->synthetic) {
344 return;
Mathias Agopian7d886472012-06-14 23:39:35 -0700345 }
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800346
347 mVSyncState->synthetic = false;
348 mCondition.notify_all();
Mathias Agopian22ffb112012-04-10 21:04:02 -0700349}
350
Ady Abraham9c53ee72020-07-22 21:16:18 -0700351void EventThread::onVSyncEvent(nsecs_t timestamp, nsecs_t expectedVSyncTimestamp,
Ady Abraham8cb21882020-08-26 18:22:05 -0700352 nsecs_t deadlineTimestamp) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800353 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800354
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800355 LOG_FATAL_IF(!mVSyncState);
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700356 const int64_t vsyncId = [&] {
357 if (mTokenManager != nullptr) {
358 return mTokenManager->generateTokenForPredictions(
359 {timestamp, deadlineTimestamp, expectedVSyncTimestamp});
360 }
361 return static_cast<int64_t>(0);
362 }();
363
Ady Abraham5facfb12020-04-22 15:18:31 -0700364 mPendingEvents.push_back(makeVSync(mVSyncState->displayId, timestamp, ++mVSyncState->count,
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700365 expectedVSyncTimestamp, deadlineTimestamp, vsyncId));
Lloyd Pique46a46b32018-01-31 19:01:18 -0800366 mCondition.notify_all();
Mathias Agopian3eb38cb2012-04-03 22:09:52 -0700367}
368
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800369void EventThread::onHotplugReceived(PhysicalDisplayId displayId, bool connected) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800370 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -0700371
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800372 mPendingEvents.push_back(makeHotplug(displayId, systemTime(), connected));
Dominik Laskowski00a6fa22018-06-06 16:42:02 -0700373 mCondition.notify_all();
Mathias Agopian148994e2012-09-19 17:31:36 -0700374}
375
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100376void EventThread::onModeChanged(PhysicalDisplayId displayId, DisplayModeId modeId,
377 nsecs_t vsyncPeriod) {
Ady Abraham447052e2019-02-13 16:07:27 -0800378 std::lock_guard<std::mutex> lock(mMutex);
379
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100380 mPendingEvents.push_back(makeModeChanged(displayId, modeId, vsyncPeriod));
Ady Abraham447052e2019-02-13 16:07:27 -0800381 mCondition.notify_all();
382}
383
Ady Abraham62f216c2020-10-13 19:07:23 -0700384void EventThread::onFrameRateOverridesChanged(PhysicalDisplayId displayId,
385 std::vector<FrameRateOverride> overrides) {
386 std::lock_guard<std::mutex> lock(mMutex);
387
388 for (auto frameRateOverride : overrides) {
389 mPendingEvents.push_back(makeFrameRateOverrideEvent(displayId, frameRateOverride));
390 }
391 mPendingEvents.push_back(makeFrameRateOverrideFlushEvent(displayId));
392
393 mCondition.notify_all();
394}
395
Alec Mouri717bcb62020-02-10 17:07:19 -0800396size_t EventThread::getEventThreadConnectionCount() {
397 std::lock_guard<std::mutex> lock(mMutex);
398 return mDisplayEventConnections.size();
399}
400
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800401void EventThread::threadMain(std::unique_lock<std::mutex>& lock) {
402 DisplayEventConsumers consumers;
403
Dominik Laskowski029cc122019-01-23 19:52:06 -0800404 while (mState != State::Quit) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800405 std::optional<DisplayEventReceiver::Event> event;
Mathias Agopian3eb38cb2012-04-03 22:09:52 -0700406
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800407 // Determine next event to dispatch.
408 if (!mPendingEvents.empty()) {
409 event = mPendingEvents.front();
410 mPendingEvents.pop_front();
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800411
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800412 switch (event->header.type) {
413 case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
414 if (event->hotplug.connected && !mVSyncState) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800415 mVSyncState.emplace(event->header.displayId);
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800416 } else if (!event->hotplug.connected && mVSyncState &&
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800417 mVSyncState->displayId == event->header.displayId) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800418 mVSyncState.reset();
419 }
420 break;
421
422 case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
423 if (mInterceptVSyncsCallback) {
424 mInterceptVSyncsCallback(event->header.timestamp);
425 }
426 break;
Dominik Laskowski029cc122019-01-23 19:52:06 -0800427 }
Mathias Agopianff28e202012-09-20 23:24:19 -0700428 }
429
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800430 bool vsyncRequested = false;
Mathias Agopian148994e2012-09-19 17:31:36 -0700431
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800432 // Find connections that should consume this event.
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700433 auto it = mDisplayEventConnections.begin();
434 while (it != mDisplayEventConnections.end()) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800435 if (const auto connection = it->promote()) {
436 vsyncRequested |= connection->vsyncRequest != VSyncRequest::None;
437
438 if (event && shouldConsumeEvent(*event, connection)) {
439 consumers.push_back(connection);
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700440 }
Mathias Agopianb4d18ed2012-09-20 23:14:05 -0700441
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700442 ++it;
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700443 } else {
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700444 it = mDisplayEventConnections.erase(it);
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700445 }
446 }
447
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800448 if (!consumers.empty()) {
449 dispatchEvent(*event, consumers);
450 consumers.clear();
451 }
452
Dominik Laskowski029cc122019-01-23 19:52:06 -0800453 State nextState;
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800454 if (mVSyncState && vsyncRequested) {
455 nextState = mVSyncState->synthetic ? State::SyntheticVSync : State::VSync;
Dominik Laskowski029cc122019-01-23 19:52:06 -0800456 } else {
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800457 ALOGW_IF(!mVSyncState, "Ignoring VSYNC request while display is disconnected");
Dominik Laskowski029cc122019-01-23 19:52:06 -0800458 nextState = State::Idle;
459 }
460
461 if (mState != nextState) {
462 if (mState == State::VSync) {
463 mVSyncSource->setVSyncEnabled(false);
464 } else if (nextState == State::VSync) {
465 mVSyncSource->setVSyncEnabled(true);
466 }
467
468 mState = nextState;
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700469 }
470
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800471 if (event) {
472 continue;
473 }
474
475 // Wait for event or client registration/request.
Dominik Laskowski029cc122019-01-23 19:52:06 -0800476 if (mState == State::Idle) {
477 mCondition.wait(lock);
478 } else {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800479 // Generate a fake VSYNC after a long timeout in case the driver stalls. When the
480 // display is off, keep feeding clients at 60 Hz.
Ady Abraham5facfb12020-04-22 15:18:31 -0700481 const std::chrono::nanoseconds timeout =
482 mState == State::SyntheticVSync ? 16ms : 1000ms;
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800483 if (mCondition.wait_for(lock, timeout) == std::cv_status::timeout) {
Ady Abraham5e7371c2020-03-24 14:47:24 -0700484 if (mState == State::VSync) {
485 ALOGW("Faking VSYNC due to driver stall for thread %s", mThreadName);
486 std::string debugInfo = "VsyncSource debug info:\n";
487 mVSyncSource->dump(debugInfo);
Ady Abraham75398722020-04-07 14:08:45 -0700488 // Log the debug info line-by-line to avoid logcat overflow
489 auto pos = debugInfo.find('\n');
490 while (pos != std::string::npos) {
491 ALOGW("%s", debugInfo.substr(0, pos).c_str());
492 debugInfo = debugInfo.substr(pos + 1);
493 pos = debugInfo.find('\n');
494 }
Ady Abraham5e7371c2020-03-24 14:47:24 -0700495 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800496
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800497 LOG_FATAL_IF(!mVSyncState);
Ady Abraham5facfb12020-04-22 15:18:31 -0700498 const auto now = systemTime(SYSTEM_TIME_MONOTONIC);
Ady Abraham8cb21882020-08-26 18:22:05 -0700499 const auto deadlineTimestamp = now + timeout.count();
500 const auto expectedVSyncTime = deadlineTimestamp + timeout.count();
Ady Abraham74e17562020-08-24 18:18:19 -0700501 // TODO(b/162890590): use TokenManager to populate vsyncId
Ady Abraham5facfb12020-04-22 15:18:31 -0700502 mPendingEvents.push_back(makeVSync(mVSyncState->displayId, now,
Ady Abraham8cb21882020-08-26 18:22:05 -0700503 ++mVSyncState->count, expectedVSyncTime,
Ady Abraham74e17562020-08-24 18:18:19 -0700504 deadlineTimestamp, /*vsyncId=*/0));
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700505 }
506 }
Lloyd Pique46a46b32018-01-31 19:01:18 -0800507 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800508}
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700509
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800510bool EventThread::shouldConsumeEvent(const DisplayEventReceiver::Event& event,
511 const sp<EventThreadConnection>& connection) const {
Ady Abraham0bb6a472020-10-12 10:22:13 -0700512 const auto throttleVsync = [&] {
513 return mThrottleVsyncCallback &&
514 mThrottleVsyncCallback(event.vsync.expectedVSyncTimestamp, connection->mOwnerUid);
515 };
516
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800517 switch (event.header.type) {
518 case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
519 return true;
520
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100521 case DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE: {
Ady Abraham62f216c2020-10-13 19:07:23 -0700522 return connection->mEventRegistration.test(
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100523 ISurfaceComposer::EventRegistration::modeChanged);
Alec Mouri60aee1c2019-10-28 16:18:59 -0700524 }
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700525
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800526 case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
527 switch (connection->vsyncRequest) {
528 case VSyncRequest::None:
529 return false;
Tim Murrayb5daa912020-09-09 21:29:13 +0000530 case VSyncRequest::SingleSuppressCallback:
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800531 connection->vsyncRequest = VSyncRequest::None;
Tim Murrayb5daa912020-09-09 21:29:13 +0000532 return false;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700533 case VSyncRequest::Single: {
534 if (throttleVsync()) {
535 return false;
536 }
Tim Murrayb5daa912020-09-09 21:29:13 +0000537 connection->vsyncRequest = VSyncRequest::SingleSuppressCallback;
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800538 return true;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700539 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800540 case VSyncRequest::Periodic:
Ady Abraham0bb6a472020-10-12 10:22:13 -0700541 if (throttleVsync()) {
542 return false;
543 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800544 return true;
545 default:
Ady Abraham0bb6a472020-10-12 10:22:13 -0700546 // We don't throttle vsync if the app set a vsync request rate
547 // since there is no easy way to do that and this is a very
548 // rare case
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800549 return event.vsync.count % vsyncPeriod(connection->vsyncRequest) == 0;
550 }
551
Ady Abraham62f216c2020-10-13 19:07:23 -0700552 case DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE:
553 [[fallthrough]];
554 case DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH:
555 return connection->mEventRegistration.test(
556 ISurfaceComposer::EventRegistration::frameRateOverride);
557
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800558 default:
559 return false;
560 }
561}
562
563void EventThread::dispatchEvent(const DisplayEventReceiver::Event& event,
564 const DisplayEventConsumers& consumers) {
565 for (const auto& consumer : consumers) {
566 switch (consumer->postEvent(event)) {
567 case NO_ERROR:
568 break;
569
570 case -EAGAIN:
571 // TODO: Try again if pipe is full.
572 ALOGW("Failed dispatching %s for %s", toString(event).c_str(),
573 toString(*consumer).c_str());
574 break;
575
576 default:
577 // Treat EPIPE and other errors as fatal.
578 removeDisplayEventConnectionLocked(consumer);
579 }
580 }
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700581}
582
Yiwei Zhang5434a782018-12-05 18:06:32 -0800583void EventThread::dump(std::string& result) const {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800584 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800585
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800586 StringAppendF(&result, "%s: state=%s VSyncState=", mThreadName, toCString(mState));
587 if (mVSyncState) {
Marin Shalamanova524a092020-07-27 21:39:55 +0200588 StringAppendF(&result, "{displayId=%s, count=%u%s}\n",
589 to_string(mVSyncState->displayId).c_str(), mVSyncState->count,
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800590 mVSyncState->synthetic ? ", synthetic" : "");
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800591 } else {
592 StringAppendF(&result, "none\n");
593 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800594
595 StringAppendF(&result, " pending events (count=%zu):\n", mPendingEvents.size());
596 for (const auto& event : mPendingEvents) {
597 StringAppendF(&result, " %s\n", toString(event).c_str());
Mathias Agopiane2c4f4e2012-04-10 18:25:31 -0700598 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800599
600 StringAppendF(&result, " connections (count=%zu):\n", mDisplayEventConnections.size());
601 for (const auto& ptr : mDisplayEventConnections) {
602 if (const auto connection = ptr.promote()) {
603 StringAppendF(&result, " %s\n", toString(*connection).c_str());
604 }
605 }
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800606}
607
Dominik Laskowski029cc122019-01-23 19:52:06 -0800608const char* EventThread::toCString(State state) {
609 switch (state) {
610 case State::Idle:
611 return "Idle";
612 case State::Quit:
613 return "Quit";
614 case State::SyntheticVSync:
615 return "SyntheticVSync";
616 case State::VSync:
617 return "VSync";
618 }
619}
620
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800621} // namespace impl
Lloyd Pique46a46b32018-01-31 19:01:18 -0800622} // namespace android
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800623
624// TODO(b/129481165): remove the #pragma below and fix conversion issues
625#pragma clang diagnostic pop // ignored "-Wconversion"