blob: a6833a5b5daf1183ca6540dd8d8275af1ddefdde [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")) {
62 int64_t maxLayers = 0;
63 auto iter = argsMap.find("-maxlayers");
64 if (iter != argsMap.end() && iter->second + 1 < static_cast<int32_t>(args.size())) {
65 maxLayers = strtol(String8(args[iter->second + 1]).c_str(), nullptr, 10);
66 maxLayers = std::clamp(maxLayers, int64_t(0), int64_t(UINT32_MAX));
67 }
68
69 dump(asProto, static_cast<uint32_t>(maxLayers), result);
70 }
71
72 if (argsMap.count("-clear")) {
73 clear();
74 }
75
76 if (argsMap.count("-enable")) {
77 enable();
78 }
79}
80
81void TimeStats::incrementTotalFrames() {
82 if (!mEnabled.load()) return;
83
84 ATRACE_CALL();
85
86 std::lock_guard<std::mutex> lock(mMutex);
87 timeStats.totalFrames++;
88}
89
Yiwei Zhang621f9d42018-05-07 10:40:55 -070090void TimeStats::incrementMissedFrames() {
Yiwei Zhang0102ad22018-05-02 17:37:17 -070091 if (!mEnabled.load()) return;
92
93 ATRACE_CALL();
94
95 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhang0102ad22018-05-02 17:37:17 -070096 timeStats.missedFrames++;
97}
98
99void TimeStats::incrementClientCompositionFrames() {
100 if (!mEnabled.load()) return;
101
102 ATRACE_CALL();
103
104 std::lock_guard<std::mutex> lock(mMutex);
105 timeStats.clientCompositionFrames++;
106}
107
108bool TimeStats::recordReadyLocked(const std::string& layerName, TimeRecord* timeRecord) {
109 if (!timeRecord->ready) {
110 ALOGV("[%s]-[%" PRIu64 "]-presentFence is still not received", layerName.c_str(),
111 timeRecord->frameNumber);
112 return false;
113 }
114
115 if (timeRecord->acquireFence != nullptr) {
116 if (timeRecord->acquireFence->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
117 return false;
118 }
119 if (timeRecord->acquireFence->getSignalTime() != Fence::SIGNAL_TIME_INVALID) {
120 timeRecord->acquireTime = timeRecord->acquireFence->getSignalTime();
121 timeRecord->acquireFence = nullptr;
122 } else {
123 ALOGV("[%s]-[%" PRIu64 "]-acquireFence signal time is invalid", layerName.c_str(),
124 timeRecord->frameNumber);
125 }
126 }
127
128 if (timeRecord->presentFence != nullptr) {
129 if (timeRecord->presentFence->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
130 return false;
131 }
132 if (timeRecord->presentFence->getSignalTime() != Fence::SIGNAL_TIME_INVALID) {
133 timeRecord->presentTime = timeRecord->presentFence->getSignalTime();
134 timeRecord->presentFence = nullptr;
135 } else {
136 ALOGV("[%s]-[%" PRIu64 "]-presentFence signal time invalid", layerName.c_str(),
137 timeRecord->frameNumber);
138 }
139 }
140
141 return true;
142}
143
144static int32_t msBetween(nsecs_t start, nsecs_t end) {
145 int64_t delta = (end - start) / 1000000;
146 delta = std::clamp(delta, int64_t(INT32_MIN), int64_t(INT32_MAX));
147 return static_cast<int32_t>(delta);
148}
149
150void TimeStats::flushAvailableRecordsToStatsLocked(const std::string& layerName) {
151 ATRACE_CALL();
152
153 LayerRecord& layerRecord = timeStatsTracker[layerName];
154 TimeRecord& prevTimeRecord = layerRecord.prevTimeRecord;
155 std::vector<TimeRecord>& timeRecords = layerRecord.timeRecords;
156 while (!timeRecords.empty()) {
157 if (!recordReadyLocked(layerName, &timeRecords[0])) break;
158 ALOGV("[%s]-[%" PRIu64 "]-presentFenceTime[%" PRId64 "]", layerName.c_str(),
159 timeRecords[0].frameNumber, timeRecords[0].presentTime);
160
161 if (prevTimeRecord.ready) {
162 if (!timeStats.stats.count(layerName)) {
163 timeStats.stats[layerName].layerName = layerName;
164 timeStats.stats[layerName].statsStart = static_cast<int64_t>(std::time(0));
165 }
166 TimeStatsHelper::TimeStatsLayer& timeStatsLayer = timeStats.stats[layerName];
167 timeStatsLayer.totalFrames++;
168
169 const int32_t postToPresentMs =
170 msBetween(timeRecords[0].postTime, timeRecords[0].presentTime);
171 ALOGV("[%s]-[%" PRIu64 "]-post2present[%d]", layerName.c_str(),
172 timeRecords[0].frameNumber, postToPresentMs);
173 timeStatsLayer.deltas["post2present"].insert(postToPresentMs);
174
175 const int32_t acquireToPresentMs =
176 msBetween(timeRecords[0].acquireTime, timeRecords[0].presentTime);
177 ALOGV("[%s]-[%" PRIu64 "]-acquire2present[%d]", layerName.c_str(),
178 timeRecords[0].frameNumber, acquireToPresentMs);
179 timeStatsLayer.deltas["acquire2present"].insert(acquireToPresentMs);
180
181 const int32_t latchToPresentMs =
182 msBetween(timeRecords[0].latchTime, timeRecords[0].presentTime);
183 ALOGV("[%s]-[%" PRIu64 "]-latch2present[%d]", layerName.c_str(),
184 timeRecords[0].frameNumber, latchToPresentMs);
185 timeStatsLayer.deltas["latch2present"].insert(latchToPresentMs);
186
187 const int32_t desiredToPresentMs =
188 msBetween(timeRecords[0].desiredTime, timeRecords[0].presentTime);
189 ALOGV("[%s]-[%" PRIu64 "]-desired2present[%d]", layerName.c_str(),
190 timeRecords[0].frameNumber, desiredToPresentMs);
191 timeStatsLayer.deltas["desired2present"].insert(desiredToPresentMs);
192
193 const int32_t presentToPresentMs =
194 msBetween(prevTimeRecord.presentTime, timeRecords[0].presentTime);
195 ALOGV("[%s]-[%" PRIu64 "]-present2present[%d]", layerName.c_str(),
196 timeRecords[0].frameNumber, presentToPresentMs);
197 timeStatsLayer.deltas["present2present"].insert(presentToPresentMs);
198
199 timeStats.stats[layerName].statsEnd = static_cast<int64_t>(std::time(0));
200 }
201 prevTimeRecord = timeRecords[0];
202 // TODO(zzyiwei): change timeRecords to use std::deque
203 timeRecords.erase(timeRecords.begin());
204 layerRecord.waitData--;
205 }
206}
207
208static bool layerNameIsValid(const std::string& layerName) {
209 // This regular expression captures the following layer names for instance:
210 // 1) StatusBat#0
211 // 2) NavigationBar#1
212 // 3) com.*#0
213 // 4) SurfaceView - com.*#0
214 // Using [-\\s\t]+ for the conjunction part between SurfaceView and com.* is
215 // a bit more robust in case there's a slight change.
216 // The layer name would only consist of . / $ _ 0-9 a-z A-Z in most cases.
217 std::regex re("(((SurfaceView[-\\s\\t]+)?com\\.[./$\\w]+)|((Status|Navigation)Bar))#\\d+");
218 return std::regex_match(layerName.begin(), layerName.end(), re);
219}
220
221void TimeStats::setPostTime(const std::string& layerName, uint64_t frameNumber, nsecs_t postTime) {
222 if (!mEnabled.load()) return;
223
224 ATRACE_CALL();
225 ALOGV("[%s]-[%" PRIu64 "]-PostTime[%" PRId64 "]", layerName.c_str(), frameNumber, postTime);
226
227 std::lock_guard<std::mutex> lock(mMutex);
228 if (!timeStatsTracker.count(layerName) && !layerNameIsValid(layerName)) {
229 return;
230 }
231 LayerRecord& layerRecord = timeStatsTracker[layerName];
232 if (layerRecord.timeRecords.size() == MAX_NUM_TIME_RECORDS) {
233 ALOGV("[%s]-timeRecords is already at its maximum size[%zu]", layerName.c_str(),
234 MAX_NUM_TIME_RECORDS);
235 // TODO(zzyiwei): if this happens, there must be a present fence missing
236 // or waitData is not in the correct position. Need to think out a
237 // reasonable way to recover from this state.
238 return;
239 }
240 // For most media content, the acquireFence is invalid because the buffer is
241 // ready at the queueBuffer stage. In this case, acquireTime should be given
242 // a default value as postTime.
243 TimeRecord timeRecord = {
244 .frameNumber = frameNumber,
245 .postTime = postTime,
246 .acquireTime = postTime,
247 };
248 layerRecord.timeRecords.push_back(timeRecord);
249 if (layerRecord.waitData < 0 ||
250 layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
251 layerRecord.waitData = layerRecord.timeRecords.size() - 1;
252}
253
254void TimeStats::setLatchTime(const std::string& layerName, uint64_t frameNumber,
255 nsecs_t latchTime) {
256 if (!mEnabled.load()) return;
257
258 ATRACE_CALL();
259 ALOGV("[%s]-[%" PRIu64 "]-LatchTime[%" PRId64 "]", layerName.c_str(), frameNumber, latchTime);
260
261 std::lock_guard<std::mutex> lock(mMutex);
262 if (!timeStatsTracker.count(layerName)) return;
263 LayerRecord& layerRecord = timeStatsTracker[layerName];
264 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
265 if (timeRecord.frameNumber == frameNumber) {
266 timeRecord.latchTime = latchTime;
267 }
268}
269
270void TimeStats::setDesiredTime(const std::string& layerName, uint64_t frameNumber,
271 nsecs_t desiredTime) {
272 if (!mEnabled.load()) return;
273
274 ATRACE_CALL();
275 ALOGV("[%s]-[%" PRIu64 "]-DesiredTime[%" PRId64 "]", layerName.c_str(), frameNumber,
276 desiredTime);
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.desiredTime = desiredTime;
284 }
285}
286
287void TimeStats::setAcquireTime(const std::string& layerName, uint64_t frameNumber,
288 nsecs_t acquireTime) {
289 if (!mEnabled.load()) return;
290
291 ATRACE_CALL();
292 ALOGV("[%s]-[%" PRIu64 "]-AcquireTime[%" PRId64 "]", layerName.c_str(), frameNumber,
293 acquireTime);
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.acquireTime = acquireTime;
301 }
302}
303
304void TimeStats::setAcquireFence(const std::string& layerName, uint64_t frameNumber,
305 const std::shared_ptr<FenceTime>& acquireFence) {
306 if (!mEnabled.load()) return;
307
308 ATRACE_CALL();
309 ALOGV("[%s]-[%" PRIu64 "]-AcquireFenceTime[%" PRId64 "]", layerName.c_str(), frameNumber,
310 acquireFence->getSignalTime());
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.acquireFence = acquireFence;
318 }
319}
320
321void TimeStats::setPresentTime(const std::string& layerName, uint64_t frameNumber,
322 nsecs_t presentTime) {
323 if (!mEnabled.load()) return;
324
325 ATRACE_CALL();
326 ALOGV("[%s]-[%" PRIu64 "]-PresentTime[%" PRId64 "]", layerName.c_str(), frameNumber,
327 presentTime);
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.presentTime = presentTime;
335 timeRecord.ready = true;
336 layerRecord.waitData++;
337 }
338
339 flushAvailableRecordsToStatsLocked(layerName);
340}
341
342void TimeStats::setPresentFence(const std::string& layerName, uint64_t frameNumber,
343 const std::shared_ptr<FenceTime>& presentFence) {
344 if (!mEnabled.load()) return;
345
346 ATRACE_CALL();
347 ALOGV("[%s]-[%" PRIu64 "]-PresentFenceTime[%" PRId64 "]", layerName.c_str(), frameNumber,
348 presentFence->getSignalTime());
349
350 std::lock_guard<std::mutex> lock(mMutex);
351 if (!timeStatsTracker.count(layerName)) return;
352 LayerRecord& layerRecord = timeStatsTracker[layerName];
353 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
354 if (timeRecord.frameNumber == frameNumber) {
355 timeRecord.presentFence = presentFence;
356 timeRecord.ready = true;
357 layerRecord.waitData++;
358 }
359
360 flushAvailableRecordsToStatsLocked(layerName);
361}
362
363void TimeStats::onDisconnect(const std::string& layerName) {
364 if (!mEnabled.load()) return;
365
366 ATRACE_CALL();
367 ALOGV("[%s]-onDisconnect", layerName.c_str());
368
369 std::lock_guard<std::mutex> lock(mMutex);
370 if (!timeStatsTracker.count(layerName)) return;
371 flushAvailableRecordsToStatsLocked(layerName);
372 timeStatsTracker.erase(layerName);
373}
374
375void TimeStats::clearLayerRecord(const std::string& layerName) {
376 if (!mEnabled.load()) return;
377
378 ATRACE_CALL();
379 ALOGV("[%s]-clearLayerRecord", layerName.c_str());
380
381 std::lock_guard<std::mutex> lock(mMutex);
382 if (!timeStatsTracker.count(layerName)) return;
383 LayerRecord& layerRecord = timeStatsTracker[layerName];
384 layerRecord.timeRecords.clear();
385 layerRecord.prevTimeRecord.ready = false;
386 layerRecord.waitData = -1;
387}
388
389void TimeStats::removeTimeRecord(const std::string& layerName, uint64_t frameNumber) {
390 if (!mEnabled.load()) return;
391
392 ATRACE_CALL();
393 ALOGV("[%s]-[%" PRIu64 "]-removeTimeRecord", layerName.c_str(), frameNumber);
394
395 std::lock_guard<std::mutex> lock(mMutex);
396 if (!timeStatsTracker.count(layerName)) return;
397 LayerRecord& layerRecord = timeStatsTracker[layerName];
398 size_t removeAt = 0;
399 for (const TimeRecord& record : layerRecord.timeRecords) {
400 if (record.frameNumber == frameNumber) break;
401 removeAt++;
402 }
403 if (removeAt == layerRecord.timeRecords.size()) return;
404 layerRecord.timeRecords.erase(layerRecord.timeRecords.begin() + removeAt);
405 if (layerRecord.waitData > static_cast<int32_t>(removeAt)) {
406 --layerRecord.waitData;
407 }
408}
409
410void TimeStats::enable() {
411 if (mEnabled.load()) return;
412
413 ATRACE_CALL();
414
415 std::lock_guard<std::mutex> lock(mMutex);
416 ALOGD("Enabled");
417 mEnabled.store(true);
418 timeStats.statsStart = static_cast<int64_t>(std::time(0));
419}
420
421void TimeStats::disable() {
422 if (!mEnabled.load()) return;
423
424 ATRACE_CALL();
425
426 std::lock_guard<std::mutex> lock(mMutex);
427 ALOGD("Disabled");
428 mEnabled.store(false);
429 timeStats.statsEnd = static_cast<int64_t>(std::time(0));
430}
431
432void TimeStats::clear() {
433 ATRACE_CALL();
434
435 std::lock_guard<std::mutex> lock(mMutex);
436 ALOGD("Cleared");
437 timeStats.dumpStats.clear();
438 timeStats.stats.clear();
439 timeStats.statsStart = (mEnabled.load() ? static_cast<int64_t>(std::time(0)) : 0);
440 timeStats.statsEnd = 0;
441 timeStats.totalFrames = 0;
442 timeStats.missedFrames = 0;
443 timeStats.clientCompositionFrames = 0;
444}
445
446bool TimeStats::isEnabled() {
447 return mEnabled.load();
448}
449
450void TimeStats::dump(bool asProto, uint32_t maxLayers, String8& result) {
451 ATRACE_CALL();
452
453 std::lock_guard<std::mutex> lock(mMutex);
454 if (timeStats.statsStart == 0) {
455 return;
456 }
457
458 timeStats.statsEnd = static_cast<int64_t>(std::time(0));
459
460 // TODO(zzyiwei): refactor dumpStats into TimeStatsHelper
461 timeStats.dumpStats.clear();
462 for (auto& ele : timeStats.stats) {
463 timeStats.dumpStats.push_back(&ele.second);
464 }
465
466 std::sort(timeStats.dumpStats.begin(), timeStats.dumpStats.end(),
467 [](TimeStatsHelper::TimeStatsLayer* const& l,
468 TimeStatsHelper::TimeStatsLayer* const& r) {
469 return l->totalFrames > r->totalFrames;
470 });
471
472 if (maxLayers != 0 && maxLayers < timeStats.dumpStats.size()) {
473 timeStats.dumpStats.resize(maxLayers);
474 }
475
476 if (asProto) {
477 dumpAsProtoLocked(result);
478 } else {
479 dumpAsTextLocked(result);
480 }
481}
482
483void TimeStats::dumpAsTextLocked(String8& result) {
484 ALOGD("Dumping TimeStats as text");
485 result.append(timeStats.toString().c_str());
486 result.append("\n");
487}
488
489void TimeStats::dumpAsProtoLocked(String8& result) {
490 ALOGD("Dumping TimeStats as proto");
491 SFTimeStatsGlobalProto timeStatsProto = timeStats.toProto();
492 result.append(timeStatsProto.SerializeAsString().c_str(), timeStatsProto.ByteSize());
493}
494
495} // namespace android