blob: a902a8ebde8f74377d0c712ed0d1fb3dc512ab48 [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>
Ady Abraham011f8ba2022-11-22 15:09:07 -080031#include <utility>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080032
Yiwei Zhang5434a782018-12-05 18:06:32 -080033#include <android-base/stringprintf.h>
34
Ady Abraham0bb6a472020-10-12 10:22:13 -070035#include <binder/IPCThreadState.h>
36
Mathias Agopiana4cb35a2012-08-20 20:07:34 -070037#include <cutils/compiler.h>
Lloyd Pique46a46b32018-01-31 19:01:18 -080038#include <cutils/sched_policy.h>
Mathias Agopiana4cb35a2012-08-20 20:07:34 -070039
Mathias Agopiand0566bc2011-11-17 17:49:17 -080040#include <gui/DisplayEventReceiver.h>
41
42#include <utils/Errors.h>
Mathias Agopian841cde52012-03-01 15:44:37 -080043#include <utils/Trace.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080044
Marin Shalamanov23c44202020-12-22 19:09:20 +010045#include "DisplayHardware/DisplayMode.h"
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -070046#include "FrameTimeline.h"
Ady Abraham011f8ba2022-11-22 15:09:07 -080047#include "VSyncDispatch.h"
48#include "VSyncTracker.h"
Marin Shalamanov23c44202020-12-22 19:09:20 +010049
50#include "EventThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080051
Ady Abraham62f216c2020-10-13 19:07:23 -070052#undef LOG_TAG
53#define LOG_TAG "EventThread"
54
Lloyd Pique46a46b32018-01-31 19:01:18 -080055using namespace std::chrono_literals;
Mathias Agopiand0566bc2011-11-17 17:49:17 -080056
Lloyd Pique46a46b32018-01-31 19:01:18 -080057namespace android {
58
Dominik Laskowskid9e4de62019-01-21 14:23:01 -080059using base::StringAppendF;
60using base::StringPrintf;
61
62namespace {
63
64auto vsyncPeriod(VSyncRequest request) {
65 return static_cast<std::underlying_type_t<VSyncRequest>>(request);
66}
67
68std::string toString(VSyncRequest request) {
69 switch (request) {
70 case VSyncRequest::None:
71 return "VSyncRequest::None";
72 case VSyncRequest::Single:
73 return "VSyncRequest::Single";
Tim Murrayb5daa912020-09-09 21:29:13 +000074 case VSyncRequest::SingleSuppressCallback:
75 return "VSyncRequest::SingleSuppressCallback";
Dominik Laskowskid9e4de62019-01-21 14:23:01 -080076 default:
77 return StringPrintf("VSyncRequest::Periodic{period=%d}", vsyncPeriod(request));
78 }
79}
80
81std::string toString(const EventThreadConnection& connection) {
82 return StringPrintf("Connection{%p, %s}", &connection,
83 toString(connection.vsyncRequest).c_str());
84}
85
86std::string toString(const DisplayEventReceiver::Event& event) {
87 switch (event.header.type) {
88 case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
Marin Shalamanova524a092020-07-27 21:39:55 +020089 return StringPrintf("Hotplug{displayId=%s, %s}",
90 to_string(event.header.displayId).c_str(),
Dominik Laskowskid9e4de62019-01-21 14:23:01 -080091 event.hotplug.connected ? "connected" : "disconnected");
92 case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
Rachel Leeb9c5a772022-02-04 21:17:37 -080093 return StringPrintf("VSync{displayId=%s, count=%u, expectedPresentationTime=%" PRId64
94 "}",
Marin Shalamanova524a092020-07-27 21:39:55 +020095 to_string(event.header.displayId).c_str(), event.vsync.count,
Rachel Leeb9c5a772022-02-04 21:17:37 -080096 event.vsync.vsyncData.preferredExpectedPresentationTime());
Marin Shalamanova7fe3042021-01-29 21:02:08 +010097 case DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE:
98 return StringPrintf("ModeChanged{displayId=%s, modeId=%u}",
99 to_string(event.header.displayId).c_str(), event.modeChange.modeId);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800100 default:
101 return "Event{}";
102 }
103}
104
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800105DisplayEventReceiver::Event makeHotplug(PhysicalDisplayId displayId, nsecs_t timestamp,
106 bool connected) {
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800107 DisplayEventReceiver::Event event;
108 event.header = {DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG, displayId, timestamp};
109 event.hotplug.connected = connected;
110 return event;
111}
112
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800113DisplayEventReceiver::Event makeVSync(PhysicalDisplayId displayId, nsecs_t timestamp,
Rachel Leeb9c5a772022-02-04 21:17:37 -0800114 uint32_t count, nsecs_t expectedPresentationTime,
Rachel Lee0d943202022-02-01 23:29:41 -0800115 nsecs_t deadlineTimestamp) {
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800116 DisplayEventReceiver::Event event;
117 event.header = {DisplayEventReceiver::DISPLAY_EVENT_VSYNC, displayId, timestamp};
118 event.vsync.count = count;
Rachel Leeb9c5a772022-02-04 21:17:37 -0800119 event.vsync.vsyncData.preferredFrameTimelineIndex = 0;
120 // Temporarily store the current vsync information in frameTimelines[0], marked as
121 // platform-preferred. When the event is dispatched later, the frame interval at that time is
122 // used with this information to generate multiple frame timeline choices.
123 event.vsync.vsyncData.frameTimelines[0] = {.vsyncId = FrameTimelineInfo::INVALID_VSYNC_ID,
124 .deadlineTimestamp = deadlineTimestamp,
125 .expectedPresentationTime =
126 expectedPresentationTime};
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800127 return event;
128}
129
Ady Abraham67434eb2022-12-01 17:48:12 -0800130DisplayEventReceiver::Event makeModeChanged(const scheduler::FrameRateMode& mode) {
Ady Abraham447052e2019-02-13 16:07:27 -0800131 DisplayEventReceiver::Event event;
Ady Abraham67434eb2022-12-01 17:48:12 -0800132 event.header = {DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE,
133 mode.modePtr->getPhysicalDisplayId(), systemTime()};
134 event.modeChange.modeId = mode.modePtr->getId().value();
135 event.modeChange.vsyncPeriod = mode.fps.getPeriodNsecs();
Ady Abraham447052e2019-02-13 16:07:27 -0800136 return event;
137}
138
Ady Abraham62f216c2020-10-13 19:07:23 -0700139DisplayEventReceiver::Event makeFrameRateOverrideEvent(PhysicalDisplayId displayId,
140 FrameRateOverride frameRateOverride) {
141 return DisplayEventReceiver::Event{
142 .header =
143 DisplayEventReceiver::Event::Header{
144 .type = DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE,
145 .displayId = displayId,
146 .timestamp = systemTime(),
147 },
148 .frameRateOverride = frameRateOverride,
149 };
150}
151
152DisplayEventReceiver::Event makeFrameRateOverrideFlushEvent(PhysicalDisplayId displayId) {
153 return DisplayEventReceiver::Event{
154 .header = DisplayEventReceiver::Event::Header{
155 .type = DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH,
156 .displayId = displayId,
157 .timestamp = systemTime(),
158 }};
159}
160
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800161} // namespace
Lloyd Pique46a46b32018-01-31 19:01:18 -0800162
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700163EventThreadConnection::EventThreadConnection(EventThread* eventThread, uid_t callingUid,
164 ResyncCallback resyncCallback,
165 EventRegistrationFlags eventRegistration)
Dominik Laskowskif654d572018-12-20 11:03:06 -0800166 : resyncCallback(std::move(resyncCallback)),
Ady Abraham0bb6a472020-10-12 10:22:13 -0700167 mOwnerUid(callingUid),
Ady Abraham62f216c2020-10-13 19:07:23 -0700168 mEventRegistration(eventRegistration),
Dominik Laskowskif654d572018-12-20 11:03:06 -0800169 mEventThread(eventThread),
170 mChannel(gui::BitTube::DefaultSize) {}
Ana Krulec85c39af2018-12-26 17:29:57 -0800171
172EventThreadConnection::~EventThreadConnection() {
173 // do nothing here -- clean-up will happen automatically
174 // when the main thread wakes up
175}
176
177void EventThreadConnection::onFirstRef() {
178 // NOTE: mEventThread doesn't hold a strong reference on us
Ady Abrahamd11bade2022-08-01 16:18:03 -0700179 mEventThread->registerDisplayEventConnection(sp<EventThreadConnection>::fromExisting(this));
Ana Krulec85c39af2018-12-26 17:29:57 -0800180}
181
Huihong Luo6fac5232021-11-22 16:05:23 -0800182binder::Status EventThreadConnection::stealReceiveChannel(gui::BitTube* outChannel) {
Ady Abraham899e8cd2022-06-06 15:16:06 -0700183 std::scoped_lock lock(mLock);
184 if (mChannel.initCheck() != NO_ERROR) {
185 return binder::Status::fromStatusT(NAME_NOT_FOUND);
186 }
187
Ana Krulec85c39af2018-12-26 17:29:57 -0800188 outChannel->setReceiveFd(mChannel.moveReceiveFd());
Alec Mouri967d5d72020-08-05 12:50:03 -0700189 outChannel->setSendFd(base::unique_fd(dup(mChannel.getSendFd())));
Huihong Luo6fac5232021-11-22 16:05:23 -0800190 return binder::Status::ok();
Ana Krulec85c39af2018-12-26 17:29:57 -0800191}
192
Huihong Luo6fac5232021-11-22 16:05:23 -0800193binder::Status EventThreadConnection::setVsyncRate(int rate) {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700194 mEventThread->setVsyncRate(static_cast<uint32_t>(rate),
195 sp<EventThreadConnection>::fromExisting(this));
Huihong Luo6fac5232021-11-22 16:05:23 -0800196 return binder::Status::ok();
Ana Krulec85c39af2018-12-26 17:29:57 -0800197}
198
Huihong Luo6fac5232021-11-22 16:05:23 -0800199binder::Status EventThreadConnection::requestNextVsync() {
Rachel Leeef2e21f2022-02-01 14:51:34 -0800200 ATRACE_CALL();
Ady Abrahamd11bade2022-08-01 16:18:03 -0700201 mEventThread->requestNextVsync(sp<EventThreadConnection>::fromExisting(this));
Huihong Luo6fac5232021-11-22 16:05:23 -0800202 return binder::Status::ok();
Ana Krulec85c39af2018-12-26 17:29:57 -0800203}
204
Rachel Leeb9c5a772022-02-04 21:17:37 -0800205binder::Status EventThreadConnection::getLatestVsyncEventData(
206 ParcelableVsyncEventData* outVsyncEventData) {
Rachel Leeef2e21f2022-02-01 14:51:34 -0800207 ATRACE_CALL();
Ady Abrahamd11bade2022-08-01 16:18:03 -0700208 outVsyncEventData->vsync =
209 mEventThread->getLatestVsyncEventData(sp<EventThreadConnection>::fromExisting(this));
Rachel Leeef2e21f2022-02-01 14:51:34 -0800210 return binder::Status::ok();
211}
212
Ana Krulec85c39af2018-12-26 17:29:57 -0800213status_t EventThreadConnection::postEvent(const DisplayEventReceiver::Event& event) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700214 constexpr auto toStatus = [](ssize_t size) {
215 return size < 0 ? status_t(size) : status_t(NO_ERROR);
216 };
217
218 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE ||
219 event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH) {
220 mPendingEvents.emplace_back(event);
221 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE) {
222 return status_t(NO_ERROR);
223 }
224
225 auto size = DisplayEventReceiver::sendEvents(&mChannel, mPendingEvents.data(),
226 mPendingEvents.size());
227 mPendingEvents.clear();
228 return toStatus(size);
229 }
230
231 auto size = DisplayEventReceiver::sendEvents(&mChannel, &event, 1);
232 return toStatus(size);
Ana Krulec85c39af2018-12-26 17:29:57 -0800233}
234
235// ---------------------------------------------------------------------------
236
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800237EventThread::~EventThread() = default;
238
239namespace impl {
240
Ady Abraham011f8ba2022-11-22 15:09:07 -0800241EventThread::EventThread(const char* name, scheduler::VsyncSchedule& vsyncSchedule,
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700242 android::frametimeline::TokenManager* tokenManager,
Jorim Jaggic0086af2021-02-12 18:18:11 +0100243 ThrottleVsyncCallback throttleVsyncCallback,
Ady Abraham011f8ba2022-11-22 15:09:07 -0800244 GetVsyncPeriodFunction getVsyncPeriodFunction,
245 std::chrono::nanoseconds workDuration,
246 std::chrono::nanoseconds readyDuration)
247 : mThreadName(name),
248 mVsyncTracer(base::StringPrintf("VSYNC-%s", name), 0),
249 mWorkDuration(base::StringPrintf("VsyncWorkDuration-%s", name), workDuration),
250 mReadyDuration(readyDuration),
251 mVsyncSchedule(vsyncSchedule),
252 mVsyncRegistration(
253 vsyncSchedule.getDispatch(),
254 [this](nsecs_t vsyncTime, nsecs_t wakeupTime, nsecs_t readyTime) {
255 onVsync(vsyncTime, wakeupTime, readyTime);
256 },
257 name),
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700258 mTokenManager(tokenManager),
Ady Abraham0bb6a472020-10-12 10:22:13 -0700259 mThrottleVsyncCallback(std::move(throttleVsyncCallback)),
Ady Abraham011f8ba2022-11-22 15:09:07 -0800260 mGetVsyncPeriodFunction(std::move(getVsyncPeriodFunction)) {
Jorim Jaggic0086af2021-02-12 18:18:11 +0100261 LOG_ALWAYS_FATAL_IF(getVsyncPeriodFunction == nullptr,
262 "getVsyncPeriodFunction must not be null");
263
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800264 mThread = std::thread([this]() NO_THREAD_SAFETY_ANALYSIS {
265 std::unique_lock<std::mutex> lock(mMutex);
266 threadMain(lock);
267 });
Lloyd Pique46a46b32018-01-31 19:01:18 -0800268
Dominik Laskowski6505f792019-09-18 11:10:05 -0700269 pthread_setname_np(mThread.native_handle(), mThreadName);
Lloyd Pique46a46b32018-01-31 19:01:18 -0800270
271 pid_t tid = pthread_gettid_np(mThread.native_handle());
272
273 // Use SCHED_FIFO to minimize jitter
274 constexpr int EVENT_THREAD_PRIORITY = 2;
275 struct sched_param param = {0};
276 param.sched_priority = EVENT_THREAD_PRIORITY;
277 if (pthread_setschedparam(mThread.native_handle(), SCHED_FIFO, &param) != 0) {
278 ALOGE("Couldn't set SCHED_FIFO for EventThread");
279 }
280
281 set_sched_policy(tid, SP_FOREGROUND);
282}
283
284EventThread::~EventThread() {
285 {
286 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski029cc122019-01-23 19:52:06 -0800287 mState = State::Quit;
Lloyd Pique46a46b32018-01-31 19:01:18 -0800288 mCondition.notify_all();
289 }
290 mThread.join();
Ruchi Kandoief472ec2014-04-02 12:50:06 -0700291}
292
Ady Abraham9c53ee72020-07-22 21:16:18 -0700293void EventThread::setDuration(std::chrono::nanoseconds workDuration,
294 std::chrono::nanoseconds readyDuration) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800295 std::lock_guard<std::mutex> lock(mMutex);
Ady Abraham011f8ba2022-11-22 15:09:07 -0800296 mWorkDuration = workDuration;
297 mReadyDuration = readyDuration;
298
299 mVsyncRegistration.update({.workDuration = mWorkDuration.get().count(),
300 .readyDuration = mReadyDuration.count(),
301 .earliestVsync = mLastVsyncCallbackTime.ns()});
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700302}
303
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700304sp<EventThreadConnection> EventThread::createEventConnection(
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700305 ResyncCallback resyncCallback, EventRegistrationFlags eventRegistration) const {
Ady Abrahamd11bade2022-08-01 16:18:03 -0700306 return sp<EventThreadConnection>::make(const_cast<EventThread*>(this),
307 IPCThreadState::self()->getCallingUid(),
308 std::move(resyncCallback), eventRegistration);
Mathias Agopian8aedd472012-01-24 16:39:14 -0800309}
310
Ana Krulec85c39af2018-12-26 17:29:57 -0800311status_t EventThread::registerDisplayEventConnection(const sp<EventThreadConnection>& connection) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800312 std::lock_guard<std::mutex> lock(mMutex);
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700313
314 // this should never happen
315 auto it = std::find(mDisplayEventConnections.cbegin(),
316 mDisplayEventConnections.cend(), connection);
317 if (it != mDisplayEventConnections.cend()) {
318 ALOGW("DisplayEventConnection %p already exists", connection.get());
319 mCondition.notify_all();
320 return ALREADY_EXISTS;
321 }
322
323 mDisplayEventConnections.push_back(connection);
Lloyd Pique46a46b32018-01-31 19:01:18 -0800324 mCondition.notify_all();
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800325 return NO_ERROR;
326}
327
Ana Krulec85c39af2018-12-26 17:29:57 -0800328void EventThread::removeDisplayEventConnectionLocked(const wp<EventThreadConnection>& connection) {
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700329 auto it = std::find(mDisplayEventConnections.cbegin(),
330 mDisplayEventConnections.cend(), connection);
331 if (it != mDisplayEventConnections.cend()) {
332 mDisplayEventConnections.erase(it);
333 }
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800334}
335
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800336void EventThread::setVsyncRate(uint32_t rate, const sp<EventThreadConnection>& connection) {
337 if (static_cast<std::underlying_type_t<VSyncRequest>>(rate) < 0) {
338 return;
339 }
340
341 std::lock_guard<std::mutex> lock(mMutex);
342
343 const auto request = rate == 0 ? VSyncRequest::None : static_cast<VSyncRequest>(rate);
344 if (connection->vsyncRequest != request) {
345 connection->vsyncRequest = request;
346 mCondition.notify_all();
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800347 }
348}
349
Ady Abraham8532d012019-05-08 14:50:56 -0700350void EventThread::requestNextVsync(const sp<EventThreadConnection>& connection) {
Dominik Laskowskif654d572018-12-20 11:03:06 -0800351 if (connection->resyncCallback) {
352 connection->resyncCallback();
Lloyd Pique24b0a482018-03-09 18:52:26 -0800353 }
Tim Murray4a4e4a22016-04-19 16:29:23 +0000354
Ana Krulec7d1d6832018-12-27 11:10:09 -0800355 std::lock_guard<std::mutex> lock(mMutex);
356
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800357 if (connection->vsyncRequest == VSyncRequest::None) {
358 connection->vsyncRequest = VSyncRequest::Single;
Lloyd Pique46a46b32018-01-31 19:01:18 -0800359 mCondition.notify_all();
Tim Murrayb5daa912020-09-09 21:29:13 +0000360 } else if (connection->vsyncRequest == VSyncRequest::SingleSuppressCallback) {
361 connection->vsyncRequest = VSyncRequest::Single;
Mathias Agopian478ae5e2011-12-06 17:22:19 -0800362 }
Mathias Agopian23748662011-12-05 14:33:34 -0800363}
364
Rachel Leeef2e21f2022-02-01 14:51:34 -0800365VsyncEventData EventThread::getLatestVsyncEventData(
366 const sp<EventThreadConnection>& connection) const {
Rachel Leeb5223cf2022-03-14 14:39:27 -0700367 // Resync so that the vsync is accurate with hardware. getLatestVsyncEventData is an alternate
368 // way to get vsync data (instead of posting callbacks to Choreographer).
369 if (connection->resyncCallback) {
370 connection->resyncCallback();
371 }
372
Rachel Leeef2e21f2022-02-01 14:51:34 -0800373 VsyncEventData vsyncEventData;
Rachel Leeb9c5a772022-02-04 21:17:37 -0800374 nsecs_t frameInterval = mGetVsyncPeriodFunction(connection->mOwnerUid);
Rachel Leeef2e21f2022-02-01 14:51:34 -0800375 vsyncEventData.frameInterval = frameInterval;
Ady Abraham011f8ba2022-11-22 15:09:07 -0800376 const auto [presentTime, deadline] = [&]() -> std::pair<nsecs_t, nsecs_t> {
Rachel Leeb9c5a772022-02-04 21:17:37 -0800377 std::lock_guard<std::mutex> lock(mMutex);
Ady Abraham011f8ba2022-11-22 15:09:07 -0800378 const auto vsyncTime = mVsyncSchedule.getTracker().nextAnticipatedVSyncTimeFrom(
379 systemTime() + mWorkDuration.get().count() + mReadyDuration.count());
380 return {vsyncTime, vsyncTime - mReadyDuration.count()};
381 }();
Rachel Leeb9c5a772022-02-04 21:17:37 -0800382 generateFrameTimeline(vsyncEventData, frameInterval, systemTime(SYSTEM_TIME_MONOTONIC),
Ady Abraham011f8ba2022-11-22 15:09:07 -0800383 presentTime, deadline);
Rachel Leeef2e21f2022-02-01 14:51:34 -0800384 return vsyncEventData;
385}
386
Mathias Agopian22ffb112012-04-10 21:04:02 -0700387void EventThread::onScreenReleased() {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800388 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800389 if (!mVSyncState || mVSyncState->synthetic) {
390 return;
Mathias Agopian22ffb112012-04-10 21:04:02 -0700391 }
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800392
393 mVSyncState->synthetic = true;
394 mCondition.notify_all();
Mathias Agopian22ffb112012-04-10 21:04:02 -0700395}
396
397void EventThread::onScreenAcquired() {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800398 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800399 if (!mVSyncState || !mVSyncState->synthetic) {
400 return;
Mathias Agopian7d886472012-06-14 23:39:35 -0700401 }
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800402
403 mVSyncState->synthetic = false;
404 mCondition.notify_all();
Mathias Agopian22ffb112012-04-10 21:04:02 -0700405}
406
Ady Abraham011f8ba2022-11-22 15:09:07 -0800407void EventThread::onVsync(nsecs_t vsyncTime, nsecs_t wakeupTime, nsecs_t readyTime) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800408 std::lock_guard<std::mutex> lock(mMutex);
Ady Abraham011f8ba2022-11-22 15:09:07 -0800409 mLastVsyncCallbackTime = TimePoint::fromNs(vsyncTime);
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800410
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800411 LOG_FATAL_IF(!mVSyncState);
Ady Abraham011f8ba2022-11-22 15:09:07 -0800412 mVsyncTracer = (mVsyncTracer + 1) % 2;
413 mPendingEvents.push_back(makeVSync(mVSyncState->displayId, wakeupTime, ++mVSyncState->count,
414 vsyncTime, readyTime));
Lloyd Pique46a46b32018-01-31 19:01:18 -0800415 mCondition.notify_all();
Mathias Agopian3eb38cb2012-04-03 22:09:52 -0700416}
417
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800418void EventThread::onHotplugReceived(PhysicalDisplayId displayId, bool connected) {
Lloyd Pique46a46b32018-01-31 19:01:18 -0800419 std::lock_guard<std::mutex> lock(mMutex);
Dominik Laskowski00a6fa22018-06-06 16:42:02 -0700420
Dominik Laskowski23b867a2019-01-22 12:44:53 -0800421 mPendingEvents.push_back(makeHotplug(displayId, systemTime(), connected));
Dominik Laskowski00a6fa22018-06-06 16:42:02 -0700422 mCondition.notify_all();
Mathias Agopian148994e2012-09-19 17:31:36 -0700423}
424
Ady Abraham67434eb2022-12-01 17:48:12 -0800425void EventThread::onModeChanged(const scheduler::FrameRateMode& mode) {
Ady Abraham447052e2019-02-13 16:07:27 -0800426 std::lock_guard<std::mutex> lock(mMutex);
427
Ady Abraham690f4612021-07-01 23:24:03 -0700428 mPendingEvents.push_back(makeModeChanged(mode));
Ady Abraham447052e2019-02-13 16:07:27 -0800429 mCondition.notify_all();
430}
431
Ady Abraham62f216c2020-10-13 19:07:23 -0700432void EventThread::onFrameRateOverridesChanged(PhysicalDisplayId displayId,
433 std::vector<FrameRateOverride> overrides) {
434 std::lock_guard<std::mutex> lock(mMutex);
435
436 for (auto frameRateOverride : overrides) {
437 mPendingEvents.push_back(makeFrameRateOverrideEvent(displayId, frameRateOverride));
438 }
439 mPendingEvents.push_back(makeFrameRateOverrideFlushEvent(displayId));
440
441 mCondition.notify_all();
442}
443
Alec Mouri717bcb62020-02-10 17:07:19 -0800444size_t EventThread::getEventThreadConnectionCount() {
445 std::lock_guard<std::mutex> lock(mMutex);
446 return mDisplayEventConnections.size();
447}
448
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800449void EventThread::threadMain(std::unique_lock<std::mutex>& lock) {
450 DisplayEventConsumers consumers;
451
Dominik Laskowski029cc122019-01-23 19:52:06 -0800452 while (mState != State::Quit) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800453 std::optional<DisplayEventReceiver::Event> event;
Mathias Agopian3eb38cb2012-04-03 22:09:52 -0700454
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800455 // Determine next event to dispatch.
456 if (!mPendingEvents.empty()) {
457 event = mPendingEvents.front();
458 mPendingEvents.pop_front();
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800459
Huihong Luoab8ffef2022-08-18 13:02:26 -0700460 if (event->header.type == DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG) {
461 if (event->hotplug.connected && !mVSyncState) {
462 mVSyncState.emplace(event->header.displayId);
463 } else if (!event->hotplug.connected && mVSyncState &&
464 mVSyncState->displayId == event->header.displayId) {
465 mVSyncState.reset();
466 }
Dominik Laskowski029cc122019-01-23 19:52:06 -0800467 }
Mathias Agopianff28e202012-09-20 23:24:19 -0700468 }
469
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800470 bool vsyncRequested = false;
Mathias Agopian148994e2012-09-19 17:31:36 -0700471
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800472 // Find connections that should consume this event.
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700473 auto it = mDisplayEventConnections.begin();
474 while (it != mDisplayEventConnections.end()) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800475 if (const auto connection = it->promote()) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800476 if (event && shouldConsumeEvent(*event, connection)) {
477 consumers.push_back(connection);
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700478 }
Mathias Agopianb4d18ed2012-09-20 23:14:05 -0700479
Ady Abraham011f8ba2022-11-22 15:09:07 -0800480 vsyncRequested |= connection->vsyncRequest != VSyncRequest::None;
481
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700482 ++it;
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700483 } else {
Chia-I Wu98cd38f2018-09-14 11:53:25 -0700484 it = mDisplayEventConnections.erase(it);
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700485 }
486 }
487
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800488 if (!consumers.empty()) {
489 dispatchEvent(*event, consumers);
490 consumers.clear();
491 }
492
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800493 if (mVSyncState && vsyncRequested) {
Ady Abraham011f8ba2022-11-22 15:09:07 -0800494 mState = mVSyncState->synthetic ? State::SyntheticVSync : State::VSync;
Dominik Laskowski029cc122019-01-23 19:52:06 -0800495 } else {
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800496 ALOGW_IF(!mVSyncState, "Ignoring VSYNC request while display is disconnected");
Ady Abraham011f8ba2022-11-22 15:09:07 -0800497 mState = State::Idle;
Dominik Laskowski029cc122019-01-23 19:52:06 -0800498 }
499
Ady Abraham011f8ba2022-11-22 15:09:07 -0800500 if (mState == State::VSync) {
501 const auto scheduleResult =
502 mVsyncRegistration.schedule({.workDuration = mWorkDuration.get().count(),
503 .readyDuration = mReadyDuration.count(),
504 .earliestVsync = mLastVsyncCallbackTime.ns()});
505 LOG_ALWAYS_FATAL_IF(!scheduleResult, "Error scheduling callback");
506 } else {
507 mVsyncRegistration.cancel();
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700508 }
509
Ady Abraham011f8ba2022-11-22 15:09:07 -0800510 if (!mPendingEvents.empty()) {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800511 continue;
512 }
513
514 // Wait for event or client registration/request.
Dominik Laskowski029cc122019-01-23 19:52:06 -0800515 if (mState == State::Idle) {
516 mCondition.wait(lock);
517 } else {
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800518 // Generate a fake VSYNC after a long timeout in case the driver stalls. When the
519 // display is off, keep feeding clients at 60 Hz.
Ady Abraham5facfb12020-04-22 15:18:31 -0700520 const std::chrono::nanoseconds timeout =
521 mState == State::SyntheticVSync ? 16ms : 1000ms;
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800522 if (mCondition.wait_for(lock, timeout) == std::cv_status::timeout) {
Ady Abraham5e7371c2020-03-24 14:47:24 -0700523 if (mState == State::VSync) {
524 ALOGW("Faking VSYNC due to driver stall for thread %s", mThreadName);
Ady Abraham5e7371c2020-03-24 14:47:24 -0700525 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800526
Dominik Laskowski1eba0202019-01-24 09:14:40 -0800527 LOG_FATAL_IF(!mVSyncState);
Ady Abraham5facfb12020-04-22 15:18:31 -0700528 const auto now = systemTime(SYSTEM_TIME_MONOTONIC);
Ady Abraham8cb21882020-08-26 18:22:05 -0700529 const auto deadlineTimestamp = now + timeout.count();
530 const auto expectedVSyncTime = deadlineTimestamp + timeout.count();
Ady Abraham5facfb12020-04-22 15:18:31 -0700531 mPendingEvents.push_back(makeVSync(mVSyncState->displayId, now,
Ady Abraham8cb21882020-08-26 18:22:05 -0700532 ++mVSyncState->count, expectedVSyncTime,
Rachel Lee0d943202022-02-01 23:29:41 -0800533 deadlineTimestamp));
Mathias Agopianf6bbd442012-08-21 15:47:28 -0700534 }
535 }
Lloyd Pique46a46b32018-01-31 19:01:18 -0800536 }
Ady Abraham011f8ba2022-11-22 15:09:07 -0800537 // cancel any pending vsync event before exiting
538 mVsyncRegistration.cancel();
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
Ady Abraham011f8ba2022-11-22 15:09:07 -0800669 const auto relativeLastCallTime =
670 ticks<std::milli, float>(mLastVsyncCallbackTime - TimePoint::now());
671 StringAppendF(&result, "mWorkDuration=%.2f mReadyDuration=%.2f last vsync time ",
672 mWorkDuration.get().count() / 1e6f, mReadyDuration.count() / 1e6f);
673 StringAppendF(&result, "%.2fms relative to now\n", relativeLastCallTime);
674
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800675 StringAppendF(&result, " pending events (count=%zu):\n", mPendingEvents.size());
676 for (const auto& event : mPendingEvents) {
677 StringAppendF(&result, " %s\n", toString(event).c_str());
Mathias Agopiane2c4f4e2012-04-10 18:25:31 -0700678 }
Dominik Laskowskid9e4de62019-01-21 14:23:01 -0800679
680 StringAppendF(&result, " connections (count=%zu):\n", mDisplayEventConnections.size());
681 for (const auto& ptr : mDisplayEventConnections) {
682 if (const auto connection = ptr.promote()) {
683 StringAppendF(&result, " %s\n", toString(*connection).c_str());
684 }
685 }
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400686 result += '\n';
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800687}
688
Dominik Laskowski029cc122019-01-23 19:52:06 -0800689const char* EventThread::toCString(State state) {
690 switch (state) {
691 case State::Idle:
692 return "Idle";
693 case State::Quit:
694 return "Quit";
695 case State::SyntheticVSync:
696 return "SyntheticVSync";
697 case State::VSync:
698 return "VSync";
699 }
700}
701
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800702} // namespace impl
Lloyd Pique46a46b32018-01-31 19:01:18 -0800703} // namespace android
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800704
705// TODO(b/129481165): remove the #pragma below and fix conversion issues
706#pragma clang diagnostic pop // ignored "-Wconversion"