• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 
17 // TODO(b/129481165): remove the #pragma below and fix conversion issues
18 #pragma clang diagnostic push
19 #pragma clang diagnostic ignored "-Wconversion"
20 
21 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
22 
23 #include <pthread.h>
24 #include <sched.h>
25 #include <sys/types.h>
26 
27 #include <chrono>
28 #include <cstdint>
29 #include <optional>
30 #include <type_traits>
31 #include <utility>
32 
33 #include <android-base/stringprintf.h>
34 
35 #include <binder/IPCThreadState.h>
36 
37 #include <cutils/compiler.h>
38 #include <cutils/sched_policy.h>
39 
40 #include <gui/DisplayEventReceiver.h>
41 
42 #include <utils/Errors.h>
43 #include <utils/Trace.h>
44 
45 #include <scheduler/VsyncConfig.h>
46 #include "DisplayHardware/DisplayMode.h"
47 #include "FrameTimeline.h"
48 #include "VSyncDispatch.h"
49 #include "VSyncTracker.h"
50 
51 #include "EventThread.h"
52 
53 #undef LOG_TAG
54 #define LOG_TAG "EventThread"
55 
56 using namespace std::chrono_literals;
57 
58 namespace android {
59 
60 using base::StringAppendF;
61 using base::StringPrintf;
62 
63 namespace {
64 
vsyncPeriod(VSyncRequest request)65 auto vsyncPeriod(VSyncRequest request) {
66     return static_cast<std::underlying_type_t<VSyncRequest>>(request);
67 }
68 
toString(VSyncRequest request)69 std::string toString(VSyncRequest request) {
70     switch (request) {
71         case VSyncRequest::None:
72             return "VSyncRequest::None";
73         case VSyncRequest::Single:
74             return "VSyncRequest::Single";
75         case VSyncRequest::SingleSuppressCallback:
76             return "VSyncRequest::SingleSuppressCallback";
77         default:
78             return StringPrintf("VSyncRequest::Periodic{period=%d}", vsyncPeriod(request));
79     }
80 }
81 
toString(const EventThreadConnection & connection)82 std::string toString(const EventThreadConnection& connection) {
83     return StringPrintf("Connection{%p, %s}", &connection,
84                         toString(connection.vsyncRequest).c_str());
85 }
86 
toString(const DisplayEventReceiver::Event & event)87 std::string toString(const DisplayEventReceiver::Event& event) {
88     switch (event.header.type) {
89         case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
90             return StringPrintf("Hotplug{displayId=%s, %s}",
91                                 to_string(event.header.displayId).c_str(),
92                                 event.hotplug.connected ? "connected" : "disconnected");
93         case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
94             return StringPrintf("VSync{displayId=%s, count=%u, expectedPresentationTime=%" PRId64
95                                 "}",
96                                 to_string(event.header.displayId).c_str(), event.vsync.count,
97                                 event.vsync.vsyncData.preferredExpectedPresentationTime());
98         case DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE:
99             return StringPrintf("ModeChanged{displayId=%s, modeId=%u}",
100                                 to_string(event.header.displayId).c_str(), event.modeChange.modeId);
101         default:
102             return "Event{}";
103     }
104 }
105 
makeHotplug(PhysicalDisplayId displayId,nsecs_t timestamp,bool connected)106 DisplayEventReceiver::Event makeHotplug(PhysicalDisplayId displayId, nsecs_t timestamp,
107                                         bool connected) {
108     DisplayEventReceiver::Event event;
109     event.header = {DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG, displayId, timestamp};
110     event.hotplug.connected = connected;
111     return event;
112 }
113 
makeVSync(PhysicalDisplayId displayId,nsecs_t timestamp,uint32_t count,nsecs_t expectedPresentationTime,nsecs_t deadlineTimestamp)114 DisplayEventReceiver::Event makeVSync(PhysicalDisplayId displayId, nsecs_t timestamp,
115                                       uint32_t count, nsecs_t expectedPresentationTime,
116                                       nsecs_t deadlineTimestamp) {
117     DisplayEventReceiver::Event event;
118     event.header = {DisplayEventReceiver::DISPLAY_EVENT_VSYNC, displayId, timestamp};
119     event.vsync.count = count;
120     event.vsync.vsyncData.preferredFrameTimelineIndex = 0;
121     // Temporarily store the current vsync information in frameTimelines[0], marked as
122     // platform-preferred. When the event is dispatched later, the frame interval at that time is
123     // used with this information to generate multiple frame timeline choices.
124     event.vsync.vsyncData.frameTimelines[0] = {.vsyncId = FrameTimelineInfo::INVALID_VSYNC_ID,
125                                                .deadlineTimestamp = deadlineTimestamp,
126                                                .expectedPresentationTime =
127                                                        expectedPresentationTime};
128     return event;
129 }
130 
makeModeChanged(const scheduler::FrameRateMode & mode)131 DisplayEventReceiver::Event makeModeChanged(const scheduler::FrameRateMode& mode) {
132     DisplayEventReceiver::Event event;
133     event.header = {DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE,
134                     mode.modePtr->getPhysicalDisplayId(), systemTime()};
135     event.modeChange.modeId = mode.modePtr->getId().value();
136     event.modeChange.vsyncPeriod = mode.fps.getPeriodNsecs();
137     return event;
138 }
139 
makeFrameRateOverrideEvent(PhysicalDisplayId displayId,FrameRateOverride frameRateOverride)140 DisplayEventReceiver::Event makeFrameRateOverrideEvent(PhysicalDisplayId displayId,
141                                                        FrameRateOverride frameRateOverride) {
142     return DisplayEventReceiver::Event{
143             .header =
144                     DisplayEventReceiver::Event::Header{
145                             .type = DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE,
146                             .displayId = displayId,
147                             .timestamp = systemTime(),
148                     },
149             .frameRateOverride = frameRateOverride,
150     };
151 }
152 
makeFrameRateOverrideFlushEvent(PhysicalDisplayId displayId)153 DisplayEventReceiver::Event makeFrameRateOverrideFlushEvent(PhysicalDisplayId displayId) {
154     return DisplayEventReceiver::Event{
155             .header = DisplayEventReceiver::Event::Header{
156                     .type = DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH,
157                     .displayId = displayId,
158                     .timestamp = systemTime(),
159             }};
160 }
161 
162 } // namespace
163 
EventThreadConnection(EventThread * eventThread,uid_t callingUid,ResyncCallback resyncCallback,EventRegistrationFlags eventRegistration)164 EventThreadConnection::EventThreadConnection(EventThread* eventThread, uid_t callingUid,
165                                              ResyncCallback resyncCallback,
166                                              EventRegistrationFlags eventRegistration)
167       : resyncCallback(std::move(resyncCallback)),
168         mOwnerUid(callingUid),
169         mEventRegistration(eventRegistration),
170         mEventThread(eventThread),
171         mChannel(gui::BitTube::DefaultSize) {}
172 
~EventThreadConnection()173 EventThreadConnection::~EventThreadConnection() {
174     // do nothing here -- clean-up will happen automatically
175     // when the main thread wakes up
176 }
177 
onFirstRef()178 void EventThreadConnection::onFirstRef() {
179     // NOTE: mEventThread doesn't hold a strong reference on us
180     mEventThread->registerDisplayEventConnection(sp<EventThreadConnection>::fromExisting(this));
181 }
182 
stealReceiveChannel(gui::BitTube * outChannel)183 binder::Status EventThreadConnection::stealReceiveChannel(gui::BitTube* outChannel) {
184     std::scoped_lock lock(mLock);
185     if (mChannel.initCheck() != NO_ERROR) {
186         return binder::Status::fromStatusT(NAME_NOT_FOUND);
187     }
188 
189     outChannel->setReceiveFd(mChannel.moveReceiveFd());
190     outChannel->setSendFd(base::unique_fd(dup(mChannel.getSendFd())));
191     return binder::Status::ok();
192 }
193 
setVsyncRate(int rate)194 binder::Status EventThreadConnection::setVsyncRate(int rate) {
195     mEventThread->setVsyncRate(static_cast<uint32_t>(rate),
196                                sp<EventThreadConnection>::fromExisting(this));
197     return binder::Status::ok();
198 }
199 
requestNextVsync()200 binder::Status EventThreadConnection::requestNextVsync() {
201     ATRACE_CALL();
202     mEventThread->requestNextVsync(sp<EventThreadConnection>::fromExisting(this));
203     return binder::Status::ok();
204 }
205 
getLatestVsyncEventData(ParcelableVsyncEventData * outVsyncEventData)206 binder::Status EventThreadConnection::getLatestVsyncEventData(
207         ParcelableVsyncEventData* outVsyncEventData) {
208     ATRACE_CALL();
209     outVsyncEventData->vsync =
210             mEventThread->getLatestVsyncEventData(sp<EventThreadConnection>::fromExisting(this));
211     return binder::Status::ok();
212 }
213 
postEvent(const DisplayEventReceiver::Event & event)214 status_t EventThreadConnection::postEvent(const DisplayEventReceiver::Event& event) {
215     constexpr auto toStatus = [](ssize_t size) {
216         return size < 0 ? status_t(size) : status_t(NO_ERROR);
217     };
218 
219     if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE ||
220         event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH) {
221         mPendingEvents.emplace_back(event);
222         if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE) {
223             return status_t(NO_ERROR);
224         }
225 
226         auto size = DisplayEventReceiver::sendEvents(&mChannel, mPendingEvents.data(),
227                                                      mPendingEvents.size());
228         mPendingEvents.clear();
229         return toStatus(size);
230     }
231 
232     auto size = DisplayEventReceiver::sendEvents(&mChannel, &event, 1);
233     return toStatus(size);
234 }
235 
236 // ---------------------------------------------------------------------------
237 
238 EventThread::~EventThread() = default;
239 
240 namespace impl {
241 
EventThread(const char * name,std::shared_ptr<scheduler::VsyncSchedule> vsyncSchedule,android::frametimeline::TokenManager * tokenManager,ThrottleVsyncCallback throttleVsyncCallback,GetVsyncPeriodFunction getVsyncPeriodFunction,std::chrono::nanoseconds workDuration,std::chrono::nanoseconds readyDuration)242 EventThread::EventThread(const char* name, std::shared_ptr<scheduler::VsyncSchedule> vsyncSchedule,
243                          android::frametimeline::TokenManager* tokenManager,
244                          ThrottleVsyncCallback throttleVsyncCallback,
245                          GetVsyncPeriodFunction getVsyncPeriodFunction,
246                          std::chrono::nanoseconds workDuration,
247                          std::chrono::nanoseconds readyDuration)
248       : mThreadName(name),
249         mVsyncTracer(base::StringPrintf("VSYNC-%s", name), 0),
250         mWorkDuration(base::StringPrintf("VsyncWorkDuration-%s", name), workDuration),
251         mReadyDuration(readyDuration),
252         mVsyncSchedule(std::move(vsyncSchedule)),
253         mVsyncRegistration(mVsyncSchedule->getDispatch(), createDispatchCallback(), name),
254         mTokenManager(tokenManager),
255         mThrottleVsyncCallback(std::move(throttleVsyncCallback)),
256         mGetVsyncPeriodFunction(std::move(getVsyncPeriodFunction)) {
257     LOG_ALWAYS_FATAL_IF(getVsyncPeriodFunction == nullptr,
258             "getVsyncPeriodFunction must not be null");
259 
260     mThread = std::thread([this]() NO_THREAD_SAFETY_ANALYSIS {
261         std::unique_lock<std::mutex> lock(mMutex);
262         threadMain(lock);
263     });
264 
265     pthread_setname_np(mThread.native_handle(), mThreadName);
266 
267     pid_t tid = pthread_gettid_np(mThread.native_handle());
268 
269     // Use SCHED_FIFO to minimize jitter
270     constexpr int EVENT_THREAD_PRIORITY = 2;
271     struct sched_param param = {0};
272     param.sched_priority = EVENT_THREAD_PRIORITY;
273     if (pthread_setschedparam(mThread.native_handle(), SCHED_FIFO, &param) != 0) {
274         ALOGE("Couldn't set SCHED_FIFO for EventThread");
275     }
276 
277     set_sched_policy(tid, SP_FOREGROUND);
278 }
279 
~EventThread()280 EventThread::~EventThread() {
281     {
282         std::lock_guard<std::mutex> lock(mMutex);
283         mState = State::Quit;
284         mCondition.notify_all();
285     }
286     mThread.join();
287 }
288 
setDuration(std::chrono::nanoseconds workDuration,std::chrono::nanoseconds readyDuration)289 void EventThread::setDuration(std::chrono::nanoseconds workDuration,
290                               std::chrono::nanoseconds readyDuration) {
291     std::lock_guard<std::mutex> lock(mMutex);
292     mWorkDuration = workDuration;
293     mReadyDuration = readyDuration;
294 
295     mVsyncRegistration.update({.workDuration = mWorkDuration.get().count(),
296                                .readyDuration = mReadyDuration.count(),
297                                .earliestVsync = mLastVsyncCallbackTime.ns()});
298 }
299 
createEventConnection(ResyncCallback resyncCallback,EventRegistrationFlags eventRegistration) const300 sp<EventThreadConnection> EventThread::createEventConnection(
301         ResyncCallback resyncCallback, EventRegistrationFlags eventRegistration) const {
302     return sp<EventThreadConnection>::make(const_cast<EventThread*>(this),
303                                            IPCThreadState::self()->getCallingUid(),
304                                            std::move(resyncCallback), eventRegistration);
305 }
306 
registerDisplayEventConnection(const sp<EventThreadConnection> & connection)307 status_t EventThread::registerDisplayEventConnection(const sp<EventThreadConnection>& connection) {
308     std::lock_guard<std::mutex> lock(mMutex);
309 
310     // this should never happen
311     auto it = std::find(mDisplayEventConnections.cbegin(),
312             mDisplayEventConnections.cend(), connection);
313     if (it != mDisplayEventConnections.cend()) {
314         ALOGW("DisplayEventConnection %p already exists", connection.get());
315         mCondition.notify_all();
316         return ALREADY_EXISTS;
317     }
318 
319     mDisplayEventConnections.push_back(connection);
320     mCondition.notify_all();
321     return NO_ERROR;
322 }
323 
removeDisplayEventConnectionLocked(const wp<EventThreadConnection> & connection)324 void EventThread::removeDisplayEventConnectionLocked(const wp<EventThreadConnection>& connection) {
325     auto it = std::find(mDisplayEventConnections.cbegin(),
326             mDisplayEventConnections.cend(), connection);
327     if (it != mDisplayEventConnections.cend()) {
328         mDisplayEventConnections.erase(it);
329     }
330 }
331 
setVsyncRate(uint32_t rate,const sp<EventThreadConnection> & connection)332 void EventThread::setVsyncRate(uint32_t rate, const sp<EventThreadConnection>& connection) {
333     if (static_cast<std::underlying_type_t<VSyncRequest>>(rate) < 0) {
334         return;
335     }
336 
337     std::lock_guard<std::mutex> lock(mMutex);
338 
339     const auto request = rate == 0 ? VSyncRequest::None : static_cast<VSyncRequest>(rate);
340     if (connection->vsyncRequest != request) {
341         connection->vsyncRequest = request;
342         mCondition.notify_all();
343     }
344 }
345 
requestNextVsync(const sp<EventThreadConnection> & connection)346 void EventThread::requestNextVsync(const sp<EventThreadConnection>& connection) {
347     if (connection->resyncCallback) {
348         connection->resyncCallback();
349     }
350 
351     std::lock_guard<std::mutex> lock(mMutex);
352 
353     if (connection->vsyncRequest == VSyncRequest::None) {
354         connection->vsyncRequest = VSyncRequest::Single;
355         mCondition.notify_all();
356     } else if (connection->vsyncRequest == VSyncRequest::SingleSuppressCallback) {
357         connection->vsyncRequest = VSyncRequest::Single;
358     }
359 }
360 
getLatestVsyncEventData(const sp<EventThreadConnection> & connection) const361 VsyncEventData EventThread::getLatestVsyncEventData(
362         const sp<EventThreadConnection>& connection) const {
363     // Resync so that the vsync is accurate with hardware. getLatestVsyncEventData is an alternate
364     // way to get vsync data (instead of posting callbacks to Choreographer).
365     if (connection->resyncCallback) {
366         connection->resyncCallback();
367     }
368 
369     VsyncEventData vsyncEventData;
370     nsecs_t frameInterval = mGetVsyncPeriodFunction(connection->mOwnerUid);
371     vsyncEventData.frameInterval = frameInterval;
372     const auto [presentTime, deadline] = [&]() -> std::pair<nsecs_t, nsecs_t> {
373         std::lock_guard<std::mutex> lock(mMutex);
374         const auto vsyncTime = mVsyncSchedule->getTracker().nextAnticipatedVSyncTimeFrom(
375                 systemTime() + mWorkDuration.get().count() + mReadyDuration.count());
376         return {vsyncTime, vsyncTime - mReadyDuration.count()};
377     }();
378     generateFrameTimeline(vsyncEventData, frameInterval, systemTime(SYSTEM_TIME_MONOTONIC),
379                           presentTime, deadline);
380     return vsyncEventData;
381 }
382 
enableSyntheticVsync(bool enable)383 void EventThread::enableSyntheticVsync(bool enable) {
384     std::lock_guard<std::mutex> lock(mMutex);
385     if (!mVSyncState || mVSyncState->synthetic == enable) {
386         return;
387     }
388 
389     mVSyncState->synthetic = enable;
390     mCondition.notify_all();
391 }
392 
onVsync(nsecs_t vsyncTime,nsecs_t wakeupTime,nsecs_t readyTime)393 void EventThread::onVsync(nsecs_t vsyncTime, nsecs_t wakeupTime, nsecs_t readyTime) {
394     std::lock_guard<std::mutex> lock(mMutex);
395     mLastVsyncCallbackTime = TimePoint::fromNs(vsyncTime);
396 
397     LOG_FATAL_IF(!mVSyncState);
398     mVsyncTracer = (mVsyncTracer + 1) % 2;
399     mPendingEvents.push_back(makeVSync(mVSyncState->displayId, wakeupTime, ++mVSyncState->count,
400                                        vsyncTime, readyTime));
401     mCondition.notify_all();
402 }
403 
onHotplugReceived(PhysicalDisplayId displayId,bool connected)404 void EventThread::onHotplugReceived(PhysicalDisplayId displayId, bool connected) {
405     std::lock_guard<std::mutex> lock(mMutex);
406 
407     mPendingEvents.push_back(makeHotplug(displayId, systemTime(), connected));
408     mCondition.notify_all();
409 }
410 
onModeChanged(const scheduler::FrameRateMode & mode)411 void EventThread::onModeChanged(const scheduler::FrameRateMode& mode) {
412     std::lock_guard<std::mutex> lock(mMutex);
413 
414     mPendingEvents.push_back(makeModeChanged(mode));
415     mCondition.notify_all();
416 }
417 
onFrameRateOverridesChanged(PhysicalDisplayId displayId,std::vector<FrameRateOverride> overrides)418 void EventThread::onFrameRateOverridesChanged(PhysicalDisplayId displayId,
419                                               std::vector<FrameRateOverride> overrides) {
420     std::lock_guard<std::mutex> lock(mMutex);
421 
422     for (auto frameRateOverride : overrides) {
423         mPendingEvents.push_back(makeFrameRateOverrideEvent(displayId, frameRateOverride));
424     }
425     mPendingEvents.push_back(makeFrameRateOverrideFlushEvent(displayId));
426 
427     mCondition.notify_all();
428 }
429 
getEventThreadConnectionCount()430 size_t EventThread::getEventThreadConnectionCount() {
431     std::lock_guard<std::mutex> lock(mMutex);
432     return mDisplayEventConnections.size();
433 }
434 
threadMain(std::unique_lock<std::mutex> & lock)435 void EventThread::threadMain(std::unique_lock<std::mutex>& lock) {
436     DisplayEventConsumers consumers;
437 
438     while (mState != State::Quit) {
439         std::optional<DisplayEventReceiver::Event> event;
440 
441         // Determine next event to dispatch.
442         if (!mPendingEvents.empty()) {
443             event = mPendingEvents.front();
444             mPendingEvents.pop_front();
445 
446             if (event->header.type == DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG) {
447                 if (event->hotplug.connected && !mVSyncState) {
448                     mVSyncState.emplace(event->header.displayId);
449                 } else if (!event->hotplug.connected && mVSyncState &&
450                            mVSyncState->displayId == event->header.displayId) {
451                     mVSyncState.reset();
452                 }
453             }
454         }
455 
456         bool vsyncRequested = false;
457 
458         // Find connections that should consume this event.
459         auto it = mDisplayEventConnections.begin();
460         while (it != mDisplayEventConnections.end()) {
461             if (const auto connection = it->promote()) {
462                 if (event && shouldConsumeEvent(*event, connection)) {
463                     consumers.push_back(connection);
464                 }
465 
466                 vsyncRequested |= connection->vsyncRequest != VSyncRequest::None;
467 
468                 ++it;
469             } else {
470                 it = mDisplayEventConnections.erase(it);
471             }
472         }
473 
474         if (!consumers.empty()) {
475             dispatchEvent(*event, consumers);
476             consumers.clear();
477         }
478 
479         if (mVSyncState && vsyncRequested) {
480             mState = mVSyncState->synthetic ? State::SyntheticVSync : State::VSync;
481         } else {
482             ALOGW_IF(!mVSyncState, "Ignoring VSYNC request while display is disconnected");
483             mState = State::Idle;
484         }
485 
486         if (mState == State::VSync) {
487             const auto scheduleResult =
488                     mVsyncRegistration.schedule({.workDuration = mWorkDuration.get().count(),
489                                                  .readyDuration = mReadyDuration.count(),
490                                                  .earliestVsync = mLastVsyncCallbackTime.ns()});
491             LOG_ALWAYS_FATAL_IF(!scheduleResult, "Error scheduling callback");
492         } else {
493             mVsyncRegistration.cancel();
494         }
495 
496         if (!mPendingEvents.empty()) {
497             continue;
498         }
499 
500         // Wait for event or client registration/request.
501         if (mState == State::Idle) {
502             mCondition.wait(lock);
503         } else {
504             // Generate a fake VSYNC after a long timeout in case the driver stalls. When the
505             // display is off, keep feeding clients at 60 Hz.
506             const std::chrono::nanoseconds timeout =
507                     mState == State::SyntheticVSync ? 16ms : 1000ms;
508             if (mCondition.wait_for(lock, timeout) == std::cv_status::timeout) {
509                 if (mState == State::VSync) {
510                     ALOGW("Faking VSYNC due to driver stall for thread %s", mThreadName);
511                 }
512 
513                 LOG_FATAL_IF(!mVSyncState);
514                 const auto now = systemTime(SYSTEM_TIME_MONOTONIC);
515                 const auto deadlineTimestamp = now + timeout.count();
516                 const auto expectedVSyncTime = deadlineTimestamp + timeout.count();
517                 mPendingEvents.push_back(makeVSync(mVSyncState->displayId, now,
518                                                    ++mVSyncState->count, expectedVSyncTime,
519                                                    deadlineTimestamp));
520             }
521         }
522     }
523     // cancel any pending vsync event before exiting
524     mVsyncRegistration.cancel();
525 }
526 
shouldConsumeEvent(const DisplayEventReceiver::Event & event,const sp<EventThreadConnection> & connection) const527 bool EventThread::shouldConsumeEvent(const DisplayEventReceiver::Event& event,
528                                      const sp<EventThreadConnection>& connection) const {
529     const auto throttleVsync = [&]() REQUIRES(mMutex) {
530         const auto& vsyncData = event.vsync.vsyncData;
531         if (connection->frameRate.isValid()) {
532             return !mVsyncSchedule->getTracker()
533                             .isVSyncInPhase(vsyncData.preferredExpectedPresentationTime(),
534                                             connection->frameRate);
535         }
536 
537         return mThrottleVsyncCallback &&
538                 mThrottleVsyncCallback(event.vsync.vsyncData.preferredExpectedPresentationTime(),
539                                        connection->mOwnerUid);
540     };
541 
542     switch (event.header.type) {
543         case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
544             return true;
545 
546         case DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE: {
547             return connection->mEventRegistration.test(
548                     gui::ISurfaceComposer::EventRegistration::modeChanged);
549         }
550 
551         case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
552             switch (connection->vsyncRequest) {
553                 case VSyncRequest::None:
554                     return false;
555                 case VSyncRequest::SingleSuppressCallback:
556                     connection->vsyncRequest = VSyncRequest::None;
557                     return false;
558                 case VSyncRequest::Single: {
559                     if (throttleVsync()) {
560                         return false;
561                     }
562                     connection->vsyncRequest = VSyncRequest::SingleSuppressCallback;
563                     return true;
564                 }
565                 case VSyncRequest::Periodic:
566                     if (throttleVsync()) {
567                         return false;
568                     }
569                     return true;
570                 default:
571                     // We don't throttle vsync if the app set a vsync request rate
572                     // since there is no easy way to do that and this is a very
573                     // rare case
574                     return event.vsync.count % vsyncPeriod(connection->vsyncRequest) == 0;
575             }
576 
577         case DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE:
578             [[fallthrough]];
579         case DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH:
580             return connection->mEventRegistration.test(
581                     gui::ISurfaceComposer::EventRegistration::frameRateOverride);
582 
583         default:
584             return false;
585     }
586 }
587 
generateToken(nsecs_t timestamp,nsecs_t deadlineTimestamp,nsecs_t expectedPresentationTime) const588 int64_t EventThread::generateToken(nsecs_t timestamp, nsecs_t deadlineTimestamp,
589                                    nsecs_t expectedPresentationTime) const {
590     if (mTokenManager != nullptr) {
591         return mTokenManager->generateTokenForPredictions(
592                 {timestamp, deadlineTimestamp, expectedPresentationTime});
593     }
594     return FrameTimelineInfo::INVALID_VSYNC_ID;
595 }
596 
generateFrameTimeline(VsyncEventData & outVsyncEventData,nsecs_t frameInterval,nsecs_t timestamp,nsecs_t preferredExpectedPresentationTime,nsecs_t preferredDeadlineTimestamp) const597 void EventThread::generateFrameTimeline(VsyncEventData& outVsyncEventData, nsecs_t frameInterval,
598                                         nsecs_t timestamp,
599                                         nsecs_t preferredExpectedPresentationTime,
600                                         nsecs_t preferredDeadlineTimestamp) const {
601     uint32_t currentIndex = 0;
602     // Add 1 to ensure the preferredFrameTimelineIndex entry (when multiplier == 0) is included.
603     for (int64_t multiplier = -VsyncEventData::kFrameTimelinesCapacity + 1;
604          currentIndex < VsyncEventData::kFrameTimelinesCapacity; multiplier++) {
605         nsecs_t deadlineTimestamp = preferredDeadlineTimestamp + multiplier * frameInterval;
606         // Valid possible frame timelines must have future values, so find a later frame timeline.
607         if (deadlineTimestamp <= timestamp) {
608             continue;
609         }
610 
611         nsecs_t expectedPresentationTime =
612                 preferredExpectedPresentationTime + multiplier * frameInterval;
613         if (expectedPresentationTime >= preferredExpectedPresentationTime +
614                     scheduler::VsyncConfig::kEarlyLatchMaxThreshold.count()) {
615             if (currentIndex == 0) {
616                 ALOGW("%s: Expected present time is too far in the future but no timelines are "
617                       "valid. preferred EPT=%" PRId64 ", Calculated EPT=%" PRId64
618                       ", multiplier=%" PRId64 ", frameInterval=%" PRId64 ", threshold=%" PRId64,
619                       __func__, preferredExpectedPresentationTime, expectedPresentationTime,
620                       multiplier, frameInterval,
621                       static_cast<int64_t>(
622                               scheduler::VsyncConfig::kEarlyLatchMaxThreshold.count()));
623             }
624             break;
625         }
626 
627         if (multiplier == 0) {
628             outVsyncEventData.preferredFrameTimelineIndex = currentIndex;
629         }
630 
631         outVsyncEventData.frameTimelines[currentIndex] =
632                 {.vsyncId = generateToken(timestamp, deadlineTimestamp, expectedPresentationTime),
633                  .deadlineTimestamp = deadlineTimestamp,
634                  .expectedPresentationTime = expectedPresentationTime};
635         currentIndex++;
636     }
637 
638     if (currentIndex == 0) {
639         ALOGW("%s: No timelines are valid. preferred EPT=%" PRId64 ", frameInterval=%" PRId64
640               ", threshold=%" PRId64,
641               __func__, preferredExpectedPresentationTime, frameInterval,
642               static_cast<int64_t>(scheduler::VsyncConfig::kEarlyLatchMaxThreshold.count()));
643         outVsyncEventData.frameTimelines[currentIndex] =
644                 {.vsyncId = generateToken(timestamp, preferredDeadlineTimestamp,
645                                           preferredExpectedPresentationTime),
646                  .deadlineTimestamp = preferredDeadlineTimestamp,
647                  .expectedPresentationTime = preferredExpectedPresentationTime};
648         currentIndex++;
649     }
650 
651     outVsyncEventData.frameTimelinesLength = currentIndex;
652 }
653 
dispatchEvent(const DisplayEventReceiver::Event & event,const DisplayEventConsumers & consumers)654 void EventThread::dispatchEvent(const DisplayEventReceiver::Event& event,
655                                 const DisplayEventConsumers& consumers) {
656     for (const auto& consumer : consumers) {
657         DisplayEventReceiver::Event copy = event;
658         if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_VSYNC) {
659             const int64_t frameInterval = mGetVsyncPeriodFunction(consumer->mOwnerUid);
660             copy.vsync.vsyncData.frameInterval = frameInterval;
661             generateFrameTimeline(copy.vsync.vsyncData, frameInterval, copy.header.timestamp,
662                                   event.vsync.vsyncData.preferredExpectedPresentationTime(),
663                                   event.vsync.vsyncData.preferredDeadlineTimestamp());
664         }
665         switch (consumer->postEvent(copy)) {
666             case NO_ERROR:
667                 break;
668 
669             case -EAGAIN:
670                 // TODO: Try again if pipe is full.
671                 ALOGW("Failed dispatching %s for %s", toString(event).c_str(),
672                       toString(*consumer).c_str());
673                 break;
674 
675             default:
676                 // Treat EPIPE and other errors as fatal.
677                 removeDisplayEventConnectionLocked(consumer);
678         }
679     }
680 }
681 
dump(std::string & result) const682 void EventThread::dump(std::string& result) const {
683     std::lock_guard<std::mutex> lock(mMutex);
684 
685     StringAppendF(&result, "%s: state=%s VSyncState=", mThreadName, toCString(mState));
686     if (mVSyncState) {
687         StringAppendF(&result, "{displayId=%s, count=%u%s}\n",
688                       to_string(mVSyncState->displayId).c_str(), mVSyncState->count,
689                       mVSyncState->synthetic ? ", synthetic" : "");
690     } else {
691         StringAppendF(&result, "none\n");
692     }
693 
694     const auto relativeLastCallTime =
695             ticks<std::milli, float>(mLastVsyncCallbackTime - TimePoint::now());
696     StringAppendF(&result, "mWorkDuration=%.2f mReadyDuration=%.2f last vsync time ",
697                   mWorkDuration.get().count() / 1e6f, mReadyDuration.count() / 1e6f);
698     StringAppendF(&result, "%.2fms relative to now\n", relativeLastCallTime);
699 
700     StringAppendF(&result, "  pending events (count=%zu):\n", mPendingEvents.size());
701     for (const auto& event : mPendingEvents) {
702         StringAppendF(&result, "    %s\n", toString(event).c_str());
703     }
704 
705     StringAppendF(&result, "  connections (count=%zu):\n", mDisplayEventConnections.size());
706     for (const auto& ptr : mDisplayEventConnections) {
707         if (const auto connection = ptr.promote()) {
708             StringAppendF(&result, "    %s\n", toString(*connection).c_str());
709         }
710     }
711     result += '\n';
712 }
713 
toCString(State state)714 const char* EventThread::toCString(State state) {
715     switch (state) {
716         case State::Idle:
717             return "Idle";
718         case State::Quit:
719             return "Quit";
720         case State::SyntheticVSync:
721             return "SyntheticVSync";
722         case State::VSync:
723             return "VSync";
724     }
725 }
726 
onNewVsyncSchedule(std::shared_ptr<scheduler::VsyncSchedule> schedule)727 void EventThread::onNewVsyncSchedule(std::shared_ptr<scheduler::VsyncSchedule> schedule) {
728     // Hold onto the old registration until after releasing the mutex to avoid deadlock.
729     scheduler::VSyncCallbackRegistration oldRegistration =
730             onNewVsyncScheduleInternal(std::move(schedule));
731 }
732 
onNewVsyncScheduleInternal(std::shared_ptr<scheduler::VsyncSchedule> schedule)733 scheduler::VSyncCallbackRegistration EventThread::onNewVsyncScheduleInternal(
734         std::shared_ptr<scheduler::VsyncSchedule> schedule) {
735     std::lock_guard<std::mutex> lock(mMutex);
736     const bool reschedule = mVsyncRegistration.cancel() == scheduler::CancelResult::Cancelled;
737     mVsyncSchedule = std::move(schedule);
738     auto oldRegistration =
739             std::exchange(mVsyncRegistration,
740                           scheduler::VSyncCallbackRegistration(mVsyncSchedule->getDispatch(),
741                                                                createDispatchCallback(),
742                                                                mThreadName));
743     if (reschedule) {
744         mVsyncRegistration.schedule({.workDuration = mWorkDuration.get().count(),
745                                      .readyDuration = mReadyDuration.count(),
746                                      .earliestVsync = mLastVsyncCallbackTime.ns()});
747     }
748     return oldRegistration;
749 }
750 
createDispatchCallback()751 scheduler::VSyncDispatch::Callback EventThread::createDispatchCallback() {
752     return [this](nsecs_t vsyncTime, nsecs_t wakeupTime, nsecs_t readyTime) {
753         onVsync(vsyncTime, wakeupTime, readyTime);
754     };
755 }
756 
757 } // namespace impl
758 } // namespace android
759 
760 // TODO(b/129481165): remove the #pragma below and fix conversion issues
761 #pragma clang diagnostic pop // ignored "-Wconversion"
762