blob: 630cef1fd4f26e136a639097d5f4cbdaea8d0475 [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 */
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080016
Yiwei Zhang0102ad22018-05-02 17:37:17 -070017#undef LOG_TAG
18#define LOG_TAG "TimeStats"
19#define ATRACE_TAG ATRACE_TAG_GRAPHICS
20
Yiwei Zhang0102ad22018-05-02 17:37:17 -070021#include <android-base/stringprintf.h>
Yiwei Zhang0102ad22018-05-02 17:37:17 -070022#include <log/log.h>
Tej Singhe2751772021-04-06 22:05:29 -070023#include <timestatsatomsproto/TimeStatsAtomsProtoHeader.h>
Yiwei Zhang0102ad22018-05-02 17:37:17 -070024#include <utils/String8.h>
Yiwei Zhang3a226d22018-10-16 09:23:03 -070025#include <utils/Timers.h>
Yiwei Zhang0102ad22018-05-02 17:37:17 -070026#include <utils/Trace.h>
27
28#include <algorithm>
Alec Mouri9519bf12019-11-15 16:54:44 -080029#include <chrono>
Alberto Gonzalez9fe14512022-09-29 21:27:34 +000030#include <cmath>
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070031#include <unordered_map>
Yiwei Zhang0102ad22018-05-02 17:37:17 -070032
Tej Singhe2751772021-04-06 22:05:29 -070033#include "TimeStats.h"
Alec Mouri9a29e672020-09-14 12:39:14 -070034#include "timestatsproto/TimeStatsHelper.h"
35
Yiwei Zhang0102ad22018-05-02 17:37:17 -070036namespace android {
37
Alec Mourifb571ea2019-01-24 18:42:10 -080038namespace impl {
39
Alec Mouri37384342020-01-02 17:23:37 -080040namespace {
Alec Mouri8e2f31b2020-01-16 22:04:35 +000041
Tej Singhe2751772021-04-06 22:05:29 -070042FrameTimingHistogram histogramToProto(const std::unordered_map<int32_t, int32_t>& histogram,
43 size_t maxPulledHistogramBuckets) {
Alec Mouri37384342020-01-02 17:23:37 -080044 auto buckets = std::vector<std::pair<int32_t, int32_t>>(histogram.begin(), histogram.end());
45 std::sort(buckets.begin(), buckets.end(),
46 [](std::pair<int32_t, int32_t>& left, std::pair<int32_t, int32_t>& right) {
47 return left.second > right.second;
48 });
49
Tej Singhe2751772021-04-06 22:05:29 -070050 FrameTimingHistogram histogramProto;
Alec Mouri37384342020-01-02 17:23:37 -080051 int histogramSize = 0;
52 for (const auto& bucket : buckets) {
53 if (++histogramSize > maxPulledHistogramBuckets) {
54 break;
55 }
Tej Singhe2751772021-04-06 22:05:29 -070056 histogramProto.add_time_millis_buckets((int32_t)bucket.first);
57 histogramProto.add_frame_counts((int64_t)bucket.second);
Alec Mouri37384342020-01-02 17:23:37 -080058 }
Tej Singhe2751772021-04-06 22:05:29 -070059 return histogramProto;
Alec Mouri37384342020-01-02 17:23:37 -080060}
Alec Mouri75de8f22021-01-20 14:53:44 -080061
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070062SurfaceflingerStatsLayerInfo_GameMode gameModeToProto(GameMode gameMode) {
Adithya Srinivasan58069dc2021-06-04 20:37:02 +000063 switch (gameMode) {
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070064 case GameMode::Unsupported:
Adithya Srinivasan58069dc2021-06-04 20:37:02 +000065 return SurfaceflingerStatsLayerInfo::GAME_MODE_UNSUPPORTED;
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070066 case GameMode::Standard:
Adithya Srinivasan58069dc2021-06-04 20:37:02 +000067 return SurfaceflingerStatsLayerInfo::GAME_MODE_STANDARD;
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070068 case GameMode::Performance:
Adithya Srinivasan58069dc2021-06-04 20:37:02 +000069 return SurfaceflingerStatsLayerInfo::GAME_MODE_PERFORMANCE;
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -070070 case GameMode::Battery:
Adithya Srinivasan58069dc2021-06-04 20:37:02 +000071 return SurfaceflingerStatsLayerInfo::GAME_MODE_BATTERY;
Xiang Wangf0c5cca2022-11-09 18:03:09 -080072 case GameMode::Custom:
73 return SurfaceflingerStatsLayerInfo::GAME_MODE_CUSTOM;
Adithya Srinivasan58069dc2021-06-04 20:37:02 +000074 default:
75 return SurfaceflingerStatsLayerInfo::GAME_MODE_UNSPECIFIED;
76 }
77}
78
Tej Singhe2751772021-04-06 22:05:29 -070079SurfaceflingerStatsLayerInfo_SetFrameRateVote frameRateVoteToProto(
80 const TimeStats::SetFrameRateVote& setFrameRateVote) {
81 using FrameRateCompatibilityEnum =
82 SurfaceflingerStatsLayerInfo::SetFrameRateVote::FrameRateCompatibility;
83 using SeamlessnessEnum = SurfaceflingerStatsLayerInfo::SetFrameRateVote::Seamlessness;
Alec Mouri75de8f22021-01-20 14:53:44 -080084
Tej Singhe2751772021-04-06 22:05:29 -070085 SurfaceflingerStatsLayerInfo_SetFrameRateVote proto;
86 proto.set_frame_rate(setFrameRateVote.frameRate);
87 proto.set_frame_rate_compatibility(
88 static_cast<FrameRateCompatibilityEnum>(setFrameRateVote.frameRateCompatibility));
89 proto.set_seamlessness(static_cast<SeamlessnessEnum>(setFrameRateVote.seamlessness));
90 return proto;
Alec Mouri75de8f22021-01-20 14:53:44 -080091}
Alec Mouri37384342020-01-02 17:23:37 -080092} // namespace
93
Huihong Luo30aa4372022-10-03 14:54:12 -070094bool TimeStats::populateGlobalAtom(std::vector<uint8_t>* pulledData) {
Alec Mouridfad9002020-02-12 17:49:09 -080095 std::lock_guard<std::mutex> lock(mMutex);
96
Alec Mouri7d436ec2021-01-27 20:40:50 -080097 if (mTimeStats.statsStartLegacy == 0) {
Tej Singhe2751772021-04-06 22:05:29 -070098 return false;
Alec Mouridfad9002020-02-12 17:49:09 -080099 }
100 flushPowerTimeLocked();
Tej Singhe2751772021-04-06 22:05:29 -0700101 SurfaceflingerStatsGlobalInfoWrapper atomList;
Alec Mouri7d436ec2021-01-27 20:40:50 -0800102 for (const auto& globalSlice : mTimeStats.stats) {
Tej Singhe2751772021-04-06 22:05:29 -0700103 SurfaceflingerStatsGlobalInfo* atom = atomList.add_atom();
104 atom->set_total_frames(mTimeStats.totalFramesLegacy);
105 atom->set_missed_frames(mTimeStats.missedFramesLegacy);
106 atom->set_client_composition_frames(mTimeStats.clientCompositionFramesLegacy);
107 atom->set_display_on_millis(mTimeStats.displayOnTimeLegacy);
108 atom->set_animation_millis(mTimeStats.presentToPresentLegacy.totalTime());
109 atom->set_event_connection_count(mTimeStats.displayEventConnectionsCountLegacy);
110 *atom->mutable_frame_duration() =
111 histogramToProto(mTimeStats.frameDurationLegacy.hist, mMaxPulledHistogramBuckets);
112 *atom->mutable_render_engine_timing() =
113 histogramToProto(mTimeStats.renderEngineTimingLegacy.hist,
114 mMaxPulledHistogramBuckets);
115 atom->set_total_timeline_frames(globalSlice.second.jankPayload.totalFrames);
116 atom->set_total_janky_frames(globalSlice.second.jankPayload.totalJankyFrames);
117 atom->set_total_janky_frames_with_long_cpu(globalSlice.second.jankPayload.totalSFLongCpu);
118 atom->set_total_janky_frames_with_long_gpu(globalSlice.second.jankPayload.totalSFLongGpu);
119 atom->set_total_janky_frames_sf_unattributed(
120 globalSlice.second.jankPayload.totalSFUnattributed);
121 atom->set_total_janky_frames_app_unattributed(
122 globalSlice.second.jankPayload.totalAppUnattributed);
123 atom->set_total_janky_frames_sf_scheduling(
124 globalSlice.second.jankPayload.totalSFScheduling);
125 atom->set_total_jank_frames_sf_prediction_error(
126 globalSlice.second.jankPayload.totalSFPredictionError);
127 atom->set_total_jank_frames_app_buffer_stuffing(
128 globalSlice.second.jankPayload.totalAppBufferStuffing);
129 atom->set_display_refresh_rate_bucket(globalSlice.first.displayRefreshRateBucket);
130 *atom->mutable_sf_deadline_misses() =
131 histogramToProto(globalSlice.second.displayDeadlineDeltas.hist,
132 mMaxPulledHistogramBuckets);
133 *atom->mutable_sf_prediction_errors() =
134 histogramToProto(globalSlice.second.displayPresentDeltas.hist,
135 mMaxPulledHistogramBuckets);
136 atom->set_render_rate_bucket(globalSlice.first.renderRateBucket);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800137 }
138
Tej Singhe2751772021-04-06 22:05:29 -0700139 // Always clear data.
Alec Mouridfad9002020-02-12 17:49:09 -0800140 clearGlobalLocked();
141
Huihong Luo30aa4372022-10-03 14:54:12 -0700142 pulledData->resize(atomList.ByteSizeLong());
143 return atomList.SerializeToArray(pulledData->data(), atomList.ByteSizeLong());
Alec Mouridfad9002020-02-12 17:49:09 -0800144}
145
Huihong Luo30aa4372022-10-03 14:54:12 -0700146bool TimeStats::populateLayerAtom(std::vector<uint8_t>* pulledData) {
Alec Mouri37384342020-01-02 17:23:37 -0800147 std::lock_guard<std::mutex> lock(mMutex);
148
Alec Mouri363faf02021-01-29 16:34:55 -0800149 std::vector<TimeStatsHelper::TimeStatsLayer*> dumpStats;
Alec Mouri7d436ec2021-01-27 20:40:50 -0800150 uint32_t numLayers = 0;
151 for (const auto& globalSlice : mTimeStats.stats) {
152 numLayers += globalSlice.second.stats.size();
153 }
154
155 dumpStats.reserve(numLayers);
156
Alec Mouri363faf02021-01-29 16:34:55 -0800157 for (auto& globalSlice : mTimeStats.stats) {
158 for (auto& layerSlice : globalSlice.second.stats) {
Alec Mouri7d436ec2021-01-27 20:40:50 -0800159 dumpStats.push_back(&layerSlice.second);
160 }
Alec Mouri37384342020-01-02 17:23:37 -0800161 }
162
163 std::sort(dumpStats.begin(), dumpStats.end(),
164 [](TimeStatsHelper::TimeStatsLayer const* l,
165 TimeStatsHelper::TimeStatsLayer const* r) {
166 return l->totalFrames > r->totalFrames;
167 });
168
169 if (mMaxPulledLayers < dumpStats.size()) {
170 dumpStats.resize(mMaxPulledLayers);
171 }
172
Tej Singhe2751772021-04-06 22:05:29 -0700173 SurfaceflingerStatsLayerInfoWrapper atomList;
Alec Mouri363faf02021-01-29 16:34:55 -0800174 for (auto& layer : dumpStats) {
Tej Singhe2751772021-04-06 22:05:29 -0700175 SurfaceflingerStatsLayerInfo* atom = atomList.add_atom();
176 atom->set_layer_name(layer->layerName);
177 atom->set_total_frames(layer->totalFrames);
178 atom->set_dropped_frames(layer->droppedFrames);
179 const auto& present2PresentHist = layer->deltas.find("present2present");
180 if (present2PresentHist != layer->deltas.cend()) {
181 *atom->mutable_present_to_present() =
182 histogramToProto(present2PresentHist->second.hist, mMaxPulledHistogramBuckets);
183 }
Alberto Gonzalez9fe14512022-09-29 21:27:34 +0000184 const auto& present2PresentDeltaHist = layer->deltas.find("present2presentDelta");
185 if (present2PresentDeltaHist != layer->deltas.cend()) {
186 *atom->mutable_present_to_present_delta() =
187 histogramToProto(present2PresentDeltaHist->second.hist,
188 mMaxPulledHistogramBuckets);
189 }
Tej Singhe2751772021-04-06 22:05:29 -0700190 const auto& post2presentHist = layer->deltas.find("post2present");
191 if (post2presentHist != layer->deltas.cend()) {
192 *atom->mutable_post_to_present() =
193 histogramToProto(post2presentHist->second.hist, mMaxPulledHistogramBuckets);
194 }
195 const auto& acquire2presentHist = layer->deltas.find("acquire2present");
196 if (acquire2presentHist != layer->deltas.cend()) {
197 *atom->mutable_acquire_to_present() =
198 histogramToProto(acquire2presentHist->second.hist, mMaxPulledHistogramBuckets);
199 }
200 const auto& latch2presentHist = layer->deltas.find("latch2present");
201 if (latch2presentHist != layer->deltas.cend()) {
202 *atom->mutable_latch_to_present() =
203 histogramToProto(latch2presentHist->second.hist, mMaxPulledHistogramBuckets);
204 }
205 const auto& desired2presentHist = layer->deltas.find("desired2present");
206 if (desired2presentHist != layer->deltas.cend()) {
207 *atom->mutable_desired_to_present() =
208 histogramToProto(desired2presentHist->second.hist, mMaxPulledHistogramBuckets);
209 }
210 const auto& post2acquireHist = layer->deltas.find("post2acquire");
211 if (post2acquireHist != layer->deltas.cend()) {
212 *atom->mutable_post_to_acquire() =
213 histogramToProto(post2acquireHist->second.hist, mMaxPulledHistogramBuckets);
Alec Mouri37384342020-01-02 17:23:37 -0800214 }
215
Tej Singhe2751772021-04-06 22:05:29 -0700216 atom->set_late_acquire_frames(layer->lateAcquireFrames);
217 atom->set_bad_desired_present_frames(layer->badDesiredPresentFrames);
218 atom->set_uid(layer->uid);
219 atom->set_total_timeline_frames(layer->jankPayload.totalFrames);
220 atom->set_total_janky_frames(layer->jankPayload.totalJankyFrames);
221 atom->set_total_janky_frames_with_long_cpu(layer->jankPayload.totalSFLongCpu);
222 atom->set_total_janky_frames_with_long_gpu(layer->jankPayload.totalSFLongGpu);
223 atom->set_total_janky_frames_sf_unattributed(layer->jankPayload.totalSFUnattributed);
224 atom->set_total_janky_frames_app_unattributed(layer->jankPayload.totalAppUnattributed);
225 atom->set_total_janky_frames_sf_scheduling(layer->jankPayload.totalSFScheduling);
226 atom->set_total_jank_frames_sf_prediction_error(layer->jankPayload.totalSFPredictionError);
227 atom->set_total_jank_frames_app_buffer_stuffing(layer->jankPayload.totalAppBufferStuffing);
228 atom->set_display_refresh_rate_bucket(layer->displayRefreshRateBucket);
229 atom->set_render_rate_bucket(layer->renderRateBucket);
230 *atom->mutable_set_frame_rate_vote() = frameRateVoteToProto(layer->setFrameRateVote);
231 *atom->mutable_app_deadline_misses() =
232 histogramToProto(layer->deltas["appDeadlineDeltas"].hist,
233 mMaxPulledHistogramBuckets);
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000234 atom->set_game_mode(gameModeToProto(layer->gameMode));
Alec Mouri37384342020-01-02 17:23:37 -0800235 }
Tej Singhe2751772021-04-06 22:05:29 -0700236
237 // Always clear data.
Alec Mouri37384342020-01-02 17:23:37 -0800238 clearLayersLocked();
239
Huihong Luo30aa4372022-10-03 14:54:12 -0700240 pulledData->resize(atomList.ByteSizeLong());
241 return atomList.SerializeToArray(pulledData->data(), atomList.ByteSizeLong());
Alec Mouri37384342020-01-02 17:23:37 -0800242}
243
Tej Singhe2751772021-04-06 22:05:29 -0700244TimeStats::TimeStats() : TimeStats(std::nullopt, std::nullopt) {}
Alec Mouri37384342020-01-02 17:23:37 -0800245
Tej Singhe2751772021-04-06 22:05:29 -0700246TimeStats::TimeStats(std::optional<size_t> maxPulledLayers,
Alec Mouri37384342020-01-02 17:23:37 -0800247 std::optional<size_t> maxPulledHistogramBuckets) {
Alec Mouri37384342020-01-02 17:23:37 -0800248 if (maxPulledLayers) {
249 mMaxPulledLayers = *maxPulledLayers;
250 }
251
252 if (maxPulledHistogramBuckets) {
253 mMaxPulledHistogramBuckets = *maxPulledHistogramBuckets;
254 }
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000255}
256
Huihong Luo30aa4372022-10-03 14:54:12 -0700257bool TimeStats::onPullAtom(const int atomId, std::vector<uint8_t>* pulledData) {
Tej Singhe2751772021-04-06 22:05:29 -0700258 bool success = false;
259 if (atomId == 10062) { // SURFACEFLINGER_STATS_GLOBAL_INFO
260 success = populateGlobalAtom(pulledData);
261 } else if (atomId == 10063) { // SURFACEFLINGER_STATS_LAYER_INFO
262 success = populateLayerAtom(pulledData);
263 }
Alec Mouri3ecd5cd2020-01-29 12:53:07 -0800264
Tej Singhe2751772021-04-06 22:05:29 -0700265 // Enable timestats now. The first full pull for a given build is expected to
266 // have empty or very little stats, as stats are first enabled after the
267 // first pull is completed for either the global or layer stats.
268 enable();
269 return success;
Alec Mourib3885ad2019-09-06 17:08:55 -0700270}
271
Dominik Laskowskic2867142019-01-21 11:33:38 -0800272void TimeStats::parseArgs(bool asProto, const Vector<String16>& args, std::string& result) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700273 ATRACE_CALL();
274
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700275 std::unordered_map<std::string, int32_t> argsMap;
Dominik Laskowskic2867142019-01-21 11:33:38 -0800276 for (size_t index = 0; index < args.size(); ++index) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700277 argsMap[std::string(String8(args[index]).c_str())] = index;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700278 }
279
280 if (argsMap.count("-disable")) {
281 disable();
282 }
283
284 if (argsMap.count("-dump")) {
Yiwei Zhang8a4015c2018-05-08 16:03:47 -0700285 std::optional<uint32_t> maxLayers = std::nullopt;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700286 auto iter = argsMap.find("-maxlayers");
287 if (iter != argsMap.end() && iter->second + 1 < static_cast<int32_t>(args.size())) {
Yiwei Zhang8a4015c2018-05-08 16:03:47 -0700288 int64_t value = strtol(String8(args[iter->second + 1]).c_str(), nullptr, 10);
289 value = std::clamp(value, int64_t(0), int64_t(UINT32_MAX));
290 maxLayers = static_cast<uint32_t>(value);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700291 }
292
Yiwei Zhang8a4015c2018-05-08 16:03:47 -0700293 dump(asProto, maxLayers, result);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700294 }
295
296 if (argsMap.count("-clear")) {
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000297 clearAll();
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700298 }
299
300 if (argsMap.count("-enable")) {
301 enable();
302 }
303}
304
Yiwei Zhang7eb58b72019-04-22 19:00:02 -0700305std::string TimeStats::miniDump() {
306 ATRACE_CALL();
307
308 std::string result = "TimeStats miniDump:\n";
309 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhange926ab52019-08-14 15:16:00 -0700310 android::base::StringAppendF(&result, "Number of layers currently being tracked is %zu\n",
Yiwei Zhang7eb58b72019-04-22 19:00:02 -0700311 mTimeStatsTracker.size());
Yiwei Zhange926ab52019-08-14 15:16:00 -0700312 android::base::StringAppendF(&result, "Number of layers in the stats pool is %zu\n",
313 mTimeStats.stats.size());
Yiwei Zhang7eb58b72019-04-22 19:00:02 -0700314 return result;
315}
316
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700317void TimeStats::incrementTotalFrames() {
318 if (!mEnabled.load()) return;
319
320 ATRACE_CALL();
321
322 std::lock_guard<std::mutex> lock(mMutex);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800323 mTimeStats.totalFramesLegacy++;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700324}
325
Yiwei Zhang621f9d42018-05-07 10:40:55 -0700326void TimeStats::incrementMissedFrames() {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700327 if (!mEnabled.load()) return;
328
329 ATRACE_CALL();
330
331 std::lock_guard<std::mutex> lock(mMutex);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800332 mTimeStats.missedFramesLegacy++;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700333}
334
Vishnu Nair9cf89262022-02-26 09:17:49 -0800335void TimeStats::pushCompositionStrategyState(const TimeStats::ClientCompositionRecord& record) {
336 if (!mEnabled.load() || !record.hasInterestingData()) {
337 return;
338 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700339
340 ATRACE_CALL();
341
342 std::lock_guard<std::mutex> lock(mMutex);
Vishnu Nair9cf89262022-02-26 09:17:49 -0800343 if (record.changed) mTimeStats.compositionStrategyChangesLegacy++;
344 if (record.hadClientComposition) mTimeStats.clientCompositionFramesLegacy++;
345 if (record.reused) mTimeStats.clientCompositionReusedFramesLegacy++;
346 if (record.predicted) mTimeStats.compositionStrategyPredictedLegacy++;
347 if (record.predictionSucceeded) mTimeStats.compositionStrategyPredictionSucceededLegacy++;
Vishnu Nair9b079a22020-01-21 14:36:08 -0800348}
349
Alec Mouri8de697e2020-03-19 10:52:01 -0700350void TimeStats::incrementRefreshRateSwitches() {
351 if (!mEnabled.load()) return;
352
353 ATRACE_CALL();
354
355 std::lock_guard<std::mutex> lock(mMutex);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800356 mTimeStats.refreshRateSwitchesLegacy++;
Alec Mouri8de697e2020-03-19 10:52:01 -0700357}
358
Alec Mouri717bcb62020-02-10 17:07:19 -0800359void TimeStats::recordDisplayEventConnectionCount(int32_t count) {
360 if (!mEnabled.load()) return;
361
362 ATRACE_CALL();
363
364 std::lock_guard<std::mutex> lock(mMutex);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800365 mTimeStats.displayEventConnectionsCountLegacy =
366 std::max(mTimeStats.displayEventConnectionsCountLegacy, count);
Alec Mouri717bcb62020-02-10 17:07:19 -0800367}
368
Ady Abraham3e8cc072021-05-11 16:29:54 -0700369static int32_t toMs(nsecs_t nanos) {
370 int64_t millis =
371 std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::nanoseconds(nanos))
372 .count();
373 millis = std::clamp(millis, int64_t(INT32_MIN), int64_t(INT32_MAX));
374 return static_cast<int32_t>(millis);
375}
376
Alec Mouri9519bf12019-11-15 16:54:44 -0800377static int32_t msBetween(nsecs_t start, nsecs_t end) {
Ady Abraham3e8cc072021-05-11 16:29:54 -0700378 return toMs(end - start);
Alec Mouri9519bf12019-11-15 16:54:44 -0800379}
380
381void TimeStats::recordFrameDuration(nsecs_t startTime, nsecs_t endTime) {
382 if (!mEnabled.load()) return;
383
384 std::lock_guard<std::mutex> lock(mMutex);
Peiyong Lin65248e02020-04-18 21:15:07 -0700385 if (mPowerTime.powerMode == PowerMode::ON) {
Alec Mouri7d436ec2021-01-27 20:40:50 -0800386 mTimeStats.frameDurationLegacy.insert(msBetween(startTime, endTime));
Alec Mouri9519bf12019-11-15 16:54:44 -0800387 }
388}
389
Alec Mourie4034bb2019-11-19 12:45:54 -0800390void TimeStats::recordRenderEngineDuration(nsecs_t startTime, nsecs_t endTime) {
391 if (!mEnabled.load()) return;
392
393 std::lock_guard<std::mutex> lock(mMutex);
394 if (mGlobalRecord.renderEngineDurations.size() == MAX_NUM_TIME_RECORDS) {
395 ALOGE("RenderEngineTimes are already at its maximum size[%zu]", MAX_NUM_TIME_RECORDS);
396 mGlobalRecord.renderEngineDurations.pop_front();
397 }
398 mGlobalRecord.renderEngineDurations.push_back({startTime, endTime});
399}
400
401void TimeStats::recordRenderEngineDuration(nsecs_t startTime,
402 const std::shared_ptr<FenceTime>& endTime) {
403 if (!mEnabled.load()) return;
404
405 std::lock_guard<std::mutex> lock(mMutex);
406 if (mGlobalRecord.renderEngineDurations.size() == MAX_NUM_TIME_RECORDS) {
407 ALOGE("RenderEngineTimes are already at its maximum size[%zu]", MAX_NUM_TIME_RECORDS);
408 mGlobalRecord.renderEngineDurations.pop_front();
409 }
410 mGlobalRecord.renderEngineDurations.push_back({startTime, endTime});
411}
412
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800413bool TimeStats::recordReadyLocked(int32_t layerId, TimeRecord* timeRecord) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700414 if (!timeRecord->ready) {
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800415 ALOGV("[%d]-[%" PRIu64 "]-presentFence is still not received", layerId,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700416 timeRecord->frameTime.frameNumber);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700417 return false;
418 }
419
420 if (timeRecord->acquireFence != nullptr) {
421 if (timeRecord->acquireFence->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
422 return false;
423 }
424 if (timeRecord->acquireFence->getSignalTime() != Fence::SIGNAL_TIME_INVALID) {
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700425 timeRecord->frameTime.acquireTime = timeRecord->acquireFence->getSignalTime();
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700426 timeRecord->acquireFence = nullptr;
427 } else {
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800428 ALOGV("[%d]-[%" PRIu64 "]-acquireFence signal time is invalid", layerId,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700429 timeRecord->frameTime.frameNumber);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700430 }
431 }
432
433 if (timeRecord->presentFence != nullptr) {
434 if (timeRecord->presentFence->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
435 return false;
436 }
437 if (timeRecord->presentFence->getSignalTime() != Fence::SIGNAL_TIME_INVALID) {
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700438 timeRecord->frameTime.presentTime = timeRecord->presentFence->getSignalTime();
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700439 timeRecord->presentFence = nullptr;
440 } else {
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800441 ALOGV("[%d]-[%" PRIu64 "]-presentFence signal time invalid", layerId,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700442 timeRecord->frameTime.frameNumber);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700443 }
444 }
445
446 return true;
447}
448
Ady Abraham3403a3f2021-04-27 16:58:40 -0700449static int32_t clampToNearestBucket(Fps fps, size_t bucketWidth) {
450 return std::round(fps.getValue() / bucketWidth) * bucketWidth;
Alec Mouri7d436ec2021-01-27 20:40:50 -0800451}
452
453void TimeStats::flushAvailableRecordsToStatsLocked(int32_t layerId, Fps displayRefreshRate,
Ady Abraham8b9e6122021-01-26 19:11:45 -0800454 std::optional<Fps> renderRate,
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000455 SetFrameRateVote frameRateVote,
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700456 GameMode gameMode) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700457 ATRACE_CALL();
Ady Abraham8b9e6122021-01-26 19:11:45 -0800458 ALOGV("[%d]-flushAvailableRecordsToStatsLocked", layerId);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700459
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800460 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700461 TimeRecord& prevTimeRecord = layerRecord.prevTimeRecord;
Alberto Gonzalez9fe14512022-09-29 21:27:34 +0000462 std::optional<int32_t>& prevPresentToPresentMs = layerRecord.prevPresentToPresentMs;
Yiwei Zhangc5f2c452018-05-08 16:31:56 -0700463 std::deque<TimeRecord>& timeRecords = layerRecord.timeRecords;
Alec Mouri7d436ec2021-01-27 20:40:50 -0800464 const int32_t refreshRateBucket =
Ady Abraham3403a3f2021-04-27 16:58:40 -0700465 clampToNearestBucket(displayRefreshRate, REFRESH_RATE_BUCKET_WIDTH);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800466 const int32_t renderRateBucket =
Ady Abraham3403a3f2021-04-27 16:58:40 -0700467 clampToNearestBucket(renderRate ? *renderRate : displayRefreshRate,
468 RENDER_RATE_BUCKET_WIDTH);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700469 while (!timeRecords.empty()) {
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800470 if (!recordReadyLocked(layerId, &timeRecords[0])) break;
471 ALOGV("[%d]-[%" PRIu64 "]-presentFenceTime[%" PRId64 "]", layerId,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700472 timeRecords[0].frameTime.frameNumber, timeRecords[0].frameTime.presentTime);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700473
474 if (prevTimeRecord.ready) {
Alec Mouri9a29e672020-09-14 12:39:14 -0700475 uid_t uid = layerRecord.uid;
Yiwei Zhangeafa5cc2019-07-26 15:06:25 -0700476 const std::string& layerName = layerRecord.layerName;
Alec Mouri7d436ec2021-01-27 20:40:50 -0800477 TimeStatsHelper::TimelineStatsKey timelineKey = {refreshRateBucket, renderRateBucket};
478 if (!mTimeStats.stats.count(timelineKey)) {
479 mTimeStats.stats[timelineKey].key = timelineKey;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700480 }
Alec Mouri7d436ec2021-01-27 20:40:50 -0800481
482 TimeStatsHelper::TimelineStats& displayStats = mTimeStats.stats[timelineKey];
483
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000484 TimeStatsHelper::LayerStatsKey layerKey = {uid, layerName, gameMode};
Alec Mouri7d436ec2021-01-27 20:40:50 -0800485 if (!displayStats.stats.count(layerKey)) {
486 displayStats.stats[layerKey].displayRefreshRateBucket = refreshRateBucket;
487 displayStats.stats[layerKey].renderRateBucket = renderRateBucket;
488 displayStats.stats[layerKey].uid = uid;
489 displayStats.stats[layerKey].layerName = layerName;
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000490 displayStats.stats[layerKey].gameMode = gameMode;
Alec Mouri7d436ec2021-01-27 20:40:50 -0800491 }
Ady Abraham8b9e6122021-01-26 19:11:45 -0800492 if (frameRateVote.frameRate > 0.0f) {
493 displayStats.stats[layerKey].setFrameRateVote = frameRateVote;
494 }
Alec Mouri7d436ec2021-01-27 20:40:50 -0800495 TimeStatsHelper::TimeStatsLayer& timeStatsLayer = displayStats.stats[layerKey];
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700496 timeStatsLayer.totalFrames++;
Yiwei Zhangeaeea062018-06-28 14:46:51 -0700497 timeStatsLayer.droppedFrames += layerRecord.droppedFrames;
Alec Mouri91f6df32020-01-30 08:48:58 -0800498 timeStatsLayer.lateAcquireFrames += layerRecord.lateAcquireFrames;
499 timeStatsLayer.badDesiredPresentFrames += layerRecord.badDesiredPresentFrames;
500
Yiwei Zhangeaeea062018-06-28 14:46:51 -0700501 layerRecord.droppedFrames = 0;
Alec Mouri91f6df32020-01-30 08:48:58 -0800502 layerRecord.lateAcquireFrames = 0;
503 layerRecord.badDesiredPresentFrames = 0;
Yiwei Zhangeaeea062018-06-28 14:46:51 -0700504
505 const int32_t postToAcquireMs = msBetween(timeRecords[0].frameTime.postTime,
506 timeRecords[0].frameTime.acquireTime);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800507 ALOGV("[%d]-[%" PRIu64 "]-post2acquire[%d]", layerId,
Yiwei Zhangeaeea062018-06-28 14:46:51 -0700508 timeRecords[0].frameTime.frameNumber, postToAcquireMs);
509 timeStatsLayer.deltas["post2acquire"].insert(postToAcquireMs);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700510
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700511 const int32_t postToPresentMs = msBetween(timeRecords[0].frameTime.postTime,
512 timeRecords[0].frameTime.presentTime);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800513 ALOGV("[%d]-[%" PRIu64 "]-post2present[%d]", layerId,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700514 timeRecords[0].frameTime.frameNumber, postToPresentMs);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700515 timeStatsLayer.deltas["post2present"].insert(postToPresentMs);
516
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700517 const int32_t acquireToPresentMs = msBetween(timeRecords[0].frameTime.acquireTime,
518 timeRecords[0].frameTime.presentTime);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800519 ALOGV("[%d]-[%" PRIu64 "]-acquire2present[%d]", layerId,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700520 timeRecords[0].frameTime.frameNumber, acquireToPresentMs);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700521 timeStatsLayer.deltas["acquire2present"].insert(acquireToPresentMs);
522
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700523 const int32_t latchToPresentMs = msBetween(timeRecords[0].frameTime.latchTime,
524 timeRecords[0].frameTime.presentTime);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800525 ALOGV("[%d]-[%" PRIu64 "]-latch2present[%d]", layerId,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700526 timeRecords[0].frameTime.frameNumber, latchToPresentMs);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700527 timeStatsLayer.deltas["latch2present"].insert(latchToPresentMs);
528
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700529 const int32_t desiredToPresentMs = msBetween(timeRecords[0].frameTime.desiredTime,
530 timeRecords[0].frameTime.presentTime);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800531 ALOGV("[%d]-[%" PRIu64 "]-desired2present[%d]", layerId,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700532 timeRecords[0].frameTime.frameNumber, desiredToPresentMs);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700533 timeStatsLayer.deltas["desired2present"].insert(desiredToPresentMs);
534
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700535 const int32_t presentToPresentMs = msBetween(prevTimeRecord.frameTime.presentTime,
536 timeRecords[0].frameTime.presentTime);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800537 ALOGV("[%d]-[%" PRIu64 "]-present2present[%d]", layerId,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700538 timeRecords[0].frameTime.frameNumber, presentToPresentMs);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700539 timeStatsLayer.deltas["present2present"].insert(presentToPresentMs);
Alberto Gonzalez9fe14512022-09-29 21:27:34 +0000540 if (prevPresentToPresentMs) {
541 const int32_t presentToPresentDeltaMs =
542 std::abs(presentToPresentMs - *prevPresentToPresentMs);
543 timeStatsLayer.deltas["present2presentDelta"].insert(presentToPresentDeltaMs);
544 }
545 prevPresentToPresentMs = presentToPresentMs;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700546 }
547 prevTimeRecord = timeRecords[0];
Yiwei Zhangc5f2c452018-05-08 16:31:56 -0700548 timeRecords.pop_front();
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700549 layerRecord.waitData--;
550 }
551}
552
Yiwei Zhang8bec7e82019-10-07 18:08:26 -0700553static constexpr const char* kPopupWindowPrefix = "PopupWindow";
554static const size_t kMinLenLayerName = std::strlen(kPopupWindowPrefix);
Yiwei Zhangbd408322018-10-15 18:31:53 -0700555
Yiwei Zhang8bec7e82019-10-07 18:08:26 -0700556// Avoid tracking the "PopupWindow:<random hash>#<number>" layers
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700557static bool layerNameIsValid(const std::string& layerName) {
Yiwei Zhang8bec7e82019-10-07 18:08:26 -0700558 return layerName.length() >= kMinLenLayerName &&
559 layerName.compare(0, kMinLenLayerName, kPopupWindowPrefix) != 0;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700560}
561
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000562bool TimeStats::canAddNewAggregatedStats(uid_t uid, const std::string& layerName,
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700563 GameMode gameMode) {
Alec Mouri7d436ec2021-01-27 20:40:50 -0800564 uint32_t layerRecords = 0;
565 for (const auto& record : mTimeStats.stats) {
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000566 if (record.second.stats.count({uid, layerName, gameMode}) > 0) {
Alec Mouri7d436ec2021-01-27 20:40:50 -0800567 return true;
568 }
569
570 layerRecords += record.second.stats.size();
571 }
572
Dominik Laskowskib4ba8f52021-09-27 18:20:58 -0700573 return layerRecords < MAX_NUM_LAYER_STATS;
Alec Mouri9a29e672020-09-14 12:39:14 -0700574}
575
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800576void TimeStats::setPostTime(int32_t layerId, uint64_t frameNumber, const std::string& layerName,
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700577 uid_t uid, nsecs_t postTime, GameMode gameMode) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700578 if (!mEnabled.load()) return;
579
580 ATRACE_CALL();
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800581 ALOGV("[%d]-[%" PRIu64 "]-[%s]-PostTime[%" PRId64 "]", layerId, frameNumber, layerName.c_str(),
Yiwei Zhang8e8fe522018-11-02 18:34:07 -0700582 postTime);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700583
584 std::lock_guard<std::mutex> lock(mMutex);
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000585 if (!canAddNewAggregatedStats(uid, layerName, gameMode)) {
Yiwei Zhange926ab52019-08-14 15:16:00 -0700586 return;
587 }
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800588 if (!mTimeStatsTracker.count(layerId) && mTimeStatsTracker.size() < MAX_NUM_LAYER_RECORDS &&
Yiwei Zhang7eb58b72019-04-22 19:00:02 -0700589 layerNameIsValid(layerName)) {
Alec Mouri9a29e672020-09-14 12:39:14 -0700590 mTimeStatsTracker[layerId].uid = uid;
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800591 mTimeStatsTracker[layerId].layerName = layerName;
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000592 mTimeStatsTracker[layerId].gameMode = gameMode;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700593 }
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800594 if (!mTimeStatsTracker.count(layerId)) return;
595 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700596 if (layerRecord.timeRecords.size() == MAX_NUM_TIME_RECORDS) {
Yiwei Zhangaf8ee942018-11-22 00:15:23 -0800597 ALOGE("[%d]-[%s]-timeRecords is at its maximum size[%zu]. Ignore this when unittesting.",
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800598 layerId, layerRecord.layerName.c_str(), MAX_NUM_TIME_RECORDS);
599 mTimeStatsTracker.erase(layerId);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700600 return;
601 }
602 // For most media content, the acquireFence is invalid because the buffer is
603 // ready at the queueBuffer stage. In this case, acquireTime should be given
604 // a default value as postTime.
605 TimeRecord timeRecord = {
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700606 .frameTime =
607 {
608 .frameNumber = frameNumber,
609 .postTime = postTime,
Yiwei Zhangaf8ee942018-11-22 00:15:23 -0800610 .latchTime = postTime,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700611 .acquireTime = postTime,
Yiwei Zhangaf8ee942018-11-22 00:15:23 -0800612 .desiredTime = postTime,
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700613 },
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700614 };
615 layerRecord.timeRecords.push_back(timeRecord);
616 if (layerRecord.waitData < 0 ||
617 layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
618 layerRecord.waitData = layerRecord.timeRecords.size() - 1;
619}
620
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800621void TimeStats::setLatchTime(int32_t layerId, uint64_t frameNumber, nsecs_t latchTime) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700622 if (!mEnabled.load()) return;
623
624 ATRACE_CALL();
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800625 ALOGV("[%d]-[%" PRIu64 "]-LatchTime[%" PRId64 "]", layerId, frameNumber, latchTime);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700626
627 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800628 if (!mTimeStatsTracker.count(layerId)) return;
629 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
Yiwei Zhangcb7dd002019-04-16 11:03:01 -0700630 if (layerRecord.waitData < 0 ||
631 layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
632 return;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700633 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700634 if (timeRecord.frameTime.frameNumber == frameNumber) {
635 timeRecord.frameTime.latchTime = latchTime;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700636 }
637}
638
Alec Mouri91f6df32020-01-30 08:48:58 -0800639void TimeStats::incrementLatchSkipped(int32_t layerId, LatchSkipReason reason) {
640 if (!mEnabled.load()) return;
641
642 ATRACE_CALL();
643 ALOGV("[%d]-LatchSkipped-Reason[%d]", layerId,
644 static_cast<std::underlying_type<LatchSkipReason>::type>(reason));
645
646 std::lock_guard<std::mutex> lock(mMutex);
647 if (!mTimeStatsTracker.count(layerId)) return;
648 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
649
650 switch (reason) {
651 case LatchSkipReason::LateAcquire:
652 layerRecord.lateAcquireFrames++;
653 break;
654 }
655}
656
657void TimeStats::incrementBadDesiredPresent(int32_t layerId) {
658 if (!mEnabled.load()) return;
659
660 ATRACE_CALL();
661 ALOGV("[%d]-BadDesiredPresent", layerId);
662
663 std::lock_guard<std::mutex> lock(mMutex);
664 if (!mTimeStatsTracker.count(layerId)) return;
665 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
666 layerRecord.badDesiredPresentFrames++;
667}
668
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800669void TimeStats::setDesiredTime(int32_t layerId, uint64_t frameNumber, nsecs_t desiredTime) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700670 if (!mEnabled.load()) return;
671
672 ATRACE_CALL();
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800673 ALOGV("[%d]-[%" PRIu64 "]-DesiredTime[%" PRId64 "]", layerId, frameNumber, desiredTime);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700674
675 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800676 if (!mTimeStatsTracker.count(layerId)) return;
677 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
Yiwei Zhangcb7dd002019-04-16 11:03:01 -0700678 if (layerRecord.waitData < 0 ||
679 layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
680 return;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700681 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700682 if (timeRecord.frameTime.frameNumber == frameNumber) {
683 timeRecord.frameTime.desiredTime = desiredTime;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700684 }
685}
686
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800687void TimeStats::setAcquireTime(int32_t layerId, uint64_t frameNumber, nsecs_t acquireTime) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700688 if (!mEnabled.load()) return;
689
690 ATRACE_CALL();
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800691 ALOGV("[%d]-[%" PRIu64 "]-AcquireTime[%" PRId64 "]", layerId, frameNumber, acquireTime);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700692
693 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800694 if (!mTimeStatsTracker.count(layerId)) return;
695 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
Yiwei Zhangcb7dd002019-04-16 11:03:01 -0700696 if (layerRecord.waitData < 0 ||
697 layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
698 return;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700699 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700700 if (timeRecord.frameTime.frameNumber == frameNumber) {
701 timeRecord.frameTime.acquireTime = acquireTime;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700702 }
703}
704
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800705void TimeStats::setAcquireFence(int32_t layerId, uint64_t frameNumber,
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700706 const std::shared_ptr<FenceTime>& acquireFence) {
707 if (!mEnabled.load()) return;
708
709 ATRACE_CALL();
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800710 ALOGV("[%d]-[%" PRIu64 "]-AcquireFenceTime[%" PRId64 "]", layerId, frameNumber,
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700711 acquireFence->getSignalTime());
712
713 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800714 if (!mTimeStatsTracker.count(layerId)) return;
715 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
Yiwei Zhangcb7dd002019-04-16 11:03:01 -0700716 if (layerRecord.waitData < 0 ||
717 layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
718 return;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700719 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700720 if (timeRecord.frameTime.frameNumber == frameNumber) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700721 timeRecord.acquireFence = acquireFence;
722 }
723}
724
Alec Mouri7d436ec2021-01-27 20:40:50 -0800725void TimeStats::setPresentTime(int32_t layerId, uint64_t frameNumber, nsecs_t presentTime,
Ady Abraham8b9e6122021-01-26 19:11:45 -0800726 Fps displayRefreshRate, std::optional<Fps> renderRate,
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700727 SetFrameRateVote frameRateVote, GameMode gameMode) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700728 if (!mEnabled.load()) return;
729
730 ATRACE_CALL();
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800731 ALOGV("[%d]-[%" PRIu64 "]-PresentTime[%" PRId64 "]", layerId, frameNumber, presentTime);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700732
733 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800734 if (!mTimeStatsTracker.count(layerId)) return;
735 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
Yiwei Zhangcb7dd002019-04-16 11:03:01 -0700736 if (layerRecord.waitData < 0 ||
737 layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
738 return;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700739 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700740 if (timeRecord.frameTime.frameNumber == frameNumber) {
741 timeRecord.frameTime.presentTime = presentTime;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700742 timeRecord.ready = true;
743 layerRecord.waitData++;
744 }
745
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000746 flushAvailableRecordsToStatsLocked(layerId, displayRefreshRate, renderRate, frameRateVote,
747 gameMode);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700748}
749
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800750void TimeStats::setPresentFence(int32_t layerId, uint64_t frameNumber,
Alec Mouri7d436ec2021-01-27 20:40:50 -0800751 const std::shared_ptr<FenceTime>& presentFence,
Ady Abraham8b9e6122021-01-26 19:11:45 -0800752 Fps displayRefreshRate, std::optional<Fps> renderRate,
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700753 SetFrameRateVote frameRateVote, GameMode gameMode) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700754 if (!mEnabled.load()) return;
755
756 ATRACE_CALL();
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800757 ALOGV("[%d]-[%" PRIu64 "]-PresentFenceTime[%" PRId64 "]", layerId, frameNumber,
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700758 presentFence->getSignalTime());
759
760 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800761 if (!mTimeStatsTracker.count(layerId)) return;
762 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
Yiwei Zhangcb7dd002019-04-16 11:03:01 -0700763 if (layerRecord.waitData < 0 ||
764 layerRecord.waitData >= static_cast<int32_t>(layerRecord.timeRecords.size()))
765 return;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700766 TimeRecord& timeRecord = layerRecord.timeRecords[layerRecord.waitData];
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700767 if (timeRecord.frameTime.frameNumber == frameNumber) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700768 timeRecord.presentFence = presentFence;
769 timeRecord.ready = true;
770 layerRecord.waitData++;
771 }
772
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000773 flushAvailableRecordsToStatsLocked(layerId, displayRefreshRate, renderRate, frameRateVote,
774 gameMode);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700775}
776
Adithya Srinivasanead17162021-02-18 02:17:37 +0000777static const constexpr int32_t kValidJankyReason = JankType::DisplayHAL |
778 JankType::SurfaceFlingerCpuDeadlineMissed | JankType::SurfaceFlingerGpuDeadlineMissed |
779 JankType::AppDeadlineMissed | JankType::PredictionError |
Adithya Srinivasan53e5c402021-04-16 17:34:30 +0000780 JankType::SurfaceFlingerScheduling;
Alec Mouri363faf02021-01-29 16:34:55 -0800781
Alec Mouri9a29e672020-09-14 12:39:14 -0700782template <class T>
783static void updateJankPayload(T& t, int32_t reasons) {
784 t.jankPayload.totalFrames++;
785
Alec Mouri9a29e672020-09-14 12:39:14 -0700786 if (reasons & kValidJankyReason) {
787 t.jankPayload.totalJankyFrames++;
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800788 if ((reasons & JankType::SurfaceFlingerCpuDeadlineMissed) != 0) {
Alec Mouri9a29e672020-09-14 12:39:14 -0700789 t.jankPayload.totalSFLongCpu++;
790 }
Jorim Jaggi5814ab82020-12-03 20:45:58 +0100791 if ((reasons & JankType::SurfaceFlingerGpuDeadlineMissed) != 0) {
Alec Mouri9a29e672020-09-14 12:39:14 -0700792 t.jankPayload.totalSFLongGpu++;
793 }
Adithya Srinivasan9b2ca3e2020-11-10 10:14:17 -0800794 if ((reasons & JankType::DisplayHAL) != 0) {
Alec Mouri9a29e672020-09-14 12:39:14 -0700795 t.jankPayload.totalSFUnattributed++;
796 }
Jorim Jaggi5814ab82020-12-03 20:45:58 +0100797 if ((reasons & JankType::AppDeadlineMissed) != 0) {
Alec Mouri9a29e672020-09-14 12:39:14 -0700798 t.jankPayload.totalAppUnattributed++;
799 }
Adithya Srinivasanead17162021-02-18 02:17:37 +0000800 if ((reasons & JankType::PredictionError) != 0) {
801 t.jankPayload.totalSFPredictionError++;
802 }
803 if ((reasons & JankType::SurfaceFlingerScheduling) != 0) {
804 t.jankPayload.totalSFScheduling++;
805 }
Adithya Srinivasan53e5c402021-04-16 17:34:30 +0000806 }
807
808 // We want to track BufferStuffing separately as it can provide info on latency issues
809 if (reasons & JankType::BufferStuffing) {
810 t.jankPayload.totalAppBufferStuffing++;
Alec Mouri9a29e672020-09-14 12:39:14 -0700811 }
812}
813
Alec Mouri363faf02021-01-29 16:34:55 -0800814void TimeStats::incrementJankyFrames(const JankyFramesInfo& info) {
Alec Mouri9a29e672020-09-14 12:39:14 -0700815 if (!mEnabled.load()) return;
816
817 ATRACE_CALL();
818 std::lock_guard<std::mutex> lock(mMutex);
819
Alec Mouri542de112020-11-13 12:07:32 -0800820 // Only update layer stats if we're already tracking the layer in TimeStats.
821 // Otherwise, continue tracking the statistic but use a default layer name instead.
Alec Mouri9a29e672020-09-14 12:39:14 -0700822 // As an implementation detail, we do this because this method is expected to be
Alec Mouri542de112020-11-13 12:07:32 -0800823 // called from FrameTimeline, whose jank classification includes transaction jank
824 // that occurs without a buffer. But, in general those layer names are not suitable as
825 // aggregation keys: e.g., it's normal and expected for Window Manager to include the hash code
826 // for an animation leash. So while we can show that jank in dumpsys, aggregating based on the
827 // layer blows up the stats size, so as a workaround drop those stats. This assumes that
828 // TimeStats will flush the first present fence for a layer *before* FrameTimeline does so that
829 // the first jank record is not dropped.
Alec Mouri9a29e672020-09-14 12:39:14 -0700830
Alec Mouri542de112020-11-13 12:07:32 -0800831 static const std::string kDefaultLayerName = "none";
Dominik Laskowskif5d0ea52021-09-26 17:27:01 -0700832 constexpr GameMode kDefaultGameMode = GameMode::Unsupported;
Alec Mouri7d436ec2021-01-27 20:40:50 -0800833
Alec Mouri363faf02021-01-29 16:34:55 -0800834 const int32_t refreshRateBucket =
Ady Abraham3403a3f2021-04-27 16:58:40 -0700835 clampToNearestBucket(info.refreshRate, REFRESH_RATE_BUCKET_WIDTH);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800836 const int32_t renderRateBucket =
Ady Abraham3403a3f2021-04-27 16:58:40 -0700837 clampToNearestBucket(info.renderRate ? *info.renderRate : info.refreshRate,
838 RENDER_RATE_BUCKET_WIDTH);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800839 const TimeStatsHelper::TimelineStatsKey timelineKey = {refreshRateBucket, renderRateBucket};
840
841 if (!mTimeStats.stats.count(timelineKey)) {
842 mTimeStats.stats[timelineKey].key = timelineKey;
Alec Mouri9a29e672020-09-14 12:39:14 -0700843 }
844
Alec Mouri7d436ec2021-01-27 20:40:50 -0800845 TimeStatsHelper::TimelineStats& timelineStats = mTimeStats.stats[timelineKey];
846
Alec Mouri363faf02021-01-29 16:34:55 -0800847 updateJankPayload<TimeStatsHelper::TimelineStats>(timelineStats, info.reasons);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800848
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000849 TimeStatsHelper::LayerStatsKey layerKey = {info.uid, info.layerName, info.gameMode};
Alec Mouri7d436ec2021-01-27 20:40:50 -0800850 if (!timelineStats.stats.count(layerKey)) {
Adithya Srinivasan58069dc2021-06-04 20:37:02 +0000851 layerKey = {info.uid, kDefaultLayerName, kDefaultGameMode};
Alec Mouri7d436ec2021-01-27 20:40:50 -0800852 timelineStats.stats[layerKey].displayRefreshRateBucket = refreshRateBucket;
853 timelineStats.stats[layerKey].renderRateBucket = renderRateBucket;
Alec Mouri363faf02021-01-29 16:34:55 -0800854 timelineStats.stats[layerKey].uid = info.uid;
Adithya Srinivasanf427f762021-06-15 19:46:26 +0000855 timelineStats.stats[layerKey].layerName = kDefaultLayerName;
856 timelineStats.stats[layerKey].gameMode = kDefaultGameMode;
Alec Mouri7d436ec2021-01-27 20:40:50 -0800857 }
858
859 TimeStatsHelper::TimeStatsLayer& timeStatsLayer = timelineStats.stats[layerKey];
Alec Mouri363faf02021-01-29 16:34:55 -0800860 updateJankPayload<TimeStatsHelper::TimeStatsLayer>(timeStatsLayer, info.reasons);
861
862 if (info.reasons & kValidJankyReason) {
863 // TimeStats Histograms only retain positive values, so we don't need to check if these
864 // deadlines were really missed if we know that the frame had jank, since deadlines
865 // that were met will be dropped.
Ady Abraham3e8cc072021-05-11 16:29:54 -0700866 timelineStats.displayDeadlineDeltas.insert(toMs(info.displayDeadlineDelta));
867 timelineStats.displayPresentDeltas.insert(toMs(info.displayPresentJitter));
868 timeStatsLayer.deltas["appDeadlineDeltas"].insert(toMs(info.appDeadlineDelta));
Alec Mouri363faf02021-01-29 16:34:55 -0800869 }
Alec Mouri9a29e672020-09-14 12:39:14 -0700870}
871
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800872void TimeStats::onDestroy(int32_t layerId) {
Yiwei Zhangdc224042018-10-18 15:34:00 -0700873 ATRACE_CALL();
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800874 ALOGV("[%d]-onDestroy", layerId);
Mikael Pessa90092f42019-08-26 17:22:04 -0700875 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800876 mTimeStatsTracker.erase(layerId);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700877}
878
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800879void TimeStats::removeTimeRecord(int32_t layerId, uint64_t frameNumber) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700880 if (!mEnabled.load()) return;
881
882 ATRACE_CALL();
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800883 ALOGV("[%d]-[%" PRIu64 "]-removeTimeRecord", layerId, frameNumber);
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700884
885 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhang1a88c402019-11-18 10:43:58 -0800886 if (!mTimeStatsTracker.count(layerId)) return;
887 LayerRecord& layerRecord = mTimeStatsTracker[layerId];
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700888 size_t removeAt = 0;
889 for (const TimeRecord& record : layerRecord.timeRecords) {
Yiwei Zhangcf50ab92018-06-14 10:50:12 -0700890 if (record.frameTime.frameNumber == frameNumber) break;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700891 removeAt++;
892 }
893 if (removeAt == layerRecord.timeRecords.size()) return;
894 layerRecord.timeRecords.erase(layerRecord.timeRecords.begin() + removeAt);
895 if (layerRecord.waitData > static_cast<int32_t>(removeAt)) {
Yiwei Zhangeaeea062018-06-28 14:46:51 -0700896 layerRecord.waitData--;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700897 }
Yiwei Zhangeaeea062018-06-28 14:46:51 -0700898 layerRecord.droppedFrames++;
Yiwei Zhang0102ad22018-05-02 17:37:17 -0700899}
900
Yiwei Zhang3a226d22018-10-16 09:23:03 -0700901void TimeStats::flushPowerTimeLocked() {
Yiwei Zhange5c49d52018-10-29 00:15:31 -0700902 if (!mEnabled.load()) return;
903
Yiwei Zhang3a226d22018-10-16 09:23:03 -0700904 nsecs_t curTime = systemTime();
905 // elapsedTime is in milliseconds.
906 int64_t elapsedTime = (curTime - mPowerTime.prevTime) / 1000000;
907
908 switch (mPowerTime.powerMode) {
Peiyong Lin65248e02020-04-18 21:15:07 -0700909 case PowerMode::ON:
Alec Mouri7d436ec2021-01-27 20:40:50 -0800910 mTimeStats.displayOnTimeLegacy += elapsedTime;
Yiwei Zhang3a226d22018-10-16 09:23:03 -0700911 break;
Peiyong Lin65248e02020-04-18 21:15:07 -0700912 case PowerMode::OFF:
913 case PowerMode::DOZE:
914 case PowerMode::DOZE_SUSPEND:
915 case PowerMode::ON_SUSPEND:
Yiwei Zhang3a226d22018-10-16 09:23:03 -0700916 default:
917 break;
918 }
919
920 mPowerTime.prevTime = curTime;
921}
922
Peiyong Lin65248e02020-04-18 21:15:07 -0700923void TimeStats::setPowerMode(PowerMode powerMode) {
Yiwei Zhang3a226d22018-10-16 09:23:03 -0700924 if (!mEnabled.load()) {
925 std::lock_guard<std::mutex> lock(mMutex);
926 mPowerTime.powerMode = powerMode;
927 return;
928 }
929
930 std::lock_guard<std::mutex> lock(mMutex);
931 if (powerMode == mPowerTime.powerMode) return;
932
933 flushPowerTimeLocked();
934 mPowerTime.powerMode = powerMode;
935}
936
Alec Mourifb571ea2019-01-24 18:42:10 -0800937void TimeStats::recordRefreshRate(uint32_t fps, nsecs_t duration) {
938 std::lock_guard<std::mutex> lock(mMutex);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800939 if (mTimeStats.refreshRateStatsLegacy.count(fps)) {
940 mTimeStats.refreshRateStatsLegacy[fps] += duration;
Alec Mourifb571ea2019-01-24 18:42:10 -0800941 } else {
Alec Mouri7d436ec2021-01-27 20:40:50 -0800942 mTimeStats.refreshRateStatsLegacy.insert({fps, duration});
Alec Mourifb571ea2019-01-24 18:42:10 -0800943 }
944}
945
Yiwei Zhangce6ebc02018-10-20 12:42:38 -0700946void TimeStats::flushAvailableGlobalRecordsToStatsLocked() {
947 ATRACE_CALL();
948
949 while (!mGlobalRecord.presentFences.empty()) {
950 const nsecs_t curPresentTime = mGlobalRecord.presentFences.front()->getSignalTime();
951 if (curPresentTime == Fence::SIGNAL_TIME_PENDING) break;
952
953 if (curPresentTime == Fence::SIGNAL_TIME_INVALID) {
954 ALOGE("GlobalPresentFence is invalid!");
955 mGlobalRecord.prevPresentTime = 0;
956 mGlobalRecord.presentFences.pop_front();
957 continue;
958 }
959
960 ALOGV("GlobalPresentFenceTime[%" PRId64 "]",
961 mGlobalRecord.presentFences.front()->getSignalTime());
962
Yiwei Zhange5c49d52018-10-29 00:15:31 -0700963 if (mGlobalRecord.prevPresentTime != 0) {
964 const int32_t presentToPresentMs =
965 msBetween(mGlobalRecord.prevPresentTime, curPresentTime);
966 ALOGV("Global present2present[%d] prev[%" PRId64 "] curr[%" PRId64 "]",
967 presentToPresentMs, mGlobalRecord.prevPresentTime, curPresentTime);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800968 mTimeStats.presentToPresentLegacy.insert(presentToPresentMs);
Yiwei Zhange5c49d52018-10-29 00:15:31 -0700969 }
Yiwei Zhangce6ebc02018-10-20 12:42:38 -0700970
Yiwei Zhangce6ebc02018-10-20 12:42:38 -0700971 mGlobalRecord.prevPresentTime = curPresentTime;
972 mGlobalRecord.presentFences.pop_front();
973 }
Alec Mourie4034bb2019-11-19 12:45:54 -0800974 while (!mGlobalRecord.renderEngineDurations.empty()) {
975 const auto duration = mGlobalRecord.renderEngineDurations.front();
976 const auto& endTime = duration.endTime;
977
978 nsecs_t endNs = -1;
979
980 if (auto val = std::get_if<nsecs_t>(&endTime)) {
981 endNs = *val;
982 } else {
983 endNs = std::get<std::shared_ptr<FenceTime>>(endTime)->getSignalTime();
984 }
985
986 if (endNs == Fence::SIGNAL_TIME_PENDING) break;
987
988 if (endNs < 0) {
989 ALOGE("RenderEngineTiming is invalid!");
990 mGlobalRecord.renderEngineDurations.pop_front();
991 continue;
992 }
993
994 const int32_t renderEngineMs = msBetween(duration.startTime, endNs);
Alec Mouri7d436ec2021-01-27 20:40:50 -0800995 mTimeStats.renderEngineTimingLegacy.insert(renderEngineMs);
Alec Mourie4034bb2019-11-19 12:45:54 -0800996
997 mGlobalRecord.renderEngineDurations.pop_front();
998 }
Yiwei Zhangce6ebc02018-10-20 12:42:38 -0700999}
1000
1001void TimeStats::setPresentFenceGlobal(const std::shared_ptr<FenceTime>& presentFence) {
1002 if (!mEnabled.load()) return;
1003
1004 ATRACE_CALL();
1005 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhange5c49d52018-10-29 00:15:31 -07001006 if (presentFence == nullptr || !presentFence->isValid()) {
1007 mGlobalRecord.prevPresentTime = 0;
1008 return;
1009 }
1010
Peiyong Lin65248e02020-04-18 21:15:07 -07001011 if (mPowerTime.powerMode != PowerMode::ON) {
1012 // Try flushing the last present fence on PowerMode::ON.
Yiwei Zhange5c49d52018-10-29 00:15:31 -07001013 flushAvailableGlobalRecordsToStatsLocked();
1014 mGlobalRecord.presentFences.clear();
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001015 mGlobalRecord.prevPresentTime = 0;
1016 return;
1017 }
1018
1019 if (mGlobalRecord.presentFences.size() == MAX_NUM_TIME_RECORDS) {
1020 // The front presentFence must be trapped in pending status in this
1021 // case. Try dequeuing the front one to recover.
1022 ALOGE("GlobalPresentFences is already at its maximum size[%zu]", MAX_NUM_TIME_RECORDS);
1023 mGlobalRecord.prevPresentTime = 0;
1024 mGlobalRecord.presentFences.pop_front();
1025 }
1026
1027 mGlobalRecord.presentFences.emplace_back(presentFence);
1028 flushAvailableGlobalRecordsToStatsLocked();
1029}
1030
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001031void TimeStats::enable() {
1032 if (mEnabled.load()) return;
1033
1034 ATRACE_CALL();
1035
1036 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001037 mEnabled.store(true);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001038 mTimeStats.statsStartLegacy = static_cast<int64_t>(std::time(0));
Yiwei Zhang3a226d22018-10-16 09:23:03 -07001039 mPowerTime.prevTime = systemTime();
Yiwei Zhange5c49d52018-10-29 00:15:31 -07001040 ALOGD("Enabled");
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001041}
1042
1043void TimeStats::disable() {
1044 if (!mEnabled.load()) return;
1045
1046 ATRACE_CALL();
1047
1048 std::lock_guard<std::mutex> lock(mMutex);
Yiwei Zhange5c49d52018-10-29 00:15:31 -07001049 flushPowerTimeLocked();
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001050 mEnabled.store(false);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001051 mTimeStats.statsEndLegacy = static_cast<int64_t>(std::time(0));
Yiwei Zhange5c49d52018-10-29 00:15:31 -07001052 ALOGD("Disabled");
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001053}
1054
Alec Mouri8e2f31b2020-01-16 22:04:35 +00001055void TimeStats::clearAll() {
1056 std::lock_guard<std::mutex> lock(mMutex);
Ady Abraham3403a3f2021-04-27 16:58:40 -07001057 mTimeStats.stats.clear();
Alec Mouri8e2f31b2020-01-16 22:04:35 +00001058 clearGlobalLocked();
1059 clearLayersLocked();
1060}
1061
1062void TimeStats::clearGlobalLocked() {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001063 ATRACE_CALL();
1064
Alec Mouri7d436ec2021-01-27 20:40:50 -08001065 mTimeStats.statsStartLegacy = (mEnabled.load() ? static_cast<int64_t>(std::time(0)) : 0);
1066 mTimeStats.statsEndLegacy = 0;
1067 mTimeStats.totalFramesLegacy = 0;
1068 mTimeStats.missedFramesLegacy = 0;
1069 mTimeStats.clientCompositionFramesLegacy = 0;
1070 mTimeStats.clientCompositionReusedFramesLegacy = 0;
Robert Carra00eb142022-03-09 13:49:30 -08001071 mTimeStats.compositionStrategyChangesLegacy = 0;
Vishnu Nair9cf89262022-02-26 09:17:49 -08001072 mTimeStats.compositionStrategyPredictedLegacy = 0;
1073 mTimeStats.compositionStrategyPredictionSucceededLegacy = 0;
1074 mTimeStats.refreshRateSwitchesLegacy = 0;
Alec Mouri7d436ec2021-01-27 20:40:50 -08001075 mTimeStats.displayEventConnectionsCountLegacy = 0;
1076 mTimeStats.displayOnTimeLegacy = 0;
1077 mTimeStats.presentToPresentLegacy.hist.clear();
1078 mTimeStats.frameDurationLegacy.hist.clear();
1079 mTimeStats.renderEngineTimingLegacy.hist.clear();
1080 mTimeStats.refreshRateStatsLegacy.clear();
Yiwei Zhang3a226d22018-10-16 09:23:03 -07001081 mPowerTime.prevTime = systemTime();
Alec Mouri56e63852021-03-09 18:17:25 -08001082 for (auto& globalRecord : mTimeStats.stats) {
1083 globalRecord.second.clearGlobals();
1084 }
Yiwei Zhange5c49d52018-10-29 00:15:31 -07001085 mGlobalRecord.prevPresentTime = 0;
1086 mGlobalRecord.presentFences.clear();
Alec Mouri8e2f31b2020-01-16 22:04:35 +00001087 ALOGD("Cleared global stats");
1088}
1089
1090void TimeStats::clearLayersLocked() {
1091 ATRACE_CALL();
1092
1093 mTimeStatsTracker.clear();
Alec Mouri56e63852021-03-09 18:17:25 -08001094
1095 for (auto& globalRecord : mTimeStats.stats) {
1096 globalRecord.second.stats.clear();
1097 }
Alec Mouri8e2f31b2020-01-16 22:04:35 +00001098 ALOGD("Cleared layer stats");
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001099}
1100
1101bool TimeStats::isEnabled() {
1102 return mEnabled.load();
1103}
1104
Yiwei Zhang5434a782018-12-05 18:06:32 -08001105void TimeStats::dump(bool asProto, std::optional<uint32_t> maxLayers, std::string& result) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001106 ATRACE_CALL();
1107
1108 std::lock_guard<std::mutex> lock(mMutex);
Alec Mouri7d436ec2021-01-27 20:40:50 -08001109 if (mTimeStats.statsStartLegacy == 0) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001110 return;
1111 }
1112
Alec Mouri7d436ec2021-01-27 20:40:50 -08001113 mTimeStats.statsEndLegacy = static_cast<int64_t>(std::time(0));
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001114
Yiwei Zhang3a226d22018-10-16 09:23:03 -07001115 flushPowerTimeLocked();
1116
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001117 if (asProto) {
Yiwei Zhang8a4015c2018-05-08 16:03:47 -07001118 ALOGD("Dumping TimeStats as proto");
Yiwei Zhangdc224042018-10-18 15:34:00 -07001119 SFTimeStatsGlobalProto timeStatsProto = mTimeStats.toProto(maxLayers);
Dominik Laskowski46470112019-08-02 13:13:11 -07001120 result.append(timeStatsProto.SerializeAsString());
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001121 } else {
Yiwei Zhang8a4015c2018-05-08 16:03:47 -07001122 ALOGD("Dumping TimeStats as text");
Yiwei Zhang5434a782018-12-05 18:06:32 -08001123 result.append(mTimeStats.toString(maxLayers));
Yiwei Zhang8a4015c2018-05-08 16:03:47 -07001124 result.append("\n");
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001125 }
1126}
1127
Alec Mourifb571ea2019-01-24 18:42:10 -08001128} // namespace impl
1129
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001130} // namespace android