blob: 890945f6f35859e9dff32c32ccd7f54f0c114884 [file] [log] [blame]
Dan Stozaec460082018-12-17 15:35:09 -08001/*
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
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Dan Stozaec460082018-12-17 15:35:09 -080021//#define LOG_NDEBUG 0
22#define ATRACE_TAG ATRACE_TAG_GRAPHICS
23#undef LOG_TAG
24#define LOG_TAG "RegionSamplingThread"
25
26#include "RegionSamplingThread.h"
27
Kevin DuBoisb325c932019-05-21 08:34:09 -070028#include <compositionengine/Display.h>
29#include <compositionengine/impl/OutputCompositionState.h>
Dominik Laskowski98041832019-08-01 18:35:59 -070030#include <cutils/properties.h>
31#include <gui/IRegionSamplingListener.h>
32#include <ui/DisplayStatInfo.h>
33#include <utils/Trace.h>
34
35#include <string>
36
Dan Stozaec460082018-12-17 15:35:09 -080037#include "DisplayDevice.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +020038#include "DisplayRenderArea.h"
Dan Stozaec460082018-12-17 15:35:09 -080039#include "Layer.h"
Marin Shalamanov1c434292020-06-12 01:47:29 +020040#include "Promise.h"
Ady Abraham8cb21882020-08-26 18:22:05 -070041#include "Scheduler/VsyncController.h"
Dan Stozaec460082018-12-17 15:35:09 -080042#include "SurfaceFlinger.h"
43
44namespace android {
Kevin DuBois413287f2019-02-25 08:46:47 -080045using namespace std::chrono_literals;
Dan Stozaec460082018-12-17 15:35:09 -080046
47template <typename T>
48struct SpHash {
49 size_t operator()(const sp<T>& p) const { return std::hash<T*>()(p.get()); }
50};
51
Kevin DuBois413287f2019-02-25 08:46:47 -080052constexpr auto lumaSamplingStepTag = "LumaSamplingStep";
53enum class samplingStep {
54 noWorkNeeded,
55 idleTimerWaiting,
John Dias84be7832019-06-18 17:05:26 -070056 waitForQuietFrame,
Kevin DuBois413287f2019-02-25 08:46:47 -080057 waitForZeroPhase,
58 waitForSamplePhase,
59 sample
60};
61
John Dias84be7832019-06-18 17:05:26 -070062constexpr auto timeForRegionSampling = 5000000ns;
63constexpr auto maxRegionSamplingSkips = 10;
Ady Abraham9c53ee72020-07-22 21:16:18 -070064constexpr auto defaultRegionSamplingWorkDuration = 3ms;
Kevin DuBois413287f2019-02-25 08:46:47 -080065constexpr auto defaultRegionSamplingPeriod = 100ms;
66constexpr auto defaultRegionSamplingTimerTimeout = 100ms;
67// TODO: (b/127403193) duration to string conversion could probably be constexpr
68template <typename Rep, typename Per>
69inline std::string toNsString(std::chrono::duration<Rep, Per> t) {
70 return std::to_string(std::chrono::duration_cast<std::chrono::nanoseconds>(t).count());
Dan Stozaec460082018-12-17 15:35:09 -080071}
72
Kevin DuBois413287f2019-02-25 08:46:47 -080073RegionSamplingThread::EnvironmentTimingTunables::EnvironmentTimingTunables() {
74 char value[PROPERTY_VALUE_MAX] = {};
75
Ady Abraham9c53ee72020-07-22 21:16:18 -070076 property_get("debug.sf.region_sampling_duration_ns", value,
77 toNsString(defaultRegionSamplingWorkDuration).c_str());
78 int const samplingDurationNsRaw = atoi(value);
Kevin DuBois413287f2019-02-25 08:46:47 -080079
80 property_get("debug.sf.region_sampling_period_ns", value,
81 toNsString(defaultRegionSamplingPeriod).c_str());
82 int const samplingPeriodNsRaw = atoi(value);
83
84 property_get("debug.sf.region_sampling_timer_timeout_ns", value,
85 toNsString(defaultRegionSamplingTimerTimeout).c_str());
86 int const samplingTimerTimeoutNsRaw = atoi(value);
87
88 if ((samplingPeriodNsRaw < 0) || (samplingTimerTimeoutNsRaw < 0)) {
89 ALOGW("User-specified sampling tuning options nonsensical. Using defaults");
Ady Abraham9c53ee72020-07-22 21:16:18 -070090 mSamplingDuration = defaultRegionSamplingWorkDuration;
Kevin DuBois413287f2019-02-25 08:46:47 -080091 mSamplingPeriod = defaultRegionSamplingPeriod;
92 mSamplingTimerTimeout = defaultRegionSamplingTimerTimeout;
93 } else {
Ady Abraham9c53ee72020-07-22 21:16:18 -070094 mSamplingDuration = std::chrono::nanoseconds(samplingDurationNsRaw);
Kevin DuBois413287f2019-02-25 08:46:47 -080095 mSamplingPeriod = std::chrono::nanoseconds(samplingPeriodNsRaw);
96 mSamplingTimerTimeout = std::chrono::nanoseconds(samplingTimerTimeoutNsRaw);
97 }
98}
99
Ady Abraham9c53ee72020-07-22 21:16:18 -0700100struct SamplingOffsetCallback : VSyncSource::Callback {
Kevin DuBois413287f2019-02-25 08:46:47 -0800101 SamplingOffsetCallback(RegionSamplingThread& samplingThread, Scheduler& scheduler,
Ady Abraham9c53ee72020-07-22 21:16:18 -0700102 std::chrono::nanoseconds targetSamplingWorkDuration)
Kevin DuBois413287f2019-02-25 08:46:47 -0800103 : mRegionSamplingThread(samplingThread),
Ady Abraham9c53ee72020-07-22 21:16:18 -0700104 mTargetSamplingWorkDuration(targetSamplingWorkDuration),
105 mVSyncSource(scheduler.makePrimaryDispSyncSource("SamplingThreadDispSyncListener", 0ns,
106 0ns,
107 /*traceVsync=*/false)) {
108 mVSyncSource->setCallback(this);
109 }
Kevin DuBois413287f2019-02-25 08:46:47 -0800110
111 ~SamplingOffsetCallback() { stopVsyncListener(); }
112
113 SamplingOffsetCallback(const SamplingOffsetCallback&) = delete;
114 SamplingOffsetCallback& operator=(const SamplingOffsetCallback&) = delete;
115
116 void startVsyncListener() {
117 std::lock_guard lock(mMutex);
118 if (mVsyncListening) return;
119
120 mPhaseIntervalSetting = Phase::ZERO;
Ady Abraham9c53ee72020-07-22 21:16:18 -0700121 mVSyncSource->setVSyncEnabled(true);
Kevin DuBois413287f2019-02-25 08:46:47 -0800122 mVsyncListening = true;
123 }
124
125 void stopVsyncListener() {
126 std::lock_guard lock(mMutex);
127 stopVsyncListenerLocked();
128 }
129
130private:
131 void stopVsyncListenerLocked() /*REQUIRES(mMutex)*/ {
132 if (!mVsyncListening) return;
133
Ady Abraham9c53ee72020-07-22 21:16:18 -0700134 mVSyncSource->setVSyncEnabled(false);
Kevin DuBois413287f2019-02-25 08:46:47 -0800135 mVsyncListening = false;
136 }
137
Ady Abraham9c53ee72020-07-22 21:16:18 -0700138 void onVSyncEvent(nsecs_t /*when*/, nsecs_t /*expectedVSyncTimestamp*/,
139 nsecs_t /*deadlineTimestamp*/) final {
Kevin DuBois413287f2019-02-25 08:46:47 -0800140 std::unique_lock<decltype(mMutex)> lock(mMutex);
141
142 if (mPhaseIntervalSetting == Phase::ZERO) {
143 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::waitForSamplePhase));
144 mPhaseIntervalSetting = Phase::SAMPLING;
Ady Abraham9c53ee72020-07-22 21:16:18 -0700145 mVSyncSource->setDuration(mTargetSamplingWorkDuration, 0ns);
Kevin DuBois413287f2019-02-25 08:46:47 -0800146 return;
147 }
148
149 if (mPhaseIntervalSetting == Phase::SAMPLING) {
150 mPhaseIntervalSetting = Phase::ZERO;
Ady Abraham9c53ee72020-07-22 21:16:18 -0700151 mVSyncSource->setDuration(0ns, 0ns);
Kevin DuBois413287f2019-02-25 08:46:47 -0800152 stopVsyncListenerLocked();
153 lock.unlock();
154 mRegionSamplingThread.notifySamplingOffset();
155 return;
156 }
157 }
158
159 RegionSamplingThread& mRegionSamplingThread;
Ady Abraham9c53ee72020-07-22 21:16:18 -0700160 const std::chrono::nanoseconds mTargetSamplingWorkDuration;
Kevin DuBois413287f2019-02-25 08:46:47 -0800161 mutable std::mutex mMutex;
162 enum class Phase {
163 ZERO,
164 SAMPLING
165 } mPhaseIntervalSetting /*GUARDED_BY(mMutex) macro doesnt work with unique_lock?*/
166 = Phase::ZERO;
167 bool mVsyncListening /*GUARDED_BY(mMutex)*/ = false;
Ady Abraham9c53ee72020-07-22 21:16:18 -0700168 std::unique_ptr<VSyncSource> mVSyncSource;
Kevin DuBois413287f2019-02-25 08:46:47 -0800169};
170
171RegionSamplingThread::RegionSamplingThread(SurfaceFlinger& flinger, Scheduler& scheduler,
172 const TimingTunables& tunables)
173 : mFlinger(flinger),
174 mScheduler(scheduler),
175 mTunables(tunables),
Ady Abraham9c53ee72020-07-22 21:16:18 -0700176 mIdleTimer(
177 std::chrono::duration_cast<std::chrono::milliseconds>(
178 mTunables.mSamplingTimerTimeout),
179 [] {}, [this] { checkForStaleLuma(); }),
Kevin DuBois413287f2019-02-25 08:46:47 -0800180 mPhaseCallback(std::make_unique<SamplingOffsetCallback>(*this, mScheduler,
Ady Abraham9c53ee72020-07-22 21:16:18 -0700181 tunables.mSamplingDuration)),
Kevin DuBois413287f2019-02-25 08:46:47 -0800182 lastSampleTime(0ns) {
Kevin DuBois26afc782019-05-06 16:46:45 -0700183 mThread = std::thread([this]() { threadMain(); });
184 pthread_setname_np(mThread.native_handle(), "RegionSamplingThread");
Kevin DuBois413287f2019-02-25 08:46:47 -0800185 mIdleTimer.start();
186}
187
188RegionSamplingThread::RegionSamplingThread(SurfaceFlinger& flinger, Scheduler& scheduler)
189 : RegionSamplingThread(flinger, scheduler,
Ady Abraham9c53ee72020-07-22 21:16:18 -0700190 TimingTunables{defaultRegionSamplingWorkDuration,
Kevin DuBois413287f2019-02-25 08:46:47 -0800191 defaultRegionSamplingPeriod,
192 defaultRegionSamplingTimerTimeout}) {}
193
Dan Stozaec460082018-12-17 15:35:09 -0800194RegionSamplingThread::~RegionSamplingThread() {
Kevin DuBois413287f2019-02-25 08:46:47 -0800195 mIdleTimer.stop();
196
Dan Stozaec460082018-12-17 15:35:09 -0800197 {
Kevin DuBois26afc782019-05-06 16:46:45 -0700198 std::lock_guard lock(mThreadControlMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800199 mRunning = false;
200 mCondition.notify_one();
201 }
202
Dan Stozaec460082018-12-17 15:35:09 -0800203 if (mThread.joinable()) {
204 mThread.join();
205 }
206}
207
Alec Mouri9a02eda2020-04-21 17:39:34 -0700208void RegionSamplingThread::addListener(const Rect& samplingArea, const wp<Layer>& stopLayer,
Dan Stozaec460082018-12-17 15:35:09 -0800209 const sp<IRegionSamplingListener>& listener) {
Dan Stozaec460082018-12-17 15:35:09 -0800210 sp<IBinder> asBinder = IInterface::asBinder(listener);
211 asBinder->linkToDeath(this);
Kevin DuBois26afc782019-05-06 16:46:45 -0700212 std::lock_guard lock(mSamplingMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800213 mDescriptors.emplace(wp<IBinder>(asBinder), Descriptor{samplingArea, stopLayer, listener});
214}
215
216void RegionSamplingThread::removeListener(const sp<IRegionSamplingListener>& listener) {
Kevin DuBois26afc782019-05-06 16:46:45 -0700217 std::lock_guard lock(mSamplingMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800218 mDescriptors.erase(wp<IBinder>(IInterface::asBinder(listener)));
219}
220
Kevin DuBois413287f2019-02-25 08:46:47 -0800221void RegionSamplingThread::checkForStaleLuma() {
Kevin DuBois26afc782019-05-06 16:46:45 -0700222 std::lock_guard lock(mThreadControlMutex);
Kevin DuBois413287f2019-02-25 08:46:47 -0800223
John Dias84be7832019-06-18 17:05:26 -0700224 if (mDiscardedFrames > 0) {
Kevin DuBois413287f2019-02-25 08:46:47 -0800225 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::waitForZeroPhase));
John Dias84be7832019-06-18 17:05:26 -0700226 mDiscardedFrames = 0;
Kevin DuBois413287f2019-02-25 08:46:47 -0800227 mPhaseCallback->startVsyncListener();
228 }
229}
230
231void RegionSamplingThread::notifyNewContent() {
232 doSample();
233}
234
235void RegionSamplingThread::notifySamplingOffset() {
236 doSample();
237}
238
239void RegionSamplingThread::doSample() {
Kevin DuBois26afc782019-05-06 16:46:45 -0700240 std::lock_guard lock(mThreadControlMutex);
Kevin DuBois413287f2019-02-25 08:46:47 -0800241 auto now = std::chrono::nanoseconds(systemTime(SYSTEM_TIME_MONOTONIC));
242 if (lastSampleTime + mTunables.mSamplingPeriod > now) {
243 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::idleTimerWaiting));
John Dias84be7832019-06-18 17:05:26 -0700244 if (mDiscardedFrames == 0) mDiscardedFrames++;
Kevin DuBois413287f2019-02-25 08:46:47 -0800245 return;
246 }
John Dias84be7832019-06-18 17:05:26 -0700247 if (mDiscardedFrames < maxRegionSamplingSkips) {
248 // If there is relatively little time left for surfaceflinger
249 // until the next vsync deadline, defer this sampling work
250 // to a later frame, when hopefully there will be more time.
251 DisplayStatInfo stats;
Ady Abraham8cb21882020-08-26 18:22:05 -0700252 mScheduler.getDisplayStatInfo(&stats, systemTime());
John Dias84be7832019-06-18 17:05:26 -0700253 if (std::chrono::nanoseconds(stats.vsyncTime) - now < timeForRegionSampling) {
254 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::waitForQuietFrame));
255 mDiscardedFrames++;
256 return;
257 }
258 }
Kevin DuBois413287f2019-02-25 08:46:47 -0800259
260 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::sample));
261
John Dias84be7832019-06-18 17:05:26 -0700262 mDiscardedFrames = 0;
Kevin DuBois413287f2019-02-25 08:46:47 -0800263 lastSampleTime = now;
264
265 mIdleTimer.reset();
266 mPhaseCallback->stopVsyncListener();
267
Dan Stozaec460082018-12-17 15:35:09 -0800268 mSampleRequested = true;
269 mCondition.notify_one();
270}
271
272void RegionSamplingThread::binderDied(const wp<IBinder>& who) {
Kevin DuBois26afc782019-05-06 16:46:45 -0700273 std::lock_guard lock(mSamplingMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800274 mDescriptors.erase(who);
275}
276
Kevin DuBoisb325c932019-05-21 08:34:09 -0700277float sampleArea(const uint32_t* data, int32_t width, int32_t height, int32_t stride,
278 uint32_t orientation, const Rect& sample_area) {
279 if (!sample_area.isValid() || (sample_area.getWidth() > width) ||
280 (sample_area.getHeight() > height)) {
281 ALOGE("invalid sampling region requested");
282 return 0.0f;
283 }
284
285 // (b/133849373) ROT_90 screencap images produced upside down
286 auto area = sample_area;
287 if (orientation & ui::Transform::ROT_90) {
288 area.top = height - area.top;
289 area.bottom = height - area.bottom;
290 std::swap(area.top, area.bottom);
Kevin DuBois69162d02019-06-04 20:22:43 -0700291
292 area.left = width - area.left;
293 area.right = width - area.right;
294 std::swap(area.left, area.right);
Kevin DuBoisb325c932019-05-21 08:34:09 -0700295 }
296
Collin Fijalkovicha95e1702019-10-28 14:46:13 -0700297 const uint32_t pixelCount = (area.bottom - area.top) * (area.right - area.left);
298 uint32_t accumulatedLuma = 0;
Dan Stozaec460082018-12-17 15:35:09 -0800299
Collin Fijalkovicha95e1702019-10-28 14:46:13 -0700300 // Calculates luma with approximation of Rec. 709 primaries
Dan Stozaec460082018-12-17 15:35:09 -0800301 for (int32_t row = area.top; row < area.bottom; ++row) {
302 const uint32_t* rowBase = data + row * stride;
303 for (int32_t column = area.left; column < area.right; ++column) {
304 uint32_t pixel = rowBase[column];
Collin Fijalkovicha95e1702019-10-28 14:46:13 -0700305 const uint32_t r = pixel & 0xFF;
306 const uint32_t g = (pixel >> 8) & 0xFF;
307 const uint32_t b = (pixel >> 16) & 0xFF;
308 const uint32_t luma = (r * 7 + b * 2 + g * 23) >> 5;
309 accumulatedLuma += luma;
Dan Stozaec460082018-12-17 15:35:09 -0800310 }
311 }
312
Collin Fijalkovicha95e1702019-10-28 14:46:13 -0700313 return accumulatedLuma / (255.0f * pixelCount);
Dan Stozaec460082018-12-17 15:35:09 -0800314}
Dan Stozaec460082018-12-17 15:35:09 -0800315
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800316std::vector<float> RegionSamplingThread::sampleBuffer(
317 const sp<GraphicBuffer>& buffer, const Point& leftTop,
Kevin DuBoisb325c932019-05-21 08:34:09 -0700318 const std::vector<RegionSamplingThread::Descriptor>& descriptors, uint32_t orientation) {
Dan Stozaec460082018-12-17 15:35:09 -0800319 void* data_raw = nullptr;
320 buffer->lock(GRALLOC_USAGE_SW_READ_OFTEN, &data_raw);
321 std::shared_ptr<uint32_t> data(reinterpret_cast<uint32_t*>(data_raw),
322 [&buffer](auto) { buffer->unlock(); });
323 if (!data) return {};
324
Kevin DuBoisb325c932019-05-21 08:34:09 -0700325 const int32_t width = buffer->getWidth();
326 const int32_t height = buffer->getHeight();
Dan Stozaec460082018-12-17 15:35:09 -0800327 const int32_t stride = buffer->getStride();
328 std::vector<float> lumas(descriptors.size());
329 std::transform(descriptors.begin(), descriptors.end(), lumas.begin(),
330 [&](auto const& descriptor) {
Kevin DuBoisb325c932019-05-21 08:34:09 -0700331 return sampleArea(data.get(), width, height, stride, orientation,
332 descriptor.area - leftTop);
Dan Stozaec460082018-12-17 15:35:09 -0800333 });
334 return lumas;
335}
336
337void RegionSamplingThread::captureSample() {
338 ATRACE_CALL();
Kevin DuBois26afc782019-05-06 16:46:45 -0700339 std::lock_guard lock(mSamplingMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800340
341 if (mDescriptors.empty()) {
342 return;
343 }
344
Marin Shalamanov1c434292020-06-12 01:47:29 +0200345 wp<const DisplayDevice> displayWeak;
346
347 ui::LayerStack layerStack;
348 ui::Transform::RotationFlags orientation;
349 ui::Size displaySize;
350
351 {
352 // TODO(b/159112860): Don't keep sp<DisplayDevice> outside of SF main thread
353 const sp<const DisplayDevice> display = mFlinger.getDefaultDisplayDevice();
354 displayWeak = display;
355 layerStack = display->getLayerStack();
356 orientation = ui::Transform::toRotationFlags(display->getOrientation());
357 displaySize = display->getSize();
358 }
Kevin DuBoisb325c932019-05-21 08:34:09 -0700359
Dan Stozaec460082018-12-17 15:35:09 -0800360 std::vector<RegionSamplingThread::Descriptor> descriptors;
361 Region sampleRegion;
362 for (const auto& [listener, descriptor] : mDescriptors) {
363 sampleRegion.orSelf(descriptor.area);
364 descriptors.emplace_back(descriptor);
365 }
366
Kevin DuBoisb325c932019-05-21 08:34:09 -0700367 auto dx = 0;
368 auto dy = 0;
369 switch (orientation) {
370 case ui::Transform::ROT_90:
Marin Shalamanov1c434292020-06-12 01:47:29 +0200371 dx = displaySize.getWidth();
Kevin DuBoisb325c932019-05-21 08:34:09 -0700372 break;
373 case ui::Transform::ROT_180:
Marin Shalamanov1c434292020-06-12 01:47:29 +0200374 dx = displaySize.getWidth();
375 dy = displaySize.getHeight();
Kevin DuBoisb325c932019-05-21 08:34:09 -0700376 break;
377 case ui::Transform::ROT_270:
Marin Shalamanov1c434292020-06-12 01:47:29 +0200378 dy = displaySize.getHeight();
Kevin DuBoisb325c932019-05-21 08:34:09 -0700379 break;
380 default:
381 break;
382 }
383
384 ui::Transform t(orientation);
385 auto screencapRegion = t.transform(sampleRegion);
386 screencapRegion = screencapRegion.translate(dx, dy);
Marin Shalamanov1c434292020-06-12 01:47:29 +0200387
388 const Rect sampledBounds = sampleRegion.bounds();
389
390 SurfaceFlinger::RenderAreaFuture renderAreaFuture = promise::defer([=] {
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200391 return DisplayRenderArea::create(displayWeak, screencapRegion.bounds(),
392 sampledBounds.getSize(), ui::Dataspace::V0_SRGB,
393 orientation);
Marin Shalamanov1c434292020-06-12 01:47:29 +0200394 });
Dan Stozaec460082018-12-17 15:35:09 -0800395
396 std::unordered_set<sp<IRegionSamplingListener>, SpHash<IRegionSamplingListener>> listeners;
397
398 auto traverseLayers = [&](const LayerVector::Visitor& visitor) {
399 bool stopLayerFound = false;
400 auto filterVisitor = [&](Layer* layer) {
401 // We don't want to capture any layers beyond the stop layer
402 if (stopLayerFound) return;
403
404 // Likewise if we just found a stop layer, set the flag and abort
405 for (const auto& [area, stopLayer, listener] : descriptors) {
406 if (layer == stopLayer.promote().get()) {
407 stopLayerFound = true;
408 return;
409 }
410 }
411
412 // Compute the layer's position on the screen
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800413 const Rect bounds = Rect(layer->getBounds());
414 const ui::Transform transform = layer->getTransform();
Dan Stozaec460082018-12-17 15:35:09 -0800415 constexpr bool roundOutwards = true;
416 Rect transformed = transform.transform(bounds, roundOutwards);
417
Marin Shalamanov1c434292020-06-12 01:47:29 +0200418 // If this layer doesn't intersect with the larger sampledBounds, skip capturing it
Dan Stozaec460082018-12-17 15:35:09 -0800419 Rect ignore;
Marin Shalamanov1c434292020-06-12 01:47:29 +0200420 if (!transformed.intersect(sampledBounds, &ignore)) return;
Dan Stozaec460082018-12-17 15:35:09 -0800421
422 // If the layer doesn't intersect a sampling area, skip capturing it
423 bool intersectsAnyArea = false;
424 for (const auto& [area, stopLayer, listener] : descriptors) {
425 if (transformed.intersect(area, &ignore)) {
426 intersectsAnyArea = true;
427 listeners.insert(listener);
428 }
429 }
430 if (!intersectsAnyArea) return;
431
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700432 ALOGV("Traversing [%s] [%d, %d, %d, %d]", layer->getDebugName(), bounds.left,
Dan Stozaec460082018-12-17 15:35:09 -0800433 bounds.top, bounds.right, bounds.bottom);
434 visitor(layer);
435 };
chaviw4b9d5e12020-08-04 18:30:35 -0700436 mFlinger.traverseLayersInLayerStack(layerStack, CaptureArgs::UNSET_UID, filterVisitor);
Dan Stozaec460082018-12-17 15:35:09 -0800437 };
438
Kevin DuBois4efd1f52019-04-29 10:09:43 -0700439 sp<GraphicBuffer> buffer = nullptr;
Marin Shalamanov1c434292020-06-12 01:47:29 +0200440 if (mCachedBuffer && mCachedBuffer->getWidth() == sampledBounds.getWidth() &&
441 mCachedBuffer->getHeight() == sampledBounds.getHeight()) {
Kevin DuBois4efd1f52019-04-29 10:09:43 -0700442 buffer = mCachedBuffer;
443 } else {
John Reck67b1e2b2020-08-26 13:17:24 -0700444 const uint32_t usage =
445 GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Marin Shalamanov1c434292020-06-12 01:47:29 +0200446 buffer = new GraphicBuffer(sampledBounds.getWidth(), sampledBounds.getHeight(),
Kevin DuBois4efd1f52019-04-29 10:09:43 -0700447 PIXEL_FORMAT_RGBA_8888, 1, usage, "RegionSamplingThread");
448 }
Dan Stozaec460082018-12-17 15:35:09 -0800449
Chavi Weingarten99eeeb82020-09-10 20:55:11 +0000450 class SyncScreenCaptureListener : public BnScreenCaptureListener {
451 public:
452 status_t onScreenCaptureComplete(const ScreenCaptureResults& captureResults) override {
453 resultsPromise.set_value(captureResults);
454 return NO_ERROR;
455 }
456
457 ScreenCaptureResults waitForResults() {
458 std::future<ScreenCaptureResults> resultsFuture = resultsPromise.get_future();
459 return resultsFuture.get();
460 }
461
462 private:
463 std::promise<ScreenCaptureResults> resultsPromise;
464 };
465
chaviw03900772020-08-18 12:34:51 -0700466 const sp<SyncScreenCaptureListener> captureListener = new SyncScreenCaptureListener();
Marin Shalamanov1c434292020-06-12 01:47:29 +0200467 mFlinger.captureScreenCommon(std::move(renderAreaFuture), traverseLayers, buffer,
chaviw03900772020-08-18 12:34:51 -0700468 true /* regionSampling */, captureListener);
469 ScreenCaptureResults captureResults = captureListener->waitForResults();
Dan Stozaec460082018-12-17 15:35:09 -0800470
471 std::vector<Descriptor> activeDescriptors;
472 for (const auto& descriptor : descriptors) {
473 if (listeners.count(descriptor.listener) != 0) {
474 activeDescriptors.emplace_back(descriptor);
475 }
476 }
477
478 ALOGV("Sampling %zu descriptors", activeDescriptors.size());
Kevin DuBoisb325c932019-05-21 08:34:09 -0700479 std::vector<float> lumas =
Marin Shalamanov1c434292020-06-12 01:47:29 +0200480 sampleBuffer(buffer, sampledBounds.leftTop(), activeDescriptors, orientation);
Dan Stozaec460082018-12-17 15:35:09 -0800481 if (lumas.size() != activeDescriptors.size()) {
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800482 ALOGW("collected %zu median luma values for %zu descriptors", lumas.size(),
483 activeDescriptors.size());
Dan Stozaec460082018-12-17 15:35:09 -0800484 return;
485 }
486
487 for (size_t d = 0; d < activeDescriptors.size(); ++d) {
488 activeDescriptors[d].listener->onSampleCollected(lumas[d]);
489 }
Kevin DuBois4efd1f52019-04-29 10:09:43 -0700490
491 // Extend the lifetime of mCachedBuffer from the previous frame to here to ensure that:
492 // 1) The region sampling thread is the last owner of the buffer, and the freeing of the buffer
493 // happens in this thread, as opposed to the main thread.
494 // 2) The listener(s) receive their notifications prior to freeing the buffer.
495 mCachedBuffer = buffer;
Kevin DuBois413287f2019-02-25 08:46:47 -0800496 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::noWorkNeeded));
Dan Stozaec460082018-12-17 15:35:09 -0800497}
498
Kevin DuBois26afc782019-05-06 16:46:45 -0700499// NO_THREAD_SAFETY_ANALYSIS is because std::unique_lock presently lacks thread safety annotations.
500void RegionSamplingThread::threadMain() NO_THREAD_SAFETY_ANALYSIS {
501 std::unique_lock<std::mutex> lock(mThreadControlMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800502 while (mRunning) {
503 if (mSampleRequested) {
504 mSampleRequested = false;
Kevin DuBois26afc782019-05-06 16:46:45 -0700505 lock.unlock();
Dan Stozaec460082018-12-17 15:35:09 -0800506 captureSample();
Kevin DuBois26afc782019-05-06 16:46:45 -0700507 lock.lock();
Dan Stozaec460082018-12-17 15:35:09 -0800508 }
Kevin DuBois26afc782019-05-06 16:46:45 -0700509 mCondition.wait(lock, [this]() REQUIRES(mThreadControlMutex) {
510 return mSampleRequested || !mRunning;
511 });
Dan Stozaec460082018-12-17 15:35:09 -0800512 }
513}
514
515} // namespace android
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800516
517// TODO(b/129481165): remove the #pragma below and fix conversion issues
518#pragma clang diagnostic pop // ignored "-Wconversion"