blob: fe83ebf1ea44f89cccf6c2077996adb0ca25a174 [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
Alec Mouri9a29e672020-09-14 12:39:14 -070019#include <../TimeStats/TimeStats.h>
Ady Abraham22c7b5c2020-09-22 19:33:40 -070020#include <gui/ISurfaceComposer.h>
Jorim Jaggi5814ab82020-12-03 20:45:58 +010021#include <gui/JankInfo.h>
Adithya Srinivasan01189672020-10-20 14:23:05 -070022#include <perfetto/trace/android/frame_timeline_event.pbzero.h>
23#include <perfetto/tracing.h>
Adithya Srinivasanf279e042020-08-17 14:56:27 -070024#include <ui/FenceTime.h>
25#include <utils/RefBase.h>
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -070026#include <utils/String16.h>
Adithya Srinivasanf279e042020-08-17 14:56:27 -070027#include <utils/Timers.h>
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -070028#include <utils/Vector.h>
Adithya Srinivasanf279e042020-08-17 14:56:27 -070029
Alec Mouri9a29e672020-09-14 12:39:14 -070030#include <deque>
31#include <mutex>
Adithya Srinivasanf279e042020-08-17 14:56:27 -070032
Alec Mouri9a29e672020-09-14 12:39:14 -070033namespace android::frametimeline {
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -070034
35enum JankMetadata {
36 // Frame was presented earlier than expected
37 EarlyPresent = 0x1,
38 // Frame was presented later than expected
39 LatePresent = 0x2,
40 // App/SF started earlier than expected
41 EarlyStart = 0x4,
42 // App/SF started later than expected
43 LateStart = 0x8,
44 // App/SF finished work earlier than the deadline
45 EarlyFinish = 0x10,
46 // App/SF finished work later than the deadline
47 LateFinish = 0x20,
48 // SF was in GPU composition
49 GpuComposition = 0x40,
50};
51
Adithya Srinivasanf279e042020-08-17 14:56:27 -070052class FrameTimelineTest;
53
54/*
55 * Collection of timestamps that can be used for both predictions and actual times.
56 */
57struct TimelineItem {
58 TimelineItem(const nsecs_t startTime = 0, const nsecs_t endTime = 0,
59 const nsecs_t presentTime = 0)
60 : startTime(startTime), endTime(endTime), presentTime(presentTime) {}
61
62 nsecs_t startTime;
63 nsecs_t endTime;
64 nsecs_t presentTime;
Ady Abraham55fa7272020-09-30 19:19:27 -070065
66 bool operator==(const TimelineItem& other) const {
67 return startTime == other.startTime && endTime == other.endTime &&
68 presentTime == other.presentTime;
69 }
70
71 bool operator!=(const TimelineItem& other) const { return !(*this == other); }
Adithya Srinivasanf279e042020-08-17 14:56:27 -070072};
73
74/*
75 * TokenManager generates a running number token for a set of predictions made by VsyncPredictor. It
76 * saves these predictions for a short period of time and returns the predictions for a given token,
77 * if it hasn't expired.
78 */
79class TokenManager {
80public:
81 virtual ~TokenManager() = default;
82
83 // Generates a token for the given set of predictions. Stores the predictions for 120ms and
84 // destroys it later.
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -070085 virtual int64_t generateTokenForPredictions(TimelineItem&& prediction) = 0;
Adithya Srinivasanf279e042020-08-17 14:56:27 -070086};
87
88enum class PredictionState {
89 Valid, // Predictions obtained successfully from the TokenManager
90 Expired, // TokenManager no longer has the predictions
91 None, // Predictions are either not present or didn't come from TokenManager
92};
93
94/*
95 * Stores a set of predictions and the corresponding actual timestamps pertaining to a single frame
96 * from the app
97 */
98class SurfaceFrame {
99public:
100 enum class PresentState {
101 Presented, // Buffer was latched and presented by SurfaceFlinger
102 Dropped, // Buffer was dropped by SurfaceFlinger
103 Unknown, // Initial state, SurfaceFlinger hasn't seen this buffer yet
104 };
105
106 virtual ~SurfaceFrame() = default;
107
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -0700108 virtual TimelineItem getPredictions() const = 0;
109 virtual TimelineItem getActuals() const = 0;
110 virtual nsecs_t getActualQueueTime() const = 0;
111 virtual PresentState getPresentState() const = 0;
112 virtual PredictionState getPredictionState() const = 0;
Adithya Srinivasan9febda82020-10-19 10:49:41 -0700113 virtual pid_t getOwnerPid() const = 0;
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700114
115 virtual void setPresentState(PresentState state) = 0;
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700116
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700117 // Actual timestamps of the app are set individually at different functions.
118 // Start time (if the app provides) and Queue time are accessible after queueing the frame,
Ady Abraham7f8a1e62020-09-28 16:09:35 -0700119 // whereas Acquire Fence time is available only during latch.
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700120 virtual void setActualStartTime(nsecs_t actualStartTime) = 0;
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700121 virtual void setActualQueueTime(nsecs_t actualQueueTime) = 0;
Ady Abraham7f8a1e62020-09-28 16:09:35 -0700122 virtual void setAcquireFenceTime(nsecs_t acquireFenceTime) = 0;
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700123};
124
125/*
126 * Maintains a history of SurfaceFrames grouped together by the vsync time in which they were
127 * presented
128 */
129class FrameTimeline {
130public:
131 virtual ~FrameTimeline() = default;
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700132 virtual TokenManager* getTokenManager() = 0;
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700133
Adithya Srinivasan01189672020-10-20 14:23:05 -0700134 // Initializes the Perfetto DataSource that emits DisplayFrame and SurfaceFrame events. Test
135 // classes can avoid double registration by mocking this function.
136 virtual void onBootFinished() = 0;
137
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700138 // Create a new surface frame, set the predictions based on a token and return it to the caller.
139 // Sets the PredictionState of SurfaceFrame.
Alec Mouri9a29e672020-09-14 12:39:14 -0700140 // Debug name is the human-readable debugging string for dumpsys.
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700141 virtual std::unique_ptr<SurfaceFrame> createSurfaceFrameForToken(
Adithya Srinivasan9febda82020-10-19 10:49:41 -0700142 pid_t ownerPid, uid_t ownerUid, std::string layerName, std::string debugName,
Alec Mouri9a29e672020-09-14 12:39:14 -0700143 std::optional<int64_t> token) = 0;
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700144
145 // Adds a new SurfaceFrame to the current DisplayFrame. Frames from multiple layers can be
146 // composited into one display frame.
147 virtual void addSurfaceFrame(std::unique_ptr<SurfaceFrame> surfaceFrame,
148 SurfaceFrame::PresentState state) = 0;
149
150 // The first function called by SF for the current DisplayFrame. Fetches SF predictions based on
151 // the token and sets the actualSfWakeTime for the current DisplayFrame.
152 virtual void setSfWakeUp(int64_t token, nsecs_t wakeupTime) = 0;
153
154 // Sets the sfPresentTime and finalizes the current DisplayFrame. Tracks the given present fence
155 // until it's signaled, and updates the present timestamps of all presented SurfaceFrames in
156 // that vsync.
157 virtual void setSfPresent(nsecs_t sfPresentTime,
158 const std::shared_ptr<FenceTime>& presentFence) = 0;
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700159
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -0700160 // Args:
161 // -jank : Dumps only the Display Frames that are either janky themselves
162 // or contain janky Surface Frames.
163 // -all : Dumps the entire list of DisplayFrames and the SurfaceFrames contained within
164 virtual void parseArgs(const Vector<String16>& args, std::string& result) = 0;
Adithya Srinivasan2d736322020-10-01 16:53:48 -0700165
166 // Sets the max number of display frames that can be stored. Called by SF backdoor.
167 virtual void setMaxDisplayFrames(uint32_t size);
168
169 // Restores the max number of display frames to default. Called by SF backdoor.
170 virtual void reset() = 0;
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700171};
172
173namespace impl {
174
175using namespace std::chrono_literals;
176
177class TokenManager : public android::frametimeline::TokenManager {
178public:
Ady Abraham22c7b5c2020-09-22 19:33:40 -0700179 TokenManager() : mCurrentToken(ISurfaceComposer::INVALID_VSYNC_ID + 1) {}
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700180 ~TokenManager() = default;
181
182 int64_t generateTokenForPredictions(TimelineItem&& predictions) override;
183 std::optional<TimelineItem> getPredictionsForToken(int64_t token);
184
185private:
186 // Friend class for testing
187 friend class android::frametimeline::FrameTimelineTest;
188
189 void flushTokens(nsecs_t flushTime) REQUIRES(mMutex);
190
191 std::unordered_map<int64_t, TimelineItem> mPredictions GUARDED_BY(mMutex);
192 std::vector<std::pair<int64_t, nsecs_t>> mTokens GUARDED_BY(mMutex);
193 int64_t mCurrentToken GUARDED_BY(mMutex);
194 std::mutex mMutex;
195 static constexpr nsecs_t kMaxRetentionTime =
196 std::chrono::duration_cast<std::chrono::nanoseconds>(120ms).count();
197};
198
199class SurfaceFrame : public android::frametimeline::SurfaceFrame {
200public:
Adithya Srinivasan01189672020-10-20 14:23:05 -0700201 SurfaceFrame(int64_t token, pid_t ownerPid, uid_t ownerUid, std::string layerName,
202 std::string debugName, PredictionState predictionState,
203 TimelineItem&& predictions);
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700204 ~SurfaceFrame() = default;
205
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -0700206 TimelineItem getPredictions() const override { return mPredictions; };
207 TimelineItem getActuals() const override;
208 nsecs_t getActualQueueTime() const override;
209 PresentState getPresentState() const override;
210 PredictionState getPredictionState() const override { return mPredictionState; };
Adithya Srinivasan9febda82020-10-19 10:49:41 -0700211 pid_t getOwnerPid() const override { return mOwnerPid; };
Jorim Jaggi5814ab82020-12-03 20:45:58 +0100212 JankType getJankType() const;
Adithya Srinivasan01189672020-10-20 14:23:05 -0700213 int64_t getToken() const { return mToken; };
Adithya Srinivasan9febda82020-10-19 10:49:41 -0700214 nsecs_t getBaseTime() const;
215 uid_t getOwnerUid() const { return mOwnerUid; };
216 const std::string& getName() const { return mLayerName; };
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700217
218 void setActualStartTime(nsecs_t actualStartTime) override;
219 void setActualQueueTime(nsecs_t actualQueueTime) override;
Ady Abraham7f8a1e62020-09-28 16:09:35 -0700220 void setAcquireFenceTime(nsecs_t acquireFenceTime) override;
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700221 void setPresentState(PresentState state) override;
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700222 void setActualPresentTime(nsecs_t presentTime);
Jorim Jaggi5814ab82020-12-03 20:45:58 +0100223 void setJankInfo(JankType jankType, int32_t jankMetadata);
Adithya Srinivasan9febda82020-10-19 10:49:41 -0700224
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -0700225 // All the timestamps are dumped relative to the baseTime
226 void dump(std::string& result, const std::string& indent, nsecs_t baseTime);
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700227
Adithya Srinivasan01189672020-10-20 14:23:05 -0700228 // Emits a packet for perfetto tracing. The function body will be executed only if tracing is
229 // enabled. The displayFrameToken is needed to link the SurfaceFrame to the corresponding
230 // DisplayFrame at the trace processor side.
231 void traceSurfaceFrame(int64_t displayFrameToken);
232
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700233private:
Adithya Srinivasan01189672020-10-20 14:23:05 -0700234 const int64_t mToken;
Adithya Srinivasan9febda82020-10-19 10:49:41 -0700235 const pid_t mOwnerPid;
Alec Mouri9a29e672020-09-14 12:39:14 -0700236 const uid_t mOwnerUid;
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700237 const std::string mLayerName;
Alec Mouri9a29e672020-09-14 12:39:14 -0700238 const std::string mDebugName;
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700239 PresentState mPresentState GUARDED_BY(mMutex);
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -0700240 const PredictionState mPredictionState;
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700241 const TimelineItem mPredictions;
242 TimelineItem mActuals GUARDED_BY(mMutex);
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -0700243 nsecs_t mActualQueueTime GUARDED_BY(mMutex);
244 mutable std::mutex mMutex;
Jorim Jaggi5814ab82020-12-03 20:45:58 +0100245 JankType mJankType GUARDED_BY(mMutex); // Enum for the type of jank
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -0700246 int32_t mJankMetadata GUARDED_BY(mMutex); // Additional details about the jank
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700247};
248
249class FrameTimeline : public android::frametimeline::FrameTimeline {
250public:
Adithya Srinivasan01189672020-10-20 14:23:05 -0700251 class FrameTimelineDataSource : public perfetto::DataSource<FrameTimelineDataSource> {
252 void OnSetup(const SetupArgs&) override{};
253 void OnStart(const StartArgs&) override{};
254 void OnStop(const StopArgs&) override{};
255 };
256
Alec Mouri9a29e672020-09-14 12:39:14 -0700257 FrameTimeline(std::shared_ptr<TimeStats> timeStats);
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700258 ~FrameTimeline() = default;
259
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700260 frametimeline::TokenManager* getTokenManager() override { return &mTokenManager; }
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700261 std::unique_ptr<frametimeline::SurfaceFrame> createSurfaceFrameForToken(
Adithya Srinivasan9febda82020-10-19 10:49:41 -0700262 pid_t ownerPid, uid_t ownerUid, std::string layerName, std::string debugName,
Alec Mouri9a29e672020-09-14 12:39:14 -0700263 std::optional<int64_t> token) override;
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700264 void addSurfaceFrame(std::unique_ptr<frametimeline::SurfaceFrame> surfaceFrame,
265 SurfaceFrame::PresentState state) override;
266 void setSfWakeUp(int64_t token, nsecs_t wakeupTime) override;
267 void setSfPresent(nsecs_t sfPresentTime,
268 const std::shared_ptr<FenceTime>& presentFence) override;
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -0700269 void parseArgs(const Vector<String16>& args, std::string& result) override;
Adithya Srinivasan2d736322020-10-01 16:53:48 -0700270 void setMaxDisplayFrames(uint32_t size) override;
271 void reset() override;
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700272
Adithya Srinivasan01189672020-10-20 14:23:05 -0700273 // Sets up the perfetto tracing backend and data source.
274 void onBootFinished() override;
275 // Registers the data source with the perfetto backend. Called as part of onBootFinished()
276 // and should not be called manually outside of tests.
277 void registerDataSource();
278
279 static constexpr char kFrameTimelineDataSource[] = "android.surfaceflinger.frametimeline";
280
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700281private:
282 // Friend class for testing
283 friend class android::frametimeline::FrameTimelineTest;
284
285 /*
286 * DisplayFrame should be used only internally within FrameTimeline.
287 */
288 struct DisplayFrame {
289 DisplayFrame();
290
Adithya Srinivasan01189672020-10-20 14:23:05 -0700291 int64_t token = ISurfaceComposer::INVALID_VSYNC_ID;
292
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700293 /* Usage of TimelineItem w.r.t SurfaceFlinger
294 * startTime Time when SurfaceFlinger wakes up to handle transactions and buffer updates
295 * endTime Time when SurfaceFlinger sends a composited frame to Display
296 * presentTime Time when the composited frame was presented on screen
297 */
298 TimelineItem surfaceFlingerPredictions;
299 TimelineItem surfaceFlingerActuals;
300
301 // Collection of predictions and actual values sent over by Layers
302 std::vector<std::unique_ptr<SurfaceFrame>> surfaceFrames;
303
Adithya Srinivasan01189672020-10-20 14:23:05 -0700304 PredictionState predictionState = PredictionState::None;
Jorim Jaggi5814ab82020-12-03 20:45:58 +0100305 JankType jankType = JankType::None; // Enum for the type of jank
Adithya Srinivasan01189672020-10-20 14:23:05 -0700306 int32_t jankMetadata = 0x0; // Additional details about the jank
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700307 };
308
309 void flushPendingPresentFences() REQUIRES(mMutex);
310 void finalizeCurrentDisplayFrame() REQUIRES(mMutex);
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -0700311 // BaseTime is the smallest timestamp in a DisplayFrame.
312 // Used for dumping all timestamps relative to the oldest, making it easy to read.
313 nsecs_t findBaseTime(const std::shared_ptr<DisplayFrame>&) REQUIRES(mMutex);
314 void dumpDisplayFrame(std::string& result, const std::shared_ptr<DisplayFrame>&,
315 nsecs_t baseTime) REQUIRES(mMutex);
316 void dumpAll(std::string& result);
317 void dumpJank(std::string& result);
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700318
Adithya Srinivasan01189672020-10-20 14:23:05 -0700319 // Emits a packet for perfetto tracing. The function body will be executed only if tracing is
320 // enabled.
321 void traceDisplayFrame(const DisplayFrame& displayFrame) REQUIRES(mMutex);
322
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700323 // Sliding window of display frames. TODO(b/168072834): compare perf with fixed size array
324 std::deque<std::shared_ptr<DisplayFrame>> mDisplayFrames GUARDED_BY(mMutex);
325 std::vector<std::pair<std::shared_ptr<FenceTime>, std::shared_ptr<DisplayFrame>>>
326 mPendingPresentFences GUARDED_BY(mMutex);
327 std::shared_ptr<DisplayFrame> mCurrentDisplayFrame GUARDED_BY(mMutex);
328 TokenManager mTokenManager;
329 std::mutex mMutex;
Adithya Srinivasan2d736322020-10-01 16:53:48 -0700330 uint32_t mMaxDisplayFrames;
Alec Mouri9a29e672020-09-14 12:39:14 -0700331 std::shared_ptr<TimeStats> mTimeStats;
Adithya Srinivasan2d736322020-10-01 16:53:48 -0700332 static constexpr uint32_t kDefaultMaxDisplayFrames = 64;
Adithya Srinivasan01189672020-10-20 14:23:05 -0700333 // The initial container size for the vector<SurfaceFrames> inside display frame. Although
334 // this number doesn't represent any bounds on the number of surface frames that can go in a
335 // display frame, this is a good starting size for the vector so that we can avoid the
336 // internal vector resizing that happens with push_back.
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700337 static constexpr uint32_t kNumSurfaceFramesInitial = 10;
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -0700338 // The various thresholds for App and SF. If the actual timestamp falls within the threshold
339 // compared to prediction, we don't treat it as a jank.
340 static constexpr nsecs_t kPresentThreshold =
341 std::chrono::duration_cast<std::chrono::nanoseconds>(2ms).count();
342 static constexpr nsecs_t kDeadlineThreshold =
343 std::chrono::duration_cast<std::chrono::nanoseconds>(2ms).count();
344 static constexpr nsecs_t kSFStartThreshold =
345 std::chrono::duration_cast<std::chrono::nanoseconds>(1ms).count();
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700346};
347
348} // namespace impl
349} // namespace android::frametimeline