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