blob: c9ab96592e784937cbe05d082b187f7ad92a3ce8 [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,
Rachel Lee0d943202022-02-01 23:29:41 -0800111 nsecs_t deadlineTimestamp) {
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;
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800117 return event;
118}
119
Ady Abraham690f4612021-07-01 23:24:03 -0700120DisplayEventReceiver::Event makeModeChanged(DisplayModePtr mode) {
Ady Abraham447052e2019-02-13 16:07:27 -0800121 DisplayEventReceiver::Event event;
Ady Abraham690f4612021-07-01 23:24:03 -0700122 event.header = {DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE, mode->getPhysicalDisplayId(),
123 systemTime()};
124 event.modeChange.modeId = mode->getId().value();
125 event.modeChange.vsyncPeriod = mode->getVsyncPeriod();
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
Huihong Luo6fac5232021-11-22 16:05:23 -0800172binder::Status EventThreadConnection::stealReceiveChannel(gui::BitTube* outChannel) {
Ana Krulec85c39af2018-12-26 17:29:57 -0800173 outChannel->setReceiveFd(mChannel.moveReceiveFd());
Alec Mouri967d5d72020-08-05 12:50:03 -0700174 outChannel->setSendFd(base::unique_fd(dup(mChannel.getSendFd())));
Huihong Luo6fac5232021-11-22 16:05:23 -0800175 return binder::Status::ok();
Ana Krulec85c39af2018-12-26 17:29:57 -0800176}
177
Huihong Luo6fac5232021-11-22 16:05:23 -0800178binder::Status EventThreadConnection::setVsyncRate(int rate) {
179 mEventThread->setVsyncRate(static_cast<uint32_t>(rate), this);
180 return binder::Status::ok();
Ana Krulec85c39af2018-12-26 17:29:57 -0800181}
182
Huihong Luo6fac5232021-11-22 16:05:23 -0800183binder::Status EventThreadConnection::requestNextVsync() {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800184 ATRACE_NAME("requestNextVsync");
Ady Abraham8532d012019-05-08 14:50:56 -0700185 mEventThread->requestNextVsync(this);
Huihong Luo6fac5232021-11-22 16:05:23 -0800186 return binder::Status::ok();
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,
Jorim Jaggic0086af2021-02-12 18:18:11 +0100220 ThrottleVsyncCallback throttleVsyncCallback,
221 GetVsyncPeriodFunction getVsyncPeriodFunction)
Dominik Laskowski6505f792019-09-18 11:10:05 -0700222 : mVSyncSource(std::move(vsyncSource)),
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700223 mTokenManager(tokenManager),
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800224 mInterceptVSyncsCallback(std::move(interceptVSyncsCallback)),
Ady Abraham0bb6a472020-10-12 10:22:13 -0700225 mThrottleVsyncCallback(std::move(throttleVsyncCallback)),
Jorim Jaggic0086af2021-02-12 18:18:11 +0100226 mGetVsyncPeriodFunction(std::move(getVsyncPeriodFunction)),
Dominik Laskowski6505f792019-09-18 11:10:05 -0700227 mThreadName(mVSyncSource->getName()) {
Jorim Jaggic0086af2021-02-12 18:18:11 +0100228
229 LOG_ALWAYS_FATAL_IF(getVsyncPeriodFunction == nullptr,
230 "getVsyncPeriodFunction must not be null");
231
Dominik Laskowski029cc122019-01-23 19:52:06 -0800232 mVSyncSource->setCallback(this);
Lloyd Pique46a46b32018-01-31 19:01:18 -0800233
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800234 mThread = std::thread([this]() NO_THREAD_SAFETY_ANALYSIS {
235 std::unique_lock<std::mutex> lock(mMutex);
236 threadMain(lock);
237 });
Lloyd Pique46a46b32018-01-31 19:01:18 -0800238
Dominik Laskowski6505f792019-09-18 11:10:05 -0700239 pthread_setname_np(mThread.native_handle(), mThreadName);
Lloyd Pique46a46b32018-01-31 19:01:18 -0800240
241 pid_t tid = pthread_gettid_np(mThread.native_handle());
242
243 // Use SCHED_FIFO to minimize jitter
244 constexpr int EVENT_THREAD_PRIORITY = 2;
245 struct sched_param param = {0};
246 param.sched_priority = EVENT_THREAD_PRIORITY;
247 if (pthread_setschedparam(mThread.native_handle(), SCHED_FIFO, &param) != 0) {
248 ALOGE("Couldn't set SCHED_FIFO for EventThread");
249 }
250
251 set_sched_policy(tid, SP_FOREGROUND);
252}
253
254EventThread::~EventThread() {
Dominik Laskowski029cc122019-01-23 19:52:06 -0800255 mVSyncSource->setCallback(nullptr);
256
Lloyd Pique46a46b32018-01-31 19:01:18 -0800257 {
258 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski029cc122019-01-23 19:52:06 -0800259 mState = State::Quit;
Lloyd Pique46a46b32018-01-31 19:01:18 -0800260 mCondition.notify_all();
261 }
262 mThread.join();
Ruchi Kandoief472ec2014-04-02 12:50:06 -0700263}
264
Ady Abraham9c53ee72020-07-22 21:16:18 -0700265void EventThread::setDuration(std::chrono::nanoseconds workDuration,
266 std::chrono::nanoseconds readyDuration) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800267 std::lock_guard<std::mutex> lock(mMutex);
Ady Abraham9c53ee72020-07-22 21:16:18 -0700268 mVSyncSource->setDuration(workDuration, readyDuration);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700269}
270
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700271sp<EventThreadConnection> EventThread::createEventConnection(
Ady Abraham62f216c2020-10-13 19:07:23 -0700272 ResyncCallback resyncCallback,
273 ISurfaceComposer::EventRegistrationFlags eventRegistration) const {
Ady Abraham0bb6a472020-10-12 10:22:13 -0700274 return new EventThreadConnection(const_cast<EventThread*>(this),
275 IPCThreadState::self()->getCallingUid(),
Ady Abraham62f216c2020-10-13 19:07:23 -0700276 std::move(resyncCallback), eventRegistration);
Mathias Agopian8aedd472012-01-24 16:39:14 -0800277}
278
Ana Krulec85c39af2018-12-26 17:29:57 -0800279status_t EventThread::registerDisplayEventConnection(const sp<EventThreadConnection>& connection) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800280 std::lock_guard<std::mutex> lock(mMutex);
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700281
282 // this should never happen
283 auto it = std::find(mDisplayEventConnections.cbegin(),
284 mDisplayEventConnections.cend(), connection);
285 if (it != mDisplayEventConnections.cend()) {
286 ALOGW("DisplayEventConnection %p already exists", connection.get());
287 mCondition.notify_all();
288 return ALREADY_EXISTS;
289 }
290
291 mDisplayEventConnections.push_back(connection);
Lloyd Pique46a46b32018-01-31 19:01:18 -0800292 mCondition.notify_all();
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800293 return NO_ERROR;
294}
295
Ana Krulec85c39af2018-12-26 17:29:57 -0800296void EventThread::removeDisplayEventConnectionLocked(const wp<EventThreadConnection>& connection) {
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700297 auto it = std::find(mDisplayEventConnections.cbegin(),
298 mDisplayEventConnections.cend(), connection);
299 if (it != mDisplayEventConnections.cend()) {
300 mDisplayEventConnections.erase(it);
301 }
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800302}
303
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800304void EventThread::setVsyncRate(uint32_t rate, const sp<EventThreadConnection>& connection) {
305 if (static_cast<std::underlying_type_t<VSyncRequest>>(rate) < 0) {
306 return;
307 }
308
309 std::lock_guard<std::mutex> lock(mMutex);
310
311 const auto request = rate == 0 ? VSyncRequest::None : static_cast<VSyncRequest>(rate);
312 if (connection->vsyncRequest != request) {
313 connection->vsyncRequest = request;
314 mCondition.notify_all();
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800315 }
316}
317
Ady Abraham8532d012019-05-08 14:50:56 -0700318void EventThread::requestNextVsync(const sp<EventThreadConnection>& connection) {
Dominik Laskowskif654d572018-12-20 11:03:06 -0800319 if (connection->resyncCallback) {
320 connection->resyncCallback();
Lloyd Pique24b0a482018-03-09 18:52:26 -0800321 }
Tim Murray4a4e4a22016-04-19 16:29:23 +0000322
Ana Krulec7d1d6832018-12-27 11:10:09 -0800323 std::lock_guard<std::mutex> lock(mMutex);
324
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800325 if (connection->vsyncRequest == VSyncRequest::None) {
326 connection->vsyncRequest = VSyncRequest::Single;
Lloyd Pique46a46b32018-01-31 19:01:18 -0800327 mCondition.notify_all();
Tim Murrayb5daa912020-09-09 21:29:13 +0000328 } else if (connection->vsyncRequest == VSyncRequest::SingleSuppressCallback) {
329 connection->vsyncRequest = VSyncRequest::Single;
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800330 }
Mathias Agopian23748662011-12-05 14:33:34 -0800331}
332
Mathias Agopian22ffb112012-04-10 21:04:02 -0700333void EventThread::onScreenReleased() {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800334 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800335 if (!mVSyncState || mVSyncState->synthetic) {
336 return;
Mathias Agopian22ffb112012-04-10 21:04:02 -0700337 }
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800338
339 mVSyncState->synthetic = true;
340 mCondition.notify_all();
Mathias Agopian22ffb112012-04-10 21:04:02 -0700341}
342
343void EventThread::onScreenAcquired() {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800344 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800345 if (!mVSyncState || !mVSyncState->synthetic) {
346 return;
Mathias Agopian7d886472012-06-14 23:39:35 -0700347 }
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800348
349 mVSyncState->synthetic = false;
350 mCondition.notify_all();
Mathias Agopian22ffb112012-04-10 21:04:02 -0700351}
352
Ady Abraham9c53ee72020-07-22 21:16:18 -0700353void EventThread::onVSyncEvent(nsecs_t timestamp, nsecs_t expectedVSyncTimestamp,
Ady Abraham8cb21882020-08-26 18:22:05 -0700354 nsecs_t deadlineTimestamp) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800355 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800356
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800357 LOG_FATAL_IF(!mVSyncState);
Ady Abraham5facfb12020-04-22 15:18:31 -0700358 mPendingEvents.push_back(makeVSync(mVSyncState->displayId, timestamp, ++mVSyncState->count,
Rachel Lee0d943202022-02-01 23:29:41 -0800359 expectedVSyncTimestamp, deadlineTimestamp));
Lloyd Pique46a46b32018-01-31 19:01:18 -0800360 mCondition.notify_all();
Mathias Agopian3eb38cb2012-04-03 22:09:52 -0700361}
362
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800363void EventThread::onHotplugReceived(PhysicalDisplayId displayId, bool connected) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800364 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -0700365
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800366 mPendingEvents.push_back(makeHotplug(displayId, systemTime(), connected));
Dominik Laskowski00a6fa22018-06-06 16:42:02 -0700367 mCondition.notify_all();
Mathias Agopian148994e2012-09-19 17:31:36 -0700368}
369
Ady Abraham690f4612021-07-01 23:24:03 -0700370void EventThread::onModeChanged(DisplayModePtr mode) {
Ady Abraham447052e2019-02-13 16:07:27 -0800371 std::lock_guard<std::mutex> lock(mMutex);
372
Ady Abraham690f4612021-07-01 23:24:03 -0700373 mPendingEvents.push_back(makeModeChanged(mode));
Ady Abraham447052e2019-02-13 16:07:27 -0800374 mCondition.notify_all();
375}
376
Ady Abraham62f216c2020-10-13 19:07:23 -0700377void EventThread::onFrameRateOverridesChanged(PhysicalDisplayId displayId,
378 std::vector<FrameRateOverride> overrides) {
379 std::lock_guard<std::mutex> lock(mMutex);
380
381 for (auto frameRateOverride : overrides) {
382 mPendingEvents.push_back(makeFrameRateOverrideEvent(displayId, frameRateOverride));
383 }
384 mPendingEvents.push_back(makeFrameRateOverrideFlushEvent(displayId));
385
386 mCondition.notify_all();
387}
388
Alec Mouri717bcb62020-02-10 17:07:19 -0800389size_t EventThread::getEventThreadConnectionCount() {
390 std::lock_guard<std::mutex> lock(mMutex);
391 return mDisplayEventConnections.size();
392}
393
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800394void EventThread::threadMain(std::unique_lock<std::mutex>& lock) {
395 DisplayEventConsumers consumers;
396
Dominik Laskowski029cc122019-01-23 19:52:06 -0800397 while (mState != State::Quit) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800398 std::optional<DisplayEventReceiver::Event> event;
Mathias Agopian3eb38cb2012-04-03 22:09:52 -0700399
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800400 // Determine next event to dispatch.
401 if (!mPendingEvents.empty()) {
402 event = mPendingEvents.front();
403 mPendingEvents.pop_front();
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800404
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800405 switch (event->header.type) {
406 case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
407 if (event->hotplug.connected && !mVSyncState) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800408 mVSyncState.emplace(event->header.displayId);
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800409 } else if (!event->hotplug.connected && mVSyncState &&
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800410 mVSyncState->displayId == event->header.displayId) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800411 mVSyncState.reset();
412 }
413 break;
414
415 case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
416 if (mInterceptVSyncsCallback) {
417 mInterceptVSyncsCallback(event->header.timestamp);
418 }
419 break;
Dominik Laskowski029cc122019-01-23 19:52:06 -0800420 }
Mathias Agopianff28e202012-09-20 23:24:19 -0700421 }
422
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800423 bool vsyncRequested = false;
Mathias Agopian148994e2012-09-19 17:31:36 -0700424
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800425 // Find connections that should consume this event.
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700426 auto it = mDisplayEventConnections.begin();
427 while (it != mDisplayEventConnections.end()) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800428 if (const auto connection = it->promote()) {
429 vsyncRequested |= connection->vsyncRequest != VSyncRequest::None;
430
431 if (event && shouldConsumeEvent(*event, connection)) {
432 consumers.push_back(connection);
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700433 }
Mathias Agopianb4d18ed2012-09-20 23:14:05 -0700434
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700435 ++it;
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700436 } else {
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700437 it = mDisplayEventConnections.erase(it);
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700438 }
439 }
440
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800441 if (!consumers.empty()) {
442 dispatchEvent(*event, consumers);
443 consumers.clear();
444 }
445
Dominik Laskowski029cc122019-01-23 19:52:06 -0800446 State nextState;
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800447 if (mVSyncState && vsyncRequested) {
448 nextState = mVSyncState->synthetic ? State::SyntheticVSync : State::VSync;
Dominik Laskowski029cc122019-01-23 19:52:06 -0800449 } else {
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800450 ALOGW_IF(!mVSyncState, "Ignoring VSYNC request while display is disconnected");
Dominik Laskowski029cc122019-01-23 19:52:06 -0800451 nextState = State::Idle;
452 }
453
454 if (mState != nextState) {
455 if (mState == State::VSync) {
456 mVSyncSource->setVSyncEnabled(false);
457 } else if (nextState == State::VSync) {
458 mVSyncSource->setVSyncEnabled(true);
459 }
460
461 mState = nextState;
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700462 }
463
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800464 if (event) {
465 continue;
466 }
467
468 // Wait for event or client registration/request.
Dominik Laskowski029cc122019-01-23 19:52:06 -0800469 if (mState == State::Idle) {
470 mCondition.wait(lock);
471 } else {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800472 // Generate a fake VSYNC after a long timeout in case the driver stalls. When the
473 // display is off, keep feeding clients at 60 Hz.
Ady Abraham5facfb12020-04-22 15:18:31 -0700474 const std::chrono::nanoseconds timeout =
475 mState == State::SyntheticVSync ? 16ms : 1000ms;
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800476 if (mCondition.wait_for(lock, timeout) == std::cv_status::timeout) {
Ady Abraham5e7371c2020-03-24 14:47:24 -0700477 if (mState == State::VSync) {
478 ALOGW("Faking VSYNC due to driver stall for thread %s", mThreadName);
479 std::string debugInfo = "VsyncSource debug info:\n";
480 mVSyncSource->dump(debugInfo);
Ady Abraham75398722020-04-07 14:08:45 -0700481 // Log the debug info line-by-line to avoid logcat overflow
482 auto pos = debugInfo.find('\n');
483 while (pos != std::string::npos) {
484 ALOGW("%s", debugInfo.substr(0, pos).c_str());
485 debugInfo = debugInfo.substr(pos + 1);
486 pos = debugInfo.find('\n');
487 }
Ady Abraham5e7371c2020-03-24 14:47:24 -0700488 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800489
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800490 LOG_FATAL_IF(!mVSyncState);
Ady Abraham5facfb12020-04-22 15:18:31 -0700491 const auto now = systemTime(SYSTEM_TIME_MONOTONIC);
Ady Abraham8cb21882020-08-26 18:22:05 -0700492 const auto deadlineTimestamp = now + timeout.count();
493 const auto expectedVSyncTime = deadlineTimestamp + timeout.count();
Ady Abraham5facfb12020-04-22 15:18:31 -0700494 mPendingEvents.push_back(makeVSync(mVSyncState->displayId, now,
Ady Abraham8cb21882020-08-26 18:22:05 -0700495 ++mVSyncState->count, expectedVSyncTime,
Rachel Lee0d943202022-02-01 23:29:41 -0800496 deadlineTimestamp));
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700497 }
498 }
Lloyd Pique46a46b32018-01-31 19:01:18 -0800499 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800500}
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700501
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800502bool EventThread::shouldConsumeEvent(const DisplayEventReceiver::Event& event,
503 const sp<EventThreadConnection>& connection) const {
Ady Abraham0bb6a472020-10-12 10:22:13 -0700504 const auto throttleVsync = [&] {
505 return mThrottleVsyncCallback &&
506 mThrottleVsyncCallback(event.vsync.expectedVSyncTimestamp, connection->mOwnerUid);
507 };
508
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800509 switch (event.header.type) {
510 case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
511 return true;
512
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100513 case DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE: {
Ady Abraham62f216c2020-10-13 19:07:23 -0700514 return connection->mEventRegistration.test(
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100515 ISurfaceComposer::EventRegistration::modeChanged);
Alec Mouri60aee1c2019-10-28 16:18:59 -0700516 }
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700517
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800518 case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
519 switch (connection->vsyncRequest) {
520 case VSyncRequest::None:
521 return false;
Tim Murrayb5daa912020-09-09 21:29:13 +0000522 case VSyncRequest::SingleSuppressCallback:
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800523 connection->vsyncRequest = VSyncRequest::None;
Tim Murrayb5daa912020-09-09 21:29:13 +0000524 return false;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700525 case VSyncRequest::Single: {
526 if (throttleVsync()) {
527 return false;
528 }
Tim Murrayb5daa912020-09-09 21:29:13 +0000529 connection->vsyncRequest = VSyncRequest::SingleSuppressCallback;
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800530 return true;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700531 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800532 case VSyncRequest::Periodic:
Ady Abraham0bb6a472020-10-12 10:22:13 -0700533 if (throttleVsync()) {
534 return false;
535 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800536 return true;
537 default:
Ady Abraham0bb6a472020-10-12 10:22:13 -0700538 // We don't throttle vsync if the app set a vsync request rate
539 // since there is no easy way to do that and this is a very
540 // rare case
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800541 return event.vsync.count % vsyncPeriod(connection->vsyncRequest) == 0;
542 }
543
Ady Abraham62f216c2020-10-13 19:07:23 -0700544 case DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE:
545 [[fallthrough]];
546 case DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH:
547 return connection->mEventRegistration.test(
548 ISurfaceComposer::EventRegistration::frameRateOverride);
549
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800550 default:
551 return false;
552 }
553}
554
Rachel Lee8d0c6102021-11-03 22:00:25 +0000555int64_t EventThread::generateToken(nsecs_t timestamp, nsecs_t deadlineTimestamp,
556 nsecs_t expectedVSyncTimestamp) const {
Rachel Lee3f028662021-11-04 19:32:24 +0000557 if (mTokenManager != nullptr) {
558 return mTokenManager->generateTokenForPredictions(
559 {timestamp, deadlineTimestamp, expectedVSyncTimestamp});
560 }
561 return FrameTimelineInfo::INVALID_VSYNC_ID;
562}
563
564void EventThread::generateFrameTimeline(DisplayEventReceiver::Event& event) const {
565 // Add 1 to ensure the preferredFrameTimelineIndex entry (when multiplier == 0) is included.
566 for (int multiplier = -DisplayEventReceiver::kFrameTimelinesLength + 1, currentIndex = 0;
567 currentIndex < DisplayEventReceiver::kFrameTimelinesLength; multiplier++) {
568 nsecs_t deadline = event.vsync.deadlineTimestamp + multiplier * event.vsync.frameInterval;
569 // Valid possible frame timelines must have future values.
570 if (deadline > event.header.timestamp) {
571 if (multiplier == 0) {
572 event.vsync.preferredFrameTimelineIndex = currentIndex;
Rachel Lee3f028662021-11-04 19:32:24 +0000573 }
Rachel Lee0d943202022-02-01 23:29:41 -0800574 nsecs_t expectedVSync =
575 event.vsync.expectedVSyncTimestamp + multiplier * event.vsync.frameInterval;
576 event.vsync.frameTimelines[currentIndex] =
577 {.vsyncId = generateToken(event.header.timestamp, deadline, expectedVSync),
578 .deadlineTimestamp = deadline,
579 .expectedVSyncTimestamp = expectedVSync};
Rachel Lee3f028662021-11-04 19:32:24 +0000580 currentIndex++;
581 }
582 }
583}
584
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800585void EventThread::dispatchEvent(const DisplayEventReceiver::Event& event,
586 const DisplayEventConsumers& consumers) {
587 for (const auto& consumer : consumers) {
Jorim Jaggic0086af2021-02-12 18:18:11 +0100588 DisplayEventReceiver::Event copy = event;
589 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_VSYNC) {
590 copy.vsync.frameInterval = mGetVsyncPeriodFunction(consumer->mOwnerUid);
Rachel Lee3f028662021-11-04 19:32:24 +0000591 generateFrameTimeline(copy);
Jorim Jaggic0086af2021-02-12 18:18:11 +0100592 }
593 switch (consumer->postEvent(copy)) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800594 case NO_ERROR:
595 break;
596
597 case -EAGAIN:
598 // TODO: Try again if pipe is full.
599 ALOGW("Failed dispatching %s for %s", toString(event).c_str(),
600 toString(*consumer).c_str());
601 break;
602
603 default:
604 // Treat EPIPE and other errors as fatal.
605 removeDisplayEventConnectionLocked(consumer);
606 }
607 }
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700608}
609
Yiwei Zhang5434a782018-12-05 18:06:32 -0800610void EventThread::dump(std::string& result) const {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800611 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800612
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800613 StringAppendF(&result, "%s: state=%s VSyncState=", mThreadName, toCString(mState));
614 if (mVSyncState) {
Marin Shalamanova524a092020-07-27 21:39:55 +0200615 StringAppendF(&result, "{displayId=%s, count=%u%s}\n",
616 to_string(mVSyncState->displayId).c_str(), mVSyncState->count,
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800617 mVSyncState->synthetic ? ", synthetic" : "");
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800618 } else {
619 StringAppendF(&result, "none\n");
620 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800621
622 StringAppendF(&result, " pending events (count=%zu):\n", mPendingEvents.size());
623 for (const auto& event : mPendingEvents) {
624 StringAppendF(&result, " %s\n", toString(event).c_str());
Mathias Agopiane2c4f4e2012-04-10 18:25:31 -0700625 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800626
627 StringAppendF(&result, " connections (count=%zu):\n", mDisplayEventConnections.size());
628 for (const auto& ptr : mDisplayEventConnections) {
629 if (const auto connection = ptr.promote()) {
630 StringAppendF(&result, " %s\n", toString(*connection).c_str());
631 }
632 }
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800633}
634
Dominik Laskowski029cc122019-01-23 19:52:06 -0800635const char* EventThread::toCString(State state) {
636 switch (state) {
637 case State::Idle:
638 return "Idle";
639 case State::Quit:
640 return "Quit";
641 case State::SyntheticVSync:
642 return "SyntheticVSync";
643 case State::VSync:
644 return "VSync";
645 }
646}
647
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800648} // namespace impl
Lloyd Pique46a46b32018-01-31 19:01:18 -0800649} // namespace android
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800650
651// TODO(b/129481165): remove the #pragma below and fix conversion issues
652#pragma clang diagnostic pop // ignored "-Wconversion"