blob: 9b03287242ad826ca3b259e9820e02c5d2a62fc7 [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#undef LOG_TAG
18#define LOG_TAG "FrameTimeline"
19#define ATRACE_TAG ATRACE_TAG_GRAPHICS
20
21#include "FrameTimeline.h"
Alec Mouriadebf5c2021-01-05 12:57:36 -080022
Adithya Srinivasanf279e042020-08-17 14:56:27 -070023#include <android-base/stringprintf.h>
Ady Abraham7f8a1e62020-09-28 16:09:35 -070024#include <utils/Log.h>
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -070025#include <utils/Trace.h>
Alec Mouriadebf5c2021-01-05 12:57:36 -080026
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -070027#include <chrono>
Adithya Srinivasanf279e042020-08-17 14:56:27 -070028#include <cinttypes>
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -070029#include <numeric>
Alec Mouriadebf5c2021-01-05 12:57:36 -080030#include <unordered_set>
Adithya Srinivasanf279e042020-08-17 14:56:27 -070031
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -080032namespace android::frametimeline {
Adithya Srinivasanf279e042020-08-17 14:56:27 -070033
34using base::StringAppendF;
Adithya Srinivasan01189672020-10-20 14:23:05 -070035using FrameTimelineEvent = perfetto::protos::pbzero::FrameTimelineEvent;
Adithya Srinivasan061c14c2021-02-11 01:19:47 +000036using FrameTimelineDataSource = impl::FrameTimeline::FrameTimelineDataSource;
Adithya Srinivasanf279e042020-08-17 14:56:27 -070037
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -070038void dumpTable(std::string& result, TimelineItem predictions, TimelineItem actuals,
39 const std::string& indent, PredictionState predictionState, nsecs_t baseTime) {
40 StringAppendF(&result, "%s", indent.c_str());
41 StringAppendF(&result, "\t\t");
42 StringAppendF(&result, " Start time\t\t|");
43 StringAppendF(&result, " End time\t\t|");
44 StringAppendF(&result, " Present time\n");
45 if (predictionState == PredictionState::Valid) {
46 // Dump the Predictions only if they are valid
47 StringAppendF(&result, "%s", indent.c_str());
48 StringAppendF(&result, "Expected\t|");
49 std::chrono::nanoseconds startTime(predictions.startTime - baseTime);
50 std::chrono::nanoseconds endTime(predictions.endTime - baseTime);
51 std::chrono::nanoseconds presentTime(predictions.presentTime - baseTime);
52 StringAppendF(&result, "\t%10.2f\t|\t%10.2f\t|\t%10.2f\n",
53 std::chrono::duration<double, std::milli>(startTime).count(),
54 std::chrono::duration<double, std::milli>(endTime).count(),
55 std::chrono::duration<double, std::milli>(presentTime).count());
56 }
57 StringAppendF(&result, "%s", indent.c_str());
58 StringAppendF(&result, "Actual \t|");
59
60 if (actuals.startTime == 0) {
61 StringAppendF(&result, "\t\tN/A\t|");
62 } else {
63 std::chrono::nanoseconds startTime(std::max<nsecs_t>(0, actuals.startTime - baseTime));
64 StringAppendF(&result, "\t%10.2f\t|",
65 std::chrono::duration<double, std::milli>(startTime).count());
66 }
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -080067 if (actuals.endTime <= 0) {
68 // Animation leashes can send the endTime as -1
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -070069 StringAppendF(&result, "\t\tN/A\t|");
70 } else {
71 std::chrono::nanoseconds endTime(actuals.endTime - baseTime);
72 StringAppendF(&result, "\t%10.2f\t|",
73 std::chrono::duration<double, std::milli>(endTime).count());
74 }
75 if (actuals.presentTime == 0) {
76 StringAppendF(&result, "\t\tN/A\n");
77 } else {
78 std::chrono::nanoseconds presentTime(std::max<nsecs_t>(0, actuals.presentTime - baseTime));
79 StringAppendF(&result, "\t%10.2f\n",
80 std::chrono::duration<double, std::milli>(presentTime).count());
81 }
82
83 StringAppendF(&result, "%s", indent.c_str());
84 StringAppendF(&result, "----------------------");
85 StringAppendF(&result, "----------------------");
86 StringAppendF(&result, "----------------------");
87 StringAppendF(&result, "----------------------\n");
88}
89
90std::string toString(PredictionState predictionState) {
91 switch (predictionState) {
92 case PredictionState::Valid:
93 return "Valid";
94 case PredictionState::Expired:
95 return "Expired";
96 case PredictionState::None:
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -070097 return "None";
98 }
99}
100
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800101std::string jankTypeBitmaskToString(int32_t jankType) {
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800102 if (jankType == JankType::None) {
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -0700103 return "None";
104 }
Adithya Srinivasan552e2a72021-01-15 03:21:53 +0000105
106 std::vector<std::string> janks;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800107 if (jankType & JankType::DisplayHAL) {
108 janks.emplace_back("Display HAL");
Adithya Srinivasan552e2a72021-01-15 03:21:53 +0000109 jankType &= ~JankType::DisplayHAL;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800110 }
111 if (jankType & JankType::SurfaceFlingerCpuDeadlineMissed) {
112 janks.emplace_back("SurfaceFlinger CPU Deadline Missed");
Adithya Srinivasan552e2a72021-01-15 03:21:53 +0000113 jankType &= ~JankType::SurfaceFlingerCpuDeadlineMissed;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800114 }
115 if (jankType & JankType::SurfaceFlingerGpuDeadlineMissed) {
116 janks.emplace_back("SurfaceFlinger GPU Deadline Missed");
Adithya Srinivasan552e2a72021-01-15 03:21:53 +0000117 jankType &= ~JankType::SurfaceFlingerGpuDeadlineMissed;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800118 }
119 if (jankType & JankType::AppDeadlineMissed) {
120 janks.emplace_back("App Deadline Missed");
Adithya Srinivasan552e2a72021-01-15 03:21:53 +0000121 jankType &= ~JankType::AppDeadlineMissed;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800122 }
123 if (jankType & JankType::PredictionError) {
124 janks.emplace_back("Prediction Error");
Adithya Srinivasan552e2a72021-01-15 03:21:53 +0000125 jankType &= ~JankType::PredictionError;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800126 }
127 if (jankType & JankType::SurfaceFlingerScheduling) {
128 janks.emplace_back("SurfaceFlinger Scheduling");
Adithya Srinivasan552e2a72021-01-15 03:21:53 +0000129 jankType &= ~JankType::SurfaceFlingerScheduling;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800130 }
131 if (jankType & JankType::BufferStuffing) {
132 janks.emplace_back("Buffer Stuffing");
Adithya Srinivasan552e2a72021-01-15 03:21:53 +0000133 jankType &= ~JankType::BufferStuffing;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800134 }
135 if (jankType & JankType::Unknown) {
136 janks.emplace_back("Unknown jank");
Adithya Srinivasan552e2a72021-01-15 03:21:53 +0000137 jankType &= ~JankType::Unknown;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800138 }
Adithya Srinivasan2045ddf2021-05-27 17:38:10 +0000139 if (jankType & JankType::SurfaceFlingerStuffing) {
140 janks.emplace_back("SurfaceFlinger Stuffing");
141 jankType &= ~JankType::SurfaceFlingerStuffing;
142 }
Adithya Srinivasan552e2a72021-01-15 03:21:53 +0000143
144 // jankType should be 0 if all types of jank were checked for.
145 LOG_ALWAYS_FATAL_IF(jankType != 0, "Unrecognized jank type value 0x%x", jankType);
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800146 return std::accumulate(janks.begin(), janks.end(), std::string(),
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -0700147 [](const std::string& l, const std::string& r) {
148 return l.empty() ? r : l + ", " + r;
149 });
150}
151
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800152std::string toString(FramePresentMetadata presentMetadata) {
153 switch (presentMetadata) {
154 case FramePresentMetadata::OnTimePresent:
155 return "On Time Present";
156 case FramePresentMetadata::LatePresent:
157 return "Late Present";
158 case FramePresentMetadata::EarlyPresent:
159 return "Early Present";
160 case FramePresentMetadata::UnknownPresent:
161 return "Unknown Present";
Adithya Srinivasan01189672020-10-20 14:23:05 -0700162 }
Adithya Srinivasan01189672020-10-20 14:23:05 -0700163}
164
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800165std::string toString(FrameReadyMetadata finishMetadata) {
166 switch (finishMetadata) {
167 case FrameReadyMetadata::OnTimeFinish:
168 return "On Time Finish";
169 case FrameReadyMetadata::LateFinish:
170 return "Late Finish";
171 case FrameReadyMetadata::UnknownFinish:
172 return "Unknown Finish";
173 }
174}
175
176std::string toString(FrameStartMetadata startMetadata) {
177 switch (startMetadata) {
178 case FrameStartMetadata::OnTimeStart:
179 return "On Time Start";
180 case FrameStartMetadata::LateStart:
181 return "Late Start";
182 case FrameStartMetadata::EarlyStart:
183 return "Early Start";
184 case FrameStartMetadata::UnknownStart:
185 return "Unknown Start";
186 }
187}
188
189std::string toString(SurfaceFrame::PresentState presentState) {
190 using PresentState = SurfaceFrame::PresentState;
191 switch (presentState) {
192 case PresentState::Presented:
193 return "Presented";
194 case PresentState::Dropped:
195 return "Dropped";
196 case PresentState::Unknown:
197 return "Unknown";
198 }
199}
200
201FrameTimelineEvent::PresentType toProto(FramePresentMetadata presentMetadata) {
202 switch (presentMetadata) {
203 case FramePresentMetadata::EarlyPresent:
204 return FrameTimelineEvent::PRESENT_EARLY;
205 case FramePresentMetadata::LatePresent:
206 return FrameTimelineEvent::PRESENT_LATE;
207 case FramePresentMetadata::OnTimePresent:
208 return FrameTimelineEvent::PRESENT_ON_TIME;
209 case FramePresentMetadata::UnknownPresent:
210 return FrameTimelineEvent::PRESENT_UNSPECIFIED;
211 }
212}
213
Adithya Srinivasan78e58af2021-02-25 00:08:08 +0000214FrameTimelineEvent::PredictionType toProto(PredictionState predictionState) {
215 switch (predictionState) {
216 case PredictionState::Valid:
217 return FrameTimelineEvent::PREDICTION_VALID;
218 case PredictionState::Expired:
219 return FrameTimelineEvent::PREDICTION_EXPIRED;
220 case PredictionState::None:
221 return FrameTimelineEvent::PREDICTION_UNKNOWN;
222 }
223}
224
Adithya Srinivasan552e2a72021-01-15 03:21:53 +0000225int32_t jankTypeBitmaskToProto(int32_t jankType) {
226 if (jankType == JankType::None) {
227 return FrameTimelineEvent::JANK_NONE;
Adithya Srinivasan01189672020-10-20 14:23:05 -0700228 }
Adithya Srinivasan552e2a72021-01-15 03:21:53 +0000229
230 int32_t protoJank = 0;
231 if (jankType & JankType::DisplayHAL) {
232 protoJank |= FrameTimelineEvent::JANK_DISPLAY_HAL;
233 jankType &= ~JankType::DisplayHAL;
234 }
235 if (jankType & JankType::SurfaceFlingerCpuDeadlineMissed) {
236 protoJank |= FrameTimelineEvent::JANK_SF_CPU_DEADLINE_MISSED;
237 jankType &= ~JankType::SurfaceFlingerCpuDeadlineMissed;
238 }
239 if (jankType & JankType::SurfaceFlingerGpuDeadlineMissed) {
240 protoJank |= FrameTimelineEvent::JANK_SF_GPU_DEADLINE_MISSED;
241 jankType &= ~JankType::SurfaceFlingerGpuDeadlineMissed;
242 }
243 if (jankType & JankType::AppDeadlineMissed) {
244 protoJank |= FrameTimelineEvent::JANK_APP_DEADLINE_MISSED;
245 jankType &= ~JankType::AppDeadlineMissed;
246 }
247 if (jankType & JankType::PredictionError) {
248 protoJank |= FrameTimelineEvent::JANK_PREDICTION_ERROR;
249 jankType &= ~JankType::PredictionError;
250 }
251 if (jankType & JankType::SurfaceFlingerScheduling) {
252 protoJank |= FrameTimelineEvent::JANK_SF_SCHEDULING;
253 jankType &= ~JankType::SurfaceFlingerScheduling;
254 }
255 if (jankType & JankType::BufferStuffing) {
256 protoJank |= FrameTimelineEvent::JANK_BUFFER_STUFFING;
257 jankType &= ~JankType::BufferStuffing;
258 }
259 if (jankType & JankType::Unknown) {
260 protoJank |= FrameTimelineEvent::JANK_UNKNOWN;
261 jankType &= ~JankType::Unknown;
262 }
Adithya Srinivasan57dc81d2021-04-14 17:31:41 +0000263 if (jankType & JankType::SurfaceFlingerStuffing) {
264 protoJank |= FrameTimelineEvent::JANK_SF_STUFFING;
265 jankType &= ~JankType::SurfaceFlingerStuffing;
266 }
Adithya Srinivasan552e2a72021-01-15 03:21:53 +0000267
268 // jankType should be 0 if all types of jank were checked for.
269 LOG_ALWAYS_FATAL_IF(jankType != 0, "Unrecognized jank type value 0x%x", jankType);
270 return protoJank;
Adithya Srinivasan01189672020-10-20 14:23:05 -0700271}
272
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800273// Returns the smallest timestamp from the set of predictions and actuals.
274nsecs_t getMinTime(PredictionState predictionState, TimelineItem predictions,
275 TimelineItem actuals) {
276 nsecs_t minTime = std::numeric_limits<nsecs_t>::max();
277 if (predictionState == PredictionState::Valid) {
278 // Checking start time for predictions is enough because start time is always lesser than
279 // endTime and presentTime.
280 minTime = std::min(minTime, predictions.startTime);
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700281 }
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700282
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800283 // Need to check startTime, endTime and presentTime for actuals because some frames might not
284 // have them set.
285 if (actuals.startTime != 0) {
286 minTime = std::min(minTime, actuals.startTime);
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700287 }
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800288 if (actuals.endTime != 0) {
289 minTime = std::min(minTime, actuals.endTime);
290 }
291 if (actuals.presentTime != 0) {
292 minTime = std::min(minTime, actuals.endTime);
293 }
294 return minTime;
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700295}
296
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +0000297int64_t TraceCookieCounter::getCookieForTracing() {
298 return ++mTraceCookie;
299}
300
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000301SurfaceFrame::SurfaceFrame(const FrameTimelineInfo& frameTimelineInfo, pid_t ownerPid,
Alec Mouriadebf5c2021-01-05 12:57:36 -0800302 uid_t ownerUid, int32_t layerId, std::string layerName,
303 std::string debugName, PredictionState predictionState,
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800304 frametimeline::TimelineItem&& predictions,
305 std::shared_ptr<TimeStats> timeStats,
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +0000306 JankClassificationThresholds thresholds,
Adithya Srinivasan785addd2021-03-09 00:38:00 +0000307 TraceCookieCounter* traceCookieCounter, bool isBuffer)
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000308 : mToken(frameTimelineInfo.vsyncId),
309 mInputEventId(frameTimelineInfo.inputEventId),
Adithya Srinivasan01189672020-10-20 14:23:05 -0700310 mOwnerPid(ownerPid),
Adithya Srinivasan9febda82020-10-19 10:49:41 -0700311 mOwnerUid(ownerUid),
Alec Mouri9a29e672020-09-14 12:39:14 -0700312 mLayerName(std::move(layerName)),
313 mDebugName(std::move(debugName)),
Alec Mouriadebf5c2021-01-05 12:57:36 -0800314 mLayerId(layerId),
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700315 mPresentState(PresentState::Unknown),
316 mPredictionState(predictionState),
317 mPredictions(predictions),
318 mActuals({0, 0, 0}),
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800319 mTimeStats(timeStats),
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +0000320 mJankClassificationThresholds(thresholds),
Adithya Srinivasan785addd2021-03-09 00:38:00 +0000321 mTraceCookieCounter(*traceCookieCounter),
322 mIsBuffer(isBuffer) {}
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700323
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700324void SurfaceFrame::setActualStartTime(nsecs_t actualStartTime) {
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000325 std::scoped_lock lock(mMutex);
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700326 mActuals.startTime = actualStartTime;
327}
328
329void SurfaceFrame::setActualQueueTime(nsecs_t actualQueueTime) {
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000330 std::scoped_lock lock(mMutex);
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700331 mActualQueueTime = actualQueueTime;
332}
Adithya Srinivasan061c14c2021-02-11 01:19:47 +0000333
Ady Abraham7f8a1e62020-09-28 16:09:35 -0700334void SurfaceFrame::setAcquireFenceTime(nsecs_t acquireFenceTime) {
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000335 std::scoped_lock lock(mMutex);
Ady Abraham7f8a1e62020-09-28 16:09:35 -0700336 mActuals.endTime = std::max(acquireFenceTime, mActualQueueTime);
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700337}
338
Adithya Srinivasan061c14c2021-02-11 01:19:47 +0000339void SurfaceFrame::setDropTime(nsecs_t dropTime) {
340 std::scoped_lock lock(mMutex);
341 mDropTime = dropTime;
342}
343
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800344void SurfaceFrame::setPresentState(PresentState presentState, nsecs_t lastLatchTime) {
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000345 std::scoped_lock lock(mMutex);
Adithya Srinivasanb9a7dab2021-01-14 23:49:46 +0000346 LOG_ALWAYS_FATAL_IF(mPresentState != PresentState::Unknown,
347 "setPresentState called on a SurfaceFrame from Layer - %s, that has a "
348 "PresentState - %s set already.",
349 mDebugName.c_str(), toString(mPresentState).c_str());
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800350 mPresentState = presentState;
351 mLastLatchTime = lastLatchTime;
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700352}
353
Alec Mouri7d436ec2021-01-27 20:40:50 -0800354void SurfaceFrame::setRenderRate(Fps renderRate) {
355 std::lock_guard<std::mutex> lock(mMutex);
356 mRenderRate = renderRate;
357}
358
Adithya Srinivasanb6a2fa12021-03-13 00:23:09 +0000359void SurfaceFrame::setGpuComposition() {
360 std::scoped_lock lock(mMutex);
361 mGpuComposition = true;
362}
363
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800364std::optional<int32_t> SurfaceFrame::getJankType() const {
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000365 std::scoped_lock lock(mMutex);
Adithya Srinivasan95619432021-02-08 21:52:51 +0000366 if (mPresentState == PresentState::Dropped) {
367 // Return no jank if it's a dropped frame since we cannot attribute a jank to a it.
368 return JankType::None;
369 }
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100370 if (mActuals.presentTime == 0) {
Adithya Srinivasan95619432021-02-08 21:52:51 +0000371 // Frame hasn't been presented yet.
Jorim Jaggi9c03b502020-11-24 23:51:31 +0100372 return std::nullopt;
373 }
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -0700374 return mJankType;
375}
376
377nsecs_t SurfaceFrame::getBaseTime() const {
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000378 std::scoped_lock lock(mMutex);
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800379 return getMinTime(mPredictionState, mPredictions, mActuals);
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -0700380}
381
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800382TimelineItem SurfaceFrame::getActuals() const {
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000383 std::scoped_lock lock(mMutex);
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800384 return mActuals;
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -0700385}
386
Adithya Srinivasan061c14c2021-02-11 01:19:47 +0000387PredictionState SurfaceFrame::getPredictionState() const {
388 std::scoped_lock lock(mMutex);
389 return mPredictionState;
390}
391
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800392SurfaceFrame::PresentState SurfaceFrame::getPresentState() const {
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000393 std::scoped_lock lock(mMutex);
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800394 return mPresentState;
395}
396
397FramePresentMetadata SurfaceFrame::getFramePresentMetadata() const {
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000398 std::scoped_lock lock(mMutex);
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800399 return mFramePresentMetadata;
400}
401
402FrameReadyMetadata SurfaceFrame::getFrameReadyMetadata() const {
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000403 std::scoped_lock lock(mMutex);
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800404 return mFrameReadyMetadata;
405}
406
Adithya Srinivasan061c14c2021-02-11 01:19:47 +0000407nsecs_t SurfaceFrame::getDropTime() const {
408 std::scoped_lock lock(mMutex);
409 return mDropTime;
410}
411
Adithya Srinivasan785addd2021-03-09 00:38:00 +0000412void SurfaceFrame::promoteToBuffer() {
413 std::scoped_lock lock(mMutex);
414 LOG_ALWAYS_FATAL_IF(mIsBuffer == true,
415 "Trying to promote an already promoted BufferSurfaceFrame from layer %s "
416 "with token %" PRId64 "",
417 mDebugName.c_str(), mToken);
418 mIsBuffer = true;
419}
420
421bool SurfaceFrame::getIsBuffer() const {
422 std::scoped_lock lock(mMutex);
423 return mIsBuffer;
424}
425
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800426void SurfaceFrame::dump(std::string& result, const std::string& indent, nsecs_t baseTime) const {
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000427 std::scoped_lock lock(mMutex);
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -0700428 StringAppendF(&result, "%s", indent.c_str());
Alec Mouri9a29e672020-09-14 12:39:14 -0700429 StringAppendF(&result, "Layer - %s", mDebugName.c_str());
Jorim Jaggi5814ab82020-12-03 20:45:58 +0100430 if (mJankType != JankType::None) {
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -0700431 // Easily identify a janky Surface Frame in the dump
432 StringAppendF(&result, " [*] ");
433 }
434 StringAppendF(&result, "\n");
435 StringAppendF(&result, "%s", indent.c_str());
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800436 StringAppendF(&result, "Token: %" PRId64 "\n", mToken);
437 StringAppendF(&result, "%s", indent.c_str());
Adithya Srinivasan785addd2021-03-09 00:38:00 +0000438 StringAppendF(&result, "Is Buffer?: %d\n", mIsBuffer);
439 StringAppendF(&result, "%s", indent.c_str());
Adithya Srinivasan9febda82020-10-19 10:49:41 -0700440 StringAppendF(&result, "Owner Pid : %d\n", mOwnerPid);
441 StringAppendF(&result, "%s", indent.c_str());
Alec Mouri7d436ec2021-01-27 20:40:50 -0800442 StringAppendF(&result, "Scheduled rendering rate: %d fps\n",
443 mRenderRate ? mRenderRate->getIntValue() : 0);
444 StringAppendF(&result, "%s", indent.c_str());
Alec Mouriadebf5c2021-01-05 12:57:36 -0800445 StringAppendF(&result, "Layer ID : %d\n", mLayerId);
446 StringAppendF(&result, "%s", indent.c_str());
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800447 StringAppendF(&result, "Present State : %s\n", toString(mPresentState).c_str());
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -0700448 StringAppendF(&result, "%s", indent.c_str());
Adithya Srinivasan061c14c2021-02-11 01:19:47 +0000449 if (mPresentState == PresentState::Dropped) {
450 std::chrono::nanoseconds dropTime(mDropTime - baseTime);
451 StringAppendF(&result, "Drop time : %10f\n",
452 std::chrono::duration<double, std::milli>(dropTime).count());
453 StringAppendF(&result, "%s", indent.c_str());
454 }
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -0700455 StringAppendF(&result, "Prediction State : %s\n", toString(mPredictionState).c_str());
456 StringAppendF(&result, "%s", indent.c_str());
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800457 StringAppendF(&result, "Jank Type : %s\n", jankTypeBitmaskToString(mJankType).c_str());
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -0700458 StringAppendF(&result, "%s", indent.c_str());
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800459 StringAppendF(&result, "Present Metadata : %s\n", toString(mFramePresentMetadata).c_str());
460 StringAppendF(&result, "%s", indent.c_str());
461 StringAppendF(&result, "Finish Metadata: %s\n", toString(mFrameReadyMetadata).c_str());
462 std::chrono::nanoseconds latchTime(
463 std::max(static_cast<int64_t>(0), mLastLatchTime - baseTime));
464 StringAppendF(&result, "%s", indent.c_str());
465 StringAppendF(&result, "Last latch time: %10f\n",
466 std::chrono::duration<double, std::milli>(latchTime).count());
467 if (mPredictionState == PredictionState::Valid) {
468 nsecs_t presentDelta = mActuals.presentTime - mPredictions.presentTime;
469 std::chrono::nanoseconds presentDeltaNs(std::abs(presentDelta));
470 StringAppendF(&result, "%s", indent.c_str());
471 StringAppendF(&result, "Present delta: %10f\n",
472 std::chrono::duration<double, std::milli>(presentDeltaNs).count());
473 }
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -0700474 dumpTable(result, mPredictions, mActuals, indent, mPredictionState, baseTime);
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700475}
476
Adithya Srinivasan785addd2021-03-09 00:38:00 +0000477std::string SurfaceFrame::miniDump() const {
478 std::scoped_lock lock(mMutex);
479 std::string result;
480 StringAppendF(&result, "Layer - %s\n", mDebugName.c_str());
481 StringAppendF(&result, "Token: %" PRId64 "\n", mToken);
482 StringAppendF(&result, "Is Buffer?: %d\n", mIsBuffer);
483 StringAppendF(&result, "Present State : %s\n", toString(mPresentState).c_str());
484 StringAppendF(&result, "Prediction State : %s\n", toString(mPredictionState).c_str());
485 StringAppendF(&result, "Jank Type : %s\n", jankTypeBitmaskToString(mJankType).c_str());
486 StringAppendF(&result, "Present Metadata : %s\n", toString(mFramePresentMetadata).c_str());
487 StringAppendF(&result, "Finish Metadata: %s\n", toString(mFrameReadyMetadata).c_str());
488 StringAppendF(&result, "Present time: %" PRId64 "", mActuals.presentTime);
489 return result;
490}
491
Adithya Srinivasan7c4ac7a2021-03-08 23:48:03 +0000492void SurfaceFrame::classifyJankLocked(int32_t displayFrameJankType, const Fps& refreshRate,
493 nsecs_t& deadlineDelta) {
494 if (mPredictionState == PredictionState::Expired ||
495 mActuals.presentTime == Fence::SIGNAL_TIME_INVALID) {
496 // Cannot do any classification for invalid present time.
497 // For prediction expired case, we do not know what happened here to classify this
498 // correctly. This could potentially be AppDeadlineMissed but that's assuming no app will
499 // request frames 120ms apart.
500 mJankType = JankType::Unknown;
501 deadlineDelta = -1;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800502 return;
503 }
504
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800505 if (mPredictionState == PredictionState::None) {
506 // Cannot do jank classification on frames that don't have a token.
507 return;
508 }
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800509
Adithya Srinivasan7c4ac7a2021-03-08 23:48:03 +0000510 deadlineDelta = mActuals.endTime - mPredictions.endTime;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800511 const nsecs_t presentDelta = mActuals.presentTime - mPredictions.presentTime;
Alec Mouriadebf5c2021-01-05 12:57:36 -0800512 const nsecs_t deltaToVsync = refreshRate.getPeriodNsecs() > 0
513 ? std::abs(presentDelta) % refreshRate.getPeriodNsecs()
514 : 0;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800515
516 if (deadlineDelta > mJankClassificationThresholds.deadlineThreshold) {
517 mFrameReadyMetadata = FrameReadyMetadata::LateFinish;
518 } else {
519 mFrameReadyMetadata = FrameReadyMetadata::OnTimeFinish;
520 }
521
522 if (std::abs(presentDelta) > mJankClassificationThresholds.presentThreshold) {
523 mFramePresentMetadata = presentDelta > 0 ? FramePresentMetadata::LatePresent
524 : FramePresentMetadata::EarlyPresent;
525 } else {
526 mFramePresentMetadata = FramePresentMetadata::OnTimePresent;
527 }
528
529 if (mFramePresentMetadata == FramePresentMetadata::OnTimePresent) {
530 // Frames presented on time are not janky.
531 mJankType = JankType::None;
532 } else if (mFramePresentMetadata == FramePresentMetadata::EarlyPresent) {
533 if (mFrameReadyMetadata == FrameReadyMetadata::OnTimeFinish) {
534 // Finish on time, Present early
535 if (deltaToVsync < mJankClassificationThresholds.presentThreshold ||
Alec Mouri7d436ec2021-01-27 20:40:50 -0800536 deltaToVsync >= refreshRate.getPeriodNsecs() -
537 mJankClassificationThresholds.presentThreshold) {
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800538 // Delta factor of vsync
539 mJankType = JankType::SurfaceFlingerScheduling;
540 } else {
541 // Delta not a factor of vsync
542 mJankType = JankType::PredictionError;
543 }
544 } else if (mFrameReadyMetadata == FrameReadyMetadata::LateFinish) {
545 // Finish late, Present early
546 mJankType = JankType::Unknown;
547 }
548 } else {
549 if (mLastLatchTime != 0 && mPredictions.endTime <= mLastLatchTime) {
550 // Buffer Stuffing.
551 mJankType |= JankType::BufferStuffing;
Adithya Srinivasan939cd4d2021-02-23 06:18:13 +0000552 // In a stuffed state, the frame could be stuck on a dequeue wait for quite some time.
553 // Because of this dequeue wait, it can be hard to tell if a frame was genuinely late.
554 // We try to do this by moving the deadline. Since the queue could be stuffed by more
555 // than one buffer, we take the last latch time as reference and give one vsync
556 // worth of time for the frame to be ready.
557 nsecs_t adjustedDeadline = mLastLatchTime + refreshRate.getPeriodNsecs();
558 if (adjustedDeadline > mActuals.endTime) {
559 mFrameReadyMetadata = FrameReadyMetadata::OnTimeFinish;
560 } else {
561 mFrameReadyMetadata = FrameReadyMetadata::LateFinish;
562 }
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800563 }
564 if (mFrameReadyMetadata == FrameReadyMetadata::OnTimeFinish) {
565 // Finish on time, Present late
566 if (displayFrameJankType != JankType::None) {
567 // Propagate displayFrame's jank if it exists
568 mJankType |= displayFrameJankType;
569 } else {
Adithya Srinivasan939cd4d2021-02-23 06:18:13 +0000570 if (!(mJankType & JankType::BufferStuffing)) {
571 // In a stuffed state, if the app finishes on time and there is no display frame
572 // jank, only buffer stuffing is the root cause of the jank.
573 if (deltaToVsync < mJankClassificationThresholds.presentThreshold ||
574 deltaToVsync >= refreshRate.getPeriodNsecs() -
575 mJankClassificationThresholds.presentThreshold) {
576 // Delta factor of vsync
577 mJankType |= JankType::SurfaceFlingerScheduling;
578 } else {
579 // Delta not a factor of vsync
580 mJankType |= JankType::PredictionError;
581 }
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800582 }
583 }
584 } else if (mFrameReadyMetadata == FrameReadyMetadata::LateFinish) {
585 // Finish late, Present late
Adithya Srinivasan8a945502021-03-19 19:12:32 +0000586 mJankType |= JankType::AppDeadlineMissed;
587 // Propagate DisplayFrame's jankType if it is janky
588 mJankType |= displayFrameJankType;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800589 }
590 }
Adithya Srinivasan7c4ac7a2021-03-08 23:48:03 +0000591}
592
593void SurfaceFrame::onPresent(nsecs_t presentTime, int32_t displayFrameJankType, Fps refreshRate,
594 nsecs_t displayDeadlineDelta, nsecs_t displayPresentDelta) {
595 std::scoped_lock lock(mMutex);
596
597 if (mPresentState != PresentState::Presented) {
598 // No need to update dropped buffers
599 return;
600 }
601
602 mActuals.presentTime = presentTime;
603 nsecs_t deadlineDelta = 0;
604
605 classifyJankLocked(displayFrameJankType, refreshRate, deadlineDelta);
606
607 if (mPredictionState != PredictionState::None) {
608 // Only update janky frames if the app used vsync predictions
609 mTimeStats->incrementJankyFrames({refreshRate, mRenderRate, mOwnerUid, mLayerName,
610 mJankType, displayDeadlineDelta, displayPresentDelta,
611 deadlineDelta});
612 }
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800613}
614
Adithya Srinivasan061c14c2021-02-11 01:19:47 +0000615void SurfaceFrame::tracePredictions(int64_t displayFrameToken) const {
Adithya Srinivasan86678502021-01-19 21:50:38 +0000616 int64_t expectedTimelineCookie = mTraceCookieCounter.getCookieForTracing();
Adithya Srinivasan061c14c2021-02-11 01:19:47 +0000617
Adithya Srinivasan86678502021-01-19 21:50:38 +0000618 // Expected timeline start
619 FrameTimelineDataSource::Trace([&](FrameTimelineDataSource::TraceContext ctx) {
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000620 std::scoped_lock lock(mMutex);
Adithya Srinivasan01189672020-10-20 14:23:05 -0700621 auto packet = ctx.NewTracePacket();
622 packet->set_timestamp_clock_id(perfetto::protos::pbzero::BUILTIN_CLOCK_MONOTONIC);
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +0000623 packet->set_timestamp(static_cast<uint64_t>(mPredictions.startTime));
Adithya Srinivasan01189672020-10-20 14:23:05 -0700624
625 auto* event = packet->set_frame_timeline_event();
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +0000626 auto* expectedSurfaceFrameStartEvent = event->set_expected_surface_frame_start();
Adithya Srinivasan01189672020-10-20 14:23:05 -0700627
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +0000628 expectedSurfaceFrameStartEvent->set_cookie(expectedTimelineCookie);
629
630 expectedSurfaceFrameStartEvent->set_token(mToken);
631 expectedSurfaceFrameStartEvent->set_display_frame_token(displayFrameToken);
632
633 expectedSurfaceFrameStartEvent->set_pid(mOwnerPid);
634 expectedSurfaceFrameStartEvent->set_layer_name(mDebugName);
635 });
Adithya Srinivasan86678502021-01-19 21:50:38 +0000636
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +0000637 // Expected timeline end
638 FrameTimelineDataSource::Trace([&](FrameTimelineDataSource::TraceContext ctx) {
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000639 std::scoped_lock lock(mMutex);
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +0000640 auto packet = ctx.NewTracePacket();
641 packet->set_timestamp_clock_id(perfetto::protos::pbzero::BUILTIN_CLOCK_MONOTONIC);
642 packet->set_timestamp(static_cast<uint64_t>(mPredictions.endTime));
643
644 auto* event = packet->set_frame_timeline_event();
645 auto* expectedSurfaceFrameEndEvent = event->set_frame_end();
646
647 expectedSurfaceFrameEndEvent->set_cookie(expectedTimelineCookie);
648 });
Adithya Srinivasan061c14c2021-02-11 01:19:47 +0000649}
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +0000650
Adithya Srinivasan061c14c2021-02-11 01:19:47 +0000651void SurfaceFrame::traceActuals(int64_t displayFrameToken) const {
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +0000652 int64_t actualTimelineCookie = mTraceCookieCounter.getCookieForTracing();
Adithya Srinivasan061c14c2021-02-11 01:19:47 +0000653
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +0000654 // Actual timeline start
655 FrameTimelineDataSource::Trace([&](FrameTimelineDataSource::TraceContext ctx) {
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000656 std::scoped_lock lock(mMutex);
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +0000657 auto packet = ctx.NewTracePacket();
658 packet->set_timestamp_clock_id(perfetto::protos::pbzero::BUILTIN_CLOCK_MONOTONIC);
659 // Actual start time is not yet available, so use expected start instead
Adithya Srinivasan061c14c2021-02-11 01:19:47 +0000660 if (mPredictionState == PredictionState::Expired) {
661 // If prediction is expired, we can't use the predicted start time. Instead, just use a
662 // start time a little earlier than the end time so that we have some info about this
663 // frame in the trace.
Adithya Srinivasanb2283c32021-04-21 21:31:56 +0000664 nsecs_t endTime =
665 (mPresentState == PresentState::Dropped ? mDropTime : mActuals.endTime);
Adithya Srinivasan061c14c2021-02-11 01:19:47 +0000666 packet->set_timestamp(
Adithya Srinivasanb2283c32021-04-21 21:31:56 +0000667 static_cast<uint64_t>(endTime - kPredictionExpiredStartTimeDelta));
Adithya Srinivasan061c14c2021-02-11 01:19:47 +0000668 } else {
669 packet->set_timestamp(static_cast<uint64_t>(mPredictions.startTime));
670 }
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +0000671
672 auto* event = packet->set_frame_timeline_event();
673 auto* actualSurfaceFrameStartEvent = event->set_actual_surface_frame_start();
674
675 actualSurfaceFrameStartEvent->set_cookie(actualTimelineCookie);
676
677 actualSurfaceFrameStartEvent->set_token(mToken);
678 actualSurfaceFrameStartEvent->set_display_frame_token(displayFrameToken);
679
680 actualSurfaceFrameStartEvent->set_pid(mOwnerPid);
681 actualSurfaceFrameStartEvent->set_layer_name(mDebugName);
Adithya Srinivasan01189672020-10-20 14:23:05 -0700682
683 if (mPresentState == PresentState::Dropped) {
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +0000684 actualSurfaceFrameStartEvent->set_present_type(FrameTimelineEvent::PRESENT_DROPPED);
Adithya Srinivasan01189672020-10-20 14:23:05 -0700685 } else if (mPresentState == PresentState::Unknown) {
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +0000686 actualSurfaceFrameStartEvent->set_present_type(FrameTimelineEvent::PRESENT_UNSPECIFIED);
Adithya Srinivasan01189672020-10-20 14:23:05 -0700687 } else {
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +0000688 actualSurfaceFrameStartEvent->set_present_type(toProto(mFramePresentMetadata));
Adithya Srinivasan01189672020-10-20 14:23:05 -0700689 }
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +0000690 actualSurfaceFrameStartEvent->set_on_time_finish(mFrameReadyMetadata ==
691 FrameReadyMetadata::OnTimeFinish);
692 actualSurfaceFrameStartEvent->set_gpu_composition(mGpuComposition);
693 actualSurfaceFrameStartEvent->set_jank_type(jankTypeBitmaskToProto(mJankType));
Adithya Srinivasan78e58af2021-02-25 00:08:08 +0000694 actualSurfaceFrameStartEvent->set_prediction_type(toProto(mPredictionState));
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +0000695 });
Adithya Srinivasan061c14c2021-02-11 01:19:47 +0000696
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +0000697 // Actual timeline end
698 FrameTimelineDataSource::Trace([&](FrameTimelineDataSource::TraceContext ctx) {
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000699 std::scoped_lock lock(mMutex);
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +0000700 auto packet = ctx.NewTracePacket();
701 packet->set_timestamp_clock_id(perfetto::protos::pbzero::BUILTIN_CLOCK_MONOTONIC);
Adithya Srinivasan061c14c2021-02-11 01:19:47 +0000702 if (mPresentState == PresentState::Dropped) {
703 packet->set_timestamp(static_cast<uint64_t>(mDropTime));
704 } else {
705 packet->set_timestamp(static_cast<uint64_t>(mActuals.endTime));
706 }
Adithya Srinivasan01189672020-10-20 14:23:05 -0700707
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +0000708 auto* event = packet->set_frame_timeline_event();
709 auto* actualSurfaceFrameEndEvent = event->set_frame_end();
Adithya Srinivasan01189672020-10-20 14:23:05 -0700710
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +0000711 actualSurfaceFrameEndEvent->set_cookie(actualTimelineCookie);
Adithya Srinivasan01189672020-10-20 14:23:05 -0700712 });
713}
714
Adithya Srinivasan061c14c2021-02-11 01:19:47 +0000715/**
716 * TODO(b/178637512): add inputEventId to the perfetto trace.
717 */
718void SurfaceFrame::trace(int64_t displayFrameToken) const {
719 if (mToken == FrameTimelineInfo::INVALID_VSYNC_ID ||
720 displayFrameToken == FrameTimelineInfo::INVALID_VSYNC_ID) {
721 // No packets can be traced with a missing token.
722 return;
723 }
724 if (getPredictionState() != PredictionState::Expired) {
725 // Expired predictions have zeroed timestamps. This cannot be used in any meaningful way in
726 // a trace.
727 tracePredictions(displayFrameToken);
728 }
729 traceActuals(displayFrameToken);
730}
731
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800732namespace impl {
733
734int64_t TokenManager::generateTokenForPredictions(TimelineItem&& predictions) {
735 ATRACE_CALL();
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000736 std::scoped_lock lock(mMutex);
Adithya Srinivasanbed4c4f2021-05-03 20:24:46 +0000737 while (mPredictions.size() >= kMaxTokens) {
738 mPredictions.erase(mPredictions.begin());
739 }
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800740 const int64_t assignedToken = mCurrentToken++;
Adithya Srinivasanbed4c4f2021-05-03 20:24:46 +0000741 mPredictions[assignedToken] = predictions;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800742 return assignedToken;
743}
744
745std::optional<TimelineItem> TokenManager::getPredictionsForToken(int64_t token) const {
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000746 std::scoped_lock lock(mMutex);
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800747 auto predictionsIterator = mPredictions.find(token);
748 if (predictionsIterator != mPredictions.end()) {
Adithya Srinivasanbed4c4f2021-05-03 20:24:46 +0000749 return predictionsIterator->second;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800750 }
751 return {};
752}
753
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800754FrameTimeline::FrameTimeline(std::shared_ptr<TimeStats> timeStats, pid_t surfaceFlingerPid,
Adithya Srinivasan82eef322021-04-10 00:06:04 +0000755 JankClassificationThresholds thresholds)
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +0000756 : mMaxDisplayFrames(kDefaultMaxDisplayFrames),
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800757 mTimeStats(std::move(timeStats)),
758 mSurfaceFlingerPid(surfaceFlingerPid),
Adithya Srinivasan82eef322021-04-10 00:06:04 +0000759 mJankClassificationThresholds(thresholds) {
760 mCurrentDisplayFrame =
761 std::make_shared<DisplayFrame>(mTimeStats, thresholds, &mTraceCookieCounter);
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +0000762}
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700763
Adithya Srinivasan01189672020-10-20 14:23:05 -0700764void FrameTimeline::onBootFinished() {
765 perfetto::TracingInitArgs args;
766 args.backends = perfetto::kSystemBackend;
767 perfetto::Tracing::Initialize(args);
768 registerDataSource();
769}
770
771void FrameTimeline::registerDataSource() {
772 perfetto::DataSourceDescriptor dsd;
773 dsd.set_name(kFrameTimelineDataSource);
774 FrameTimelineDataSource::Register(dsd);
775}
776
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800777std::shared_ptr<SurfaceFrame> FrameTimeline::createSurfaceFrameForToken(
Alec Mouriadebf5c2021-01-05 12:57:36 -0800778 const FrameTimelineInfo& frameTimelineInfo, pid_t ownerPid, uid_t ownerUid, int32_t layerId,
Adithya Srinivasan785addd2021-03-09 00:38:00 +0000779 std::string layerName, std::string debugName, bool isBuffer) {
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700780 ATRACE_CALL();
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000781 if (frameTimelineInfo.vsyncId == FrameTimelineInfo::INVALID_VSYNC_ID) {
Alec Mouriadebf5c2021-01-05 12:57:36 -0800782 return std::make_shared<SurfaceFrame>(frameTimelineInfo, ownerPid, ownerUid, layerId,
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000783 std::move(layerName), std::move(debugName),
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800784 PredictionState::None, TimelineItem(), mTimeStats,
Adithya Srinivasan785addd2021-03-09 00:38:00 +0000785 mJankClassificationThresholds, &mTraceCookieCounter,
786 isBuffer);
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700787 }
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000788 std::optional<TimelineItem> predictions =
789 mTokenManager.getPredictionsForToken(frameTimelineInfo.vsyncId);
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700790 if (predictions) {
Alec Mouriadebf5c2021-01-05 12:57:36 -0800791 return std::make_shared<SurfaceFrame>(frameTimelineInfo, ownerPid, ownerUid, layerId,
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000792 std::move(layerName), std::move(debugName),
793 PredictionState::Valid, std::move(*predictions),
794 mTimeStats, mJankClassificationThresholds,
Adithya Srinivasan785addd2021-03-09 00:38:00 +0000795 &mTraceCookieCounter, isBuffer);
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700796 }
Alec Mouriadebf5c2021-01-05 12:57:36 -0800797 return std::make_shared<SurfaceFrame>(frameTimelineInfo, ownerPid, ownerUid, layerId,
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000798 std::move(layerName), std::move(debugName),
799 PredictionState::Expired, TimelineItem(), mTimeStats,
Adithya Srinivasan785addd2021-03-09 00:38:00 +0000800 mJankClassificationThresholds, &mTraceCookieCounter,
801 isBuffer);
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700802}
803
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800804FrameTimeline::DisplayFrame::DisplayFrame(std::shared_ptr<TimeStats> timeStats,
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +0000805 JankClassificationThresholds thresholds,
806 TraceCookieCounter* traceCookieCounter)
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800807 : mSurfaceFlingerPredictions(TimelineItem()),
808 mSurfaceFlingerActuals(TimelineItem()),
809 mTimeStats(timeStats),
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +0000810 mJankClassificationThresholds(thresholds),
811 mTraceCookieCounter(*traceCookieCounter) {
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800812 mSurfaceFrames.reserve(kNumSurfaceFramesInitial);
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700813}
814
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800815void FrameTimeline::addSurfaceFrame(std::shared_ptr<SurfaceFrame> surfaceFrame) {
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700816 ATRACE_CALL();
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000817 std::scoped_lock lock(mMutex);
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800818 mCurrentDisplayFrame->addSurfaceFrame(surfaceFrame);
819}
820
Alec Mouri7d436ec2021-01-27 20:40:50 -0800821void FrameTimeline::setSfWakeUp(int64_t token, nsecs_t wakeUpTime, Fps refreshRate) {
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800822 ATRACE_CALL();
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000823 std::scoped_lock lock(mMutex);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800824 mCurrentDisplayFrame->onSfWakeUp(token, refreshRate,
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800825 mTokenManager.getPredictionsForToken(token), wakeUpTime);
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700826}
827
828void FrameTimeline::setSfPresent(nsecs_t sfPresentTime,
Adithya Srinivasanb6a2fa12021-03-13 00:23:09 +0000829 const std::shared_ptr<FenceTime>& presentFence,
Adithya Srinivasan36b01af2021-04-07 22:29:47 +0000830 const std::shared_ptr<FenceTime>& gpuFence) {
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700831 ATRACE_CALL();
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000832 std::scoped_lock lock(mMutex);
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800833 mCurrentDisplayFrame->setActualEndTime(sfPresentTime);
Adithya Srinivasan36b01af2021-04-07 22:29:47 +0000834 mCurrentDisplayFrame->setGpuFence(gpuFence);
Adithya Srinivasanf279e042020-08-17 14:56:27 -0700835 mPendingPresentFences.emplace_back(std::make_pair(presentFence, mCurrentDisplayFrame));
836 flushPendingPresentFences();
837 finalizeCurrentDisplayFrame();
838}
839
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800840void FrameTimeline::DisplayFrame::addSurfaceFrame(std::shared_ptr<SurfaceFrame> surfaceFrame) {
841 mSurfaceFrames.push_back(surfaceFrame);
842}
843
Alec Mouri7d436ec2021-01-27 20:40:50 -0800844void FrameTimeline::DisplayFrame::onSfWakeUp(int64_t token, Fps refreshRate,
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800845 std::optional<TimelineItem> predictions,
846 nsecs_t wakeUpTime) {
847 mToken = token;
Alec Mouri7d436ec2021-01-27 20:40:50 -0800848 mRefreshRate = refreshRate;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800849 if (!predictions) {
850 mPredictionState = PredictionState::Expired;
851 } else {
852 mPredictionState = PredictionState::Valid;
853 mSurfaceFlingerPredictions = *predictions;
854 }
855 mSurfaceFlingerActuals.startTime = wakeUpTime;
856}
857
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800858void FrameTimeline::DisplayFrame::setPredictions(PredictionState predictionState,
859 TimelineItem predictions) {
860 mPredictionState = predictionState;
861 mSurfaceFlingerPredictions = predictions;
862}
863
864void FrameTimeline::DisplayFrame::setActualStartTime(nsecs_t actualStartTime) {
865 mSurfaceFlingerActuals.startTime = actualStartTime;
866}
867
868void FrameTimeline::DisplayFrame::setActualEndTime(nsecs_t actualEndTime) {
869 mSurfaceFlingerActuals.endTime = actualEndTime;
870}
871
Adithya Srinivasan36b01af2021-04-07 22:29:47 +0000872void FrameTimeline::DisplayFrame::setGpuFence(const std::shared_ptr<FenceTime>& gpuFence) {
873 mGpuFence = gpuFence;
Adithya Srinivasanb6a2fa12021-03-13 00:23:09 +0000874}
875
Adithya Srinivasan57dc81d2021-04-14 17:31:41 +0000876void FrameTimeline::DisplayFrame::classifyJank(nsecs_t& deadlineDelta, nsecs_t& deltaToVsync,
877 nsecs_t previousPresentTime) {
Adithya Srinivasan7c4ac7a2021-03-08 23:48:03 +0000878 if (mPredictionState == PredictionState::Expired ||
879 mSurfaceFlingerActuals.presentTime == Fence::SIGNAL_TIME_INVALID) {
Adithya Srinivasande272452021-04-10 00:21:00 +0000880 // Cannot do jank classification with expired predictions or invalid signal times. Set the
881 // deltas to 0 as both negative and positive deltas are used as real values.
Adithya Srinivasan061c14c2021-02-11 01:19:47 +0000882 mJankType = JankType::Unknown;
Adithya Srinivasande272452021-04-10 00:21:00 +0000883 deadlineDelta = 0;
884 deltaToVsync = 0;
Adithya Srinivasan061c14c2021-02-11 01:19:47 +0000885 return;
886 }
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800887
888 // Delta between the expected present and the actual present
889 const nsecs_t presentDelta =
890 mSurfaceFlingerActuals.presentTime - mSurfaceFlingerPredictions.presentTime;
Adithya Srinivasan36b01af2021-04-07 22:29:47 +0000891 // Sf actual end time represents the CPU end time. In case of HWC, SF's end time would have
892 // included the time for composition. However, for GPU composition, the final end time is max(sf
893 // end time, gpu fence time).
894 nsecs_t combinedEndTime = mSurfaceFlingerActuals.endTime;
895 if (mGpuFence != FenceTime::NO_FENCE) {
896 combinedEndTime = std::max(combinedEndTime, mGpuFence->getSignalTime());
897 }
898 deadlineDelta = combinedEndTime - mSurfaceFlingerPredictions.endTime;
Alec Mouri363faf02021-01-29 16:34:55 -0800899
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800900 // How far off was the presentDelta when compared to the vsyncPeriod. Used in checking if there
901 // was a prediction error or not.
Adithya Srinivasan115ac692021-03-06 01:21:30 +0000902 deltaToVsync = mRefreshRate.getPeriodNsecs() > 0
Alec Mouriadebf5c2021-01-05 12:57:36 -0800903 ? std::abs(presentDelta) % mRefreshRate.getPeriodNsecs()
904 : 0;
Adithya Srinivasan115ac692021-03-06 01:21:30 +0000905
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800906 if (std::abs(presentDelta) > mJankClassificationThresholds.presentThreshold) {
907 mFramePresentMetadata = presentDelta > 0 ? FramePresentMetadata::LatePresent
908 : FramePresentMetadata::EarlyPresent;
909 } else {
910 mFramePresentMetadata = FramePresentMetadata::OnTimePresent;
911 }
912
Adithya Srinivasan36b01af2021-04-07 22:29:47 +0000913 if (combinedEndTime > mSurfaceFlingerPredictions.endTime) {
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800914 mFrameReadyMetadata = FrameReadyMetadata::LateFinish;
915 } else {
916 mFrameReadyMetadata = FrameReadyMetadata::OnTimeFinish;
917 }
918
919 if (std::abs(mSurfaceFlingerActuals.startTime - mSurfaceFlingerPredictions.startTime) >
920 mJankClassificationThresholds.startThreshold) {
921 mFrameStartMetadata =
922 mSurfaceFlingerActuals.startTime > mSurfaceFlingerPredictions.startTime
923 ? FrameStartMetadata::LateStart
924 : FrameStartMetadata::EarlyStart;
925 }
926
927 if (mFramePresentMetadata != FramePresentMetadata::OnTimePresent) {
928 // Do jank classification only if present is not on time
929 if (mFramePresentMetadata == FramePresentMetadata::EarlyPresent) {
930 if (mFrameReadyMetadata == FrameReadyMetadata::OnTimeFinish) {
931 // Finish on time, Present early
932 if (deltaToVsync < mJankClassificationThresholds.presentThreshold ||
Alec Mouri7d436ec2021-01-27 20:40:50 -0800933 deltaToVsync >= (mRefreshRate.getPeriodNsecs() -
934 mJankClassificationThresholds.presentThreshold)) {
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800935 // Delta is a factor of vsync if its within the presentTheshold on either side
936 // of the vsyncPeriod. Example: 0-2ms and 9-11ms are both within the threshold
937 // of the vsyncPeriod if the threshold was 2ms and the vsyncPeriod was 11ms.
938 mJankType = JankType::SurfaceFlingerScheduling;
939 } else {
940 // Delta is not a factor of vsync,
941 mJankType = JankType::PredictionError;
942 }
943 } else if (mFrameReadyMetadata == FrameReadyMetadata::LateFinish) {
944 // Finish late, Present early
945 mJankType = JankType::SurfaceFlingerScheduling;
946 } else {
947 // Finish time unknown
948 mJankType = JankType::Unknown;
949 }
950 } else if (mFramePresentMetadata == FramePresentMetadata::LatePresent) {
Adithya Srinivasan57dc81d2021-04-14 17:31:41 +0000951 if (std::abs(mSurfaceFlingerPredictions.presentTime - previousPresentTime) <=
952 mJankClassificationThresholds.presentThreshold ||
953 previousPresentTime > mSurfaceFlingerPredictions.presentTime) {
954 // The previous frame was either presented in the current frame's expected vsync or
955 // it was presented even later than the current frame's expected vsync.
956 mJankType = JankType::SurfaceFlingerStuffing;
957 }
958 if (mFrameReadyMetadata == FrameReadyMetadata::OnTimeFinish &&
959 !(mJankType & JankType::SurfaceFlingerStuffing)) {
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800960 // Finish on time, Present late
961 if (deltaToVsync < mJankClassificationThresholds.presentThreshold ||
Alec Mouri7d436ec2021-01-27 20:40:50 -0800962 deltaToVsync >= (mRefreshRate.getPeriodNsecs() -
963 mJankClassificationThresholds.presentThreshold)) {
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800964 // Delta is a factor of vsync if its within the presentTheshold on either side
965 // of the vsyncPeriod. Example: 0-2ms and 9-11ms are both within the threshold
966 // of the vsyncPeriod if the threshold was 2ms and the vsyncPeriod was 11ms.
967 mJankType = JankType::DisplayHAL;
968 } else {
969 // Delta is not a factor of vsync
970 mJankType = JankType::PredictionError;
971 }
972 } else if (mFrameReadyMetadata == FrameReadyMetadata::LateFinish) {
Adithya Srinivasan57dc81d2021-04-14 17:31:41 +0000973 if (!(mJankType & JankType::SurfaceFlingerStuffing) ||
974 mSurfaceFlingerActuals.presentTime - previousPresentTime >
975 mRefreshRate.getPeriodNsecs() +
976 mJankClassificationThresholds.presentThreshold) {
977 // Classify CPU vs GPU if SF wasn't stuffed or if SF was stuffed but this frame
978 // was presented more than a vsync late.
Adithya Srinivasan36b01af2021-04-07 22:29:47 +0000979 if (mGpuFence != FenceTime::NO_FENCE &&
980 mSurfaceFlingerActuals.endTime - mSurfaceFlingerActuals.startTime <
981 mRefreshRate.getPeriodNsecs()) {
982 // If SF was in GPU composition and the CPU work finished before the vsync
983 // period, classify it as GPU deadline missed.
984 mJankType = JankType::SurfaceFlingerGpuDeadlineMissed;
985 } else {
986 mJankType = JankType::SurfaceFlingerCpuDeadlineMissed;
987 }
Adithya Srinivasan939cd4d2021-02-23 06:18:13 +0000988 }
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800989 } else {
990 // Finish time unknown
991 mJankType = JankType::Unknown;
992 }
993 } else {
994 // Present unknown
995 mJankType = JankType::Unknown;
996 }
997 }
Adithya Srinivasan115ac692021-03-06 01:21:30 +0000998}
999
Adithya Srinivasan57dc81d2021-04-14 17:31:41 +00001000void FrameTimeline::DisplayFrame::onPresent(nsecs_t signalTime, nsecs_t previousPresentTime) {
Adithya Srinivasan115ac692021-03-06 01:21:30 +00001001 mSurfaceFlingerActuals.presentTime = signalTime;
1002 nsecs_t deadlineDelta = 0;
1003 nsecs_t deltaToVsync = 0;
Adithya Srinivasan57dc81d2021-04-14 17:31:41 +00001004 classifyJank(deadlineDelta, deltaToVsync, previousPresentTime);
Adithya Srinivasan115ac692021-03-06 01:21:30 +00001005
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08001006 for (auto& surfaceFrame : mSurfaceFrames) {
Alec Mouri363faf02021-01-29 16:34:55 -08001007 surfaceFrame->onPresent(signalTime, mJankType, mRefreshRate, deadlineDelta, deltaToVsync);
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08001008 }
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08001009}
1010
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001011void FrameTimeline::DisplayFrame::tracePredictions(pid_t surfaceFlingerPid) const {
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +00001012 int64_t expectedTimelineCookie = mTraceCookieCounter.getCookieForTracing();
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001013
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +00001014 // Expected timeline start
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08001015 FrameTimelineDataSource::Trace([&](FrameTimelineDataSource::TraceContext ctx) {
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08001016 auto packet = ctx.NewTracePacket();
1017 packet->set_timestamp_clock_id(perfetto::protos::pbzero::BUILTIN_CLOCK_MONOTONIC);
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +00001018 packet->set_timestamp(static_cast<uint64_t>(mSurfaceFlingerPredictions.startTime));
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08001019
1020 auto* event = packet->set_frame_timeline_event();
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +00001021 auto* expectedDisplayFrameStartEvent = event->set_expected_display_frame_start();
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08001022
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +00001023 expectedDisplayFrameStartEvent->set_cookie(expectedTimelineCookie);
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08001024
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +00001025 expectedDisplayFrameStartEvent->set_token(mToken);
1026 expectedDisplayFrameStartEvent->set_pid(surfaceFlingerPid);
1027 });
Adithya Srinivasan86678502021-01-19 21:50:38 +00001028
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +00001029 // Expected timeline end
1030 FrameTimelineDataSource::Trace([&](FrameTimelineDataSource::TraceContext ctx) {
1031 auto packet = ctx.NewTracePacket();
1032 packet->set_timestamp_clock_id(perfetto::protos::pbzero::BUILTIN_CLOCK_MONOTONIC);
1033 packet->set_timestamp(static_cast<uint64_t>(mSurfaceFlingerPredictions.endTime));
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08001034
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +00001035 auto* event = packet->set_frame_timeline_event();
1036 auto* expectedDisplayFrameEndEvent = event->set_frame_end();
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08001037
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +00001038 expectedDisplayFrameEndEvent->set_cookie(expectedTimelineCookie);
1039 });
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001040}
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +00001041
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001042void FrameTimeline::DisplayFrame::traceActuals(pid_t surfaceFlingerPid) const {
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +00001043 int64_t actualTimelineCookie = mTraceCookieCounter.getCookieForTracing();
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001044
1045 // Actual timeline start
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +00001046 FrameTimelineDataSource::Trace([&](FrameTimelineDataSource::TraceContext ctx) {
1047 auto packet = ctx.NewTracePacket();
1048 packet->set_timestamp_clock_id(perfetto::protos::pbzero::BUILTIN_CLOCK_MONOTONIC);
1049 packet->set_timestamp(static_cast<uint64_t>(mSurfaceFlingerActuals.startTime));
1050
1051 auto* event = packet->set_frame_timeline_event();
1052 auto* actualDisplayFrameStartEvent = event->set_actual_display_frame_start();
1053
1054 actualDisplayFrameStartEvent->set_cookie(actualTimelineCookie);
1055
1056 actualDisplayFrameStartEvent->set_token(mToken);
1057 actualDisplayFrameStartEvent->set_pid(surfaceFlingerPid);
1058
1059 actualDisplayFrameStartEvent->set_present_type(toProto(mFramePresentMetadata));
1060 actualDisplayFrameStartEvent->set_on_time_finish(mFrameReadyMetadata ==
1061 FrameReadyMetadata::OnTimeFinish);
Adithya Srinivasan36b01af2021-04-07 22:29:47 +00001062 actualDisplayFrameStartEvent->set_gpu_composition(mGpuFence != FenceTime::NO_FENCE);
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +00001063 actualDisplayFrameStartEvent->set_jank_type(jankTypeBitmaskToProto(mJankType));
Adithya Srinivasan78e58af2021-02-25 00:08:08 +00001064 actualDisplayFrameStartEvent->set_prediction_type(toProto(mPredictionState));
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +00001065 });
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001066
1067 // Actual timeline end
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +00001068 FrameTimelineDataSource::Trace([&](FrameTimelineDataSource::TraceContext ctx) {
1069 auto packet = ctx.NewTracePacket();
1070 packet->set_timestamp_clock_id(perfetto::protos::pbzero::BUILTIN_CLOCK_MONOTONIC);
Adithya Srinivasan1a971632021-02-26 23:10:29 +00001071 packet->set_timestamp(static_cast<uint64_t>(mSurfaceFlingerActuals.presentTime));
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +00001072
1073 auto* event = packet->set_frame_timeline_event();
1074 auto* actualDisplayFrameEndEvent = event->set_frame_end();
1075
1076 actualDisplayFrameEndEvent->set_cookie(actualTimelineCookie);
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08001077 });
Adithya Srinivasan061c14c2021-02-11 01:19:47 +00001078}
1079
1080void FrameTimeline::DisplayFrame::trace(pid_t surfaceFlingerPid) const {
1081 if (mToken == FrameTimelineInfo::INVALID_VSYNC_ID) {
1082 // DisplayFrame should not have an invalid token.
1083 ALOGE("Cannot trace DisplayFrame with invalid token");
1084 return;
1085 }
1086
1087 if (mPredictionState == PredictionState::Valid) {
1088 // Expired and unknown predictions have zeroed timestamps. This cannot be used in any
1089 // meaningful way in a trace.
1090 tracePredictions(surfaceFlingerPid);
1091 }
1092 traceActuals(surfaceFlingerPid);
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08001093
1094 for (auto& surfaceFrame : mSurfaceFrames) {
1095 surfaceFrame->trace(mToken);
1096 }
1097}
1098
Alec Mouriadebf5c2021-01-05 12:57:36 -08001099float FrameTimeline::computeFps(const std::unordered_set<int32_t>& layerIds) {
1100 if (layerIds.empty()) {
1101 return 0.0f;
1102 }
1103
1104 std::vector<nsecs_t> presentTimes;
1105 {
1106 std::scoped_lock lock(mMutex);
1107 presentTimes.reserve(mDisplayFrames.size());
1108 for (size_t i = 0; i < mDisplayFrames.size(); i++) {
1109 const auto& displayFrame = mDisplayFrames[i];
1110 if (displayFrame->getActuals().presentTime <= 0) {
1111 continue;
1112 }
1113 for (const auto& surfaceFrame : displayFrame->getSurfaceFrames()) {
1114 if (surfaceFrame->getPresentState() == SurfaceFrame::PresentState::Presented &&
1115 layerIds.count(surfaceFrame->getLayerId()) > 0) {
1116 // We're looking for DisplayFrames that presents at least one layer from
1117 // layerIds, so push the present time and skip looking through the rest of the
1118 // SurfaceFrames.
1119 presentTimes.push_back(displayFrame->getActuals().presentTime);
1120 break;
1121 }
1122 }
1123 }
1124 }
1125
1126 // FPS can't be computed when there's fewer than 2 presented frames.
1127 if (presentTimes.size() <= 1) {
1128 return 0.0f;
1129 }
1130
1131 nsecs_t priorPresentTime = -1;
1132 nsecs_t totalPresentToPresentWalls = 0;
1133
1134 for (const nsecs_t presentTime : presentTimes) {
1135 if (priorPresentTime == -1) {
1136 priorPresentTime = presentTime;
1137 continue;
1138 }
1139
1140 totalPresentToPresentWalls += (presentTime - priorPresentTime);
1141 priorPresentTime = presentTime;
1142 }
1143
1144 if (CC_UNLIKELY(totalPresentToPresentWalls <= 0)) {
1145 ALOGW("Invalid total present-to-present duration when computing fps: %" PRId64,
1146 totalPresentToPresentWalls);
1147 return 0.0f;
1148 }
1149
1150 const constexpr nsecs_t kOneSecond =
1151 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
1152 // (10^9 nanoseconds / second) * (N present deltas) / (total nanoseconds in N present deltas) =
1153 // M frames / second
1154 return kOneSecond * static_cast<nsecs_t>((presentTimes.size() - 1)) /
1155 static_cast<float>(totalPresentToPresentWalls);
1156}
1157
Adithya Srinivasanf279e042020-08-17 14:56:27 -07001158void FrameTimeline::flushPendingPresentFences() {
1159 for (size_t i = 0; i < mPendingPresentFences.size(); i++) {
1160 const auto& pendingPresentFence = mPendingPresentFences[i];
1161 nsecs_t signalTime = Fence::SIGNAL_TIME_INVALID;
1162 if (pendingPresentFence.first && pendingPresentFence.first->isValid()) {
1163 signalTime = pendingPresentFence.first->getSignalTime();
1164 if (signalTime == Fence::SIGNAL_TIME_PENDING) {
1165 continue;
1166 }
1167 }
Adithya Srinivasan7c4ac7a2021-03-08 23:48:03 +00001168 auto& displayFrame = pendingPresentFence.second;
Adithya Srinivasan57dc81d2021-04-14 17:31:41 +00001169 displayFrame->onPresent(signalTime, mPreviousPresentTime);
Adithya Srinivasan7c4ac7a2021-03-08 23:48:03 +00001170 displayFrame->trace(mSurfaceFlingerPid);
Adithya Srinivasan57dc81d2021-04-14 17:31:41 +00001171 mPreviousPresentTime = signalTime;
Adithya Srinivasanf279e042020-08-17 14:56:27 -07001172
1173 mPendingPresentFences.erase(mPendingPresentFences.begin() + static_cast<int>(i));
1174 --i;
1175 }
1176}
1177
1178void FrameTimeline::finalizeCurrentDisplayFrame() {
Adithya Srinivasan2d736322020-10-01 16:53:48 -07001179 while (mDisplayFrames.size() >= mMaxDisplayFrames) {
Adithya Srinivasanf279e042020-08-17 14:56:27 -07001180 // We maintain only a fixed number of frames' data. Pop older frames
1181 mDisplayFrames.pop_front();
1182 }
1183 mDisplayFrames.push_back(mCurrentDisplayFrame);
1184 mCurrentDisplayFrame.reset();
Adithya Srinivasan05bd2d12021-01-11 18:49:58 +00001185 mCurrentDisplayFrame = std::make_shared<DisplayFrame>(mTimeStats, mJankClassificationThresholds,
Adithya Srinivasan82eef322021-04-10 00:06:04 +00001186 &mTraceCookieCounter);
Adithya Srinivasanf279e042020-08-17 14:56:27 -07001187}
1188
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08001189nsecs_t FrameTimeline::DisplayFrame::getBaseTime() const {
1190 nsecs_t baseTime =
1191 getMinTime(mPredictionState, mSurfaceFlingerPredictions, mSurfaceFlingerActuals);
1192 for (const auto& surfaceFrame : mSurfaceFrames) {
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07001193 nsecs_t surfaceFrameBaseTime = surfaceFrame->getBaseTime();
1194 if (surfaceFrameBaseTime != 0) {
1195 baseTime = std::min(baseTime, surfaceFrameBaseTime);
1196 }
1197 }
1198 return baseTime;
1199}
1200
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08001201void FrameTimeline::DisplayFrame::dumpJank(std::string& result, nsecs_t baseTime,
1202 int displayFrameCount) const {
1203 if (mJankType == JankType::None) {
1204 // Check if any Surface Frame has been janky
1205 bool isJanky = false;
1206 for (const auto& surfaceFrame : mSurfaceFrames) {
1207 if (surfaceFrame->getJankType() != JankType::None) {
1208 isJanky = true;
1209 break;
1210 }
1211 }
1212 if (!isJanky) {
1213 return;
1214 }
1215 }
1216 StringAppendF(&result, "Display Frame %d", displayFrameCount);
1217 dump(result, baseTime);
1218}
1219
1220void FrameTimeline::DisplayFrame::dumpAll(std::string& result, nsecs_t baseTime) const {
1221 dump(result, baseTime);
1222}
1223
1224void FrameTimeline::DisplayFrame::dump(std::string& result, nsecs_t baseTime) const {
1225 if (mJankType != JankType::None) {
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07001226 // Easily identify a janky Display Frame in the dump
1227 StringAppendF(&result, " [*] ");
1228 }
1229 StringAppendF(&result, "\n");
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08001230 StringAppendF(&result, "Prediction State : %s\n", toString(mPredictionState).c_str());
1231 StringAppendF(&result, "Jank Type : %s\n", jankTypeBitmaskToString(mJankType).c_str());
1232 StringAppendF(&result, "Present Metadata : %s\n", toString(mFramePresentMetadata).c_str());
1233 StringAppendF(&result, "Finish Metadata: %s\n", toString(mFrameReadyMetadata).c_str());
1234 StringAppendF(&result, "Start Metadata: %s\n", toString(mFrameStartMetadata).c_str());
Alec Mouri7d436ec2021-01-27 20:40:50 -08001235 std::chrono::nanoseconds vsyncPeriod(mRefreshRate.getPeriodNsecs());
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08001236 StringAppendF(&result, "Vsync Period: %10f\n",
1237 std::chrono::duration<double, std::milli>(vsyncPeriod).count());
1238 nsecs_t presentDelta =
1239 mSurfaceFlingerActuals.presentTime - mSurfaceFlingerPredictions.presentTime;
1240 std::chrono::nanoseconds presentDeltaNs(std::abs(presentDelta));
1241 StringAppendF(&result, "Present delta: %10f\n",
1242 std::chrono::duration<double, std::milli>(presentDeltaNs).count());
Alec Mouri7d436ec2021-01-27 20:40:50 -08001243 std::chrono::nanoseconds deltaToVsync(std::abs(presentDelta) % mRefreshRate.getPeriodNsecs());
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08001244 StringAppendF(&result, "Present delta %% refreshrate: %10f\n",
1245 std::chrono::duration<double, std::milli>(deltaToVsync).count());
1246 dumpTable(result, mSurfaceFlingerPredictions, mSurfaceFlingerActuals, "", mPredictionState,
1247 baseTime);
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07001248 StringAppendF(&result, "\n");
1249 std::string indent = " "; // 4 spaces
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08001250 for (const auto& surfaceFrame : mSurfaceFrames) {
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07001251 surfaceFrame->dump(result, indent, baseTime);
1252 }
1253 StringAppendF(&result, "\n");
1254}
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08001255
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07001256void FrameTimeline::dumpAll(std::string& result) {
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -10001257 std::scoped_lock lock(mMutex);
Adithya Srinivasanf279e042020-08-17 14:56:27 -07001258 StringAppendF(&result, "Number of display frames : %d\n", (int)mDisplayFrames.size());
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08001259 nsecs_t baseTime = (mDisplayFrames.empty()) ? 0 : mDisplayFrames[0]->getBaseTime();
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07001260 for (size_t i = 0; i < mDisplayFrames.size(); i++) {
1261 StringAppendF(&result, "Display Frame %d", static_cast<int>(i));
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08001262 mDisplayFrames[i]->dumpAll(result, baseTime);
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07001263 }
1264}
1265
1266void FrameTimeline::dumpJank(std::string& result) {
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -10001267 std::scoped_lock lock(mMutex);
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08001268 nsecs_t baseTime = (mDisplayFrames.empty()) ? 0 : mDisplayFrames[0]->getBaseTime();
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07001269 for (size_t i = 0; i < mDisplayFrames.size(); i++) {
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08001270 mDisplayFrames[i]->dumpJank(result, baseTime, static_cast<int>(i));
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07001271 }
1272}
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08001273
Adithya Srinivasan8fc601d2020-09-25 13:51:09 -07001274void FrameTimeline::parseArgs(const Vector<String16>& args, std::string& result) {
1275 ATRACE_CALL();
1276 std::unordered_map<std::string, bool> argsMap;
1277 for (size_t i = 0; i < args.size(); i++) {
1278 argsMap[std::string(String8(args[i]).c_str())] = true;
1279 }
1280 if (argsMap.count("-jank")) {
1281 dumpJank(result);
1282 }
1283 if (argsMap.count("-all")) {
1284 dumpAll(result);
Adithya Srinivasanf279e042020-08-17 14:56:27 -07001285 }
1286}
1287
Adithya Srinivasan2d736322020-10-01 16:53:48 -07001288void FrameTimeline::setMaxDisplayFrames(uint32_t size) {
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -10001289 std::scoped_lock lock(mMutex);
Adithya Srinivasan2d736322020-10-01 16:53:48 -07001290
1291 // The size can either increase or decrease, clear everything, to be consistent
1292 mDisplayFrames.clear();
1293 mPendingPresentFences.clear();
1294 mMaxDisplayFrames = size;
1295}
1296
1297void FrameTimeline::reset() {
1298 setMaxDisplayFrames(kDefaultMaxDisplayFrames);
1299}
1300
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -08001301} // namespace impl
1302} // namespace android::frametimeline