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