1 /*
2 * Copyright 2019 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 // TODO(b/129481165): remove the #pragma below and fix conversion issues
18 #pragma clang diagnostic push
19 #pragma clang diagnostic ignored "-Wconversion"
20 #pragma clang diagnostic ignored "-Wextra"
21
22 //#define LOG_NDEBUG 0
23 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
24 #undef LOG_TAG
25 #define LOG_TAG "RegionSamplingThread"
26
27 #include "RegionSamplingThread.h"
28
29 #include <compositionengine/Display.h>
30 #include <compositionengine/impl/OutputCompositionState.h>
31 #include <cutils/properties.h>
32 #include <ftl/future.h>
33 #include <gui/SpHash.h>
34 #include <gui/SyncScreenCaptureListener.h>
35 #include <renderengine/impl/ExternalTexture.h>
36 #include <ui/DisplayStatInfo.h>
37 #include <utils/Trace.h>
38
39 #include <string>
40
41 #include "DisplayDevice.h"
42 #include "DisplayRenderArea.h"
43 #include "FrontEnd/LayerCreationArgs.h"
44 #include "Layer.h"
45 #include "Scheduler/VsyncController.h"
46 #include "SurfaceFlinger.h"
47
48 namespace android {
49 using namespace std::chrono_literals;
50
51 using gui::SpHash;
52
53 constexpr auto lumaSamplingStepTag = "LumaSamplingStep";
54 enum class samplingStep {
55 noWorkNeeded,
56 idleTimerWaiting,
57 waitForQuietFrame,
58 waitForSamplePhase,
59 sample
60 };
61
62 constexpr auto defaultRegionSamplingWorkDuration = 3ms;
63 constexpr auto defaultRegionSamplingPeriod = 100ms;
64 constexpr auto defaultRegionSamplingTimerTimeout = 100ms;
65 constexpr auto maxRegionSamplingDelay = 100ms;
66 // TODO: (b/127403193) duration to string conversion could probably be constexpr
67 template <typename Rep, typename Per>
toNsString(std::chrono::duration<Rep,Per> t)68 inline std::string toNsString(std::chrono::duration<Rep, Per> t) {
69 return std::to_string(std::chrono::duration_cast<std::chrono::nanoseconds>(t).count());
70 }
71
EnvironmentTimingTunables()72 RegionSamplingThread::EnvironmentTimingTunables::EnvironmentTimingTunables() {
73 char value[PROPERTY_VALUE_MAX] = {};
74
75 property_get("debug.sf.region_sampling_duration_ns", value,
76 toNsString(defaultRegionSamplingWorkDuration).c_str());
77 int const samplingDurationNsRaw = atoi(value);
78
79 property_get("debug.sf.region_sampling_period_ns", value,
80 toNsString(defaultRegionSamplingPeriod).c_str());
81 int const samplingPeriodNsRaw = atoi(value);
82
83 property_get("debug.sf.region_sampling_timer_timeout_ns", value,
84 toNsString(defaultRegionSamplingTimerTimeout).c_str());
85 int const samplingTimerTimeoutNsRaw = atoi(value);
86
87 if ((samplingPeriodNsRaw < 0) || (samplingTimerTimeoutNsRaw < 0)) {
88 ALOGW("User-specified sampling tuning options nonsensical. Using defaults");
89 mSamplingDuration = defaultRegionSamplingWorkDuration;
90 mSamplingPeriod = defaultRegionSamplingPeriod;
91 mSamplingTimerTimeout = defaultRegionSamplingTimerTimeout;
92 } else {
93 mSamplingDuration = std::chrono::nanoseconds(samplingDurationNsRaw);
94 mSamplingPeriod = std::chrono::nanoseconds(samplingPeriodNsRaw);
95 mSamplingTimerTimeout = std::chrono::nanoseconds(samplingTimerTimeoutNsRaw);
96 }
97 }
98
RegionSamplingThread(SurfaceFlinger & flinger,const TimingTunables & tunables)99 RegionSamplingThread::RegionSamplingThread(SurfaceFlinger& flinger, const TimingTunables& tunables)
100 : mFlinger(flinger),
101 mTunables(tunables),
102 mIdleTimer(
103 "RegSampIdle",
104 std::chrono::duration_cast<std::chrono::milliseconds>(
105 mTunables.mSamplingTimerTimeout),
106 [] {}, [this] { checkForStaleLuma(); }),
107 mLastSampleTime(0ns) {
__anond93eb2c40302() 108 mThread = std::thread([this]() { threadMain(); });
109 pthread_setname_np(mThread.native_handle(), "RegionSampling");
110 mIdleTimer.start();
111 }
112
RegionSamplingThread(SurfaceFlinger & flinger)113 RegionSamplingThread::RegionSamplingThread(SurfaceFlinger& flinger)
114 : RegionSamplingThread(flinger,
115 TimingTunables{defaultRegionSamplingWorkDuration,
116 defaultRegionSamplingPeriod,
117 defaultRegionSamplingTimerTimeout}) {}
118
~RegionSamplingThread()119 RegionSamplingThread::~RegionSamplingThread() {
120 mIdleTimer.stop();
121
122 {
123 std::lock_guard lock(mThreadControlMutex);
124 mRunning = false;
125 mCondition.notify_one();
126 }
127
128 if (mThread.joinable()) {
129 mThread.join();
130 }
131 }
132
addListener(const Rect & samplingArea,uint32_t stopLayerId,const sp<IRegionSamplingListener> & listener)133 void RegionSamplingThread::addListener(const Rect& samplingArea, uint32_t stopLayerId,
134 const sp<IRegionSamplingListener>& listener) {
135 sp<IBinder> asBinder = IInterface::asBinder(listener);
136 asBinder->linkToDeath(sp<DeathRecipient>::fromExisting(this));
137 std::lock_guard lock(mSamplingMutex);
138 mDescriptors.emplace(wp<IBinder>(asBinder), Descriptor{samplingArea, stopLayerId, listener});
139 }
140
removeListener(const sp<IRegionSamplingListener> & listener)141 void RegionSamplingThread::removeListener(const sp<IRegionSamplingListener>& listener) {
142 std::lock_guard lock(mSamplingMutex);
143 mDescriptors.erase(wp<IBinder>(IInterface::asBinder(listener)));
144 }
145
checkForStaleLuma()146 void RegionSamplingThread::checkForStaleLuma() {
147 std::lock_guard lock(mThreadControlMutex);
148
149 if (mSampleRequestTime.has_value()) {
150 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::waitForSamplePhase));
151 mSampleRequestTime.reset();
152 mFlinger.scheduleSample();
153 }
154 }
155
onCompositionComplete(std::optional<std::chrono::steady_clock::time_point> samplingDeadline)156 void RegionSamplingThread::onCompositionComplete(
157 std::optional<std::chrono::steady_clock::time_point> samplingDeadline) {
158 doSample(samplingDeadline);
159 }
160
doSample(std::optional<std::chrono::steady_clock::time_point> samplingDeadline)161 void RegionSamplingThread::doSample(
162 std::optional<std::chrono::steady_clock::time_point> samplingDeadline) {
163 std::lock_guard lock(mThreadControlMutex);
164 const auto now = std::chrono::steady_clock::now();
165 if (mLastSampleTime + mTunables.mSamplingPeriod > now) {
166 // content changed, but we sampled not too long ago, so we need to sample some time in the
167 // future.
168 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::idleTimerWaiting));
169 mSampleRequestTime = now;
170 return;
171 }
172 if (!mSampleRequestTime.has_value() || now - *mSampleRequestTime < maxRegionSamplingDelay) {
173 // If there is relatively little time left for surfaceflinger
174 // until the next vsync deadline, defer this sampling work
175 // to a later frame, when hopefully there will be more time.
176 if (samplingDeadline.has_value() && now + mTunables.mSamplingDuration > *samplingDeadline) {
177 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::waitForQuietFrame));
178 mSampleRequestTime = mSampleRequestTime.value_or(now);
179 return;
180 }
181 }
182
183 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::sample));
184
185 mSampleRequestTime.reset();
186 mLastSampleTime = now;
187
188 mIdleTimer.reset();
189
190 mSampleRequested = true;
191 mCondition.notify_one();
192 }
193
binderDied(const wp<IBinder> & who)194 void RegionSamplingThread::binderDied(const wp<IBinder>& who) {
195 std::lock_guard lock(mSamplingMutex);
196 mDescriptors.erase(who);
197 }
198
sampleArea(const uint32_t * data,int32_t width,int32_t height,int32_t stride,uint32_t orientation,const Rect & sample_area)199 float sampleArea(const uint32_t* data, int32_t width, int32_t height, int32_t stride,
200 uint32_t orientation, const Rect& sample_area) {
201 if (!sample_area.isValid() || (sample_area.getWidth() > width) ||
202 (sample_area.getHeight() > height)) {
203 ALOGE("invalid sampling region requested");
204 return 0.0f;
205 }
206
207 const uint32_t pixelCount =
208 (sample_area.bottom - sample_area.top) * (sample_area.right - sample_area.left);
209 uint32_t accumulatedLuma = 0;
210
211 // Calculates luma with approximation of Rec. 709 primaries
212 for (int32_t row = sample_area.top; row < sample_area.bottom; ++row) {
213 const uint32_t* rowBase = data + row * stride;
214 for (int32_t column = sample_area.left; column < sample_area.right; ++column) {
215 uint32_t pixel = rowBase[column];
216 const uint32_t r = pixel & 0xFF;
217 const uint32_t g = (pixel >> 8) & 0xFF;
218 const uint32_t b = (pixel >> 16) & 0xFF;
219 const uint32_t luma = (r * 7 + b * 2 + g * 23) >> 5;
220 accumulatedLuma += luma;
221 }
222 }
223
224 return accumulatedLuma / (255.0f * pixelCount);
225 }
226
sampleBuffer(const sp<GraphicBuffer> & buffer,const Point & leftTop,const std::vector<RegionSamplingThread::Descriptor> & descriptors,uint32_t orientation)227 std::vector<float> RegionSamplingThread::sampleBuffer(
228 const sp<GraphicBuffer>& buffer, const Point& leftTop,
229 const std::vector<RegionSamplingThread::Descriptor>& descriptors, uint32_t orientation) {
230 void* data_raw = nullptr;
231 buffer->lock(GRALLOC_USAGE_SW_READ_OFTEN, &data_raw);
232 std::shared_ptr<uint32_t> data(reinterpret_cast<uint32_t*>(data_raw),
233 [&buffer](auto) { buffer->unlock(); });
234 if (!data) return {};
235
236 const int32_t width = buffer->getWidth();
237 const int32_t height = buffer->getHeight();
238 const int32_t stride = buffer->getStride();
239 std::vector<float> lumas(descriptors.size());
240 std::transform(descriptors.begin(), descriptors.end(), lumas.begin(),
241 [&](auto const& descriptor) {
242 return sampleArea(data.get(), width, height, stride, orientation,
243 descriptor.area - leftTop);
244 });
245 return lumas;
246 }
247
captureSample()248 void RegionSamplingThread::captureSample() {
249 ATRACE_CALL();
250 std::lock_guard lock(mSamplingMutex);
251
252 if (mDescriptors.empty()) {
253 return;
254 }
255
256 wp<const DisplayDevice> displayWeak;
257
258 ui::LayerStack layerStack;
259 ui::Transform::RotationFlags orientation;
260 ui::Size displaySize;
261
262 {
263 // TODO(b/159112860): Don't keep sp<DisplayDevice> outside of SF main thread
264 const sp<const DisplayDevice> display = mFlinger.getDefaultDisplayDevice();
265 displayWeak = display;
266 layerStack = display->getLayerStack();
267 orientation = ui::Transform::toRotationFlags(display->getOrientation());
268 displaySize = display->getSize();
269 }
270
271 std::vector<RegionSamplingThread::Descriptor> descriptors;
272 Region sampleRegion;
273 for (const auto& [listener, descriptor] : mDescriptors) {
274 sampleRegion.orSelf(descriptor.area);
275 descriptors.emplace_back(descriptor);
276 }
277
278 const Rect sampledBounds = sampleRegion.bounds();
279 constexpr bool kUseIdentityTransform = false;
280 constexpr bool kHintForSeamlessTransition = false;
281
282 SurfaceFlinger::RenderAreaFuture renderAreaFuture = ftl::defer([=] {
283 return DisplayRenderArea::create(displayWeak, sampledBounds, sampledBounds.getSize(),
284 ui::Dataspace::V0_SRGB, kUseIdentityTransform,
285 kHintForSeamlessTransition);
286 });
287
288 std::unordered_set<sp<IRegionSamplingListener>, SpHash<IRegionSamplingListener>> listeners;
289
290 auto layerFilterFn = [&](const char* layerName, uint32_t layerId, const Rect& bounds,
291 const ui::Transform transform, bool& outStopTraversal) -> bool {
292 // Likewise if we just found a stop layer, set the flag and abort
293 for (const auto& [area, stopLayerId, listener] : descriptors) {
294 if (stopLayerId != UNASSIGNED_LAYER_ID && layerId == stopLayerId) {
295 outStopTraversal = true;
296 return false;
297 }
298 }
299
300 // Compute the layer's position on the screen
301 constexpr bool roundOutwards = true;
302 Rect transformed = transform.transform(bounds, roundOutwards);
303
304 // If this layer doesn't intersect with the larger sampledBounds, skip capturing it
305 Rect ignore;
306 if (!transformed.intersect(sampledBounds, &ignore)) return false;
307
308 // If the layer doesn't intersect a sampling area, skip capturing it
309 bool intersectsAnyArea = false;
310 for (const auto& [area, stopLayer, listener] : descriptors) {
311 if (transformed.intersect(area, &ignore)) {
312 intersectsAnyArea = true;
313 listeners.insert(listener);
314 }
315 }
316 if (!intersectsAnyArea) return false;
317
318 ALOGV("Traversing [%s] [%d, %d, %d, %d]", layerName, bounds.left, bounds.top, bounds.right,
319 bounds.bottom);
320
321 return true;
322 };
323
324 std::function<std::vector<std::pair<Layer*, sp<LayerFE>>>()> getLayerSnapshots;
325 if (mFlinger.mLayerLifecycleManagerEnabled) {
326 auto filterFn = [&](const frontend::LayerSnapshot& snapshot,
327 bool& outStopTraversal) -> bool {
328 const Rect bounds =
329 frontend::RequestedLayerState::reduce(Rect(snapshot.geomLayerBounds),
330 snapshot.transparentRegionHint);
331 const ui::Transform transform = snapshot.geomLayerTransform;
332 return layerFilterFn(snapshot.name.c_str(), snapshot.path.id, bounds, transform,
333 outStopTraversal);
334 };
335 getLayerSnapshots =
336 mFlinger.getLayerSnapshotsForScreenshots(layerStack, CaptureArgs::UNSET_UID,
337 filterFn);
338 } else {
339 auto traverseLayers = [&](const LayerVector::Visitor& visitor) {
340 bool stopLayerFound = false;
341 auto filterVisitor = [&](Layer* layer) {
342 // We don't want to capture any layers beyond the stop layer
343 if (stopLayerFound) return;
344
345 if (!layerFilterFn(layer->getDebugName(), layer->getSequence(),
346 Rect(layer->getBounds()), layer->getTransform(),
347 stopLayerFound)) {
348 return;
349 }
350 visitor(layer);
351 };
352 mFlinger.traverseLayersInLayerStack(layerStack, CaptureArgs::UNSET_UID, {},
353 filterVisitor);
354 };
355 getLayerSnapshots = RenderArea::fromTraverseLayersLambda(traverseLayers);
356 }
357
358 std::shared_ptr<renderengine::ExternalTexture> buffer = nullptr;
359 if (mCachedBuffer && mCachedBuffer->getBuffer()->getWidth() == sampledBounds.getWidth() &&
360 mCachedBuffer->getBuffer()->getHeight() == sampledBounds.getHeight()) {
361 buffer = mCachedBuffer;
362 } else {
363 const uint32_t usage =
364 GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
365 sp<GraphicBuffer> graphicBuffer =
366 sp<GraphicBuffer>::make(sampledBounds.getWidth(), sampledBounds.getHeight(),
367 PIXEL_FORMAT_RGBA_8888, 1, usage, "RegionSamplingThread");
368 const status_t bufferStatus = graphicBuffer->initCheck();
369 LOG_ALWAYS_FATAL_IF(bufferStatus != OK, "captureSample: Buffer failed to allocate: %d",
370 bufferStatus);
371 buffer = std::make_shared<
372 renderengine::impl::ExternalTexture>(graphicBuffer, mFlinger.getRenderEngine(),
373 renderengine::impl::ExternalTexture::Usage::
374 WRITEABLE);
375 }
376
377 constexpr bool kRegionSampling = true;
378 constexpr bool kGrayscale = false;
379
380 if (const auto fenceResult =
381 mFlinger.captureScreenCommon(std::move(renderAreaFuture), getLayerSnapshots, buffer,
382 kRegionSampling, kGrayscale, nullptr)
383 .get();
384 fenceResult.ok()) {
385 fenceResult.value()->waitForever(LOG_TAG);
386 }
387
388 std::vector<Descriptor> activeDescriptors;
389 for (const auto& descriptor : descriptors) {
390 if (listeners.count(descriptor.listener) != 0) {
391 activeDescriptors.emplace_back(descriptor);
392 }
393 }
394
395 ALOGV("Sampling %zu descriptors", activeDescriptors.size());
396 std::vector<float> lumas = sampleBuffer(buffer->getBuffer(), sampledBounds.leftTop(),
397 activeDescriptors, orientation);
398 if (lumas.size() != activeDescriptors.size()) {
399 ALOGW("collected %zu median luma values for %zu descriptors", lumas.size(),
400 activeDescriptors.size());
401 return;
402 }
403
404 for (size_t d = 0; d < activeDescriptors.size(); ++d) {
405 activeDescriptors[d].listener->onSampleCollected(lumas[d]);
406 }
407
408 mCachedBuffer = buffer;
409 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::noWorkNeeded));
410 }
411
412 // NO_THREAD_SAFETY_ANALYSIS is because std::unique_lock presently lacks thread safety annotations.
threadMain()413 void RegionSamplingThread::threadMain() NO_THREAD_SAFETY_ANALYSIS {
414 std::unique_lock<std::mutex> lock(mThreadControlMutex);
415 while (mRunning) {
416 if (mSampleRequested) {
417 mSampleRequested = false;
418 lock.unlock();
419 captureSample();
420 lock.lock();
421 }
422 mCondition.wait(lock, [this]() REQUIRES(mThreadControlMutex) {
423 return mSampleRequested || !mRunning;
424 });
425 }
426 }
427
428 } // namespace android
429
430 // TODO(b/129481165): remove the #pragma below and fix conversion issues
431 #pragma clang diagnostic pop // ignored "-Wconversion -Wextra"
432