blob: cd64da08d1917d5d5f0c1d3efd321a9b556a8fd1 [file] [log] [blame]
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001/*
2 * Copyright 2018 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#undef LOG_TAG
17#define LOG_TAG "TimeStats"
18#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
20#include "TimeStats.h"
21
22#include <android-base/stringprintf.h>
23
24#include <log/log.h>
25
26#include <utils/String8.h>
27#include <utils/Trace.h>
28
29#include <algorithm>
30#include <regex>
31
32namespace android {
33
34TimeStats& TimeStats::getInstance() {
35 static std::unique_ptr<TimeStats> sInstance;
36 static std::once_flag sOnceFlag;
37
38 std::call_once(sOnceFlag, [] { sInstance.reset(new TimeStats); });
39 return *sInstance.get();
40}
41
42void TimeStats::parseArgs(bool asProto, const Vector<String16>& args, size_t& index,
43 String8& result) {
44 ATRACE_CALL();
45
46 if (args.size() > index + 10) {
47 ALOGD("Invalid args count");
48 return;
49 }
50
51 std::unordered_map<std::string, int32_t> argsMap;
52 while (index < args.size()) {
53 argsMap[std::string(String8(args[index]).c_str())] = index;
54 ++index;
55 }
56
57 if (argsMap.count("-disable")) {
58 disable();
59 }
60
61 if (argsMap.count("-dump")) {
Yiwei Zhang8a4015c2018-05-08 16:03:47 -070062 std::optional<uint32_t> maxLayers = std::nullopt;
Yiwei Zhang0102ad22018-05-02 17:37:17 -070063 auto iter = argsMap.find("-maxlayers");
64 if (iter != argsMap.end() && iter->second + 1 < static_cast<int32_t>(args.size())) {
Yiwei Zhang8a4015c2018-05-08 16:03:47 -070065 int64_t value = strtol(String8(args[iter->second + 1]).c_str(), nullptr, 10);
66 value = std::clamp(value, int64_t(0), int64_t(UINT32_MAX));
67 maxLayers = static_cast<uint32_t>(value);
Yiwei Zhang0102ad22018-05-02 17:37:17 -070068 }
69
Yiwei Zhang8a4015c2018-05-08 16:03:47 -070070 dump(asProto, maxLayers, result);
Yiwei Zhang0102ad22018-05-02 17:37:17 -070071 }
72
73 if (argsMap.count("-clear")) {
74 clear();
75 }
76
77 if (argsMap.count("-enable")) {
78 enable();
79 }
80}
81
82void TimeStats::incrementTotalFrames() {
83 if (!mEnabled.load()) return;
84
85 ATRACE_CALL();
86
87 std::lock_guard<std::mutex> lock(mMutex);
88 timeStats.totalFrames++;
89}
90
Yiwei Zhang621f9d42018-05-07 10:40:55 -070091void TimeStats::incrementMissedFrames() {
Yiwei Zhang0102ad22018-05-02 17:37:17 -070092 if (!mEnabled.load()) return;
93
94 ATRACE_CALL();
95
96 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhang0102ad22018-05-02 17:37:17 -070097 timeStats.missedFrames++;
98}
99
100void TimeStats::incrementClientCompositionFrames() {
101 if (!mEnabled.load()) return;
102
103 ATRACE_CALL();
104
105 std::lock_guard<std::mutex> lock(mMutex);
106 timeStats.clientCompositionFrames++;
107}
108
109bool TimeStats::recordReadyLocked(const std::string& layerName, TimeRecord* timeRecord) {
110 if (!timeRecord->ready) {
111 ALOGV("[%s]-[%" PRIu64 "]-presentFence is still not received", layerName.c_str(),
112 timeRecord->frameNumber);
113 return false;
114 }
115
116 if (timeRecord->acquireFence != nullptr) {
117 if (timeRecord->acquireFence->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
118 return false;
119 }
120 if (timeRecord->acquireFence->getSignalTime() != Fence::SIGNAL_TIME_INVALID) {
121 timeRecord->acquireTime = timeRecord->acquireFence->getSignalTime();
122 timeRecord->acquireFence = nullptr;
123 } else {
124 ALOGV("[%s]-[%" PRIu64 "]-acquireFence signal time is invalid", layerName.c_str(),
125 timeRecord->frameNumber);
126 }
127 }
128
129 if (timeRecord->presentFence != nullptr) {
130 if (timeRecord->presentFence->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
131 return false;
132 }
133 if (timeRecord->presentFence->getSignalTime() != Fence::SIGNAL_TIME_INVALID) {
134 timeRecord->presentTime = timeRecord->presentFence->getSignalTime();
135 timeRecord->presentFence = nullptr;
136 } else {
137 ALOGV("[%s]-[%" PRIu64 "]-presentFence signal time invalid", layerName.c_str(),
138 timeRecord->frameNumber);
139 }
140 }
141
142 return true;
143}
144
145static int32_t msBetween(nsecs_t start, nsecs_t end) {
146 int64_t delta = (end - start) / 1000000;
147 delta = std::clamp(delta, int64_t(INT32_MIN), int64_t(INT32_MAX));
148 return static_cast<int32_t>(delta);
149}
150
Yiwei Zhang8a4015c2018-05-08 16:03:47 -0700151static std::string getPackageName(const std::string& layerName) {
152 // This regular expression captures the following for instance:
153 // StatusBar in StatusBar#0
154 // com.appname in com.appname/com.appname.activity#0
155 // com.appname in SurfaceView - com.appname/com.appname.activity#0
156 const std::regex re("(?:SurfaceView[-\\s\\t]+)?([^/]+).*#\\d+");
157 std::smatch match;
158 if (std::regex_match(layerName.begin(), layerName.end(), match, re)) {
159 // There must be a match for group 1 otherwise the whole string is not
160 // matched and the above will return false
161 return match[1];
162 }
163 return "";
164}
165
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700166void TimeStats::flushAvailableRecordsToStatsLocked(const std::string& layerName) {
167 ATRACE_CALL();
168
169 LayerRecord& layerRecord = timeStatsTracker[layerName];
170 TimeRecord& prevTimeRecord = layerRecord.prevTimeRecord;
171 std::vector<TimeRecord>& timeRecords = layerRecord.timeRecords;
172 while (!timeRecords.empty()) {
173 if (!recordReadyLocked(layerName, &timeRecords[0])) break;
174 ALOGV("[%s]-[%" PRIu64 "]-presentFenceTime[%" PRId64 "]", layerName.c_str(),
175 timeRecords[0].frameNumber, timeRecords[0].presentTime);
176
177 if (prevTimeRecord.ready) {
178 if (!timeStats.stats.count(layerName)) {
179 timeStats.stats[layerName].layerName = layerName;
Yiwei Zhang8a4015c2018-05-08 16:03:47 -0700180 timeStats.stats[layerName].packageName = getPackageName(layerName);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700181 timeStats.stats[layerName].statsStart = static_cast<int64_t>(std::time(0));
182 }
183 TimeStatsHelper::TimeStatsLayer& timeStatsLayer = timeStats.stats[layerName];
184 timeStatsLayer.totalFrames++;
185
186 const int32_t postToPresentMs =
187 msBetween(timeRecords[0].postTime, timeRecords[0].presentTime);
188 ALOGV("[%s]-[%" PRIu64 "]-post2present[%d]", layerName.c_str(),
189 timeRecords[0].frameNumber, postToPresentMs);
190 timeStatsLayer.deltas["post2present"].insert(postToPresentMs);
191
192 const int32_t acquireToPresentMs =
193 msBetween(timeRecords[0].acquireTime, timeRecords[0].presentTime);
194 ALOGV("[%s]-[%" PRIu64 "]-acquire2present[%d]", layerName.c_str(),
195 timeRecords[0].frameNumber, acquireToPresentMs);
196 timeStatsLayer.deltas["acquire2present"].insert(acquireToPresentMs);
197
198 const int32_t latchToPresentMs =
199 msBetween(timeRecords[0].latchTime, timeRecords[0].presentTime);
200 ALOGV("[%s]-[%" PRIu64 "]-latch2present[%d]", layerName.c_str(),
201 timeRecords[0].frameNumber, latchToPresentMs);
202 timeStatsLayer.deltas["latch2present"].insert(latchToPresentMs);
203
204 const int32_t desiredToPresentMs =
205 msBetween(timeRecords[0].desiredTime, timeRecords[0].presentTime);
206 ALOGV("[%s]-[%" PRIu64 "]-desired2present[%d]", layerName.c_str(),
207 timeRecords[0].frameNumber, desiredToPresentMs);
208 timeStatsLayer.deltas["desired2present"].insert(desiredToPresentMs);
209
210 const int32_t presentToPresentMs =
211 msBetween(prevTimeRecord.presentTime, timeRecords[0].presentTime);
212 ALOGV("[%s]-[%" PRIu64 "]-present2present[%d]", layerName.c_str(),
213 timeRecords[0].frameNumber, presentToPresentMs);
214 timeStatsLayer.deltas["present2present"].insert(presentToPresentMs);
215
216 timeStats.stats[layerName].statsEnd = static_cast<int64_t>(std::time(0));
217 }
218 prevTimeRecord = timeRecords[0];
219 // TODO(zzyiwei): change timeRecords to use std::deque
220 timeRecords.erase(timeRecords.begin());
221 layerRecord.waitData--;
222 }
223}
224
225static bool layerNameIsValid(const std::string& layerName) {
226 // This regular expression captures the following layer names for instance:
227 // 1) StatusBat#0
228 // 2) NavigationBar#1
229 // 3) com.*#0
230 // 4) SurfaceView - com.*#0
231 // Using [-\\s\t]+ for the conjunction part between SurfaceView and com.* is
232 // a bit more robust in case there's a slight change.
233 // The layer name would only consist of . / $ _ 0-9 a-z A-Z in most cases.
234 std::regex re("(((SurfaceView[-\\s\\t]+)?com\\.[./$\\w]+)|((Status|Navigation)Bar))#\\d+");
235 return std::regex_match(layerName.begin(), layerName.end(), re);
236}
237
238void TimeStats::setPostTime(const std::string& layerName, uint64_t frameNumber, nsecs_t postTime) {
239 if (!mEnabled.load()) return;
240
241 ATRACE_CALL();
242 ALOGV("[%s]-[%" PRIu64 "]-PostTime[%" PRId64 "]", layerName.c_str(), frameNumber, postTime);
243
244 std::lock_guard<std::mutex> lock(mMutex);
245 if (!timeStatsTracker.count(layerName) && !layerNameIsValid(layerName)) {
246 return;
247 }
248 LayerRecord& layerRecord = timeStatsTracker[layerName];
249 if (layerRecord.timeRecords.size() == MAX_NUM_TIME_RECORDS) {
250 ALOGV("[%s]-timeRecords is already at its maximum size[%zu]", layerName.c_str(),
251 MAX_NUM_TIME_RECORDS);
252 // TODO(zzyiwei): if this happens, there must be a present fence missing
253 // or waitData is not in the correct position. Need to think out a
254 // reasonable way to recover from this state.
255 return;
256 }
257 // For most media content, the acquireFence is invalid because the buffer is
258 // ready at the queueBuffer stage. In this case, acquireTime should be given
259 // a default value as postTime.
260 TimeRecord timeRecord = {
261 .frameNumber = frameNumber,
262 .postTime = postTime,
263 .acquireTime = postTime,
264 };
265 layerRecord.timeRecords.push_back(timeRecord);
266 if (layerRecord.waitData < 0 ||
267 layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
268 layerRecord.waitData = layerRecord.timeRecords.size() - 1;
269}
270
271void TimeStats::setLatchTime(const std::string& layerName, uint64_t frameNumber,
272 nsecs_t latchTime) {
273 if (!mEnabled.load()) return;
274
275 ATRACE_CALL();
276 ALOGV("[%s]-[%" PRIu64 "]-LatchTime[%" PRId64 "]", layerName.c_str(), frameNumber, latchTime);
277
278 std::lock_guard<std::mutex> lock(mMutex);
279 if (!timeStatsTracker.count(layerName)) return;
280 LayerRecord& layerRecord = timeStatsTracker[layerName];
281 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
282 if (timeRecord.frameNumber == frameNumber) {
283 timeRecord.latchTime = latchTime;
284 }
285}
286
287void TimeStats::setDesiredTime(const std::string& layerName, uint64_t frameNumber,
288 nsecs_t desiredTime) {
289 if (!mEnabled.load()) return;
290
291 ATRACE_CALL();
292 ALOGV("[%s]-[%" PRIu64 "]-DesiredTime[%" PRId64 "]", layerName.c_str(), frameNumber,
293 desiredTime);
294
295 std::lock_guard<std::mutex> lock(mMutex);
296 if (!timeStatsTracker.count(layerName)) return;
297 LayerRecord& layerRecord = timeStatsTracker[layerName];
298 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
299 if (timeRecord.frameNumber == frameNumber) {
300 timeRecord.desiredTime = desiredTime;
301 }
302}
303
304void TimeStats::setAcquireTime(const std::string& layerName, uint64_t frameNumber,
305 nsecs_t acquireTime) {
306 if (!mEnabled.load()) return;
307
308 ATRACE_CALL();
309 ALOGV("[%s]-[%" PRIu64 "]-AcquireTime[%" PRId64 "]", layerName.c_str(), frameNumber,
310 acquireTime);
311
312 std::lock_guard<std::mutex> lock(mMutex);
313 if (!timeStatsTracker.count(layerName)) return;
314 LayerRecord& layerRecord = timeStatsTracker[layerName];
315 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
316 if (timeRecord.frameNumber == frameNumber) {
317 timeRecord.acquireTime = acquireTime;
318 }
319}
320
321void TimeStats::setAcquireFence(const std::string& layerName, uint64_t frameNumber,
322 const std::shared_ptr<FenceTime>& acquireFence) {
323 if (!mEnabled.load()) return;
324
325 ATRACE_CALL();
326 ALOGV("[%s]-[%" PRIu64 "]-AcquireFenceTime[%" PRId64 "]", layerName.c_str(), frameNumber,
327 acquireFence->getSignalTime());
328
329 std::lock_guard<std::mutex> lock(mMutex);
330 if (!timeStatsTracker.count(layerName)) return;
331 LayerRecord& layerRecord = timeStatsTracker[layerName];
332 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
333 if (timeRecord.frameNumber == frameNumber) {
334 timeRecord.acquireFence = acquireFence;
335 }
336}
337
338void TimeStats::setPresentTime(const std::string& layerName, uint64_t frameNumber,
339 nsecs_t presentTime) {
340 if (!mEnabled.load()) return;
341
342 ATRACE_CALL();
343 ALOGV("[%s]-[%" PRIu64 "]-PresentTime[%" PRId64 "]", layerName.c_str(), frameNumber,
344 presentTime);
345
346 std::lock_guard<std::mutex> lock(mMutex);
347 if (!timeStatsTracker.count(layerName)) return;
348 LayerRecord& layerRecord = timeStatsTracker[layerName];
349 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
350 if (timeRecord.frameNumber == frameNumber) {
351 timeRecord.presentTime = presentTime;
352 timeRecord.ready = true;
353 layerRecord.waitData++;
354 }
355
356 flushAvailableRecordsToStatsLocked(layerName);
357}
358
359void TimeStats::setPresentFence(const std::string& layerName, uint64_t frameNumber,
360 const std::shared_ptr<FenceTime>& presentFence) {
361 if (!mEnabled.load()) return;
362
363 ATRACE_CALL();
364 ALOGV("[%s]-[%" PRIu64 "]-PresentFenceTime[%" PRId64 "]", layerName.c_str(), frameNumber,
365 presentFence->getSignalTime());
366
367 std::lock_guard<std::mutex> lock(mMutex);
368 if (!timeStatsTracker.count(layerName)) return;
369 LayerRecord& layerRecord = timeStatsTracker[layerName];
370 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
371 if (timeRecord.frameNumber == frameNumber) {
372 timeRecord.presentFence = presentFence;
373 timeRecord.ready = true;
374 layerRecord.waitData++;
375 }
376
377 flushAvailableRecordsToStatsLocked(layerName);
378}
379
380void TimeStats::onDisconnect(const std::string& layerName) {
381 if (!mEnabled.load()) return;
382
383 ATRACE_CALL();
384 ALOGV("[%s]-onDisconnect", layerName.c_str());
385
386 std::lock_guard<std::mutex> lock(mMutex);
387 if (!timeStatsTracker.count(layerName)) return;
388 flushAvailableRecordsToStatsLocked(layerName);
389 timeStatsTracker.erase(layerName);
390}
391
392void TimeStats::clearLayerRecord(const std::string& layerName) {
393 if (!mEnabled.load()) return;
394
395 ATRACE_CALL();
396 ALOGV("[%s]-clearLayerRecord", layerName.c_str());
397
398 std::lock_guard<std::mutex> lock(mMutex);
399 if (!timeStatsTracker.count(layerName)) return;
400 LayerRecord& layerRecord = timeStatsTracker[layerName];
401 layerRecord.timeRecords.clear();
402 layerRecord.prevTimeRecord.ready = false;
403 layerRecord.waitData = -1;
404}
405
406void TimeStats::removeTimeRecord(const std::string& layerName, uint64_t frameNumber) {
407 if (!mEnabled.load()) return;
408
409 ATRACE_CALL();
410 ALOGV("[%s]-[%" PRIu64 "]-removeTimeRecord", layerName.c_str(), frameNumber);
411
412 std::lock_guard<std::mutex> lock(mMutex);
413 if (!timeStatsTracker.count(layerName)) return;
414 LayerRecord& layerRecord = timeStatsTracker[layerName];
415 size_t removeAt = 0;
416 for (const TimeRecord& record : layerRecord.timeRecords) {
417 if (record.frameNumber == frameNumber) break;
418 removeAt++;
419 }
420 if (removeAt == layerRecord.timeRecords.size()) return;
421 layerRecord.timeRecords.erase(layerRecord.timeRecords.begin() + removeAt);
422 if (layerRecord.waitData > static_cast<int32_t>(removeAt)) {
423 --layerRecord.waitData;
424 }
425}
426
427void TimeStats::enable() {
428 if (mEnabled.load()) return;
429
430 ATRACE_CALL();
431
432 std::lock_guard<std::mutex> lock(mMutex);
433 ALOGD("Enabled");
434 mEnabled.store(true);
435 timeStats.statsStart = static_cast<int64_t>(std::time(0));
436}
437
438void TimeStats::disable() {
439 if (!mEnabled.load()) return;
440
441 ATRACE_CALL();
442
443 std::lock_guard<std::mutex> lock(mMutex);
444 ALOGD("Disabled");
445 mEnabled.store(false);
446 timeStats.statsEnd = static_cast<int64_t>(std::time(0));
447}
448
449void TimeStats::clear() {
450 ATRACE_CALL();
451
452 std::lock_guard<std::mutex> lock(mMutex);
453 ALOGD("Cleared");
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700454 timeStats.stats.clear();
455 timeStats.statsStart = (mEnabled.load() ? static_cast<int64_t>(std::time(0)) : 0);
456 timeStats.statsEnd = 0;
457 timeStats.totalFrames = 0;
458 timeStats.missedFrames = 0;
459 timeStats.clientCompositionFrames = 0;
460}
461
462bool TimeStats::isEnabled() {
463 return mEnabled.load();
464}
465
Yiwei Zhang8a4015c2018-05-08 16:03:47 -0700466void TimeStats::dump(bool asProto, std::optional<uint32_t> maxLayers, String8& result) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700467 ATRACE_CALL();
468
469 std::lock_guard<std::mutex> lock(mMutex);
470 if (timeStats.statsStart == 0) {
471 return;
472 }
473
474 timeStats.statsEnd = static_cast<int64_t>(std::time(0));
475
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700476 if (asProto) {
Yiwei Zhang8a4015c2018-05-08 16:03:47 -0700477 ALOGD("Dumping TimeStats as proto");
478 SFTimeStatsGlobalProto timeStatsProto = timeStats.toProto(maxLayers);
479 result.append(timeStatsProto.SerializeAsString().c_str(), timeStatsProto.ByteSize());
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700480 } else {
Yiwei Zhang8a4015c2018-05-08 16:03:47 -0700481 ALOGD("Dumping TimeStats as text");
482 result.append(timeStats.toString(maxLayers).c_str());
483 result.append("\n");
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700484 }
485}
486
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700487} // namespace android