1 /*
2 * Copyright 2021 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 "Planner"
19 // #define LOG_NDEBUG 0
20 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
21
22 #include <android-base/properties.h>
23 #include <common/FlagManager.h>
24 #include <common/trace.h>
25 #include <compositionengine/impl/planner/Flattener.h>
26 #include <compositionengine/impl/planner/LayerState.h>
27
28 using time_point = std::chrono::steady_clock::time_point;
29 using namespace std::chrono_literals;
30
31 namespace android::compositionengine::impl::planner {
32
33 namespace {
34
35 // True if the underlying layer stack is the same modulo state that would be expected to be
36 // different like specific buffers, false otherwise.
isSameStack(const std::vector<const LayerState * > & incomingLayers,const std::vector<CachedSet> & cachedSets)37 bool isSameStack(const std::vector<const LayerState*>& incomingLayers,
38 const std::vector<CachedSet>& cachedSets) {
39 std::vector<const LayerState*> existingLayers;
40 for (auto& cachedSet : cachedSets) {
41 for (auto& layer : cachedSet.getConstituentLayers()) {
42 existingLayers.push_back(layer.getState());
43 }
44 }
45
46 if (incomingLayers.size() != existingLayers.size()) {
47 return false;
48 }
49
50 for (size_t i = 0; i < incomingLayers.size(); i++) {
51 // Checking the IDs here is very strict, but we do this as otherwise we may mistakenly try
52 // to access destroyed OutputLayers later on.
53 if (incomingLayers[i]->getId() != existingLayers[i]->getId()) {
54 return false;
55 }
56
57 // Do not unflatten if source crop is only moved.
58 if (FlagManager::getInstance().cache_when_source_crop_layer_only_moved() &&
59 incomingLayers[i]->isSourceCropSizeEqual(*(existingLayers[i])) &&
60 incomingLayers[i]->getDifferingFields(*(existingLayers[i])) ==
61 LayerStateField::SourceCrop) {
62 continue;
63 }
64
65 if (incomingLayers[i]->getDifferingFields(*(existingLayers[i])) != LayerStateField::None) {
66 return false;
67 }
68 }
69 return true;
70 }
71
72 } // namespace
73
Flattener(renderengine::RenderEngine & renderEngine,const Tunables & tunables)74 Flattener::Flattener(renderengine::RenderEngine& renderEngine, const Tunables& tunables)
75 : mRenderEngine(renderEngine), mTunables(tunables), mTexturePool(mRenderEngine) {}
76
flattenLayers(const std::vector<const LayerState * > & layers,NonBufferHash hash,time_point now)77 NonBufferHash Flattener::flattenLayers(const std::vector<const LayerState*>& layers,
78 NonBufferHash hash, time_point now) {
79 SFTRACE_CALL();
80 const size_t unflattenedDisplayCost = calculateDisplayCost(layers);
81 mUnflattenedDisplayCost += unflattenedDisplayCost;
82
83 // We invalidate the layer cache if:
84 // 1. We're not tracking any layers, or
85 // 2. The last seen hashed geometry changed between frames, or
86 // 3. A stricter equality check demonstrates that the layer stack really did change, since the
87 // hashed geometry does not guarantee uniqueness.
88 if (mCurrentGeometry != hash || (!mLayers.empty() && !isSameStack(layers, mLayers))) {
89 resetActivities(hash, now);
90 mFlattenedDisplayCost += unflattenedDisplayCost;
91 return hash;
92 }
93
94 ++mInitialLayerCounts[layers.size()];
95
96 // Only buildCachedSets if these layers are already stored in mLayers.
97 // Otherwise (i.e. mergeWithCachedSets returns false), the time has not
98 // changed, so buildCachedSets will never find any runs.
99 const bool alreadyHadCachedSets = mergeWithCachedSets(layers, now);
100
101 ++mFinalLayerCounts[mLayers.size()];
102
103 if (alreadyHadCachedSets) {
104 buildCachedSets(now);
105 hash = computeLayersHash();
106 }
107
108 return hash;
109 }
110
renderCachedSets(const OutputCompositionState & outputState,std::optional<std::chrono::steady_clock::time_point> renderDeadline,bool deviceHandlesColorTransform)111 void Flattener::renderCachedSets(
112 const OutputCompositionState& outputState,
113 std::optional<std::chrono::steady_clock::time_point> renderDeadline,
114 bool deviceHandlesColorTransform) {
115 SFTRACE_CALL();
116
117 if (!mNewCachedSet) {
118 return;
119 }
120
121 // Ensure that a cached set has a valid buffer first
122 if (mNewCachedSet->hasRenderedBuffer()) {
123 SFTRACE_NAME("mNewCachedSet->hasRenderedBuffer()");
124 return;
125 }
126
127 const auto now = std::chrono::steady_clock::now();
128
129 // If we have a render deadline, and the flattener is configured to skip rendering if we don't
130 // have enough time, then we skip rendering the cached set if we think that we'll steal too much
131 // time from the next frame.
132 if (renderDeadline && mTunables.mRenderScheduling) {
133 if (const auto estimatedRenderFinish =
134 now + mTunables.mRenderScheduling->cachedSetRenderDuration;
135 estimatedRenderFinish > *renderDeadline) {
136 mNewCachedSet->incrementSkipCount();
137
138 if (mNewCachedSet->getSkipCount() <=
139 mTunables.mRenderScheduling->maxDeferRenderAttempts) {
140 SFTRACE_FORMAT("DeadlinePassed: exceeded deadline by: %d us",
141 std::chrono::duration_cast<std::chrono::microseconds>(
142 estimatedRenderFinish - *renderDeadline)
143 .count());
144 return;
145 } else {
146 SFTRACE_NAME("DeadlinePassed: exceeded max skips");
147 }
148 }
149 }
150
151 mNewCachedSet->render(mRenderEngine, mTexturePool, outputState, deviceHandlesColorTransform);
152 }
153
dumpLayers(std::string & result) const154 void Flattener::dumpLayers(std::string& result) const {
155 result.append(" Current layers:");
156 for (const CachedSet& layer : mLayers) {
157 result.append("\n");
158 layer.dump(result);
159 }
160 }
161
dump(std::string & result) const162 void Flattener::dump(std::string& result) const {
163 const auto now = std::chrono::steady_clock::now();
164
165 base::StringAppendF(&result, "Flattener state:\n");
166
167 result.append("\n Statistics:\n");
168
169 result.append(" Display cost (in screen-size buffers):\n");
170 const size_t displayArea = static_cast<size_t>(mDisplaySize.width * mDisplaySize.height);
171 base::StringAppendF(&result, " Unflattened: %.2f\n",
172 static_cast<float>(mUnflattenedDisplayCost) / displayArea);
173 base::StringAppendF(&result, " Flattened: %.2f\n",
174 static_cast<float>(mFlattenedDisplayCost) / displayArea);
175
176 const auto compareLayerCounts = [](const std::pair<size_t, size_t>& left,
177 const std::pair<size_t, size_t>& right) {
178 return left.first < right.first;
179 };
180
181 const size_t maxLayerCount = mInitialLayerCounts.empty()
182 ? 0u
183 : std::max_element(mInitialLayerCounts.cbegin(), mInitialLayerCounts.cend(),
184 compareLayerCounts)
185 ->first;
186
187 result.append("\n Initial counts:\n");
188 for (size_t count = 1; count < maxLayerCount; ++count) {
189 size_t initial = mInitialLayerCounts.count(count) > 0 ? mInitialLayerCounts.at(count) : 0;
190 base::StringAppendF(&result, " % 2zd: %zd\n", count, initial);
191 }
192
193 result.append("\n Final counts:\n");
194 for (size_t count = 1; count < maxLayerCount; ++count) {
195 size_t final = mFinalLayerCounts.count(count) > 0 ? mFinalLayerCounts.at(count) : 0;
196 base::StringAppendF(&result, " % 2zd: %zd\n", count, final);
197 }
198
199 base::StringAppendF(&result, "\n Cached sets created: %zd\n", mCachedSetCreationCount);
200 base::StringAppendF(&result, " Cost: %.2f\n",
201 static_cast<float>(mCachedSetCreationCost) / displayArea);
202
203 const auto lastUpdate =
204 std::chrono::duration_cast<std::chrono::milliseconds>(now - mLastGeometryUpdate);
205 base::StringAppendF(&result, "\n Current hash %016zx, last update %sago\n\n", mCurrentGeometry,
206 durationString(lastUpdate).c_str());
207
208 dumpLayers(result);
209
210 base::StringAppendF(&result, "\n");
211 mTexturePool.dump(result);
212 }
213
calculateDisplayCost(const std::vector<const LayerState * > & layers) const214 size_t Flattener::calculateDisplayCost(const std::vector<const LayerState*>& layers) const {
215 Region coveredRegion;
216 size_t displayCost = 0;
217 bool hasClientComposition = false;
218
219 for (const LayerState* layer : layers) {
220 coveredRegion.orSelf(layer->getDisplayFrame());
221
222 // Regardless of composition type, we always have to read each input once
223 displayCost += static_cast<size_t>(layer->getDisplayFrame().width() *
224 layer->getDisplayFrame().height());
225
226 hasClientComposition |= layer->getCompositionType() ==
227 aidl::android::hardware::graphics::composer3::Composition::CLIENT;
228 }
229
230 if (hasClientComposition) {
231 // If there is client composition, the client target buffer has to be both written by the
232 // GPU and read by the DPU, so we pay its cost twice
233 displayCost += 2 *
234 static_cast<size_t>(coveredRegion.bounds().width() *
235 coveredRegion.bounds().height());
236 }
237
238 return displayCost;
239 }
240
resetActivities(NonBufferHash hash,time_point now)241 void Flattener::resetActivities(NonBufferHash hash, time_point now) {
242 ALOGV("[%s]", __func__);
243
244 mCurrentGeometry = hash;
245 mLastGeometryUpdate = now;
246 mLayers.clear();
247
248 if (mNewCachedSet) {
249 mNewCachedSet = std::nullopt;
250 }
251 }
252
computeLayersHash() const253 NonBufferHash Flattener::computeLayersHash() const{
254 size_t hash = 0;
255 for (const auto& layer : mLayers) {
256 android::hashCombineSingleHashed(hash, layer.getNonBufferHash());
257 }
258 return hash;
259 }
260
261 // Only called if the geometry matches the last frame. Return true if mLayers
262 // was already populated with these layers, i.e. on the second and following
263 // calls with the same geometry.
mergeWithCachedSets(const std::vector<const LayerState * > & layers,time_point now)264 bool Flattener::mergeWithCachedSets(const std::vector<const LayerState*>& layers, time_point now) {
265 SFTRACE_CALL();
266 std::vector<CachedSet> merged;
267
268 if (mLayers.empty()) {
269 merged.reserve(layers.size());
270 for (const LayerState* layer : layers) {
271 merged.emplace_back(layer, now);
272 mFlattenedDisplayCost += merged.back().getDisplayCost();
273 }
274 mLayers = std::move(merged);
275 return false;
276 }
277
278 // the compiler should strip out the following no-op loops when ALOGV is off
279 ALOGV("[%s] Incoming layers:", __func__);
280 for (const LayerState* layer : layers) {
281 ALOGV("%s", layer->getName().c_str());
282 }
283
284 ALOGV("[%s] Current layers:", __func__);
285 for (const CachedSet& layer : mLayers) {
286 const auto dumper = [&] {
287 std::string dump;
288 layer.dump(dump);
289 return dump;
290 };
291 ALOGV("%s", dumper().c_str());
292 }
293
294 auto currentLayerIter = mLayers.begin();
295 auto incomingLayerIter = layers.begin();
296
297 // If not null, this represents the layer that is blurring the layer before
298 // currentLayerIter. The blurring was stored in the override buffer, so the
299 // layer that requests the blur no longer needs to do any blurring.
300 compositionengine::OutputLayer* priorBlurLayer = nullptr;
301
302 while (incomingLayerIter != layers.end()) {
303 if (mNewCachedSet &&
304 mNewCachedSet->getFirstLayer().getState()->getId() == (*incomingLayerIter)->getId()) {
305 if (mNewCachedSet->hasBufferUpdate()) {
306 ALOGV("[%s] Dropping new cached set", __func__);
307 mNewCachedSet = std::nullopt;
308 } else if (mNewCachedSet->hasReadyBuffer()) {
309 ALOGV("[%s] Found ready buffer", __func__);
310 size_t skipCount = mNewCachedSet->getLayerCount();
311 while (skipCount != 0) {
312 auto* peekThroughLayer = mNewCachedSet->getHolePunchLayer();
313 const size_t layerCount = currentLayerIter->getLayerCount();
314 for (size_t i = 0; i < layerCount; ++i) {
315 bool disableBlur = priorBlurLayer &&
316 priorBlurLayer == (*incomingLayerIter)->getOutputLayer();
317 OutputLayer::CompositionState& state =
318 (*incomingLayerIter)->getOutputLayer()->editState();
319
320 state.overrideInfo = {
321 .buffer = mNewCachedSet->getBuffer(),
322 .acquireFence = mNewCachedSet->getDrawFence(),
323 .displayFrame = mNewCachedSet->getTextureBounds(),
324 .dataspace = mNewCachedSet->getOutputDataspace(),
325 .displaySpace = mNewCachedSet->getOutputSpace(),
326 .damageRegion = Region::INVALID_REGION,
327 .visibleRegion = mNewCachedSet->getVisibleRegion(),
328 .peekThroughLayer = peekThroughLayer,
329 .disableBackgroundBlur = disableBlur,
330 };
331 ++incomingLayerIter;
332 }
333 ++currentLayerIter;
334
335 skipCount -= layerCount;
336 }
337 priorBlurLayer = mNewCachedSet->getBlurLayer();
338 merged.emplace_back(std::move(*mNewCachedSet));
339 mNewCachedSet = std::nullopt;
340 continue;
341 }
342 }
343
344 if (!currentLayerIter->hasBufferUpdate()) {
345 currentLayerIter->incrementAge();
346 merged.emplace_back(*currentLayerIter);
347
348 // Skip the incoming layers corresponding to this valid current layer
349 const size_t layerCount = currentLayerIter->getLayerCount();
350 auto* peekThroughLayer = currentLayerIter->getHolePunchLayer();
351 for (size_t i = 0; i < layerCount; ++i) {
352 bool disableBlur =
353 priorBlurLayer && priorBlurLayer == (*incomingLayerIter)->getOutputLayer();
354 OutputLayer::CompositionState& state =
355 (*incomingLayerIter)->getOutputLayer()->editState();
356 state.overrideInfo = {
357 .buffer = currentLayerIter->getBuffer(),
358 .acquireFence = currentLayerIter->getDrawFence(),
359 .displayFrame = currentLayerIter->getTextureBounds(),
360 .dataspace = currentLayerIter->getOutputDataspace(),
361 .displaySpace = currentLayerIter->getOutputSpace(),
362 .damageRegion = Region(),
363 .visibleRegion = currentLayerIter->getVisibleRegion(),
364 .peekThroughLayer = peekThroughLayer,
365 .disableBackgroundBlur = disableBlur,
366 };
367 ++incomingLayerIter;
368 }
369 priorBlurLayer = currentLayerIter->getBlurLayer();
370 } else if (currentLayerIter->getLayerCount() > 1) {
371 // Break the current layer into its constituent layers
372 for (CachedSet& layer : currentLayerIter->decompose()) {
373 bool disableBlur =
374 priorBlurLayer && priorBlurLayer == (*incomingLayerIter)->getOutputLayer();
375 OutputLayer::CompositionState& state =
376 (*incomingLayerIter)->getOutputLayer()->editState();
377 state.overrideInfo.disableBackgroundBlur = disableBlur;
378 layer.updateAge(now);
379 merged.emplace_back(layer);
380 ++incomingLayerIter;
381 }
382 } else {
383 bool disableBlur =
384 priorBlurLayer && priorBlurLayer == (*incomingLayerIter)->getOutputLayer();
385 OutputLayer::CompositionState& state =
386 (*incomingLayerIter)->getOutputLayer()->editState();
387 state.overrideInfo.disableBackgroundBlur = disableBlur;
388 currentLayerIter->updateAge(now);
389 merged.emplace_back(*currentLayerIter);
390 ++incomingLayerIter;
391 priorBlurLayer = currentLayerIter->getBlurLayer();
392 }
393 ++currentLayerIter;
394 }
395
396 for (const CachedSet& layer : merged) {
397 mFlattenedDisplayCost += layer.getDisplayCost();
398 }
399
400 mLayers = std::move(merged);
401 return true;
402 }
403
findCandidateRuns(time_point now) const404 std::vector<Flattener::Run> Flattener::findCandidateRuns(time_point now) const {
405 SFTRACE_CALL();
406 std::vector<Run> runs;
407 bool isPartOfRun = false;
408 Run::Builder builder;
409 bool firstLayer = true;
410 bool runHasFirstLayer = false;
411
412 for (auto currentSet = mLayers.cbegin(); currentSet != mLayers.cend(); ++currentSet) {
413 bool layerIsInactive = now - currentSet->getLastUpdate() > mTunables.mActiveLayerTimeout;
414 const bool layerHasBlur = currentSet->hasBlurBehind();
415 const bool layerDeniedFromCaching = currentSet->cachingHintExcludesLayers();
416
417 // Layers should also be considered inactive whenever their framerate is lower than 1fps.
418 if (!layerIsInactive && currentSet->getLayerCount() == kNumLayersFpsConsideration) {
419 auto layerFps = currentSet->getFirstLayer().getState()->getFps();
420 if (layerFps > 0 && layerFps <= kFpsActiveThreshold) {
421 SFTRACE_FORMAT("layer is considered inactive due to low FPS [%s] %f",
422 currentSet->getFirstLayer().getName().c_str(), layerFps);
423 layerIsInactive = true;
424 }
425 }
426
427 if (!layerDeniedFromCaching && layerIsInactive &&
428 (firstLayer || runHasFirstLayer || !layerHasBlur) &&
429 !currentSet->hasKnownColorShift()) {
430 if (isPartOfRun) {
431 builder.increment();
432 } else {
433 builder.init(currentSet);
434 if (firstLayer) {
435 runHasFirstLayer = true;
436 }
437 isPartOfRun = true;
438 }
439 } else if (isPartOfRun) {
440 builder.setHolePunchCandidate(&(*currentSet));
441
442 // If we're here then this blur layer recently had an active buffer updating, meaning
443 // that there is exactly one layer. Blur radius currently is part of layer stack
444 // geometry, so we're also guaranteed that the background blur radius hasn't changed for
445 // at least as long as this new inactive cached set.
446 if (runHasFirstLayer && layerHasBlur &&
447 currentSet->getFirstLayer().getBackgroundBlurRadius() > 0) {
448 builder.setBlurringLayer(&(*currentSet));
449 }
450 if (auto run = builder.validateAndBuild(); run) {
451 runs.push_back(*run);
452 }
453
454 runHasFirstLayer = false;
455 builder.reset();
456 isPartOfRun = false;
457 }
458
459 firstLayer = false;
460 }
461
462 // If we're in the middle of a run at the end, we still need to validate and build it.
463 if (isPartOfRun) {
464 if (auto run = builder.validateAndBuild(); run) {
465 runs.push_back(*run);
466 }
467 }
468
469 ALOGV("[%s] Found %zu candidate runs", __func__, runs.size());
470
471 return runs;
472 }
473
findBestRun(std::vector<Flattener::Run> & runs) const474 std::optional<Flattener::Run> Flattener::findBestRun(std::vector<Flattener::Run>& runs) const {
475 if (runs.empty()) {
476 return std::nullopt;
477 }
478
479 // TODO (b/181192467): Choose the best run, instead of just the first.
480 return runs[0];
481 }
482
buildCachedSets(time_point now)483 void Flattener::buildCachedSets(time_point now) {
484 SFTRACE_CALL();
485 if (mLayers.empty()) {
486 ALOGV("[%s] No layers found, returning", __func__);
487 return;
488 }
489
490 // Don't try to build a new cached set if we already have a new one in progress
491 if (mNewCachedSet) {
492 return;
493 }
494
495 for (const CachedSet& layer : mLayers) {
496 // TODO (b/191997217): make it less aggressive, and sync with findCandidateRuns
497 if (layer.hasProtectedLayers()) {
498 SFTRACE_NAME("layer->hasProtectedLayers()");
499 return;
500 }
501 }
502
503 std::vector<Run> runs = findCandidateRuns(now);
504
505 std::optional<Run> bestRun = findBestRun(runs);
506
507 if (!bestRun) {
508 return;
509 }
510
511 mNewCachedSet.emplace(*bestRun->getStart());
512 mNewCachedSet->setLastUpdate(now);
513 auto currentSet = bestRun->getStart();
514 while (mNewCachedSet->getLayerCount() < bestRun->getLayerLength()) {
515 ++currentSet;
516 mNewCachedSet->append(*currentSet);
517 }
518
519 if (bestRun->getBlurringLayer()) {
520 mNewCachedSet->addBackgroundBlurLayer(*bestRun->getBlurringLayer());
521 }
522
523 if (mTunables.mEnableHolePunch && bestRun->getHolePunchCandidate() &&
524 bestRun->getHolePunchCandidate()->requiresHolePunch()) {
525 // Add the pip layer to mNewCachedSet, but in a special way - it should
526 // replace the buffer with a clear round rect.
527 mNewCachedSet->addHolePunchLayerIfFeasible(*bestRun->getHolePunchCandidate(),
528 bestRun->getStart() == mLayers.cbegin());
529 }
530
531 // TODO(b/181192467): Actually compute new LayerState vector and corresponding hash for each run
532 // and feedback into the predictor
533
534 ++mCachedSetCreationCount;
535 mCachedSetCreationCost += mNewCachedSet->getCreationCost();
536
537 // note the compiler should strip the follow no-op statements when ALOGV is off
538 const auto dumper = [&] {
539 std::string setDump;
540 mNewCachedSet->dump(setDump);
541 return setDump;
542 };
543 ALOGV("[%s] Added new cached set:\n%s", __func__, dumper().c_str());
544 }
545
546 } // namespace android::compositionengine::impl::planner
547