xref: /aosp_15_r20/frameworks/native/services/surfaceflinger/Scheduler/VSyncDispatch.h (revision 38e8c45f13ce32b0dcecb25141ffecaf386fa17f)
1 /*
2  * Copyright 2019 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 <functional>
20 #include <optional>
21 #include <string>
22 
23 #include <ftl/mixins.h>
24 #include <scheduler/Time.h>
25 #include <utils/Timers.h>
26 
27 namespace android::scheduler {
28 
29 struct ScheduleResult {
30     TimePoint callbackTime;
31     TimePoint vsyncTime;
32 };
33 
34 enum class CancelResult { Cancelled, TooLate, Error };
35 
36 /*
37  * VSyncDispatch is a class that will dispatch callbacks relative to system vsync events.
38  */
39 class VSyncDispatch {
40 public:
41     struct CallbackToken : ftl::DefaultConstructible<CallbackToken, size_t>,
42                            ftl::Equatable<CallbackToken>,
43                            ftl::Incrementable<CallbackToken> {
44         using DefaultConstructible::DefaultConstructible;
45     };
46 
47     virtual ~VSyncDispatch();
48 
49     /*
50      * A callback that can be registered to be awoken at a given time relative to a vsync event.
51      * \param [in] vsyncTime:        The timestamp of the vsync the callback is for.
52      * \param [in] targetWakeupTime: The timestamp of intended wakeup time of the cb.
53      * \param [in] readyTime:        The timestamp of intended time where client needs to finish
54      *                               its work by.
55      */
56     using Callback =
57             std::function<void(nsecs_t vsyncTime, nsecs_t targetWakeupTime, nsecs_t readyTime)>;
58 
59     /*
60      * Registers a callback that will be called at designated points on the vsync timeline.
61      * The callback can be scheduled, rescheduled targeting vsync times, or cancelled.
62      * The token returned must be cleaned up via unregisterCallback.
63      *
64      * \param [in] callbackFn   A function to schedule for callback. The resources needed to invoke
65      *                          callbackFn must have lifetimes encompassing the lifetime of the
66      *                          CallbackToken returned.
67      * \param [in] callbackName A human-readable, unique name to identify the callback.
68      * \return                  A token that can be used to schedule, reschedule, or cancel the
69      *                          invocation of callbackFn.
70      *
71      */
72     virtual CallbackToken registerCallback(Callback, std::string callbackName) = 0;
73 
74     /*
75      * Unregisters a callback.
76      *
77      * \param [in] token        The callback to unregister.
78      *
79      */
80     virtual void unregisterCallback(CallbackToken token) = 0;
81 
82     /*
83      * Timing information about a scheduled callback
84      *
85      * @workDuration:  The time needed for the client to perform its work
86      * @readyDuration: The time needed for the client to be ready before a vsync event.
87      *                 For external (non-SF) clients, not only do we need to account for their
88      *                 workDuration, but we also need to account for the time SF will take to
89      *                 process their buffer/transaction. In this case, readyDuration will be set
90      *                 to the SF duration in order to provide enough end-to-end time, and to be
91      *                 able to provide the ready-by time (deadline) on the callback.
92      *                 For internal clients, we don't need to add additional padding, so
93      *                 readyDuration will typically be 0.
94      * @lastVsync: The targeted display time. This will be snapped to the closest
95      *                 predicted vsync time after lastVsync.
96      * @committedVsyncOpt: The display time that is committed to the callback as the
97      *                 target vsync time.
98      *
99      * callback will be dispatched at 'workDuration + readyDuration' nanoseconds before a vsync
100      * event.
101      */
102     struct ScheduleTiming {
103         nsecs_t workDuration = 0;
104         nsecs_t readyDuration = 0;
105         nsecs_t lastVsync = 0;
106         std::optional<nsecs_t> committedVsyncOpt;
107 
108         bool operator==(const ScheduleTiming& other) const {
109             return workDuration == other.workDuration && readyDuration == other.readyDuration &&
110                     lastVsync == other.lastVsync && committedVsyncOpt == other.committedVsyncOpt;
111         }
112 
113         bool operator!=(const ScheduleTiming& other) const { return !(*this == other); }
114     };
115 
116     /*
117      * Schedules the registered callback to be dispatched.
118      *
119      * The callback will be dispatched at 'workDuration + readyDuration' nanoseconds before a vsync
120      * event.
121      *
122      * The caller designates the earliest vsync event that should be targeted by the lastVsync
123      * parameter.
124      * The callback will be scheduled at (workDuration + readyDuration - predictedVsync), where
125      * predictedVsync is the first vsync event time where ( predictedVsync >= lastVsync ).
126      *
127      * If (workDuration + readyDuration - lastVsync) is in the past, or if a callback has
128      * already been dispatched for the predictedVsync, an error will be returned.
129      *
130      * It is valid to reschedule a callback to a different time.
131      *
132      * \param [in] token           The callback to schedule.
133      * \param [in] scheduleTiming  The timing information for this schedule call
134      * \return                     The expected callback time if a callback was scheduled,
135      *                             along with VSYNC time for the callback scheduled.
136      *                             std::nullopt if the callback is not registered.
137      */
138     virtual std::optional<ScheduleResult> schedule(CallbackToken token,
139                                                    ScheduleTiming scheduleTiming) = 0;
140 
141     /*
142      * Update the timing information for a scheduled callback.
143      * If the callback is not scheduled, then this function does nothing.
144      *
145      * \param [in] token           The callback to schedule.
146      * \param [in] scheduleTiming  The timing information for this schedule call
147      * \return                     The expected callback time if a callback was scheduled,
148      *                             along with VSYNC time for the callback scheduled.
149      *                             std::nullopt if the callback is not registered.
150      */
151     virtual std::optional<ScheduleResult> update(CallbackToken token,
152                                                  ScheduleTiming scheduleTiming) = 0;
153 
154     /* Cancels a scheduled callback, if possible.
155      *
156      * \param [in] token    The callback to cancel.
157      * \return              A CancelResult::TooLate if the callback was already dispatched.
158      *                      A CancelResult::Cancelled if the callback was successfully cancelled.
159      *                      A CancelResult::Error if there was an pre-condition violation.
160      */
161     virtual CancelResult cancel(CallbackToken token) = 0;
162 
163     virtual void dump(std::string& result) const = 0;
164 
165 protected:
166     VSyncDispatch() = default;
167 
168     VSyncDispatch(const VSyncDispatch&) = delete;
169     VSyncDispatch& operator=(const VSyncDispatch&) = delete;
170 };
171 
172 class VSyncCallbackRegistration {
173 public:
174     VSyncCallbackRegistration(std::shared_ptr<VSyncDispatch>, VSyncDispatch::Callback,
175                               std::string callbackName);
176     ~VSyncCallbackRegistration();
177 
178     VSyncCallbackRegistration(VSyncCallbackRegistration&&);
179     VSyncCallbackRegistration& operator=(VSyncCallbackRegistration&&);
180 
181     // See documentation for VSyncDispatch::schedule.
182     std::optional<ScheduleResult> schedule(VSyncDispatch::ScheduleTiming scheduleTiming);
183 
184     // See documentation for VSyncDispatch::update.
185     std::optional<ScheduleResult> update(VSyncDispatch::ScheduleTiming scheduleTiming);
186 
187     // See documentation for VSyncDispatch::cancel.
188     CancelResult cancel();
189 
190 private:
191     friend class VSyncCallbackRegistrationTest;
192 
193     std::shared_ptr<VSyncDispatch> mDispatch;
194     std::optional<VSyncDispatch::CallbackToken> mToken;
195 };
196 
197 } // namespace android::scheduler
198