1 /*
2 * Copyright 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #undef LOG_TAG
18 #define LOG_TAG "LayerHistory"
19 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
20
21 #include "LayerHistory.h"
22
23 #include <android-base/stringprintf.h>
24 #include <cutils/properties.h>
25 #include <gui/TraceUtils.h>
26 #include <utils/Log.h>
27 #include <utils/Timers.h>
28
29 #include <algorithm>
30 #include <cmath>
31 #include <string>
32 #include <utility>
33
34 #include "../Layer.h"
35 #include "EventThread.h"
36 #include "LayerInfo.h"
37
38 namespace android::scheduler {
39
40 namespace {
41
isLayerActive(const LayerInfo & info,nsecs_t threshold)42 bool isLayerActive(const LayerInfo& info, nsecs_t threshold) {
43 // Layers with an explicit vote are always kept active
44 if (info.getSetFrameRateVote().rate.isValid()) {
45 return true;
46 }
47
48 return info.isVisible() && info.getLastUpdatedTime() >= threshold;
49 }
50
traceEnabled()51 bool traceEnabled() {
52 return property_get_bool("debug.sf.layer_history_trace", false);
53 }
54
useFrameRatePriority()55 bool useFrameRatePriority() {
56 char value[PROPERTY_VALUE_MAX];
57 property_get("debug.sf.use_frame_rate_priority", value, "1");
58 return atoi(value);
59 }
60
trace(const LayerInfo & info,LayerHistory::LayerVoteType type,int fps)61 void trace(const LayerInfo& info, LayerHistory::LayerVoteType type, int fps) {
62 const auto traceType = [&](LayerHistory::LayerVoteType checkedType, int value) {
63 ATRACE_INT(info.getTraceTag(checkedType), type == checkedType ? value : 0);
64 };
65
66 traceType(LayerHistory::LayerVoteType::NoVote, 1);
67 traceType(LayerHistory::LayerVoteType::Heuristic, fps);
68 traceType(LayerHistory::LayerVoteType::ExplicitDefault, fps);
69 traceType(LayerHistory::LayerVoteType::ExplicitExactOrMultiple, fps);
70 traceType(LayerHistory::LayerVoteType::ExplicitExact, fps);
71 traceType(LayerHistory::LayerVoteType::Min, 1);
72 traceType(LayerHistory::LayerVoteType::Max, 1);
73
74 ALOGD("%s: %s @ %d Hz", __FUNCTION__, info.getName().c_str(), fps);
75 }
76
getVoteType(LayerInfo::FrameRateCompatibility compatibility,bool contentDetectionEnabled)77 LayerHistory::LayerVoteType getVoteType(LayerInfo::FrameRateCompatibility compatibility,
78 bool contentDetectionEnabled) {
79 LayerHistory::LayerVoteType voteType;
80 if (!contentDetectionEnabled || compatibility == LayerInfo::FrameRateCompatibility::NoVote) {
81 voteType = LayerHistory::LayerVoteType::NoVote;
82 } else if (compatibility == LayerInfo::FrameRateCompatibility::Min) {
83 voteType = LayerHistory::LayerVoteType::Min;
84 } else {
85 voteType = LayerHistory::LayerVoteType::Heuristic;
86 }
87 return voteType;
88 }
89
90 } // namespace
91
LayerHistory()92 LayerHistory::LayerHistory()
93 : mTraceEnabled(traceEnabled()), mUseFrameRatePriority(useFrameRatePriority()) {
94 LayerInfo::setTraceEnabled(mTraceEnabled);
95 }
96
97 LayerHistory::~LayerHistory() = default;
98
registerLayer(Layer * layer,bool contentDetectionEnabled)99 void LayerHistory::registerLayer(Layer* layer, bool contentDetectionEnabled) {
100 std::lock_guard lock(mLock);
101 LOG_ALWAYS_FATAL_IF(findLayer(layer->getSequence()).first != LayerStatus::NotFound,
102 "%s already registered", layer->getName().c_str());
103 LayerVoteType type =
104 getVoteType(layer->getDefaultFrameRateCompatibility(), contentDetectionEnabled);
105 auto info = std::make_unique<LayerInfo>(layer->getName(), layer->getOwnerUid(), type);
106
107 // The layer can be placed on either map, it is assumed that partitionLayers() will be called
108 // to correct them.
109 mInactiveLayerInfos.insert({layer->getSequence(), std::make_pair(layer, std::move(info))});
110 }
111
deregisterLayer(Layer * layer)112 void LayerHistory::deregisterLayer(Layer* layer) {
113 std::lock_guard lock(mLock);
114 if (!mActiveLayerInfos.erase(layer->getSequence())) {
115 if (!mInactiveLayerInfos.erase(layer->getSequence())) {
116 LOG_ALWAYS_FATAL("%s: unknown layer %p", __FUNCTION__, layer);
117 }
118 }
119 }
120
record(int32_t id,const LayerProps & layerProps,nsecs_t presentTime,nsecs_t now,LayerUpdateType updateType)121 void LayerHistory::record(int32_t id, const LayerProps& layerProps, nsecs_t presentTime,
122 nsecs_t now, LayerUpdateType updateType) {
123 std::lock_guard lock(mLock);
124 auto [found, layerPair] = findLayer(id);
125 if (found == LayerStatus::NotFound) {
126 // Offscreen layer
127 ALOGV("%s: %d not registered", __func__, id);
128 return;
129 }
130
131 const auto& info = layerPair->second;
132 info->setLastPresentTime(presentTime, now, updateType, mModeChangePending, layerProps);
133
134 // Set frame rate to attached choreographer.
135 // TODO(b/260898223): Change to use layer hierarchy and handle frame rate vote.
136 if (updateType == LayerUpdateType::SetFrameRate) {
137 auto range = mAttachedChoreographers.equal_range(id);
138 auto it = range.first;
139 while (it != range.second) {
140 sp<EventThreadConnection> choreographerConnection = it->second.promote();
141 if (choreographerConnection) {
142 choreographerConnection->frameRate = layerProps.setFrameRateVote.rate;
143 it++;
144 } else {
145 it = mAttachedChoreographers.erase(it);
146 }
147 }
148 }
149
150 // Activate layer if inactive.
151 if (found == LayerStatus::LayerInInactiveMap) {
152 mActiveLayerInfos.insert(
153 {id, std::make_pair(layerPair->first, std::move(layerPair->second))});
154 mInactiveLayerInfos.erase(id);
155 }
156 }
157
setDefaultFrameRateCompatibility(Layer * layer,bool contentDetectionEnabled)158 void LayerHistory::setDefaultFrameRateCompatibility(Layer* layer, bool contentDetectionEnabled) {
159 std::lock_guard lock(mLock);
160 auto id = layer->getSequence();
161
162 auto [found, layerPair] = findLayer(id);
163 if (found == LayerStatus::NotFound) {
164 // Offscreen layer
165 ALOGV("%s: %s not registered", __func__, layer->getName().c_str());
166 return;
167 }
168
169 const auto& info = layerPair->second;
170 info->setDefaultLayerVote(
171 getVoteType(layer->getDefaultFrameRateCompatibility(), contentDetectionEnabled));
172 }
173
summarize(const RefreshRateSelector & selector,nsecs_t now)174 auto LayerHistory::summarize(const RefreshRateSelector& selector, nsecs_t now) -> Summary {
175 ATRACE_CALL();
176 Summary summary;
177
178 std::lock_guard lock(mLock);
179
180 partitionLayers(now);
181
182 for (const auto& [key, value] : mActiveLayerInfos) {
183 auto& info = value.second;
184 const auto frameRateSelectionPriority = info->getFrameRateSelectionPriority();
185 const auto layerFocused = Layer::isLayerFocusedBasedOnPriority(frameRateSelectionPriority);
186 ALOGV("%s has priority: %d %s focused", info->getName().c_str(), frameRateSelectionPriority,
187 layerFocused ? "" : "not");
188
189 ATRACE_FORMAT("%s", info->getName().c_str());
190 const auto vote = info->getRefreshRateVote(selector, now);
191 // Skip NoVote layer as those don't have any requirements
192 if (vote.type == LayerVoteType::NoVote) {
193 continue;
194 }
195
196 // Compute the layer's position on the screen
197 const Rect bounds = Rect(info->getBounds());
198 const ui::Transform transform = info->getTransform();
199 constexpr bool roundOutwards = true;
200 Rect transformed = transform.transform(bounds, roundOutwards);
201
202 const float layerArea = transformed.getWidth() * transformed.getHeight();
203 float weight = mDisplayArea ? layerArea / mDisplayArea : 0.0f;
204 ATRACE_FORMAT_INSTANT("%s %s (%d%)", ftl::enum_string(vote.type).c_str(),
205 to_string(vote.fps).c_str(), weight * 100);
206 summary.push_back({info->getName(), info->getOwnerUid(), vote.type, vote.fps,
207 vote.seamlessness, weight, layerFocused});
208
209 if (CC_UNLIKELY(mTraceEnabled)) {
210 trace(*info, vote.type, vote.fps.getIntValue());
211 }
212 }
213
214 return summary;
215 }
216
partitionLayers(nsecs_t now)217 void LayerHistory::partitionLayers(nsecs_t now) {
218 ATRACE_CALL();
219 const nsecs_t threshold = getActiveLayerThreshold(now);
220
221 // iterate over inactive map
222 LayerInfos::iterator it = mInactiveLayerInfos.begin();
223 while (it != mInactiveLayerInfos.end()) {
224 auto& [layerUnsafe, info] = it->second;
225 if (isLayerActive(*info, threshold)) {
226 // move this to the active map
227
228 mActiveLayerInfos.insert({it->first, std::move(it->second)});
229 it = mInactiveLayerInfos.erase(it);
230 } else {
231 if (CC_UNLIKELY(mTraceEnabled)) {
232 trace(*info, LayerVoteType::NoVote, 0);
233 }
234 info->onLayerInactive(now);
235 it++;
236 }
237 }
238
239 // iterate over active map
240 it = mActiveLayerInfos.begin();
241 while (it != mActiveLayerInfos.end()) {
242 auto& [layerUnsafe, info] = it->second;
243 if (isLayerActive(*info, threshold)) {
244 // Set layer vote if set
245 const auto frameRate = info->getSetFrameRateVote();
246 const auto voteType = [&]() {
247 switch (frameRate.type) {
248 case Layer::FrameRateCompatibility::Default:
249 return LayerVoteType::ExplicitDefault;
250 case Layer::FrameRateCompatibility::Min:
251 return LayerVoteType::Min;
252 case Layer::FrameRateCompatibility::ExactOrMultiple:
253 return LayerVoteType::ExplicitExactOrMultiple;
254 case Layer::FrameRateCompatibility::NoVote:
255 return LayerVoteType::NoVote;
256 case Layer::FrameRateCompatibility::Exact:
257 return LayerVoteType::ExplicitExact;
258 }
259 }();
260
261 if (frameRate.rate.isValid() || voteType == LayerVoteType::NoVote) {
262 const auto type = info->isVisible() ? voteType : LayerVoteType::NoVote;
263 info->setLayerVote({type, frameRate.rate, frameRate.seamlessness});
264 } else {
265 info->resetLayerVote();
266 }
267
268 it++;
269 } else {
270 if (CC_UNLIKELY(mTraceEnabled)) {
271 trace(*info, LayerVoteType::NoVote, 0);
272 }
273 info->onLayerInactive(now);
274 // move this to the inactive map
275 mInactiveLayerInfos.insert({it->first, std::move(it->second)});
276 it = mActiveLayerInfos.erase(it);
277 }
278 }
279 }
280
clear()281 void LayerHistory::clear() {
282 std::lock_guard lock(mLock);
283 for (const auto& [key, value] : mActiveLayerInfos) {
284 value.second->clearHistory(systemTime());
285 }
286 }
287
dump() const288 std::string LayerHistory::dump() const {
289 std::lock_guard lock(mLock);
290 return base::StringPrintf("{size=%zu, active=%zu}",
291 mActiveLayerInfos.size() + mInactiveLayerInfos.size(),
292 mActiveLayerInfos.size());
293 }
294
getLayerFramerate(nsecs_t now,int32_t id) const295 float LayerHistory::getLayerFramerate(nsecs_t now, int32_t id) const {
296 std::lock_guard lock(mLock);
297 auto [found, layerPair] = findLayer(id);
298 if (found != LayerStatus::NotFound) {
299 return layerPair->second->getFps(now).getValue();
300 }
301 return 0.f;
302 }
303
attachChoreographer(int32_t layerId,const sp<EventThreadConnection> & choreographerConnection)304 void LayerHistory::attachChoreographer(int32_t layerId,
305 const sp<EventThreadConnection>& choreographerConnection) {
306 std::lock_guard lock(mLock);
307 mAttachedChoreographers.insert({layerId, wp<EventThreadConnection>(choreographerConnection)});
308 }
309
findLayer(int32_t id)310 auto LayerHistory::findLayer(int32_t id) -> std::pair<LayerStatus, LayerPair*> {
311 // the layer could be in either the active or inactive map, try both
312 auto it = mActiveLayerInfos.find(id);
313 if (it != mActiveLayerInfos.end()) {
314 return {LayerStatus::LayerInActiveMap, &(it->second)};
315 }
316 it = mInactiveLayerInfos.find(id);
317 if (it != mInactiveLayerInfos.end()) {
318 return {LayerStatus::LayerInInactiveMap, &(it->second)};
319 }
320 return {LayerStatus::NotFound, nullptr};
321 }
322
isSmallDirtyArea(uint32_t dirtyArea,float threshold) const323 bool LayerHistory::isSmallDirtyArea(uint32_t dirtyArea, float threshold) const {
324 const float ratio = (float)dirtyArea / mDisplayArea;
325 const bool isSmallDirty = ratio <= threshold;
326 ATRACE_FORMAT_INSTANT("small dirty=%s, ratio=%.3f", isSmallDirty ? "true" : "false", ratio);
327 return isSmallDirty;
328 }
329
330 } // namespace android::scheduler
331