blob: b207d9993a52e3f28166503443d32c4993d77b98 [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;
Yiwei Zhangc5f2c452018-05-08 16:31:56 -0700155 std::deque<TimeRecord>& timeRecords = layerRecord.timeRecords;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700156 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];
Yiwei Zhangc5f2c452018-05-08 16:31:56 -0700202 timeRecords.pop_front();
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700203 layerRecord.waitData--;
204 }
205}
206
207static bool layerNameIsValid(const std::string& layerName) {
208 // This regular expression captures the following layer names for instance:
209 // 1) StatusBat#0
210 // 2) NavigationBar#1
211 // 3) com.*#0
212 // 4) SurfaceView - com.*#0
213 // Using [-\\s\t]+ for the conjunction part between SurfaceView and com.* is
214 // a bit more robust in case there's a slight change.
215 // The layer name would only consist of . / $ _ 0-9 a-z A-Z in most cases.
216 std::regex re("(((SurfaceView[-\\s\\t]+)?com\\.[./$\\w]+)|((Status|Navigation)Bar))#\\d+");
217 return std::regex_match(layerName.begin(), layerName.end(), re);
218}
219
220void TimeStats::setPostTime(const std::string& layerName, uint64_t frameNumber, nsecs_t postTime) {
221 if (!mEnabled.load()) return;
222
223 ATRACE_CALL();
224 ALOGV("[%s]-[%" PRIu64 "]-PostTime[%" PRId64 "]", layerName.c_str(), frameNumber, postTime);
225
226 std::lock_guard<std::mutex> lock(mMutex);
227 if (!timeStatsTracker.count(layerName) && !layerNameIsValid(layerName)) {
228 return;
229 }
230 LayerRecord& layerRecord = timeStatsTracker[layerName];
231 if (layerRecord.timeRecords.size() == MAX_NUM_TIME_RECORDS) {
232 ALOGV("[%s]-timeRecords is already at its maximum size[%zu]", layerName.c_str(),
233 MAX_NUM_TIME_RECORDS);
234 // TODO(zzyiwei): if this happens, there must be a present fence missing
235 // or waitData is not in the correct position. Need to think out a
236 // reasonable way to recover from this state.
237 return;
238 }
239 // For most media content, the acquireFence is invalid because the buffer is
240 // ready at the queueBuffer stage. In this case, acquireTime should be given
241 // a default value as postTime.
242 TimeRecord timeRecord = {
243 .frameNumber = frameNumber,
244 .postTime = postTime,
245 .acquireTime = postTime,
246 };
247 layerRecord.timeRecords.push_back(timeRecord);
248 if (layerRecord.waitData < 0 ||
249 layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
250 layerRecord.waitData = layerRecord.timeRecords.size() - 1;
251}
252
253void TimeStats::setLatchTime(const std::string& layerName, uint64_t frameNumber,
254 nsecs_t latchTime) {
255 if (!mEnabled.load()) return;
256
257 ATRACE_CALL();
258 ALOGV("[%s]-[%" PRIu64 "]-LatchTime[%" PRId64 "]", layerName.c_str(), frameNumber, latchTime);
259
260 std::lock_guard<std::mutex> lock(mMutex);
261 if (!timeStatsTracker.count(layerName)) return;
262 LayerRecord& layerRecord = timeStatsTracker[layerName];
263 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
264 if (timeRecord.frameNumber == frameNumber) {
265 timeRecord.latchTime = latchTime;
266 }
267}
268
269void TimeStats::setDesiredTime(const std::string& layerName, uint64_t frameNumber,
270 nsecs_t desiredTime) {
271 if (!mEnabled.load()) return;
272
273 ATRACE_CALL();
274 ALOGV("[%s]-[%" PRIu64 "]-DesiredTime[%" PRId64 "]", layerName.c_str(), frameNumber,
275 desiredTime);
276
277 std::lock_guard<std::mutex> lock(mMutex);
278 if (!timeStatsTracker.count(layerName)) return;
279 LayerRecord& layerRecord = timeStatsTracker[layerName];
280 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
281 if (timeRecord.frameNumber == frameNumber) {
282 timeRecord.desiredTime = desiredTime;
283 }
284}
285
286void TimeStats::setAcquireTime(const std::string& layerName, uint64_t frameNumber,
287 nsecs_t acquireTime) {
288 if (!mEnabled.load()) return;
289
290 ATRACE_CALL();
291 ALOGV("[%s]-[%" PRIu64 "]-AcquireTime[%" PRId64 "]", layerName.c_str(), frameNumber,
292 acquireTime);
293
294 std::lock_guard<std::mutex> lock(mMutex);
295 if (!timeStatsTracker.count(layerName)) return;
296 LayerRecord& layerRecord = timeStatsTracker[layerName];
297 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
298 if (timeRecord.frameNumber == frameNumber) {
299 timeRecord.acquireTime = acquireTime;
300 }
301}
302
303void TimeStats::setAcquireFence(const std::string& layerName, uint64_t frameNumber,
304 const std::shared_ptr<FenceTime>& acquireFence) {
305 if (!mEnabled.load()) return;
306
307 ATRACE_CALL();
308 ALOGV("[%s]-[%" PRIu64 "]-AcquireFenceTime[%" PRId64 "]", layerName.c_str(), frameNumber,
309 acquireFence->getSignalTime());
310
311 std::lock_guard<std::mutex> lock(mMutex);
312 if (!timeStatsTracker.count(layerName)) return;
313 LayerRecord& layerRecord = timeStatsTracker[layerName];
314 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
315 if (timeRecord.frameNumber == frameNumber) {
316 timeRecord.acquireFence = acquireFence;
317 }
318}
319
320void TimeStats::setPresentTime(const std::string& layerName, uint64_t frameNumber,
321 nsecs_t presentTime) {
322 if (!mEnabled.load()) return;
323
324 ATRACE_CALL();
325 ALOGV("[%s]-[%" PRIu64 "]-PresentTime[%" PRId64 "]", layerName.c_str(), frameNumber,
326 presentTime);
327
328 std::lock_guard<std::mutex> lock(mMutex);
329 if (!timeStatsTracker.count(layerName)) return;
330 LayerRecord& layerRecord = timeStatsTracker[layerName];
331 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
332 if (timeRecord.frameNumber == frameNumber) {
333 timeRecord.presentTime = presentTime;
334 timeRecord.ready = true;
335 layerRecord.waitData++;
336 }
337
338 flushAvailableRecordsToStatsLocked(layerName);
339}
340
341void TimeStats::setPresentFence(const std::string& layerName, uint64_t frameNumber,
342 const std::shared_ptr<FenceTime>& presentFence) {
343 if (!mEnabled.load()) return;
344
345 ATRACE_CALL();
346 ALOGV("[%s]-[%" PRIu64 "]-PresentFenceTime[%" PRId64 "]", layerName.c_str(), frameNumber,
347 presentFence->getSignalTime());
348
349 std::lock_guard<std::mutex> lock(mMutex);
350 if (!timeStatsTracker.count(layerName)) return;
351 LayerRecord& layerRecord = timeStatsTracker[layerName];
352 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
353 if (timeRecord.frameNumber == frameNumber) {
354 timeRecord.presentFence = presentFence;
355 timeRecord.ready = true;
356 layerRecord.waitData++;
357 }
358
359 flushAvailableRecordsToStatsLocked(layerName);
360}
361
362void TimeStats::onDisconnect(const std::string& layerName) {
363 if (!mEnabled.load()) return;
364
365 ATRACE_CALL();
366 ALOGV("[%s]-onDisconnect", layerName.c_str());
367
368 std::lock_guard<std::mutex> lock(mMutex);
369 if (!timeStatsTracker.count(layerName)) return;
370 flushAvailableRecordsToStatsLocked(layerName);
371 timeStatsTracker.erase(layerName);
372}
373
374void TimeStats::clearLayerRecord(const std::string& layerName) {
375 if (!mEnabled.load()) return;
376
377 ATRACE_CALL();
378 ALOGV("[%s]-clearLayerRecord", layerName.c_str());
379
380 std::lock_guard<std::mutex> lock(mMutex);
381 if (!timeStatsTracker.count(layerName)) return;
382 LayerRecord& layerRecord = timeStatsTracker[layerName];
383 layerRecord.timeRecords.clear();
384 layerRecord.prevTimeRecord.ready = false;
385 layerRecord.waitData = -1;
386}
387
388void TimeStats::removeTimeRecord(const std::string& layerName, uint64_t frameNumber) {
389 if (!mEnabled.load()) return;
390
391 ATRACE_CALL();
392 ALOGV("[%s]-[%" PRIu64 "]-removeTimeRecord", layerName.c_str(), frameNumber);
393
394 std::lock_guard<std::mutex> lock(mMutex);
395 if (!timeStatsTracker.count(layerName)) return;
396 LayerRecord& layerRecord = timeStatsTracker[layerName];
397 size_t removeAt = 0;
398 for (const TimeRecord& record : layerRecord.timeRecords) {
399 if (record.frameNumber == frameNumber) break;
400 removeAt++;
401 }
402 if (removeAt == layerRecord.timeRecords.size()) return;
403 layerRecord.timeRecords.erase(layerRecord.timeRecords.begin() + removeAt);
404 if (layerRecord.waitData > static_cast<int32_t>(removeAt)) {
405 --layerRecord.waitData;
406 }
407}
408
409void TimeStats::enable() {
410 if (mEnabled.load()) return;
411
412 ATRACE_CALL();
413
414 std::lock_guard<std::mutex> lock(mMutex);
415 ALOGD("Enabled");
416 mEnabled.store(true);
417 timeStats.statsStart = static_cast<int64_t>(std::time(0));
418}
419
420void TimeStats::disable() {
421 if (!mEnabled.load()) return;
422
423 ATRACE_CALL();
424
425 std::lock_guard<std::mutex> lock(mMutex);
426 ALOGD("Disabled");
427 mEnabled.store(false);
428 timeStats.statsEnd = static_cast<int64_t>(std::time(0));
429}
430
431void TimeStats::clear() {
432 ATRACE_CALL();
433
434 std::lock_guard<std::mutex> lock(mMutex);
435 ALOGD("Cleared");
436 timeStats.dumpStats.clear();
437 timeStats.stats.clear();
438 timeStats.statsStart = (mEnabled.load() ? static_cast<int64_t>(std::time(0)) : 0);
439 timeStats.statsEnd = 0;
440 timeStats.totalFrames = 0;
441 timeStats.missedFrames = 0;
442 timeStats.clientCompositionFrames = 0;
443}
444
445bool TimeStats::isEnabled() {
446 return mEnabled.load();
447}
448
449void TimeStats::dump(bool asProto, uint32_t maxLayers, String8& result) {
450 ATRACE_CALL();
451
452 std::lock_guard<std::mutex> lock(mMutex);
453 if (timeStats.statsStart == 0) {
454 return;
455 }
456
457 timeStats.statsEnd = static_cast<int64_t>(std::time(0));
458
459 // TODO(zzyiwei): refactor dumpStats into TimeStatsHelper
460 timeStats.dumpStats.clear();
461 for (auto& ele : timeStats.stats) {
462 timeStats.dumpStats.push_back(&ele.second);
463 }
464
465 std::sort(timeStats.dumpStats.begin(), timeStats.dumpStats.end(),
466 [](TimeStatsHelper::TimeStatsLayer* const& l,
467 TimeStatsHelper::TimeStatsLayer* const& r) {
468 return l->totalFrames > r->totalFrames;
469 });
470
471 if (maxLayers != 0 && maxLayers < timeStats.dumpStats.size()) {
472 timeStats.dumpStats.resize(maxLayers);
473 }
474
475 if (asProto) {
476 dumpAsProtoLocked(result);
477 } else {
478 dumpAsTextLocked(result);
479 }
480}
481
482void TimeStats::dumpAsTextLocked(String8& result) {
483 ALOGD("Dumping TimeStats as text");
484 result.append(timeStats.toString().c_str());
485 result.append("\n");
486}
487
488void TimeStats::dumpAsProtoLocked(String8& result) {
489 ALOGD("Dumping TimeStats as proto");
490 SFTimeStatsGlobalProto timeStatsProto = timeStats.toProto();
491 result.append(timeStatsProto.SerializeAsString().c_str(), timeStatsProto.ByteSize());
492}
493
494} // namespace android