blob: cbea77e8fbe8e73e378e1ab200074fcdb1501d5c [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
Ady Abraham62f216c2020-10-13 19:07:23 -0700160EventThreadConnection::EventThreadConnection(
161 EventThread* eventThread, uid_t callingUid, ResyncCallback resyncCallback,
162 ISurfaceComposer::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) {
Ana Krulec85c39af2018-12-26 17:29:57 -0800180 outChannel->setReceiveFd(mChannel.moveReceiveFd());
Alec Mouri967d5d72020-08-05 12:50:03 -0700181 outChannel->setSendFd(base::unique_fd(dup(mChannel.getSendFd())));
Huihong Luo6fac5232021-11-22 16:05:23 -0800182 return binder::Status::ok();
Ana Krulec85c39af2018-12-26 17:29:57 -0800183}
184
Huihong Luo6fac5232021-11-22 16:05:23 -0800185binder::Status EventThreadConnection::setVsyncRate(int rate) {
186 mEventThread->setVsyncRate(static_cast<uint32_t>(rate), this);
187 return binder::Status::ok();
Ana Krulec85c39af2018-12-26 17:29:57 -0800188}
189
Huihong Luo6fac5232021-11-22 16:05:23 -0800190binder::Status EventThreadConnection::requestNextVsync() {
Rachel Leeef2e21f2022-02-01 14:51:34 -0800191 ATRACE_CALL();
Ady Abraham8532d012019-05-08 14:50:56 -0700192 mEventThread->requestNextVsync(this);
Huihong Luo6fac5232021-11-22 16:05:23 -0800193 return binder::Status::ok();
Ana Krulec85c39af2018-12-26 17:29:57 -0800194}
195
Rachel Leeb9c5a772022-02-04 21:17:37 -0800196binder::Status EventThreadConnection::getLatestVsyncEventData(
197 ParcelableVsyncEventData* outVsyncEventData) {
Rachel Leeef2e21f2022-02-01 14:51:34 -0800198 ATRACE_CALL();
Rachel Leeb9c5a772022-02-04 21:17:37 -0800199 outVsyncEventData->vsync = mEventThread->getLatestVsyncEventData(this);
Rachel Leeef2e21f2022-02-01 14:51:34 -0800200 return binder::Status::ok();
201}
202
Ana Krulec85c39af2018-12-26 17:29:57 -0800203status_t EventThreadConnection::postEvent(const DisplayEventReceiver::Event& event) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700204 constexpr auto toStatus = [](ssize_t size) {
205 return size < 0 ? status_t(size) : status_t(NO_ERROR);
206 };
207
208 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE ||
209 event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH) {
210 mPendingEvents.emplace_back(event);
211 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE) {
212 return status_t(NO_ERROR);
213 }
214
215 auto size = DisplayEventReceiver::sendEvents(&mChannel, mPendingEvents.data(),
216 mPendingEvents.size());
217 mPendingEvents.clear();
218 return toStatus(size);
219 }
220
221 auto size = DisplayEventReceiver::sendEvents(&mChannel, &event, 1);
222 return toStatus(size);
Ana Krulec85c39af2018-12-26 17:29:57 -0800223}
224
225// ---------------------------------------------------------------------------
226
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800227EventThread::~EventThread() = default;
228
229namespace impl {
230
Dominik Laskowski6505f792019-09-18 11:10:05 -0700231EventThread::EventThread(std::unique_ptr<VSyncSource> vsyncSource,
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700232 android::frametimeline::TokenManager* tokenManager,
Ady Abraham0bb6a472020-10-12 10:22:13 -0700233 InterceptVSyncsCallback interceptVSyncsCallback,
Jorim Jaggic0086af2021-02-12 18:18:11 +0100234 ThrottleVsyncCallback throttleVsyncCallback,
235 GetVsyncPeriodFunction getVsyncPeriodFunction)
Dominik Laskowski6505f792019-09-18 11:10:05 -0700236 : mVSyncSource(std::move(vsyncSource)),
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700237 mTokenManager(tokenManager),
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800238 mInterceptVSyncsCallback(std::move(interceptVSyncsCallback)),
Ady Abraham0bb6a472020-10-12 10:22:13 -0700239 mThrottleVsyncCallback(std::move(throttleVsyncCallback)),
Jorim Jaggic0086af2021-02-12 18:18:11 +0100240 mGetVsyncPeriodFunction(std::move(getVsyncPeriodFunction)),
Dominik Laskowski6505f792019-09-18 11:10:05 -0700241 mThreadName(mVSyncSource->getName()) {
Jorim Jaggic0086af2021-02-12 18:18:11 +0100242
243 LOG_ALWAYS_FATAL_IF(getVsyncPeriodFunction == nullptr,
244 "getVsyncPeriodFunction must not be null");
245
Dominik Laskowski029cc122019-01-23 19:52:06 -0800246 mVSyncSource->setCallback(this);
Lloyd Pique46a46b32018-01-31 19:01:18 -0800247
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800248 mThread = std::thread([this]() NO_THREAD_SAFETY_ANALYSIS {
249 std::unique_lock<std::mutex> lock(mMutex);
250 threadMain(lock);
251 });
Lloyd Pique46a46b32018-01-31 19:01:18 -0800252
Dominik Laskowski6505f792019-09-18 11:10:05 -0700253 pthread_setname_np(mThread.native_handle(), mThreadName);
Lloyd Pique46a46b32018-01-31 19:01:18 -0800254
255 pid_t tid = pthread_gettid_np(mThread.native_handle());
256
257 // Use SCHED_FIFO to minimize jitter
258 constexpr int EVENT_THREAD_PRIORITY = 2;
259 struct sched_param param = {0};
260 param.sched_priority = EVENT_THREAD_PRIORITY;
261 if (pthread_setschedparam(mThread.native_handle(), SCHED_FIFO, &param) != 0) {
262 ALOGE("Couldn't set SCHED_FIFO for EventThread");
263 }
264
265 set_sched_policy(tid, SP_FOREGROUND);
266}
267
268EventThread::~EventThread() {
Dominik Laskowski029cc122019-01-23 19:52:06 -0800269 mVSyncSource->setCallback(nullptr);
270
Lloyd Pique46a46b32018-01-31 19:01:18 -0800271 {
272 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski029cc122019-01-23 19:52:06 -0800273 mState = State::Quit;
Lloyd Pique46a46b32018-01-31 19:01:18 -0800274 mCondition.notify_all();
275 }
276 mThread.join();
Ruchi Kandoief472ec2014-04-02 12:50:06 -0700277}
278
Ady Abraham9c53ee72020-07-22 21:16:18 -0700279void EventThread::setDuration(std::chrono::nanoseconds workDuration,
280 std::chrono::nanoseconds readyDuration) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800281 std::lock_guard<std::mutex> lock(mMutex);
Ady Abraham9c53ee72020-07-22 21:16:18 -0700282 mVSyncSource->setDuration(workDuration, readyDuration);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700283}
284
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700285sp<EventThreadConnection> EventThread::createEventConnection(
Ady Abraham62f216c2020-10-13 19:07:23 -0700286 ResyncCallback resyncCallback,
287 ISurfaceComposer::EventRegistrationFlags eventRegistration) const {
Ady Abraham0bb6a472020-10-12 10:22:13 -0700288 return new EventThreadConnection(const_cast<EventThread*>(this),
289 IPCThreadState::self()->getCallingUid(),
Ady Abraham62f216c2020-10-13 19:07:23 -0700290 std::move(resyncCallback), eventRegistration);
Mathias Agopian8aedd472012-01-24 16:39:14 -0800291}
292
Ana Krulec85c39af2018-12-26 17:29:57 -0800293status_t EventThread::registerDisplayEventConnection(const sp<EventThreadConnection>& connection) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800294 std::lock_guard<std::mutex> lock(mMutex);
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700295
296 // this should never happen
297 auto it = std::find(mDisplayEventConnections.cbegin(),
298 mDisplayEventConnections.cend(), connection);
299 if (it != mDisplayEventConnections.cend()) {
300 ALOGW("DisplayEventConnection %p already exists", connection.get());
301 mCondition.notify_all();
302 return ALREADY_EXISTS;
303 }
304
305 mDisplayEventConnections.push_back(connection);
Lloyd Pique46a46b32018-01-31 19:01:18 -0800306 mCondition.notify_all();
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800307 return NO_ERROR;
308}
309
Ana Krulec85c39af2018-12-26 17:29:57 -0800310void EventThread::removeDisplayEventConnectionLocked(const wp<EventThreadConnection>& connection) {
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700311 auto it = std::find(mDisplayEventConnections.cbegin(),
312 mDisplayEventConnections.cend(), connection);
313 if (it != mDisplayEventConnections.cend()) {
314 mDisplayEventConnections.erase(it);
315 }
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800316}
317
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800318void EventThread::setVsyncRate(uint32_t rate, const sp<EventThreadConnection>& connection) {
319 if (static_cast<std::underlying_type_t<VSyncRequest>>(rate) < 0) {
320 return;
321 }
322
323 std::lock_guard<std::mutex> lock(mMutex);
324
325 const auto request = rate == 0 ? VSyncRequest::None : static_cast<VSyncRequest>(rate);
326 if (connection->vsyncRequest != request) {
327 connection->vsyncRequest = request;
328 mCondition.notify_all();
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800329 }
330}
331
Ady Abraham8532d012019-05-08 14:50:56 -0700332void EventThread::requestNextVsync(const sp<EventThreadConnection>& connection) {
Dominik Laskowskif654d572018-12-20 11:03:06 -0800333 if (connection->resyncCallback) {
334 connection->resyncCallback();
Lloyd Pique24b0a482018-03-09 18:52:26 -0800335 }
Tim Murray4a4e4a22016-04-19 16:29:23 +0000336
Ana Krulec7d1d6832018-12-27 11:10:09 -0800337 std::lock_guard<std::mutex> lock(mMutex);
338
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800339 if (connection->vsyncRequest == VSyncRequest::None) {
340 connection->vsyncRequest = VSyncRequest::Single;
Lloyd Pique46a46b32018-01-31 19:01:18 -0800341 mCondition.notify_all();
Tim Murrayb5daa912020-09-09 21:29:13 +0000342 } else if (connection->vsyncRequest == VSyncRequest::SingleSuppressCallback) {
343 connection->vsyncRequest = VSyncRequest::Single;
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800344 }
Mathias Agopian23748662011-12-05 14:33:34 -0800345}
346
Rachel Leeef2e21f2022-02-01 14:51:34 -0800347VsyncEventData EventThread::getLatestVsyncEventData(
348 const sp<EventThreadConnection>& connection) const {
Rachel Leeb5223cf2022-03-14 14:39:27 -0700349 // Resync so that the vsync is accurate with hardware. getLatestVsyncEventData is an alternate
350 // way to get vsync data (instead of posting callbacks to Choreographer).
351 if (connection->resyncCallback) {
352 connection->resyncCallback();
353 }
354
Rachel Leeef2e21f2022-02-01 14:51:34 -0800355 VsyncEventData vsyncEventData;
Rachel Leeb9c5a772022-02-04 21:17:37 -0800356 nsecs_t frameInterval = mGetVsyncPeriodFunction(connection->mOwnerUid);
Rachel Leeef2e21f2022-02-01 14:51:34 -0800357 vsyncEventData.frameInterval = frameInterval;
Rachel Leeb9c5a772022-02-04 21:17:37 -0800358 VSyncSource::VSyncData vsyncData;
359 {
360 std::lock_guard<std::mutex> lock(mMutex);
361 vsyncData = mVSyncSource->getLatestVSyncData();
362 }
363 generateFrameTimeline(vsyncEventData, frameInterval, systemTime(SYSTEM_TIME_MONOTONIC),
364 vsyncData.expectedPresentationTime, vsyncData.deadlineTimestamp);
Rachel Leeef2e21f2022-02-01 14:51:34 -0800365 return vsyncEventData;
366}
367
Mathias Agopian22ffb112012-04-10 21:04:02 -0700368void EventThread::onScreenReleased() {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800369 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800370 if (!mVSyncState || mVSyncState->synthetic) {
371 return;
Mathias Agopian22ffb112012-04-10 21:04:02 -0700372 }
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800373
374 mVSyncState->synthetic = true;
375 mCondition.notify_all();
Mathias Agopian22ffb112012-04-10 21:04:02 -0700376}
377
378void EventThread::onScreenAcquired() {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800379 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800380 if (!mVSyncState || !mVSyncState->synthetic) {
381 return;
Mathias Agopian7d886472012-06-14 23:39:35 -0700382 }
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800383
384 mVSyncState->synthetic = false;
385 mCondition.notify_all();
Mathias Agopian22ffb112012-04-10 21:04:02 -0700386}
387
Rachel Leef16da3c2022-01-20 13:57:18 -0800388void EventThread::onVSyncEvent(nsecs_t timestamp, VSyncSource::VSyncData vsyncData) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800389 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800390
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800391 LOG_FATAL_IF(!mVSyncState);
Ady Abraham5facfb12020-04-22 15:18:31 -0700392 mPendingEvents.push_back(makeVSync(mVSyncState->displayId, timestamp, ++mVSyncState->count,
Rachel Leeb9c5a772022-02-04 21:17:37 -0800393 vsyncData.expectedPresentationTime,
Rachel Leef16da3c2022-01-20 13:57:18 -0800394 vsyncData.deadlineTimestamp));
Lloyd Pique46a46b32018-01-31 19:01:18 -0800395 mCondition.notify_all();
Mathias Agopian3eb38cb2012-04-03 22:09:52 -0700396}
397
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800398void EventThread::onHotplugReceived(PhysicalDisplayId displayId, bool connected) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800399 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -0700400
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800401 mPendingEvents.push_back(makeHotplug(displayId, systemTime(), connected));
Dominik Laskowski00a6fa22018-06-06 16:42:02 -0700402 mCondition.notify_all();
Mathias Agopian148994e2012-09-19 17:31:36 -0700403}
404
Ady Abraham690f4612021-07-01 23:24:03 -0700405void EventThread::onModeChanged(DisplayModePtr mode) {
Ady Abraham447052e2019-02-13 16:07:27 -0800406 std::lock_guard<std::mutex> lock(mMutex);
407
Ady Abraham690f4612021-07-01 23:24:03 -0700408 mPendingEvents.push_back(makeModeChanged(mode));
Ady Abraham447052e2019-02-13 16:07:27 -0800409 mCondition.notify_all();
410}
411
Ady Abraham62f216c2020-10-13 19:07:23 -0700412void EventThread::onFrameRateOverridesChanged(PhysicalDisplayId displayId,
413 std::vector<FrameRateOverride> overrides) {
414 std::lock_guard<std::mutex> lock(mMutex);
415
416 for (auto frameRateOverride : overrides) {
417 mPendingEvents.push_back(makeFrameRateOverrideEvent(displayId, frameRateOverride));
418 }
419 mPendingEvents.push_back(makeFrameRateOverrideFlushEvent(displayId));
420
421 mCondition.notify_all();
422}
423
Alec Mouri717bcb62020-02-10 17:07:19 -0800424size_t EventThread::getEventThreadConnectionCount() {
425 std::lock_guard<std::mutex> lock(mMutex);
426 return mDisplayEventConnections.size();
427}
428
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800429void EventThread::threadMain(std::unique_lock<std::mutex>& lock) {
430 DisplayEventConsumers consumers;
431
Dominik Laskowski029cc122019-01-23 19:52:06 -0800432 while (mState != State::Quit) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800433 std::optional<DisplayEventReceiver::Event> event;
Mathias Agopian3eb38cb2012-04-03 22:09:52 -0700434
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800435 // Determine next event to dispatch.
436 if (!mPendingEvents.empty()) {
437 event = mPendingEvents.front();
438 mPendingEvents.pop_front();
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800439
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800440 switch (event->header.type) {
441 case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
442 if (event->hotplug.connected && !mVSyncState) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800443 mVSyncState.emplace(event->header.displayId);
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800444 } else if (!event->hotplug.connected && mVSyncState &&
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800445 mVSyncState->displayId == event->header.displayId) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800446 mVSyncState.reset();
447 }
448 break;
449
450 case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
451 if (mInterceptVSyncsCallback) {
452 mInterceptVSyncsCallback(event->header.timestamp);
453 }
454 break;
Dominik Laskowski029cc122019-01-23 19:52:06 -0800455 }
Mathias Agopianff28e202012-09-20 23:24:19 -0700456 }
457
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800458 bool vsyncRequested = false;
Mathias Agopian148994e2012-09-19 17:31:36 -0700459
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800460 // Find connections that should consume this event.
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700461 auto it = mDisplayEventConnections.begin();
462 while (it != mDisplayEventConnections.end()) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800463 if (const auto connection = it->promote()) {
464 vsyncRequested |= connection->vsyncRequest != VSyncRequest::None;
465
466 if (event && shouldConsumeEvent(*event, connection)) {
467 consumers.push_back(connection);
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700468 }
Mathias Agopianb4d18ed2012-09-20 23:14:05 -0700469
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700470 ++it;
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700471 } else {
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700472 it = mDisplayEventConnections.erase(it);
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700473 }
474 }
475
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800476 if (!consumers.empty()) {
477 dispatchEvent(*event, consumers);
478 consumers.clear();
479 }
480
Dominik Laskowski029cc122019-01-23 19:52:06 -0800481 State nextState;
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800482 if (mVSyncState && vsyncRequested) {
483 nextState = mVSyncState->synthetic ? State::SyntheticVSync : State::VSync;
Dominik Laskowski029cc122019-01-23 19:52:06 -0800484 } else {
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800485 ALOGW_IF(!mVSyncState, "Ignoring VSYNC request while display is disconnected");
Dominik Laskowski029cc122019-01-23 19:52:06 -0800486 nextState = State::Idle;
487 }
488
489 if (mState != nextState) {
490 if (mState == State::VSync) {
491 mVSyncSource->setVSyncEnabled(false);
492 } else if (nextState == State::VSync) {
493 mVSyncSource->setVSyncEnabled(true);
494 }
495
496 mState = nextState;
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700497 }
498
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800499 if (event) {
500 continue;
501 }
502
503 // Wait for event or client registration/request.
Dominik Laskowski029cc122019-01-23 19:52:06 -0800504 if (mState == State::Idle) {
505 mCondition.wait(lock);
506 } else {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800507 // Generate a fake VSYNC after a long timeout in case the driver stalls. When the
508 // display is off, keep feeding clients at 60 Hz.
Ady Abraham5facfb12020-04-22 15:18:31 -0700509 const std::chrono::nanoseconds timeout =
510 mState == State::SyntheticVSync ? 16ms : 1000ms;
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800511 if (mCondition.wait_for(lock, timeout) == std::cv_status::timeout) {
Ady Abraham5e7371c2020-03-24 14:47:24 -0700512 if (mState == State::VSync) {
513 ALOGW("Faking VSYNC due to driver stall for thread %s", mThreadName);
514 std::string debugInfo = "VsyncSource debug info:\n";
515 mVSyncSource->dump(debugInfo);
Ady Abraham75398722020-04-07 14:08:45 -0700516 // Log the debug info line-by-line to avoid logcat overflow
517 auto pos = debugInfo.find('\n');
518 while (pos != std::string::npos) {
519 ALOGW("%s", debugInfo.substr(0, pos).c_str());
520 debugInfo = debugInfo.substr(pos + 1);
521 pos = debugInfo.find('\n');
522 }
Ady Abraham5e7371c2020-03-24 14:47:24 -0700523 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800524
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800525 LOG_FATAL_IF(!mVSyncState);
Ady Abraham5facfb12020-04-22 15:18:31 -0700526 const auto now = systemTime(SYSTEM_TIME_MONOTONIC);
Ady Abraham8cb21882020-08-26 18:22:05 -0700527 const auto deadlineTimestamp = now + timeout.count();
528 const auto expectedVSyncTime = deadlineTimestamp + timeout.count();
Ady Abraham5facfb12020-04-22 15:18:31 -0700529 mPendingEvents.push_back(makeVSync(mVSyncState->displayId, now,
Ady Abraham8cb21882020-08-26 18:22:05 -0700530 ++mVSyncState->count, expectedVSyncTime,
Rachel Lee0d943202022-02-01 23:29:41 -0800531 deadlineTimestamp));
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700532 }
533 }
Lloyd Pique46a46b32018-01-31 19:01:18 -0800534 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800535}
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700536
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800537bool EventThread::shouldConsumeEvent(const DisplayEventReceiver::Event& event,
538 const sp<EventThreadConnection>& connection) const {
Ady Abraham0bb6a472020-10-12 10:22:13 -0700539 const auto throttleVsync = [&] {
540 return mThrottleVsyncCallback &&
Rachel Leeb9c5a772022-02-04 21:17:37 -0800541 mThrottleVsyncCallback(event.vsync.vsyncData.preferredExpectedPresentationTime(),
542 connection->mOwnerUid);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700543 };
544
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800545 switch (event.header.type) {
546 case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
547 return true;
548
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100549 case DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE: {
Ady Abraham62f216c2020-10-13 19:07:23 -0700550 return connection->mEventRegistration.test(
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100551 ISurfaceComposer::EventRegistration::modeChanged);
Alec Mouri60aee1c2019-10-28 16:18:59 -0700552 }
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700553
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800554 case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
555 switch (connection->vsyncRequest) {
556 case VSyncRequest::None:
557 return false;
Tim Murrayb5daa912020-09-09 21:29:13 +0000558 case VSyncRequest::SingleSuppressCallback:
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800559 connection->vsyncRequest = VSyncRequest::None;
Tim Murrayb5daa912020-09-09 21:29:13 +0000560 return false;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700561 case VSyncRequest::Single: {
562 if (throttleVsync()) {
563 return false;
564 }
Tim Murrayb5daa912020-09-09 21:29:13 +0000565 connection->vsyncRequest = VSyncRequest::SingleSuppressCallback;
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800566 return true;
Ady Abraham0bb6a472020-10-12 10:22:13 -0700567 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800568 case VSyncRequest::Periodic:
Ady Abraham0bb6a472020-10-12 10:22:13 -0700569 if (throttleVsync()) {
570 return false;
571 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800572 return true;
573 default:
Ady Abraham0bb6a472020-10-12 10:22:13 -0700574 // We don't throttle vsync if the app set a vsync request rate
575 // since there is no easy way to do that and this is a very
576 // rare case
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800577 return event.vsync.count % vsyncPeriod(connection->vsyncRequest) == 0;
578 }
579
Ady Abraham62f216c2020-10-13 19:07:23 -0700580 case DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE:
581 [[fallthrough]];
582 case DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH:
583 return connection->mEventRegistration.test(
584 ISurfaceComposer::EventRegistration::frameRateOverride);
585
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800586 default:
587 return false;
588 }
589}
590
Rachel Lee8d0c6102021-11-03 22:00:25 +0000591int64_t EventThread::generateToken(nsecs_t timestamp, nsecs_t deadlineTimestamp,
Rachel Leeb9c5a772022-02-04 21:17:37 -0800592 nsecs_t expectedPresentationTime) const {
Rachel Lee3f028662021-11-04 19:32:24 +0000593 if (mTokenManager != nullptr) {
594 return mTokenManager->generateTokenForPredictions(
Rachel Leeb9c5a772022-02-04 21:17:37 -0800595 {timestamp, deadlineTimestamp, expectedPresentationTime});
Rachel Lee3f028662021-11-04 19:32:24 +0000596 }
597 return FrameTimelineInfo::INVALID_VSYNC_ID;
598}
599
Rachel Leeb9c5a772022-02-04 21:17:37 -0800600void EventThread::generateFrameTimeline(VsyncEventData& outVsyncEventData, nsecs_t frameInterval,
601 nsecs_t timestamp,
602 nsecs_t preferredExpectedPresentationTime,
603 nsecs_t preferredDeadlineTimestamp) const {
Rachel Lee3f028662021-11-04 19:32:24 +0000604 // Add 1 to ensure the preferredFrameTimelineIndex entry (when multiplier == 0) is included.
Rachel Leeef2e21f2022-02-01 14:51:34 -0800605 for (int64_t multiplier = -VsyncEventData::kFrameTimelinesLength + 1, currentIndex = 0;
Rachel Lee18c34372022-01-20 13:57:18 -0800606 currentIndex < VsyncEventData::kFrameTimelinesLength; multiplier++) {
Rachel Leeb9c5a772022-02-04 21:17:37 -0800607 nsecs_t deadlineTimestamp = preferredDeadlineTimestamp + multiplier * frameInterval;
Rachel Lee3f028662021-11-04 19:32:24 +0000608 // Valid possible frame timelines must have future values.
Rachel Leeb9c5a772022-02-04 21:17:37 -0800609 if (deadlineTimestamp > timestamp) {
Rachel Lee3f028662021-11-04 19:32:24 +0000610 if (multiplier == 0) {
Rachel Leeb9c5a772022-02-04 21:17:37 -0800611 outVsyncEventData.preferredFrameTimelineIndex = currentIndex;
Rachel Lee3f028662021-11-04 19:32:24 +0000612 }
Rachel Leeb9c5a772022-02-04 21:17:37 -0800613 nsecs_t expectedPresentationTime =
614 preferredExpectedPresentationTime + multiplier * frameInterval;
615 outVsyncEventData.frameTimelines[currentIndex] =
616 {.vsyncId =
617 generateToken(timestamp, deadlineTimestamp, expectedPresentationTime),
618 .deadlineTimestamp = deadlineTimestamp,
619 .expectedPresentationTime = expectedPresentationTime};
Rachel Lee3f028662021-11-04 19:32:24 +0000620 currentIndex++;
621 }
622 }
623}
624
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800625void EventThread::dispatchEvent(const DisplayEventReceiver::Event& event,
626 const DisplayEventConsumers& consumers) {
627 for (const auto& consumer : consumers) {
Jorim Jaggic0086af2021-02-12 18:18:11 +0100628 DisplayEventReceiver::Event copy = event;
629 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_VSYNC) {
Rachel Leeb9c5a772022-02-04 21:17:37 -0800630 const int64_t frameInterval = mGetVsyncPeriodFunction(consumer->mOwnerUid);
631 copy.vsync.vsyncData.frameInterval = frameInterval;
632 generateFrameTimeline(copy.vsync.vsyncData, frameInterval, copy.header.timestamp,
633 event.vsync.vsyncData.preferredExpectedPresentationTime(),
634 event.vsync.vsyncData.preferredDeadlineTimestamp());
Jorim Jaggic0086af2021-02-12 18:18:11 +0100635 }
636 switch (consumer->postEvent(copy)) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800637 case NO_ERROR:
638 break;
639
640 case -EAGAIN:
641 // TODO: Try again if pipe is full.
642 ALOGW("Failed dispatching %s for %s", toString(event).c_str(),
643 toString(*consumer).c_str());
644 break;
645
646 default:
647 // Treat EPIPE and other errors as fatal.
648 removeDisplayEventConnectionLocked(consumer);
649 }
650 }
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700651}
652
Yiwei Zhang5434a782018-12-05 18:06:32 -0800653void EventThread::dump(std::string& result) const {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800654 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800655
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800656 StringAppendF(&result, "%s: state=%s VSyncState=", mThreadName, toCString(mState));
657 if (mVSyncState) {
Marin Shalamanova524a092020-07-27 21:39:55 +0200658 StringAppendF(&result, "{displayId=%s, count=%u%s}\n",
659 to_string(mVSyncState->displayId).c_str(), mVSyncState->count,
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800660 mVSyncState->synthetic ? ", synthetic" : "");
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800661 } else {
662 StringAppendF(&result, "none\n");
663 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800664
665 StringAppendF(&result, " pending events (count=%zu):\n", mPendingEvents.size());
666 for (const auto& event : mPendingEvents) {
667 StringAppendF(&result, " %s\n", toString(event).c_str());
Mathias Agopiane2c4f4e2012-04-10 18:25:31 -0700668 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800669
670 StringAppendF(&result, " connections (count=%zu):\n", mDisplayEventConnections.size());
671 for (const auto& ptr : mDisplayEventConnections) {
672 if (const auto connection = ptr.promote()) {
673 StringAppendF(&result, " %s\n", toString(*connection).c_str());
674 }
675 }
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800676}
677
Dominik Laskowski029cc122019-01-23 19:52:06 -0800678const char* EventThread::toCString(State state) {
679 switch (state) {
680 case State::Idle:
681 return "Idle";
682 case State::Quit:
683 return "Quit";
684 case State::SyntheticVSync:
685 return "SyntheticVSync";
686 case State::VSync:
687 return "VSync";
688 }
689}
690
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800691} // namespace impl
Lloyd Pique46a46b32018-01-31 19:01:18 -0800692} // namespace android
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800693
694// TODO(b/129481165): remove the #pragma below and fix conversion issues
695#pragma clang diagnostic pop // ignored "-Wconversion"