blob: d152ab25448c797adca42f0dd1018f9c7b71a3e3 [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:
Rachel Leeb9c5a772022-02-04 21:17:37 -080090 return StringPrintf("VSync{displayId=%s, count=%u, expectedPresentationTime=%" PRId64
91 "}",
Marin Shalamanova524a092020-07-27 21:39:55 +020092 to_string(event.header.displayId).c_str(), event.vsync.count,
Rachel Leeb9c5a772022-02-04 21:17:37 -080093 event.vsync.vsyncData.preferredExpectedPresentationTime());
Marin Shalamanova7fe3042021-01-29 21:02:08 +010094 case DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE:
95 return StringPrintf("ModeChanged{displayId=%s, modeId=%u}",
96 to_string(event.header.displayId).c_str(), event.modeChange.modeId);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -080097 default:
98 return "Event{}";
99 }
100}
101
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800102DisplayEventReceiver::Event makeHotplug(PhysicalDisplayId displayId, nsecs_t timestamp,
103 bool connected) {
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800104 DisplayEventReceiver::Event event;
105 event.header = {DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG, displayId, timestamp};
106 event.hotplug.connected = connected;
107 return event;
108}
109
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800110DisplayEventReceiver::Event makeVSync(PhysicalDisplayId displayId, nsecs_t timestamp,
Rachel Leeb9c5a772022-02-04 21:17:37 -0800111 uint32_t count, nsecs_t expectedPresentationTime,
Rachel Lee0d943202022-02-01 23:29:41 -0800112 nsecs_t deadlineTimestamp) {
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800113 DisplayEventReceiver::Event event;
114 event.header = {DisplayEventReceiver::DISPLAY_EVENT_VSYNC, displayId, timestamp};
115 event.vsync.count = count;
Rachel Leeb9c5a772022-02-04 21:17:37 -0800116 event.vsync.vsyncData.preferredFrameTimelineIndex = 0;
117 // Temporarily store the current vsync information in frameTimelines[0], marked as
118 // platform-preferred. When the event is dispatched later, the frame interval at that time is
119 // used with this information to generate multiple frame timeline choices.
120 event.vsync.vsyncData.frameTimelines[0] = {.vsyncId = FrameTimelineInfo::INVALID_VSYNC_ID,
121 .deadlineTimestamp = deadlineTimestamp,
122 .expectedPresentationTime =
123 expectedPresentationTime};
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800124 return event;
125}
126
Ady Abraham690f4612021-07-01 23:24:03 -0700127DisplayEventReceiver::Event makeModeChanged(DisplayModePtr mode) {
Ady Abraham447052e2019-02-13 16:07:27 -0800128 DisplayEventReceiver::Event event;
Ady Abraham690f4612021-07-01 23:24:03 -0700129 event.header = {DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE, mode->getPhysicalDisplayId(),
130 systemTime()};
131 event.modeChange.modeId = mode->getId().value();
132 event.modeChange.vsyncPeriod = mode->getVsyncPeriod();
Ady Abraham447052e2019-02-13 16:07:27 -0800133 return event;
134}
135
Ady Abraham62f216c2020-10-13 19:07:23 -0700136DisplayEventReceiver::Event makeFrameRateOverrideEvent(PhysicalDisplayId displayId,
137 FrameRateOverride frameRateOverride) {
138 return DisplayEventReceiver::Event{
139 .header =
140 DisplayEventReceiver::Event::Header{
141 .type = DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE,
142 .displayId = displayId,
143 .timestamp = systemTime(),
144 },
145 .frameRateOverride = frameRateOverride,
146 };
147}
148
149DisplayEventReceiver::Event makeFrameRateOverrideFlushEvent(PhysicalDisplayId displayId) {
150 return DisplayEventReceiver::Event{
151 .header = DisplayEventReceiver::Event::Header{
152 .type = DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH,
153 .displayId = displayId,
154 .timestamp = systemTime(),
155 }};
156}
157
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800158} // namespace
Lloyd Pique46a46b32018-01-31 19:01:18 -0800159
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700160EventThreadConnection::EventThreadConnection(EventThread* eventThread, uid_t callingUid,
161 ResyncCallback resyncCallback,
162 EventRegistrationFlags eventRegistration)
Dominik Laskowskif654d572018-12-20 11:03:06 -0800163 : resyncCallback(std::move(resyncCallback)),
Ady Abraham0bb6a472020-10-12 10:22:13 -0700164 mOwnerUid(callingUid),
Ady Abraham62f216c2020-10-13 19:07:23 -0700165 mEventRegistration(eventRegistration),
Dominik Laskowskif654d572018-12-20 11:03:06 -0800166 mEventThread(eventThread),
167 mChannel(gui::BitTube::DefaultSize) {}
Ana Krulec85c39af2018-12-26 17:29:57 -0800168
169EventThreadConnection::~EventThreadConnection() {
170 // do nothing here -- clean-up will happen automatically
171 // when the main thread wakes up
172}
173
174void EventThreadConnection::onFirstRef() {
175 // NOTE: mEventThread doesn't hold a strong reference on us
176 mEventThread->registerDisplayEventConnection(this);
177}
178
Huihong Luo6fac5232021-11-22 16:05:23 -0800179binder::Status EventThreadConnection::stealReceiveChannel(gui::BitTube* outChannel) {
Ady Abraham899e8cd2022-06-06 15:16:06 -0700180 std::scoped_lock lock(mLock);
181 if (mChannel.initCheck() != NO_ERROR) {
182 return binder::Status::fromStatusT(NAME_NOT_FOUND);
183 }
184
Ana Krulec85c39af2018-12-26 17:29:57 -0800185 outChannel->setReceiveFd(mChannel.moveReceiveFd());
Alec Mouri967d5d72020-08-05 12:50:03 -0700186 outChannel->setSendFd(base::unique_fd(dup(mChannel.getSendFd())));
Huihong Luo6fac5232021-11-22 16:05:23 -0800187 return binder::Status::ok();
Ana Krulec85c39af2018-12-26 17:29:57 -0800188}
189
Huihong Luo6fac5232021-11-22 16:05:23 -0800190binder::Status EventThreadConnection::setVsyncRate(int rate) {
191 mEventThread->setVsyncRate(static_cast<uint32_t>(rate), this);
192 return binder::Status::ok();
Ana Krulec85c39af2018-12-26 17:29:57 -0800193}
194
Huihong Luo6fac5232021-11-22 16:05:23 -0800195binder::Status EventThreadConnection::requestNextVsync() {
Rachel Leeef2e21f2022-02-01 14:51:34 -0800196 ATRACE_CALL();
Ady Abraham8532d012019-05-08 14:50:56 -0700197 mEventThread->requestNextVsync(this);
Huihong Luo6fac5232021-11-22 16:05:23 -0800198 return binder::Status::ok();
Ana Krulec85c39af2018-12-26 17:29:57 -0800199}
200
Rachel Leeb9c5a772022-02-04 21:17:37 -0800201binder::Status EventThreadConnection::getLatestVsyncEventData(
202 ParcelableVsyncEventData* outVsyncEventData) {
Rachel Leeef2e21f2022-02-01 14:51:34 -0800203 ATRACE_CALL();
Rachel Leeb9c5a772022-02-04 21:17:37 -0800204 outVsyncEventData->vsync = mEventThread->getLatestVsyncEventData(this);
Rachel Leeef2e21f2022-02-01 14:51:34 -0800205 return binder::Status::ok();
206}
207
Ana Krulec85c39af2018-12-26 17:29:57 -0800208status_t EventThreadConnection::postEvent(const DisplayEventReceiver::Event& event) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700209 constexpr auto toStatus = [](ssize_t size) {
210 return size < 0 ? status_t(size) : status_t(NO_ERROR);
211 };
212
213 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE ||
214 event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH) {
215 mPendingEvents.emplace_back(event);
216 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE) {
217 return status_t(NO_ERROR);
218 }
219
220 auto size = DisplayEventReceiver::sendEvents(&mChannel, mPendingEvents.data(),
221 mPendingEvents.size());
222 mPendingEvents.clear();
223 return toStatus(size);
224 }
225
226 auto size = DisplayEventReceiver::sendEvents(&mChannel, &event, 1);
227 return toStatus(size);
Ana Krulec85c39af2018-12-26 17:29:57 -0800228}
229
230// ---------------------------------------------------------------------------
231
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800232EventThread::~EventThread() = default;
233
234namespace impl {
235
Dominik Laskowski6505f792019-09-18 11:10:05 -0700236EventThread::EventThread(std::unique_ptr<VSyncSource> vsyncSource,
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700237 android::frametimeline::TokenManager* tokenManager,
Ady Abraham0bb6a472020-10-12 10:22:13 -0700238 InterceptVSyncsCallback interceptVSyncsCallback,
Jorim Jaggic0086af2021-02-12 18:18:11 +0100239 ThrottleVsyncCallback throttleVsyncCallback,
240 GetVsyncPeriodFunction getVsyncPeriodFunction)
Dominik Laskowski6505f792019-09-18 11:10:05 -0700241 : mVSyncSource(std::move(vsyncSource)),
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700242 mTokenManager(tokenManager),
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800243 mInterceptVSyncsCallback(std::move(interceptVSyncsCallback)),
Ady Abraham0bb6a472020-10-12 10:22:13 -0700244 mThrottleVsyncCallback(std::move(throttleVsyncCallback)),
Jorim Jaggic0086af2021-02-12 18:18:11 +0100245 mGetVsyncPeriodFunction(std::move(getVsyncPeriodFunction)),
Dominik Laskowski6505f792019-09-18 11:10:05 -0700246 mThreadName(mVSyncSource->getName()) {
Jorim Jaggic0086af2021-02-12 18:18:11 +0100247
248 LOG_ALWAYS_FATAL_IF(getVsyncPeriodFunction == nullptr,
249 "getVsyncPeriodFunction must not be null");
250
Dominik Laskowski029cc122019-01-23 19:52:06 -0800251 mVSyncSource->setCallback(this);
Lloyd Pique46a46b32018-01-31 19:01:18 -0800252
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800253 mThread = std::thread([this]() NO_THREAD_SAFETY_ANALYSIS {
254 std::unique_lock<std::mutex> lock(mMutex);
255 threadMain(lock);
256 });
Lloyd Pique46a46b32018-01-31 19:01:18 -0800257
Dominik Laskowski6505f792019-09-18 11:10:05 -0700258 pthread_setname_np(mThread.native_handle(), mThreadName);
Lloyd Pique46a46b32018-01-31 19:01:18 -0800259
260 pid_t tid = pthread_gettid_np(mThread.native_handle());
261
262 // Use SCHED_FIFO to minimize jitter
263 constexpr int EVENT_THREAD_PRIORITY = 2;
264 struct sched_param param = {0};
265 param.sched_priority = EVENT_THREAD_PRIORITY;
266 if (pthread_setschedparam(mThread.native_handle(), SCHED_FIFO, &param) != 0) {
267 ALOGE("Couldn't set SCHED_FIFO for EventThread");
268 }
269
270 set_sched_policy(tid, SP_FOREGROUND);
271}
272
273EventThread::~EventThread() {
Dominik Laskowski029cc122019-01-23 19:52:06 -0800274 mVSyncSource->setCallback(nullptr);
275
Lloyd Pique46a46b32018-01-31 19:01:18 -0800276 {
277 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski029cc122019-01-23 19:52:06 -0800278 mState = State::Quit;
Lloyd Pique46a46b32018-01-31 19:01:18 -0800279 mCondition.notify_all();
280 }
281 mThread.join();
Ruchi Kandoief472ec2014-04-02 12:50:06 -0700282}
283
Ady Abraham9c53ee72020-07-22 21:16:18 -0700284void EventThread::setDuration(std::chrono::nanoseconds workDuration,
285 std::chrono::nanoseconds readyDuration) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800286 std::lock_guard<std::mutex> lock(mMutex);
Ady Abraham9c53ee72020-07-22 21:16:18 -0700287 mVSyncSource->setDuration(workDuration, readyDuration);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700288}
289
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700290sp<EventThreadConnection> EventThread::createEventConnection(
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700291 ResyncCallback resyncCallback, EventRegistrationFlags eventRegistration) const {
Ady Abraham0bb6a472020-10-12 10:22:13 -0700292 return new EventThreadConnection(const_cast<EventThread*>(this),
293 IPCThreadState::self()->getCallingUid(),
Ady Abraham62f216c2020-10-13 19:07:23 -0700294 std::move(resyncCallback), eventRegistration);
Mathias Agopian8aedd472012-01-24 16:39:14 -0800295}
296
Ana Krulec85c39af2018-12-26 17:29:57 -0800297status_t EventThread::registerDisplayEventConnection(const sp<EventThreadConnection>& connection) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800298 std::lock_guard<std::mutex> lock(mMutex);
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700299
300 // this should never happen
301 auto it = std::find(mDisplayEventConnections.cbegin(),
302 mDisplayEventConnections.cend(), connection);
303 if (it != mDisplayEventConnections.cend()) {
304 ALOGW("DisplayEventConnection %p already exists", connection.get());
305 mCondition.notify_all();
306 return ALREADY_EXISTS;
307 }
308
309 mDisplayEventConnections.push_back(connection);
Lloyd Pique46a46b32018-01-31 19:01:18 -0800310 mCondition.notify_all();
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800311 return NO_ERROR;
312}
313
Ana Krulec85c39af2018-12-26 17:29:57 -0800314void EventThread::removeDisplayEventConnectionLocked(const wp<EventThreadConnection>& connection) {
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700315 auto it = std::find(mDisplayEventConnections.cbegin(),
316 mDisplayEventConnections.cend(), connection);
317 if (it != mDisplayEventConnections.cend()) {
318 mDisplayEventConnections.erase(it);
319 }
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800320}
321
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800322void EventThread::setVsyncRate(uint32_t rate, const sp<EventThreadConnection>& connection) {
323 if (static_cast<std::underlying_type_t<VSyncRequest>>(rate) < 0) {
324 return;
325 }
326
327 std::lock_guard<std::mutex> lock(mMutex);
328
329 const auto request = rate == 0 ? VSyncRequest::None : static_cast<VSyncRequest>(rate);
330 if (connection->vsyncRequest != request) {
331 connection->vsyncRequest = request;
332 mCondition.notify_all();
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800333 }
334}
335
Ady Abraham8532d012019-05-08 14:50:56 -0700336void EventThread::requestNextVsync(const sp<EventThreadConnection>& connection) {
Dominik Laskowskif654d572018-12-20 11:03:06 -0800337 if (connection->resyncCallback) {
338 connection->resyncCallback();
Lloyd Pique24b0a482018-03-09 18:52:26 -0800339 }
Tim Murray4a4e4a22016-04-19 16:29:23 +0000340
Ana Krulec7d1d6832018-12-27 11:10:09 -0800341 std::lock_guard<std::mutex> lock(mMutex);
342
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800343 if (connection->vsyncRequest == VSyncRequest::None) {
344 connection->vsyncRequest = VSyncRequest::Single;
Lloyd Pique46a46b32018-01-31 19:01:18 -0800345 mCondition.notify_all();
Tim Murrayb5daa912020-09-09 21:29:13 +0000346 } else if (connection->vsyncRequest == VSyncRequest::SingleSuppressCallback) {
347 connection->vsyncRequest = VSyncRequest::Single;
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800348 }
Mathias Agopian23748662011-12-05 14:33:34 -0800349}
350
Rachel Leeef2e21f2022-02-01 14:51:34 -0800351VsyncEventData EventThread::getLatestVsyncEventData(
352 const sp<EventThreadConnection>& connection) const {
Rachel Leeb5223cf2022-03-14 14:39:27 -0700353 // Resync so that the vsync is accurate with hardware. getLatestVsyncEventData is an alternate
354 // way to get vsync data (instead of posting callbacks to Choreographer).
355 if (connection->resyncCallback) {
356 connection->resyncCallback();
357 }
358
Rachel Leeef2e21f2022-02-01 14:51:34 -0800359 VsyncEventData vsyncEventData;
Rachel Leeb9c5a772022-02-04 21:17:37 -0800360 nsecs_t frameInterval = mGetVsyncPeriodFunction(connection->mOwnerUid);
Rachel Leeef2e21f2022-02-01 14:51:34 -0800361 vsyncEventData.frameInterval = frameInterval;
Rachel Leeb9c5a772022-02-04 21:17:37 -0800362 VSyncSource::VSyncData vsyncData;
363 {
364 std::lock_guard<std::mutex> lock(mMutex);
365 vsyncData = mVSyncSource->getLatestVSyncData();
366 }
367 generateFrameTimeline(vsyncEventData, frameInterval, systemTime(SYSTEM_TIME_MONOTONIC),
368 vsyncData.expectedPresentationTime, vsyncData.deadlineTimestamp);
Rachel Leeef2e21f2022-02-01 14:51:34 -0800369 return vsyncEventData;
370}
371
Mathias Agopian22ffb112012-04-10 21:04:02 -0700372void EventThread::onScreenReleased() {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800373 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800374 if (!mVSyncState || mVSyncState->synthetic) {
375 return;
Mathias Agopian22ffb112012-04-10 21:04:02 -0700376 }
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800377
378 mVSyncState->synthetic = true;
379 mCondition.notify_all();
Mathias Agopian22ffb112012-04-10 21:04:02 -0700380}
381
382void EventThread::onScreenAcquired() {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800383 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800384 if (!mVSyncState || !mVSyncState->synthetic) {
385 return;
Mathias Agopian7d886472012-06-14 23:39:35 -0700386 }
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800387
388 mVSyncState->synthetic = false;
389 mCondition.notify_all();
Mathias Agopian22ffb112012-04-10 21:04:02 -0700390}
391
Rachel Leef16da3c2022-01-20 13:57:18 -0800392void EventThread::onVSyncEvent(nsecs_t timestamp, VSyncSource::VSyncData vsyncData) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800393 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800394
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800395 LOG_FATAL_IF(!mVSyncState);
Ady Abraham5facfb12020-04-22 15:18:31 -0700396 mPendingEvents.push_back(makeVSync(mVSyncState->displayId, timestamp, ++mVSyncState->count,
Rachel Leeb9c5a772022-02-04 21:17:37 -0800397 vsyncData.expectedPresentationTime,
Rachel Leef16da3c2022-01-20 13:57:18 -0800398 vsyncData.deadlineTimestamp));
Lloyd Pique46a46b32018-01-31 19:01:18 -0800399 mCondition.notify_all();
Mathias Agopian3eb38cb2012-04-03 22:09:52 -0700400}
401
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800402void EventThread::onHotplugReceived(PhysicalDisplayId displayId, bool connected) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800403 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -0700404
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800405 mPendingEvents.push_back(makeHotplug(displayId, systemTime(), connected));
Dominik Laskowski00a6fa22018-06-06 16:42:02 -0700406 mCondition.notify_all();
Mathias Agopian148994e2012-09-19 17:31:36 -0700407}
408
Ady Abraham690f4612021-07-01 23:24:03 -0700409void EventThread::onModeChanged(DisplayModePtr mode) {
Ady Abraham447052e2019-02-13 16:07:27 -0800410 std::lock_guard<std::mutex> lock(mMutex);
411
Ady Abraham690f4612021-07-01 23:24:03 -0700412 mPendingEvents.push_back(makeModeChanged(mode));
Ady Abraham447052e2019-02-13 16:07:27 -0800413 mCondition.notify_all();
414}
415
Ady Abraham62f216c2020-10-13 19:07:23 -0700416void EventThread::onFrameRateOverridesChanged(PhysicalDisplayId displayId,
417 std::vector<FrameRateOverride> overrides) {
418 std::lock_guard<std::mutex> lock(mMutex);
419
420 for (auto frameRateOverride : overrides) {
421 mPendingEvents.push_back(makeFrameRateOverrideEvent(displayId, frameRateOverride));
422 }
423 mPendingEvents.push_back(makeFrameRateOverrideFlushEvent(displayId));
424
425 mCondition.notify_all();
426}
427
Alec Mouri717bcb62020-02-10 17:07:19 -0800428size_t EventThread::getEventThreadConnectionCount() {
429 std::lock_guard<std::mutex> lock(mMutex);
430 return mDisplayEventConnections.size();
431}
432
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800433void EventThread::threadMain(std::unique_lock<std::mutex>& lock) {
434 DisplayEventConsumers consumers;
435
Dominik Laskowski029cc122019-01-23 19:52:06 -0800436 while (mState != State::Quit) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800437 std::optional<DisplayEventReceiver::Event> event;
Mathias Agopian3eb38cb2012-04-03 22:09:52 -0700438
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800439 // Determine next event to dispatch.
440 if (!mPendingEvents.empty()) {
441 event = mPendingEvents.front();
442 mPendingEvents.pop_front();
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800443
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800444 switch (event->header.type) {
445 case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
446 if (event->hotplug.connected && !mVSyncState) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800447 mVSyncState.emplace(event->header.displayId);
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800448 } else if (!event->hotplug.connected && mVSyncState &&
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800449 mVSyncState->displayId == event->header.displayId) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800450 mVSyncState.reset();
451 }
452 break;
453
454 case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
455 if (mInterceptVSyncsCallback) {
456 mInterceptVSyncsCallback(event->header.timestamp);
457 }
458 break;
Dominik Laskowski029cc122019-01-23 19:52:06 -0800459 }
Mathias Agopianff28e202012-09-20 23:24:19 -0700460 }
461
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800462 bool vsyncRequested = false;
Mathias Agopian148994e2012-09-19 17:31:36 -0700463
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800464 // Find connections that should consume this event.
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700465 auto it = mDisplayEventConnections.begin();
466 while (it != mDisplayEventConnections.end()) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800467 if (const auto connection = it->promote()) {
468 vsyncRequested |= connection->vsyncRequest != VSyncRequest::None;
469
470 if (event && shouldConsumeEvent(*event, connection)) {
471 consumers.push_back(connection);
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700472 }
Mathias Agopianb4d18ed2012-09-20 23:14:05 -0700473
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700474 ++it;
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700475 } else {
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700476 it = mDisplayEventConnections.erase(it);
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700477 }
478 }
479
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800480 if (!consumers.empty()) {
481 dispatchEvent(*event, consumers);
482 consumers.clear();
483 }
484
Dominik Laskowski029cc122019-01-23 19:52:06 -0800485 State nextState;
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800486 if (mVSyncState && vsyncRequested) {
487 nextState = mVSyncState->synthetic ? State::SyntheticVSync : State::VSync;
Dominik Laskowski029cc122019-01-23 19:52:06 -0800488 } else {
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800489 ALOGW_IF(!mVSyncState, "Ignoring VSYNC request while display is disconnected");
Dominik Laskowski029cc122019-01-23 19:52:06 -0800490 nextState = State::Idle;
491 }
492
493 if (mState != nextState) {
494 if (mState == State::VSync) {
495 mVSyncSource->setVSyncEnabled(false);
496 } else if (nextState == State::VSync) {
497 mVSyncSource->setVSyncEnabled(true);
498 }
499
500 mState = nextState;
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700501 }
502
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800503 if (event) {
504 continue;
505 }
506
507 // Wait for event or client registration/request.
Dominik Laskowski029cc122019-01-23 19:52:06 -0800508 if (mState == State::Idle) {
509 mCondition.wait(lock);
510 } else {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800511 // Generate a fake VSYNC after a long timeout in case the driver stalls. When the
512 // display is off, keep feeding clients at 60 Hz.
Ady Abraham5facfb12020-04-22 15:18:31 -0700513 const std::chrono::nanoseconds timeout =
514 mState == State::SyntheticVSync ? 16ms : 1000ms;
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800515 if (mCondition.wait_for(lock, timeout) == std::cv_status::timeout) {
Ady Abraham5e7371c2020-03-24 14:47:24 -0700516 if (mState == State::VSync) {
517 ALOGW("Faking VSYNC due to driver stall for thread %s", mThreadName);
518 std::string debugInfo = "VsyncSource debug info:\n";
519 mVSyncSource->dump(debugInfo);
Ady Abraham75398722020-04-07 14:08:45 -0700520 // Log the debug info line-by-line to avoid logcat overflow
521 auto pos = debugInfo.find('\n');
522 while (pos != std::string::npos) {
523 ALOGW("%s", debugInfo.substr(0, pos).c_str());
524 debugInfo = debugInfo.substr(pos + 1);
525 pos = debugInfo.find('\n');
526 }
Ady Abraham5e7371c2020-03-24 14:47:24 -0700527 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800528
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800529 LOG_FATAL_IF(!mVSyncState);
Ady Abraham5facfb12020-04-22 15:18:31 -0700530 const auto now = systemTime(SYSTEM_TIME_MONOTONIC);
Ady Abraham8cb21882020-08-26 18:22:05 -0700531 const auto deadlineTimestamp = now + timeout.count();
532 const auto expectedVSyncTime = deadlineTimestamp + timeout.count();
Ady Abraham5facfb12020-04-22 15:18:31 -0700533 mPendingEvents.push_back(makeVSync(mVSyncState->displayId, now,
Ady Abraham8cb21882020-08-26 18:22:05 -0700534 ++mVSyncState->count, expectedVSyncTime,
Rachel Lee0d943202022-02-01 23:29:41 -0800535 deadlineTimestamp));
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700536 }
537 }
Lloyd Pique46a46b32018-01-31 19:01:18 -0800538 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800539}
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700540
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800541bool EventThread::shouldConsumeEvent(const DisplayEventReceiver::Event& event,
542 const sp<EventThreadConnection>& connection) const {
Ady Abraham0bb6a472020-10-12 10:22:13 -0700543 const auto throttleVsync = [&] {
544 return mThrottleVsyncCallback &&
Rachel Leeb9c5a772022-02-04 21:17:37 -0800545 mThrottleVsyncCallback(event.vsync.vsyncData.preferredExpectedPresentationTime(),
546 connection->mOwnerUid);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700547 };
548
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800549 switch (event.header.type) {
550 case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
551 return true;
552
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100553 case DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE: {
Ady Abraham62f216c2020-10-13 19:07:23 -0700554 return connection->mEventRegistration.test(
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700555 gui::ISurfaceComposer::EventRegistration::modeChanged);
Alec Mouri60aee1c2019-10-28 16:18:59 -0700556 }
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700557
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800558 case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
559 switch (connection->vsyncRequest) {
560 case VSyncRequest::None:
561 return false;
Tim Murrayb5daa912020-09-09 21:29:13 +0000562 case VSyncRequest::SingleSuppressCallback:
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800563 connection->vsyncRequest = VSyncRequest::None;
Tim Murrayb5daa912020-09-09 21:29:13 +0000564 return false;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700565 case VSyncRequest::Single: {
566 if (throttleVsync()) {
567 return false;
568 }
Tim Murrayb5daa912020-09-09 21:29:13 +0000569 connection->vsyncRequest = VSyncRequest::SingleSuppressCallback;
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800570 return true;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700571 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800572 case VSyncRequest::Periodic:
Ady Abraham0bb6a472020-10-12 10:22:13 -0700573 if (throttleVsync()) {
574 return false;
575 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800576 return true;
577 default:
Ady Abraham0bb6a472020-10-12 10:22:13 -0700578 // We don't throttle vsync if the app set a vsync request rate
579 // since there is no easy way to do that and this is a very
580 // rare case
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800581 return event.vsync.count % vsyncPeriod(connection->vsyncRequest) == 0;
582 }
583
Ady Abraham62f216c2020-10-13 19:07:23 -0700584 case DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE:
585 [[fallthrough]];
586 case DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH:
587 return connection->mEventRegistration.test(
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700588 gui::ISurfaceComposer::EventRegistration::frameRateOverride);
Ady Abraham62f216c2020-10-13 19:07:23 -0700589
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800590 default:
591 return false;
592 }
593}
594
Rachel Lee8d0c6102021-11-03 22:00:25 +0000595int64_t EventThread::generateToken(nsecs_t timestamp, nsecs_t deadlineTimestamp,
Rachel Leeb9c5a772022-02-04 21:17:37 -0800596 nsecs_t expectedPresentationTime) const {
Rachel Lee3f028662021-11-04 19:32:24 +0000597 if (mTokenManager != nullptr) {
598 return mTokenManager->generateTokenForPredictions(
Rachel Leeb9c5a772022-02-04 21:17:37 -0800599 {timestamp, deadlineTimestamp, expectedPresentationTime});
Rachel Lee3f028662021-11-04 19:32:24 +0000600 }
601 return FrameTimelineInfo::INVALID_VSYNC_ID;
602}
603
Rachel Leeb9c5a772022-02-04 21:17:37 -0800604void EventThread::generateFrameTimeline(VsyncEventData& outVsyncEventData, nsecs_t frameInterval,
605 nsecs_t timestamp,
606 nsecs_t preferredExpectedPresentationTime,
607 nsecs_t preferredDeadlineTimestamp) const {
Rachel Lee3f028662021-11-04 19:32:24 +0000608 // Add 1 to ensure the preferredFrameTimelineIndex entry (when multiplier == 0) is included.
Rachel Leeef2e21f2022-02-01 14:51:34 -0800609 for (int64_t multiplier = -VsyncEventData::kFrameTimelinesLength + 1, currentIndex = 0;
Rachel Lee18c34372022-01-20 13:57:18 -0800610 currentIndex < VsyncEventData::kFrameTimelinesLength; multiplier++) {
Rachel Leeb9c5a772022-02-04 21:17:37 -0800611 nsecs_t deadlineTimestamp = preferredDeadlineTimestamp + multiplier * frameInterval;
Rachel Lee3f028662021-11-04 19:32:24 +0000612 // Valid possible frame timelines must have future values.
Rachel Leeb9c5a772022-02-04 21:17:37 -0800613 if (deadlineTimestamp > timestamp) {
Rachel Lee3f028662021-11-04 19:32:24 +0000614 if (multiplier == 0) {
Rachel Leeb9c5a772022-02-04 21:17:37 -0800615 outVsyncEventData.preferredFrameTimelineIndex = currentIndex;
Rachel Lee3f028662021-11-04 19:32:24 +0000616 }
Rachel Leeb9c5a772022-02-04 21:17:37 -0800617 nsecs_t expectedPresentationTime =
618 preferredExpectedPresentationTime + multiplier * frameInterval;
619 outVsyncEventData.frameTimelines[currentIndex] =
620 {.vsyncId =
621 generateToken(timestamp, deadlineTimestamp, expectedPresentationTime),
622 .deadlineTimestamp = deadlineTimestamp,
623 .expectedPresentationTime = expectedPresentationTime};
Rachel Lee3f028662021-11-04 19:32:24 +0000624 currentIndex++;
625 }
626 }
627}
628
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800629void EventThread::dispatchEvent(const DisplayEventReceiver::Event& event,
630 const DisplayEventConsumers& consumers) {
631 for (const auto& consumer : consumers) {
Jorim Jaggic0086af2021-02-12 18:18:11 +0100632 DisplayEventReceiver::Event copy = event;
633 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_VSYNC) {
Rachel Leeb9c5a772022-02-04 21:17:37 -0800634 const int64_t frameInterval = mGetVsyncPeriodFunction(consumer->mOwnerUid);
635 copy.vsync.vsyncData.frameInterval = frameInterval;
636 generateFrameTimeline(copy.vsync.vsyncData, frameInterval, copy.header.timestamp,
637 event.vsync.vsyncData.preferredExpectedPresentationTime(),
638 event.vsync.vsyncData.preferredDeadlineTimestamp());
Jorim Jaggic0086af2021-02-12 18:18:11 +0100639 }
640 switch (consumer->postEvent(copy)) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800641 case NO_ERROR:
642 break;
643
644 case -EAGAIN:
645 // TODO: Try again if pipe is full.
646 ALOGW("Failed dispatching %s for %s", toString(event).c_str(),
647 toString(*consumer).c_str());
648 break;
649
650 default:
651 // Treat EPIPE and other errors as fatal.
652 removeDisplayEventConnectionLocked(consumer);
653 }
654 }
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700655}
656
Yiwei Zhang5434a782018-12-05 18:06:32 -0800657void EventThread::dump(std::string& result) const {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800658 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800659
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800660 StringAppendF(&result, "%s: state=%s VSyncState=", mThreadName, toCString(mState));
661 if (mVSyncState) {
Marin Shalamanova524a092020-07-27 21:39:55 +0200662 StringAppendF(&result, "{displayId=%s, count=%u%s}\n",
663 to_string(mVSyncState->displayId).c_str(), mVSyncState->count,
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800664 mVSyncState->synthetic ? ", synthetic" : "");
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800665 } else {
666 StringAppendF(&result, "none\n");
667 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800668
669 StringAppendF(&result, " pending events (count=%zu):\n", mPendingEvents.size());
670 for (const auto& event : mPendingEvents) {
671 StringAppendF(&result, " %s\n", toString(event).c_str());
Mathias Agopiane2c4f4e2012-04-10 18:25:31 -0700672 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800673
674 StringAppendF(&result, " connections (count=%zu):\n", mDisplayEventConnections.size());
675 for (const auto& ptr : mDisplayEventConnections) {
676 if (const auto connection = ptr.promote()) {
677 StringAppendF(&result, " %s\n", toString(*connection).c_str());
678 }
679 }
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800680}
681
Dominik Laskowski029cc122019-01-23 19:52:06 -0800682const char* EventThread::toCString(State state) {
683 switch (state) {
684 case State::Idle:
685 return "Idle";
686 case State::Quit:
687 return "Quit";
688 case State::SyntheticVSync:
689 return "SyntheticVSync";
690 case State::VSync:
691 return "VSync";
692 }
693}
694
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800695} // namespace impl
Lloyd Pique46a46b32018-01-31 19:01:18 -0800696} // namespace android
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800697
698// TODO(b/129481165): remove the #pragma below and fix conversion issues
699#pragma clang diagnostic pop // ignored "-Wconversion"