blob: 538ea1288be51cb78314bdabae0375869a8f7b3b [file] [log] [blame]
Adithya Srinivasanf279e042020-08-17 14:56:27 -07001/*
2 * Copyright 2020 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
Dominik Laskowskif6b4ba62021-11-09 12:46:10 -080019#include <atomic>
20#include <chrono>
21#include <deque>
22#include <memory>
23#include <mutex>
24#include <optional>
25#include <string>
26
Ady Abraham22c7b5c2020-09-22 19:33:40 -070027#include <gui/ISurfaceComposer.h>
Jorim Jaggi5814ab82020-12-03 20:45:58 +010028#include <gui/JankInfo.h>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070029#include <gui/LayerMetadata.h>
Adithya Srinivasan01189672020-10-20 14:23:05 -070030#include <perfetto/trace/android/frame_timeline_event.pbzero.h>
31#include <perfetto/tracing.h>
Adithya Srinivasanf279e042020-08-17 14:56:27 -070032#include <ui/FenceTime.h>
33#include <utils/RefBase.h>
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -070034#include <utils/String16.h>
Adithya Srinivasanf279e042020-08-17 14:56:27 -070035#include <utils/Timers.h>
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -070036#include <utils/Vector.h>
Adithya Srinivasanf279e042020-08-17 14:56:27 -070037
Dominik Laskowskif6b4ba62021-11-09 12:46:10 -080038#include <scheduler/Fps.h>
39
40#include "../TimeStats/TimeStats.h"
Adithya Srinivasanf279e042020-08-17 14:56:27 -070041
Alec Mouri9a29e672020-09-14 12:39:14 -070042namespace android::frametimeline {
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -070043
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -080044class FrameTimelineTest;
45
46using namespace std::chrono_literals;
47
48// Metadata indicating how the frame was presented w.r.t expected present time.
49enum class FramePresentMetadata : int8_t {
50 // Frame was presented on time
51 OnTimePresent,
52 // Frame was presented late
53 LatePresent,
54 // Frame was presented early
55 EarlyPresent,
56 // Unknown/initial state
57 UnknownPresent,
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -070058};
59
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -080060// Metadata comparing the frame's actual finish time to the expected deadline.
61enum class FrameReadyMetadata : int8_t {
62 // App/SF finished on time. Early finish is treated as on time since the goal of any component
63 // is to finish before the deadline.
64 OnTimeFinish,
65 // App/SF finished work later than expected
66 LateFinish,
67 // Unknown/initial state
68 UnknownFinish,
69};
70
71// Metadata comparing the frame's actual start time to the expected start time.
72enum class FrameStartMetadata : int8_t {
73 // App/SF started on time
74 OnTimeStart,
75 // App/SF started later than expected
76 LateStart,
77 // App/SF started earlier than expected
78 EarlyStart,
79 // Unknown/initial state
80 UnknownStart,
81};
Adithya Srinivasanf279e042020-08-17 14:56:27 -070082
83/*
84 * Collection of timestamps that can be used for both predictions and actual times.
85 */
86struct TimelineItem {
87 TimelineItem(const nsecs_t startTime = 0, const nsecs_t endTime = 0,
88 const nsecs_t presentTime = 0)
89 : startTime(startTime), endTime(endTime), presentTime(presentTime) {}
90
91 nsecs_t startTime;
92 nsecs_t endTime;
93 nsecs_t presentTime;
Ady Abraham55fa7272020-09-30 19:19:27 -070094
95 bool operator==(const TimelineItem& other) const {
96 return startTime == other.startTime && endTime == other.endTime &&
97 presentTime == other.presentTime;
98 }
99
100 bool operator!=(const TimelineItem& other) const { return !(*this == other); }
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700101};
102
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800103struct JankClassificationThresholds {
104 // The various thresholds for App and SF. If the actual timestamp falls within the threshold
105 // compared to prediction, we treat it as on time.
106 nsecs_t presentThreshold = std::chrono::duration_cast<std::chrono::nanoseconds>(2ms).count();
Adithya Srinivasan54996e22021-06-25 22:26:45 +0000107 nsecs_t deadlineThreshold = std::chrono::duration_cast<std::chrono::nanoseconds>(0ms).count();
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800108 nsecs_t startThreshold = std::chrono::duration_cast<std::chrono::nanoseconds>(2ms).count();
109};
110
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700111/*
112 * TokenManager generates a running number token for a set of predictions made by VsyncPredictor. It
113 * saves these predictions for a short period of time and returns the predictions for a given token,
114 * if it hasn't expired.
115 */
116class TokenManager {
117public:
118 virtual ~TokenManager() = default;
119
120 // Generates a token for the given set of predictions. Stores the predictions for 120ms and
121 // destroys it later.
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700122 virtual int64_t generateTokenForPredictions(TimelineItem&& prediction) = 0;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800123
124 // Returns the stored predictions for a given token, if the predictions haven't expired.
125 virtual std::optional<TimelineItem> getPredictionsForToken(int64_t token) const = 0;
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700126};
127
128enum class PredictionState {
129 Valid, // Predictions obtained successfully from the TokenManager
130 Expired, // TokenManager no longer has the predictions
131 None, // Predictions are either not present or didn't come from TokenManager
132};
133
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +0000134/*
135 * Trace cookie is used to send start and end timestamps of <Surface/Display>Frames separately
136 * without needing to resend all the other information. We send all info to perfetto, along with a
137 * new cookie, in the start of a frame. For the corresponding end, we just send the same cookie.
138 * This helps in reducing the amount of data emitted by the producer.
139 */
140class TraceCookieCounter {
141public:
142 int64_t getCookieForTracing();
143
144private:
145 // Friend class for testing
146 friend class android::frametimeline::FrameTimelineTest;
147
148 std::atomic<int64_t> mTraceCookie = 0;
149};
150
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700151class SurfaceFrame {
152public:
153 enum class PresentState {
154 Presented, // Buffer was latched and presented by SurfaceFlinger
155 Dropped, // Buffer was dropped by SurfaceFlinger
156 Unknown, // Initial state, SurfaceFlinger hasn't seen this buffer yet
157 };
158
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800159 // Only FrameTimeline can construct a SurfaceFrame as it provides Predictions(through
160 // TokenManager), Thresholds and TimeStats pointer.
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000161 SurfaceFrame(const FrameTimelineInfo& frameTimelineInfo, pid_t ownerPid, uid_t ownerUid,
Alec Mouriadebf5c2021-01-05 12:57:36 -0800162 int32_t layerId, std::string layerName, std::string debugName,
163 PredictionState predictionState, TimelineItem&& predictions,
164 std::shared_ptr<TimeStats> timeStats, JankClassificationThresholds thresholds,
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700165 TraceCookieCounter* traceCookieCounter, bool isBuffer, GameMode);
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800166 ~SurfaceFrame() = default;
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700167
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800168 // Returns std::nullopt if the frame hasn't been classified yet.
169 // Used by both SF and FrameTimeline.
170 std::optional<int32_t> getJankType() const;
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700171
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800172 // Functions called by SF
173 int64_t getToken() const { return mToken; };
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000174 int32_t getInputEventId() const { return mInputEventId; };
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800175 TimelineItem getPredictions() const { return mPredictions; };
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700176 // Actual timestamps of the app are set individually at different functions.
177 // Start time (if the app provides) and Queue time are accessible after queueing the frame,
Adithya Srinivasan061c14c2021-02-11 01:19:47 +0000178 // whereas Acquire Fence time is available only during latch. Drop time is available at the time
179 // the buffer was dropped.
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800180 void setActualStartTime(nsecs_t actualStartTime);
181 void setActualQueueTime(nsecs_t actualQueueTime);
182 void setAcquireFenceTime(nsecs_t acquireFenceTime);
Adithya Srinivasan061c14c2021-02-11 01:19:47 +0000183 void setDropTime(nsecs_t dropTime);
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800184 void setPresentState(PresentState presentState, nsecs_t lastLatchTime = 0);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800185 void setRenderRate(Fps renderRate);
Pascal Muetschardac7bcd92023-10-03 15:05:36 +0200186 // Return the render rate if it exists, otherwise returns the DisplayFrame's render rate.
187 Fps getRenderRate() const;
Adithya Srinivasanb6a2fa12021-03-13 00:23:09 +0000188 void setGpuComposition();
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100189
Adithya Srinivasan785addd2021-03-09 00:38:00 +0000190 // When a bufferless SurfaceFrame is promoted to a buffer SurfaceFrame, we also have to update
191 // isBuffer.
192 void promoteToBuffer();
193
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800194 // Functions called by FrameTimeline
195 // BaseTime is the smallest timestamp in this SurfaceFrame.
196 // Used for dumping all timestamps relative to the oldest, making it easy to read.
197 nsecs_t getBaseTime() const;
198 // Sets the actual present time, appropriate metadata and classifies the jank.
Alec Mouri363faf02021-01-29 16:34:55 -0800199 // displayRefreshRate, displayDeadlineDelta, and displayPresentDelta are propagated from the
200 // display frame.
201 void onPresent(nsecs_t presentTime, int32_t displayFrameJankType, Fps refreshRate,
Pascal Muetschardac7bcd92023-10-03 15:05:36 +0200202 Fps displayFrameRenderRate, nsecs_t displayDeadlineDelta,
203 nsecs_t displayPresentDelta);
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800204 // All the timestamps are dumped relative to the baseTime
205 void dump(std::string& result, const std::string& indent, nsecs_t baseTime) const;
Adithya Srinivasan785addd2021-03-09 00:38:00 +0000206 // Dumps only the layer, token, is buffer, jank metadata, prediction and present states.
207 std::string miniDump() const;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800208 // Emits a packet for perfetto tracing. The function body will be executed only if tracing is
209 // enabled. The displayFrameToken is needed to link the SurfaceFrame to the corresponding
Ady Abraham57f8e182022-03-08 15:54:33 -0800210 // DisplayFrame at the trace processor side. monoBootOffset is the difference
211 // between SYSTEM_TIME_BOOTTIME and SYSTEM_TIME_MONOTONIC.
212 void trace(int64_t displayFrameToken, nsecs_t monoBootOffset) const;
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100213
Adithya Srinivasan061c14c2021-02-11 01:19:47 +0000214 // Getter functions used only by FrameTimelineTests and SurfaceFrame internally
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800215 TimelineItem getActuals() const;
216 pid_t getOwnerPid() const { return mOwnerPid; };
Alec Mouriadebf5c2021-01-05 12:57:36 -0800217 int32_t getLayerId() const { return mLayerId; };
Adithya Srinivasan061c14c2021-02-11 01:19:47 +0000218 PredictionState getPredictionState() const;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800219 PresentState getPresentState() const;
220 FrameReadyMetadata getFrameReadyMetadata() const;
221 FramePresentMetadata getFramePresentMetadata() const;
Adithya Srinivasan061c14c2021-02-11 01:19:47 +0000222 nsecs_t getDropTime() const;
Adithya Srinivasan785addd2021-03-09 00:38:00 +0000223 bool getIsBuffer() const;
Adithya Srinivasan061c14c2021-02-11 01:19:47 +0000224
225 // For prediction expired frames, this delta is subtracted from the actual end time to get a
226 // start time decent enough to see in traces.
227 // TODO(b/172587309): Remove this when we have actual start times.
228 static constexpr nsecs_t kPredictionExpiredStartTimeDelta =
229 std::chrono::duration_cast<std::chrono::nanoseconds>(2ms).count();
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800230
231private:
Ady Abraham57f8e182022-03-08 15:54:33 -0800232 void tracePredictions(int64_t displayFrameToken, nsecs_t monoBootOffset) const;
233 void traceActuals(int64_t displayFrameToken, nsecs_t monoBootOffset) const;
Adithya Srinivasan7c4ac7a2021-03-08 23:48:03 +0000234 void classifyJankLocked(int32_t displayFrameJankType, const Fps& refreshRate,
235 nsecs_t& deadlineDelta) REQUIRES(mMutex);
Adithya Srinivasan061c14c2021-02-11 01:19:47 +0000236
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800237 const int64_t mToken;
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000238 const int32_t mInputEventId;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800239 const pid_t mOwnerPid;
240 const uid_t mOwnerUid;
241 const std::string mLayerName;
242 const std::string mDebugName;
Alec Mouriadebf5c2021-01-05 12:57:36 -0800243 const int32_t mLayerId;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800244 PresentState mPresentState GUARDED_BY(mMutex);
245 const PredictionState mPredictionState;
246 const TimelineItem mPredictions;
247 TimelineItem mActuals GUARDED_BY(mMutex);
248 std::shared_ptr<TimeStats> mTimeStats;
249 const JankClassificationThresholds mJankClassificationThresholds;
250 nsecs_t mActualQueueTime GUARDED_BY(mMutex) = 0;
Adithya Srinivasan061c14c2021-02-11 01:19:47 +0000251 nsecs_t mDropTime GUARDED_BY(mMutex) = 0;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800252 mutable std::mutex mMutex;
253 // Bitmask for the type of jank
254 int32_t mJankType GUARDED_BY(mMutex) = JankType::None;
255 // Indicates if this frame was composited by the GPU or not
256 bool mGpuComposition GUARDED_BY(mMutex) = false;
Pascal Muetschardac7bcd92023-10-03 15:05:36 +0200257 // Refresh rate for this frame.
258 Fps mDisplayFrameRenderRate GUARDED_BY(mMutex);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800259 // Rendering rate for this frame.
260 std::optional<Fps> mRenderRate GUARDED_BY(mMutex);
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800261 // Enum for the type of present
262 FramePresentMetadata mFramePresentMetadata GUARDED_BY(mMutex) =
263 FramePresentMetadata::UnknownPresent;
264 // Enum for the type of finish
265 FrameReadyMetadata mFrameReadyMetadata GUARDED_BY(mMutex) = FrameReadyMetadata::UnknownFinish;
266 // Time when the previous buffer from the same layer was latched by SF. This is used in checking
267 // for BufferStuffing where the current buffer is expected to be ready but the previous buffer
268 // was latched instead.
269 nsecs_t mLastLatchTime GUARDED_BY(mMutex) = 0;
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +0000270 // TraceCookieCounter is used to obtain the cookie for sendig trace packets to perfetto. Using a
271 // reference here because the counter is owned by FrameTimeline, which outlives SurfaceFrame.
272 TraceCookieCounter& mTraceCookieCounter;
Adithya Srinivasan785addd2021-03-09 00:38:00 +0000273 // Tells if the SurfaceFrame is representing a buffer or a transaction without a
274 // buffer(animations)
275 bool mIsBuffer;
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000276 // GameMode from the layer. Used in metrics.
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700277 GameMode mGameMode = GameMode::Unsupported;
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700278};
279
280/*
281 * Maintains a history of SurfaceFrames grouped together by the vsync time in which they were
282 * presented
283 */
284class FrameTimeline {
285public:
286 virtual ~FrameTimeline() = default;
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700287 virtual TokenManager* getTokenManager() = 0;
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700288
Adithya Srinivasan01189672020-10-20 14:23:05 -0700289 // Initializes the Perfetto DataSource that emits DisplayFrame and SurfaceFrame events. Test
290 // classes can avoid double registration by mocking this function.
291 virtual void onBootFinished() = 0;
292
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700293 // Create a new surface frame, set the predictions based on a token and return it to the caller.
Alec Mouri9a29e672020-09-14 12:39:14 -0700294 // Debug name is the human-readable debugging string for dumpsys.
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000295 virtual std::shared_ptr<SurfaceFrame> createSurfaceFrameForToken(
296 const FrameTimelineInfo& frameTimelineInfo, pid_t ownerPid, uid_t ownerUid,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000297 int32_t layerId, std::string layerName, std::string debugName, bool isBuffer,
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700298 GameMode) = 0;
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700299
300 // Adds a new SurfaceFrame to the current DisplayFrame. Frames from multiple layers can be
301 // composited into one display frame.
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800302 virtual void addSurfaceFrame(std::shared_ptr<SurfaceFrame> surfaceFrame) = 0;
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700303
304 // The first function called by SF for the current DisplayFrame. Fetches SF predictions based on
305 // the token and sets the actualSfWakeTime for the current DisplayFrame.
Pascal Muetschardac7bcd92023-10-03 15:05:36 +0200306 virtual void setSfWakeUp(int64_t token, nsecs_t wakeupTime, Fps refreshRate,
307 Fps renderRate) = 0;
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700308
Adithya Srinivasan36b01af2021-04-07 22:29:47 +0000309 // Sets the sfPresentTime and finalizes the current DisplayFrame. Tracks the
Adithya Srinivasanb6a2fa12021-03-13 00:23:09 +0000310 // given present fence until it's signaled, and updates the present timestamps of all presented
Adithya Srinivasan36b01af2021-04-07 22:29:47 +0000311 // SurfaceFrames in that vsync. If a gpuFence was also provided, its tracked in the
312 // corresponding DisplayFrame.
Adithya Srinivasanb6a2fa12021-03-13 00:23:09 +0000313 virtual void setSfPresent(nsecs_t sfPresentTime, const std::shared_ptr<FenceTime>& presentFence,
Adithya Srinivasan36b01af2021-04-07 22:29:47 +0000314 const std::shared_ptr<FenceTime>& gpuFence) = 0;
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700315
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -0700316 // Args:
317 // -jank : Dumps only the Display Frames that are either janky themselves
318 // or contain janky Surface Frames.
319 // -all : Dumps the entire list of DisplayFrames and the SurfaceFrames contained within
320 virtual void parseArgs(const Vector<String16>& args, std::string& result) = 0;
Adithya Srinivasan2d736322020-10-01 16:53:48 -0700321
322 // Sets the max number of display frames that can be stored. Called by SF backdoor.
Josh Gaoade0f672023-01-17 14:59:04 -0800323 virtual void setMaxDisplayFrames(uint32_t size) = 0;
Adithya Srinivasan2d736322020-10-01 16:53:48 -0700324
Alec Mouriadebf5c2021-01-05 12:57:36 -0800325 // Computes the historical fps for the provided set of layer IDs
326 // The fps is compted from the linear timeline of present timestamps for DisplayFrames
327 // containing at least one layer ID.
Josh Gaoade0f672023-01-17 14:59:04 -0800328 virtual float computeFps(const std::unordered_set<int32_t>& layerIds) = 0;
Alec Mouriadebf5c2021-01-05 12:57:36 -0800329
Adithya Srinivasan2d736322020-10-01 16:53:48 -0700330 // Restores the max number of display frames to default. Called by SF backdoor.
331 virtual void reset() = 0;
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700332};
333
334namespace impl {
335
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700336class TokenManager : public android::frametimeline::TokenManager {
337public:
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000338 TokenManager() : mCurrentToken(FrameTimelineInfo::INVALID_VSYNC_ID + 1) {}
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700339 ~TokenManager() = default;
340
341 int64_t generateTokenForPredictions(TimelineItem&& predictions) override;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800342 std::optional<TimelineItem> getPredictionsForToken(int64_t token) const override;
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700343
344private:
345 // Friend class for testing
346 friend class android::frametimeline::FrameTimelineTest;
347
348 void flushTokens(nsecs_t flushTime) REQUIRES(mMutex);
349
Adithya Srinivasanbed4c4f2021-05-03 20:24:46 +0000350 std::map<int64_t, TimelineItem> mPredictions GUARDED_BY(mMutex);
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700351 int64_t mCurrentToken GUARDED_BY(mMutex);
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800352 mutable std::mutex mMutex;
Adithya Srinivasanbed4c4f2021-05-03 20:24:46 +0000353 static constexpr size_t kMaxTokens = 500;
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700354};
355
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700356class FrameTimeline : public android::frametimeline::FrameTimeline {
357public:
Adithya Srinivasan01189672020-10-20 14:23:05 -0700358 class FrameTimelineDataSource : public perfetto::DataSource<FrameTimelineDataSource> {
359 void OnSetup(const SetupArgs&) override{};
360 void OnStart(const StartArgs&) override{};
361 void OnStop(const StopArgs&) override{};
362 };
363
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800364 /*
365 * DisplayFrame should be used only internally within FrameTimeline. All members and methods are
366 * guarded by FrameTimeline's mMutex.
367 */
368 class DisplayFrame {
369 public:
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +0000370 DisplayFrame(std::shared_ptr<TimeStats> timeStats, JankClassificationThresholds thresholds,
Adithya Srinivasan82eef322021-04-10 00:06:04 +0000371 TraceCookieCounter* traceCookieCounter);
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800372 virtual ~DisplayFrame() = default;
373 // Dumpsys interface - dumps only if the DisplayFrame itself is janky or is at least one
374 // SurfaceFrame is janky.
375 void dumpJank(std::string& result, nsecs_t baseTime, int displayFrameCount) const;
376 // Dumpsys interface - dumps all data irrespective of jank
377 void dumpAll(std::string& result, nsecs_t baseTime) const;
378 // Emits a packet for perfetto tracing. The function body will be executed only if tracing
Ady Abraham57f8e182022-03-08 15:54:33 -0800379 // is enabled. monoBootOffset is the difference between SYSTEM_TIME_BOOTTIME
380 // and SYSTEM_TIME_MONOTONIC.
381 void trace(pid_t surfaceFlingerPid, nsecs_t monoBootOffset) const;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800382 // Sets the token, vsyncPeriod, predictions and SF start time.
Pascal Muetschardac7bcd92023-10-03 15:05:36 +0200383 void onSfWakeUp(int64_t token, Fps refreshRate, Fps renderRate,
384 std::optional<TimelineItem> predictions, nsecs_t wakeUpTime);
Adithya Srinivasan115ac692021-03-06 01:21:30 +0000385 // Sets the appropriate metadata and classifies the jank.
Adithya Srinivasan57dc81d2021-04-14 17:31:41 +0000386 void onPresent(nsecs_t signalTime, nsecs_t previousPresentTime);
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800387 // Adds the provided SurfaceFrame to the current display frame.
388 void addSurfaceFrame(std::shared_ptr<SurfaceFrame> surfaceFrame);
389
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800390 void setPredictions(PredictionState predictionState, TimelineItem predictions);
391 void setActualStartTime(nsecs_t actualStartTime);
392 void setActualEndTime(nsecs_t actualEndTime);
Adithya Srinivasan36b01af2021-04-07 22:29:47 +0000393 void setGpuFence(const std::shared_ptr<FenceTime>& gpuFence);
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800394
395 // BaseTime is the smallest timestamp in a DisplayFrame.
396 // Used for dumping all timestamps relative to the oldest, making it easy to read.
397 nsecs_t getBaseTime() const;
398
399 // Functions to be used only in testing.
400 TimelineItem getActuals() const { return mSurfaceFlingerActuals; };
401 TimelineItem getPredictions() const { return mSurfaceFlingerPredictions; };
Adithya Srinivasan939cd4d2021-02-23 06:18:13 +0000402 FrameStartMetadata getFrameStartMetadata() const { return mFrameStartMetadata; };
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800403 FramePresentMetadata getFramePresentMetadata() const { return mFramePresentMetadata; };
404 FrameReadyMetadata getFrameReadyMetadata() const { return mFrameReadyMetadata; };
405 int32_t getJankType() const { return mJankType; }
406 const std::vector<std::shared_ptr<SurfaceFrame>>& getSurfaceFrames() const {
407 return mSurfaceFrames;
408 }
409
410 private:
411 void dump(std::string& result, nsecs_t baseTime) const;
Ady Abraham57f8e182022-03-08 15:54:33 -0800412 void tracePredictions(pid_t surfaceFlingerPid, nsecs_t monoBootOffset) const;
413 void traceActuals(pid_t surfaceFlingerPid, nsecs_t monoBootOffset) const;
Adithya Srinivasan57dc81d2021-04-14 17:31:41 +0000414 void classifyJank(nsecs_t& deadlineDelta, nsecs_t& deltaToVsync,
415 nsecs_t previousPresentTime);
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800416
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000417 int64_t mToken = FrameTimelineInfo::INVALID_VSYNC_ID;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800418
419 /* Usage of TimelineItem w.r.t SurfaceFlinger
420 * startTime Time when SurfaceFlinger wakes up to handle transactions and buffer updates
421 * endTime Time when SurfaceFlinger sends a composited frame to Display
422 * presentTime Time when the composited frame was presented on screen
423 */
424 TimelineItem mSurfaceFlingerPredictions;
425 TimelineItem mSurfaceFlingerActuals;
426 std::shared_ptr<TimeStats> mTimeStats;
427 const JankClassificationThresholds mJankClassificationThresholds;
428
429 // Collection of predictions and actual values sent over by Layers
430 std::vector<std::shared_ptr<SurfaceFrame>> mSurfaceFrames;
431
432 PredictionState mPredictionState = PredictionState::None;
433 // Bitmask for the type of jank
434 int32_t mJankType = JankType::None;
Adithya Srinivasan36b01af2021-04-07 22:29:47 +0000435 // A valid gpu fence indicates that the DisplayFrame was composited by the GPU
436 std::shared_ptr<FenceTime> mGpuFence = FenceTime::NO_FENCE;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800437 // Enum for the type of present
438 FramePresentMetadata mFramePresentMetadata = FramePresentMetadata::UnknownPresent;
439 // Enum for the type of finish
440 FrameReadyMetadata mFrameReadyMetadata = FrameReadyMetadata::UnknownFinish;
441 // Enum for the type of start
442 FrameStartMetadata mFrameStartMetadata = FrameStartMetadata::UnknownStart;
443 // The refresh rate (vsync period) in nanoseconds as seen by SF during this DisplayFrame's
444 // timeline
Alec Mouri7d436ec2021-01-27 20:40:50 -0800445 Fps mRefreshRate;
Pascal Muetschardac7bcd92023-10-03 15:05:36 +0200446 // The current render rate for this DisplayFrame.
447 Fps mRenderRate;
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +0000448 // TraceCookieCounter is used to obtain the cookie for sendig trace packets to perfetto.
449 // Using a reference here because the counter is owned by FrameTimeline, which outlives
450 // DisplayFrame.
451 TraceCookieCounter& mTraceCookieCounter;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800452 };
453
454 FrameTimeline(std::shared_ptr<TimeStats> timeStats, pid_t surfaceFlingerPid,
Ady Abraham57f8e182022-03-08 15:54:33 -0800455 JankClassificationThresholds thresholds = {}, bool useBootTimeClock = true);
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700456 ~FrameTimeline() = default;
457
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700458 frametimeline::TokenManager* getTokenManager() override { return &mTokenManager; }
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000459 std::shared_ptr<SurfaceFrame> createSurfaceFrameForToken(
460 const FrameTimelineInfo& frameTimelineInfo, pid_t ownerPid, uid_t ownerUid,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000461 int32_t layerId, std::string layerName, std::string debugName, bool isBuffer,
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700462 GameMode) override;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800463 void addSurfaceFrame(std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame) override;
Pascal Muetschardac7bcd92023-10-03 15:05:36 +0200464 void setSfWakeUp(int64_t token, nsecs_t wakeupTime, Fps refreshRate, Fps renderRate) override;
Adithya Srinivasanb6a2fa12021-03-13 00:23:09 +0000465 void setSfPresent(nsecs_t sfPresentTime, const std::shared_ptr<FenceTime>& presentFence,
Adithya Srinivasan36b01af2021-04-07 22:29:47 +0000466 const std::shared_ptr<FenceTime>& gpuFence = FenceTime::NO_FENCE) override;
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -0700467 void parseArgs(const Vector<String16>& args, std::string& result) override;
Adithya Srinivasan2d736322020-10-01 16:53:48 -0700468 void setMaxDisplayFrames(uint32_t size) override;
Alec Mouriadebf5c2021-01-05 12:57:36 -0800469 float computeFps(const std::unordered_set<int32_t>& layerIds) override;
Adithya Srinivasan2d736322020-10-01 16:53:48 -0700470 void reset() override;
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700471
Adithya Srinivasan01189672020-10-20 14:23:05 -0700472 // Sets up the perfetto tracing backend and data source.
473 void onBootFinished() override;
474 // Registers the data source with the perfetto backend. Called as part of onBootFinished()
475 // and should not be called manually outside of tests.
476 void registerDataSource();
477
478 static constexpr char kFrameTimelineDataSource[] = "android.surfaceflinger.frametimeline";
479
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700480private:
481 // Friend class for testing
482 friend class android::frametimeline::FrameTimelineTest;
483
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700484 void flushPendingPresentFences() REQUIRES(mMutex);
Ady Abrahamfcb16862022-10-10 14:35:21 -0700485 std::optional<size_t> getFirstSignalFenceIndex() const REQUIRES(mMutex);
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700486 void finalizeCurrentDisplayFrame() REQUIRES(mMutex);
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -0700487 void dumpAll(std::string& result);
488 void dumpJank(std::string& result);
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700489
490 // Sliding window of display frames. TODO(b/168072834): compare perf with fixed size array
491 std::deque<std::shared_ptr<DisplayFrame>> mDisplayFrames GUARDED_BY(mMutex);
492 std::vector<std::pair<std::shared_ptr<FenceTime>, std::shared_ptr<DisplayFrame>>>
493 mPendingPresentFences GUARDED_BY(mMutex);
494 std::shared_ptr<DisplayFrame> mCurrentDisplayFrame GUARDED_BY(mMutex);
495 TokenManager mTokenManager;
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +0000496 TraceCookieCounter mTraceCookieCounter;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800497 mutable std::mutex mMutex;
Ady Abraham57f8e182022-03-08 15:54:33 -0800498 const bool mUseBootTimeClock;
Adithya Srinivasan2d736322020-10-01 16:53:48 -0700499 uint32_t mMaxDisplayFrames;
Alec Mouri9a29e672020-09-14 12:39:14 -0700500 std::shared_ptr<TimeStats> mTimeStats;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800501 const pid_t mSurfaceFlingerPid;
Adithya Srinivasan57dc81d2021-04-14 17:31:41 +0000502 nsecs_t mPreviousPresentTime = 0;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800503 const JankClassificationThresholds mJankClassificationThresholds;
Adithya Srinivasan2d736322020-10-01 16:53:48 -0700504 static constexpr uint32_t kDefaultMaxDisplayFrames = 64;
Adithya Srinivasan01189672020-10-20 14:23:05 -0700505 // The initial container size for the vector<SurfaceFrames> inside display frame. Although
506 // this number doesn't represent any bounds on the number of surface frames that can go in a
507 // display frame, this is a good starting size for the vector so that we can avoid the
508 // internal vector resizing that happens with push_back.
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700509 static constexpr uint32_t kNumSurfaceFramesInitial = 10;
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700510};
511
512} // namespace impl
513} // namespace android::frametimeline