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 #pragma once 18 19 #include <android-base/thread_annotations.h> 20 #include <android/gui/BnDisplayEventConnection.h> 21 #include <gui/DisplayEventReceiver.h> 22 #include <private/gui/BitTube.h> 23 #include <sys/types.h> 24 #include <utils/Errors.h> 25 26 #include <condition_variable> 27 #include <cstdint> 28 #include <deque> 29 #include <mutex> 30 #include <optional> 31 #include <thread> 32 #include <vector> 33 34 #include "DisplayHardware/DisplayMode.h" 35 36 // --------------------------------------------------------------------------- 37 namespace android { 38 // --------------------------------------------------------------------------- 39 40 class EventThread; 41 class EventThreadTest; 42 class SurfaceFlinger; 43 44 namespace frametimeline { 45 class TokenManager; 46 } // namespace frametimeline 47 48 using gui::ParcelableVsyncEventData; 49 using gui::VsyncEventData; 50 51 // --------------------------------------------------------------------------- 52 53 using ResyncCallback = std::function<void()>; 54 using FrameRateOverride = DisplayEventReceiver::Event::FrameRateOverride; 55 56 enum class VSyncRequest { 57 None = -2, 58 // Single wakes up for the next two frames to avoid scheduler overhead 59 Single = -1, 60 // SingleSuppressCallback only wakes up for the next frame 61 SingleSuppressCallback = 0, 62 Periodic = 1, 63 // Subsequent values are periods. 64 }; 65 66 class VSyncSource { 67 public: 68 class VSyncData { 69 public: 70 nsecs_t expectedPresentationTime; 71 nsecs_t deadlineTimestamp; 72 }; 73 74 class Callback { 75 public: ~Callback()76 virtual ~Callback() {} 77 virtual void onVSyncEvent(nsecs_t when, VSyncData vsyncData) = 0; 78 }; 79 ~VSyncSource()80 virtual ~VSyncSource() {} 81 82 virtual const char* getName() const = 0; 83 virtual void setVSyncEnabled(bool enable) = 0; 84 virtual void setCallback(Callback* callback) = 0; 85 virtual void setDuration(std::chrono::nanoseconds workDuration, 86 std::chrono::nanoseconds readyDuration) = 0; 87 virtual VSyncData getLatestVSyncData() const = 0; 88 89 virtual void dump(std::string& result) const = 0; 90 }; 91 92 class EventThreadConnection : public gui::BnDisplayEventConnection { 93 public: 94 EventThreadConnection(EventThread*, uid_t callingUid, ResyncCallback, 95 ISurfaceComposer::EventRegistrationFlags eventRegistration = {}); 96 virtual ~EventThreadConnection(); 97 98 virtual status_t postEvent(const DisplayEventReceiver::Event& event); 99 100 binder::Status stealReceiveChannel(gui::BitTube* outChannel) override; 101 binder::Status setVsyncRate(int rate) override; 102 binder::Status requestNextVsync() override; // asynchronous 103 binder::Status getLatestVsyncEventData(ParcelableVsyncEventData* outVsyncEventData) override; 104 105 // Called in response to requestNextVsync. 106 const ResyncCallback resyncCallback; 107 108 VSyncRequest vsyncRequest = VSyncRequest::None; 109 const uid_t mOwnerUid; 110 const ISurfaceComposer::EventRegistrationFlags mEventRegistration; 111 112 private: 113 virtual void onFirstRef(); 114 EventThread* const mEventThread; 115 std::mutex mLock; 116 gui::BitTube mChannel GUARDED_BY(mLock); 117 118 std::vector<DisplayEventReceiver::Event> mPendingEvents; 119 }; 120 121 class EventThread { 122 public: 123 virtual ~EventThread(); 124 125 virtual sp<EventThreadConnection> createEventConnection( 126 ResyncCallback, 127 ISurfaceComposer::EventRegistrationFlags eventRegistration = {}) const = 0; 128 129 // called before the screen is turned off from main thread 130 virtual void onScreenReleased() = 0; 131 132 // called after the screen is turned on from main thread 133 virtual void onScreenAcquired() = 0; 134 135 virtual void onHotplugReceived(PhysicalDisplayId displayId, bool connected) = 0; 136 137 // called when SF changes the active mode and apps needs to be notified about the change 138 virtual void onModeChanged(DisplayModePtr) = 0; 139 140 // called when SF updates the Frame Rate Override list 141 virtual void onFrameRateOverridesChanged(PhysicalDisplayId displayId, 142 std::vector<FrameRateOverride> overrides) = 0; 143 144 virtual void dump(std::string& result) const = 0; 145 146 virtual void setDuration(std::chrono::nanoseconds workDuration, 147 std::chrono::nanoseconds readyDuration) = 0; 148 149 virtual status_t registerDisplayEventConnection( 150 const sp<EventThreadConnection>& connection) = 0; 151 virtual void setVsyncRate(uint32_t rate, const sp<EventThreadConnection>& connection) = 0; 152 // Requests the next vsync. If resetIdleTimer is set to true, it resets the idle timer. 153 virtual void requestNextVsync(const sp<EventThreadConnection>& connection) = 0; 154 virtual VsyncEventData getLatestVsyncEventData( 155 const sp<EventThreadConnection>& connection) const = 0; 156 157 // Retrieves the number of event connections tracked by this EventThread. 158 virtual size_t getEventThreadConnectionCount() = 0; 159 }; 160 161 namespace impl { 162 163 class EventThread : public android::EventThread, private VSyncSource::Callback { 164 public: 165 using InterceptVSyncsCallback = std::function<void(nsecs_t)>; 166 using ThrottleVsyncCallback = std::function<bool(nsecs_t, uid_t)>; 167 using GetVsyncPeriodFunction = std::function<nsecs_t(uid_t)>; 168 169 EventThread(std::unique_ptr<VSyncSource>, frametimeline::TokenManager*, InterceptVSyncsCallback, 170 ThrottleVsyncCallback, GetVsyncPeriodFunction); 171 ~EventThread(); 172 173 sp<EventThreadConnection> createEventConnection( 174 ResyncCallback, 175 ISurfaceComposer::EventRegistrationFlags eventRegistration = {}) const override; 176 177 status_t registerDisplayEventConnection(const sp<EventThreadConnection>& connection) override; 178 void setVsyncRate(uint32_t rate, const sp<EventThreadConnection>& connection) override; 179 void requestNextVsync(const sp<EventThreadConnection>& connection) override; 180 VsyncEventData getLatestVsyncEventData( 181 const sp<EventThreadConnection>& connection) const override; 182 183 // called before the screen is turned off from main thread 184 void onScreenReleased() override; 185 186 // called after the screen is turned on from main thread 187 void onScreenAcquired() override; 188 189 void onHotplugReceived(PhysicalDisplayId displayId, bool connected) override; 190 191 void onModeChanged(DisplayModePtr) override; 192 193 void onFrameRateOverridesChanged(PhysicalDisplayId displayId, 194 std::vector<FrameRateOverride> overrides) override; 195 196 void dump(std::string& result) const override; 197 198 void setDuration(std::chrono::nanoseconds workDuration, 199 std::chrono::nanoseconds readyDuration) override; 200 201 size_t getEventThreadConnectionCount() override; 202 203 private: 204 friend EventThreadTest; 205 206 using DisplayEventConsumers = std::vector<sp<EventThreadConnection>>; 207 208 void threadMain(std::unique_lock<std::mutex>& lock) REQUIRES(mMutex); 209 210 bool shouldConsumeEvent(const DisplayEventReceiver::Event& event, 211 const sp<EventThreadConnection>& connection) const REQUIRES(mMutex); 212 void dispatchEvent(const DisplayEventReceiver::Event& event, 213 const DisplayEventConsumers& consumers) REQUIRES(mMutex); 214 215 void removeDisplayEventConnectionLocked(const wp<EventThreadConnection>& connection) 216 REQUIRES(mMutex); 217 218 // Implements VSyncSource::Callback 219 void onVSyncEvent(nsecs_t timestamp, VSyncSource::VSyncData vsyncData) override; 220 221 int64_t generateToken(nsecs_t timestamp, nsecs_t deadlineTimestamp, 222 nsecs_t expectedPresentationTime) const; 223 void generateFrameTimeline(VsyncEventData& outVsyncEventData, nsecs_t frameInterval, 224 nsecs_t timestamp, nsecs_t preferredExpectedPresentationTime, 225 nsecs_t preferredDeadlineTimestamp) const; 226 227 const std::unique_ptr<VSyncSource> mVSyncSource GUARDED_BY(mMutex); 228 frametimeline::TokenManager* const mTokenManager; 229 230 const InterceptVSyncsCallback mInterceptVSyncsCallback; 231 const ThrottleVsyncCallback mThrottleVsyncCallback; 232 const GetVsyncPeriodFunction mGetVsyncPeriodFunction; 233 const char* const mThreadName; 234 235 std::thread mThread; 236 mutable std::mutex mMutex; 237 mutable std::condition_variable mCondition; 238 239 std::vector<wp<EventThreadConnection>> mDisplayEventConnections GUARDED_BY(mMutex); 240 std::deque<DisplayEventReceiver::Event> mPendingEvents GUARDED_BY(mMutex); 241 242 // VSYNC state of connected display. 243 struct VSyncState { VSyncStateVSyncState244 explicit VSyncState(PhysicalDisplayId displayId) : displayId(displayId) {} 245 246 const PhysicalDisplayId displayId; 247 248 // Number of VSYNC events since display was connected. 249 uint32_t count = 0; 250 251 // True if VSYNC should be faked, e.g. when display is off. 252 bool synthetic = false; 253 }; 254 255 // TODO(b/74619554): Create per-display threads waiting on respective VSYNC signals, 256 // and support headless mode by injecting a fake display with synthetic VSYNC. 257 std::optional<VSyncState> mVSyncState GUARDED_BY(mMutex); 258 259 // State machine for event loop. 260 enum class State { 261 Idle, 262 Quit, 263 SyntheticVSync, 264 VSync, 265 }; 266 267 State mState GUARDED_BY(mMutex) = State::Idle; 268 269 static const char* toCString(State); 270 }; 271 272 // --------------------------------------------------------------------------- 273 274 } // namespace impl 275 } // namespace android 276