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(DisplayModePtr) = 0;
128 
129     // called when SF updates the Frame Rate Override list
130     virtual void onFrameRateOverridesChanged(PhysicalDisplayId displayId,
131                                              std::vector<FrameRateOverride> overrides) = 0;
132 
133     virtual void dump(std::string& result) const = 0;
134 
135     virtual void setDuration(std::chrono::nanoseconds workDuration,
136                              std::chrono::nanoseconds readyDuration) = 0;
137 
138     virtual status_t registerDisplayEventConnection(
139             const sp<EventThreadConnection>& connection) = 0;
140     virtual void setVsyncRate(uint32_t rate, const sp<EventThreadConnection>& connection) = 0;
141     // Requests the next vsync. If resetIdleTimer is set to true, it resets the idle timer.
142     virtual void requestNextVsync(const sp<EventThreadConnection>& connection) = 0;
143 
144     // Retrieves the number of event connections tracked by this EventThread.
145     virtual size_t getEventThreadConnectionCount() = 0;
146 };
147 
148 namespace impl {
149 
150 class EventThread : public android::EventThread, private VSyncSource::Callback {
151 public:
152     using InterceptVSyncsCallback = std::function<void(nsecs_t)>;
153     using ThrottleVsyncCallback = std::function<bool(nsecs_t, uid_t)>;
154     using GetVsyncPeriodFunction = std::function<nsecs_t(uid_t)>;
155 
156     EventThread(std::unique_ptr<VSyncSource>, frametimeline::TokenManager*, InterceptVSyncsCallback,
157                 ThrottleVsyncCallback, GetVsyncPeriodFunction);
158     ~EventThread();
159 
160     sp<EventThreadConnection> createEventConnection(
161             ResyncCallback,
162             ISurfaceComposer::EventRegistrationFlags eventRegistration = {}) const override;
163 
164     status_t registerDisplayEventConnection(const sp<EventThreadConnection>& connection) override;
165     void setVsyncRate(uint32_t rate, const sp<EventThreadConnection>& connection) override;
166     void requestNextVsync(const sp<EventThreadConnection>& connection) override;
167 
168     // called before the screen is turned off from main thread
169     void onScreenReleased() override;
170 
171     // called after the screen is turned on from main thread
172     void onScreenAcquired() override;
173 
174     void onHotplugReceived(PhysicalDisplayId displayId, bool connected) override;
175 
176     void onModeChanged(DisplayModePtr) override;
177 
178     void onFrameRateOverridesChanged(PhysicalDisplayId displayId,
179                                      std::vector<FrameRateOverride> overrides) override;
180 
181     void dump(std::string& result) const override;
182 
183     void setDuration(std::chrono::nanoseconds workDuration,
184                      std::chrono::nanoseconds readyDuration) override;
185 
186     size_t getEventThreadConnectionCount() override;
187 
188 private:
189     friend EventThreadTest;
190 
191     using DisplayEventConsumers = std::vector<sp<EventThreadConnection>>;
192 
193     void threadMain(std::unique_lock<std::mutex>& lock) REQUIRES(mMutex);
194 
195     bool shouldConsumeEvent(const DisplayEventReceiver::Event& event,
196                             const sp<EventThreadConnection>& connection) const REQUIRES(mMutex);
197     void dispatchEvent(const DisplayEventReceiver::Event& event,
198                        const DisplayEventConsumers& consumers) REQUIRES(mMutex);
199 
200     void removeDisplayEventConnectionLocked(const wp<EventThreadConnection>& connection)
201             REQUIRES(mMutex);
202 
203     // Implements VSyncSource::Callback
204     void onVSyncEvent(nsecs_t timestamp, nsecs_t expectedVSyncTimestamp,
205                       nsecs_t deadlineTimestamp) override;
206 
207     const std::unique_ptr<VSyncSource> mVSyncSource GUARDED_BY(mMutex);
208     frametimeline::TokenManager* const mTokenManager;
209 
210     const InterceptVSyncsCallback mInterceptVSyncsCallback;
211     const ThrottleVsyncCallback mThrottleVsyncCallback;
212     const GetVsyncPeriodFunction mGetVsyncPeriodFunction;
213     const char* const mThreadName;
214 
215     std::thread mThread;
216     mutable std::mutex mMutex;
217     mutable std::condition_variable mCondition;
218 
219     std::vector<wp<EventThreadConnection>> mDisplayEventConnections GUARDED_BY(mMutex);
220     std::deque<DisplayEventReceiver::Event> mPendingEvents GUARDED_BY(mMutex);
221 
222     // VSYNC state of connected display.
223     struct VSyncState {
VSyncStateVSyncState224         explicit VSyncState(PhysicalDisplayId displayId) : displayId(displayId) {}
225 
226         const PhysicalDisplayId displayId;
227 
228         // Number of VSYNC events since display was connected.
229         uint32_t count = 0;
230 
231         // True if VSYNC should be faked, e.g. when display is off.
232         bool synthetic = false;
233     };
234 
235     // TODO(b/74619554): Create per-display threads waiting on respective VSYNC signals,
236     // and support headless mode by injecting a fake display with synthetic VSYNC.
237     std::optional<VSyncState> mVSyncState GUARDED_BY(mMutex);
238 
239     // State machine for event loop.
240     enum class State {
241         Idle,
242         Quit,
243         SyntheticVSync,
244         VSync,
245     };
246 
247     State mState GUARDED_BY(mMutex) = State::Idle;
248 
249     static const char* toCString(State);
250 };
251 
252 // ---------------------------------------------------------------------------
253 
254 } // namespace impl
255 } // namespace android
256