blob: ad4877bdeb19a9a9ff007525c3596e78900701ae [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>
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -080031#include <ftl/future.h>
Dominik Laskowski98041832019-08-01 18:35:59 -070032#include <gui/IRegionSamplingListener.h>
chaviwe7b9f272020-08-18 16:08:59 -070033#include <gui/SyncScreenCaptureListener.h>
Dominik Laskowski98041832019-08-01 18:35:59 -070034#include <ui/DisplayStatInfo.h>
35#include <utils/Trace.h>
36
37#include <string>
38
Dan Stozaec460082018-12-17 15:35:09 -080039#include "DisplayDevice.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +020040#include "DisplayRenderArea.h"
Dan Stozaec460082018-12-17 15:35:09 -080041#include "Layer.h"
Ady Abraham8cb21882020-08-26 18:22:05 -070042#include "Scheduler/VsyncController.h"
Dan Stozaec460082018-12-17 15:35:09 -080043#include "SurfaceFlinger.h"
44
45namespace android {
Kevin DuBois413287f2019-02-25 08:46:47 -080046using namespace std::chrono_literals;
Dan Stozaec460082018-12-17 15:35:09 -080047
48template <typename T>
49struct SpHash {
50 size_t operator()(const sp<T>& p) const { return std::hash<T*>()(p.get()); }
51};
52
Kevin DuBois413287f2019-02-25 08:46:47 -080053constexpr auto lumaSamplingStepTag = "LumaSamplingStep";
54enum class samplingStep {
55 noWorkNeeded,
56 idleTimerWaiting,
John Dias84be7832019-06-18 17:05:26 -070057 waitForQuietFrame,
Kevin DuBois413287f2019-02-25 08:46:47 -080058 waitForZeroPhase,
59 waitForSamplePhase,
60 sample
61};
62
John Dias84be7832019-06-18 17:05:26 -070063constexpr auto timeForRegionSampling = 5000000ns;
64constexpr auto maxRegionSamplingSkips = 10;
Ady Abraham9c53ee72020-07-22 21:16:18 -070065constexpr auto defaultRegionSamplingWorkDuration = 3ms;
Kevin DuBois413287f2019-02-25 08:46:47 -080066constexpr auto defaultRegionSamplingPeriod = 100ms;
67constexpr auto defaultRegionSamplingTimerTimeout = 100ms;
68// TODO: (b/127403193) duration to string conversion could probably be constexpr
69template <typename Rep, typename Per>
70inline std::string toNsString(std::chrono::duration<Rep, Per> t) {
71 return std::to_string(std::chrono::duration_cast<std::chrono::nanoseconds>(t).count());
Dan Stozaec460082018-12-17 15:35:09 -080072}
73
Kevin DuBois413287f2019-02-25 08:46:47 -080074RegionSamplingThread::EnvironmentTimingTunables::EnvironmentTimingTunables() {
75 char value[PROPERTY_VALUE_MAX] = {};
76
Ady Abraham9c53ee72020-07-22 21:16:18 -070077 property_get("debug.sf.region_sampling_duration_ns", value,
78 toNsString(defaultRegionSamplingWorkDuration).c_str());
79 int const samplingDurationNsRaw = atoi(value);
Kevin DuBois413287f2019-02-25 08:46:47 -080080
81 property_get("debug.sf.region_sampling_period_ns", value,
82 toNsString(defaultRegionSamplingPeriod).c_str());
83 int const samplingPeriodNsRaw = atoi(value);
84
85 property_get("debug.sf.region_sampling_timer_timeout_ns", value,
86 toNsString(defaultRegionSamplingTimerTimeout).c_str());
87 int const samplingTimerTimeoutNsRaw = atoi(value);
88
89 if ((samplingPeriodNsRaw < 0) || (samplingTimerTimeoutNsRaw < 0)) {
90 ALOGW("User-specified sampling tuning options nonsensical. Using defaults");
Ady Abraham9c53ee72020-07-22 21:16:18 -070091 mSamplingDuration = defaultRegionSamplingWorkDuration;
Kevin DuBois413287f2019-02-25 08:46:47 -080092 mSamplingPeriod = defaultRegionSamplingPeriod;
93 mSamplingTimerTimeout = defaultRegionSamplingTimerTimeout;
94 } else {
Ady Abraham9c53ee72020-07-22 21:16:18 -070095 mSamplingDuration = std::chrono::nanoseconds(samplingDurationNsRaw);
Kevin DuBois413287f2019-02-25 08:46:47 -080096 mSamplingPeriod = std::chrono::nanoseconds(samplingPeriodNsRaw);
97 mSamplingTimerTimeout = std::chrono::nanoseconds(samplingTimerTimeoutNsRaw);
98 }
99}
100
Ady Abraham9c53ee72020-07-22 21:16:18 -0700101struct SamplingOffsetCallback : VSyncSource::Callback {
Kevin DuBois413287f2019-02-25 08:46:47 -0800102 SamplingOffsetCallback(RegionSamplingThread& samplingThread, Scheduler& scheduler,
Ady Abraham9c53ee72020-07-22 21:16:18 -0700103 std::chrono::nanoseconds targetSamplingWorkDuration)
Kevin DuBois413287f2019-02-25 08:46:47 -0800104 : mRegionSamplingThread(samplingThread),
Ady Abraham9c53ee72020-07-22 21:16:18 -0700105 mTargetSamplingWorkDuration(targetSamplingWorkDuration),
106 mVSyncSource(scheduler.makePrimaryDispSyncSource("SamplingThreadDispSyncListener", 0ns,
107 0ns,
108 /*traceVsync=*/false)) {
109 mVSyncSource->setCallback(this);
110 }
Kevin DuBois413287f2019-02-25 08:46:47 -0800111
112 ~SamplingOffsetCallback() { stopVsyncListener(); }
113
114 SamplingOffsetCallback(const SamplingOffsetCallback&) = delete;
115 SamplingOffsetCallback& operator=(const SamplingOffsetCallback&) = delete;
116
117 void startVsyncListener() {
118 std::lock_guard lock(mMutex);
119 if (mVsyncListening) return;
120
121 mPhaseIntervalSetting = Phase::ZERO;
Ady Abraham9c53ee72020-07-22 21:16:18 -0700122 mVSyncSource->setVSyncEnabled(true);
Kevin DuBois413287f2019-02-25 08:46:47 -0800123 mVsyncListening = true;
124 }
125
126 void stopVsyncListener() {
127 std::lock_guard lock(mMutex);
128 stopVsyncListenerLocked();
129 }
130
131private:
132 void stopVsyncListenerLocked() /*REQUIRES(mMutex)*/ {
133 if (!mVsyncListening) return;
134
Ady Abraham9c53ee72020-07-22 21:16:18 -0700135 mVSyncSource->setVSyncEnabled(false);
Kevin DuBois413287f2019-02-25 08:46:47 -0800136 mVsyncListening = false;
137 }
138
Ady Abraham9c53ee72020-07-22 21:16:18 -0700139 void onVSyncEvent(nsecs_t /*when*/, nsecs_t /*expectedVSyncTimestamp*/,
140 nsecs_t /*deadlineTimestamp*/) final {
Kevin DuBois413287f2019-02-25 08:46:47 -0800141 std::unique_lock<decltype(mMutex)> lock(mMutex);
142
143 if (mPhaseIntervalSetting == Phase::ZERO) {
144 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::waitForSamplePhase));
145 mPhaseIntervalSetting = Phase::SAMPLING;
Ady Abraham9c53ee72020-07-22 21:16:18 -0700146 mVSyncSource->setDuration(mTargetSamplingWorkDuration, 0ns);
Kevin DuBois413287f2019-02-25 08:46:47 -0800147 return;
148 }
149
150 if (mPhaseIntervalSetting == Phase::SAMPLING) {
151 mPhaseIntervalSetting = Phase::ZERO;
Ady Abraham9c53ee72020-07-22 21:16:18 -0700152 mVSyncSource->setDuration(0ns, 0ns);
Kevin DuBois413287f2019-02-25 08:46:47 -0800153 stopVsyncListenerLocked();
154 lock.unlock();
155 mRegionSamplingThread.notifySamplingOffset();
156 return;
157 }
158 }
159
160 RegionSamplingThread& mRegionSamplingThread;
Ady Abraham9c53ee72020-07-22 21:16:18 -0700161 const std::chrono::nanoseconds mTargetSamplingWorkDuration;
Kevin DuBois413287f2019-02-25 08:46:47 -0800162 mutable std::mutex mMutex;
163 enum class Phase {
164 ZERO,
165 SAMPLING
166 } mPhaseIntervalSetting /*GUARDED_BY(mMutex) macro doesnt work with unique_lock?*/
167 = Phase::ZERO;
168 bool mVsyncListening /*GUARDED_BY(mMutex)*/ = false;
Ady Abraham9c53ee72020-07-22 21:16:18 -0700169 std::unique_ptr<VSyncSource> mVSyncSource;
Kevin DuBois413287f2019-02-25 08:46:47 -0800170};
171
172RegionSamplingThread::RegionSamplingThread(SurfaceFlinger& flinger, Scheduler& scheduler,
173 const TimingTunables& tunables)
174 : mFlinger(flinger),
175 mScheduler(scheduler),
176 mTunables(tunables),
Ady Abraham9c53ee72020-07-22 21:16:18 -0700177 mIdleTimer(
Ady Abrahamdb3dfee2020-11-17 17:07:12 -0800178 "RegionSamplingIdleTimer",
Ady Abraham9c53ee72020-07-22 21:16:18 -0700179 std::chrono::duration_cast<std::chrono::milliseconds>(
180 mTunables.mSamplingTimerTimeout),
181 [] {}, [this] { checkForStaleLuma(); }),
Kevin DuBois413287f2019-02-25 08:46:47 -0800182 mPhaseCallback(std::make_unique<SamplingOffsetCallback>(*this, mScheduler,
Ady Abraham9c53ee72020-07-22 21:16:18 -0700183 tunables.mSamplingDuration)),
Kevin DuBois413287f2019-02-25 08:46:47 -0800184 lastSampleTime(0ns) {
Kevin DuBois26afc782019-05-06 16:46:45 -0700185 mThread = std::thread([this]() { threadMain(); });
186 pthread_setname_np(mThread.native_handle(), "RegionSamplingThread");
Kevin DuBois413287f2019-02-25 08:46:47 -0800187 mIdleTimer.start();
188}
189
190RegionSamplingThread::RegionSamplingThread(SurfaceFlinger& flinger, Scheduler& scheduler)
191 : RegionSamplingThread(flinger, scheduler,
Ady Abraham9c53ee72020-07-22 21:16:18 -0700192 TimingTunables{defaultRegionSamplingWorkDuration,
Kevin DuBois413287f2019-02-25 08:46:47 -0800193 defaultRegionSamplingPeriod,
194 defaultRegionSamplingTimerTimeout}) {}
195
Dan Stozaec460082018-12-17 15:35:09 -0800196RegionSamplingThread::~RegionSamplingThread() {
Kevin DuBois413287f2019-02-25 08:46:47 -0800197 mIdleTimer.stop();
198
Dan Stozaec460082018-12-17 15:35:09 -0800199 {
Kevin DuBois26afc782019-05-06 16:46:45 -0700200 std::lock_guard lock(mThreadControlMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800201 mRunning = false;
202 mCondition.notify_one();
203 }
204
Dan Stozaec460082018-12-17 15:35:09 -0800205 if (mThread.joinable()) {
206 mThread.join();
207 }
208}
209
Alec Mouri9a02eda2020-04-21 17:39:34 -0700210void RegionSamplingThread::addListener(const Rect& samplingArea, const wp<Layer>& stopLayer,
Dan Stozaec460082018-12-17 15:35:09 -0800211 const sp<IRegionSamplingListener>& listener) {
Dan Stozaec460082018-12-17 15:35:09 -0800212 sp<IBinder> asBinder = IInterface::asBinder(listener);
213 asBinder->linkToDeath(this);
Kevin DuBois26afc782019-05-06 16:46:45 -0700214 std::lock_guard lock(mSamplingMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800215 mDescriptors.emplace(wp<IBinder>(asBinder), Descriptor{samplingArea, stopLayer, listener});
216}
217
218void RegionSamplingThread::removeListener(const sp<IRegionSamplingListener>& listener) {
Kevin DuBois26afc782019-05-06 16:46:45 -0700219 std::lock_guard lock(mSamplingMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800220 mDescriptors.erase(wp<IBinder>(IInterface::asBinder(listener)));
221}
222
Kevin DuBois413287f2019-02-25 08:46:47 -0800223void RegionSamplingThread::checkForStaleLuma() {
Kevin DuBois26afc782019-05-06 16:46:45 -0700224 std::lock_guard lock(mThreadControlMutex);
Kevin DuBois413287f2019-02-25 08:46:47 -0800225
John Dias84be7832019-06-18 17:05:26 -0700226 if (mDiscardedFrames > 0) {
Kevin DuBois413287f2019-02-25 08:46:47 -0800227 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::waitForZeroPhase));
John Dias84be7832019-06-18 17:05:26 -0700228 mDiscardedFrames = 0;
Kevin DuBois413287f2019-02-25 08:46:47 -0800229 mPhaseCallback->startVsyncListener();
230 }
231}
232
233void RegionSamplingThread::notifyNewContent() {
234 doSample();
235}
236
237void RegionSamplingThread::notifySamplingOffset() {
238 doSample();
239}
240
241void RegionSamplingThread::doSample() {
Kevin DuBois26afc782019-05-06 16:46:45 -0700242 std::lock_guard lock(mThreadControlMutex);
Kevin DuBois413287f2019-02-25 08:46:47 -0800243 auto now = std::chrono::nanoseconds(systemTime(SYSTEM_TIME_MONOTONIC));
244 if (lastSampleTime + mTunables.mSamplingPeriod > now) {
245 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::idleTimerWaiting));
John Dias84be7832019-06-18 17:05:26 -0700246 if (mDiscardedFrames == 0) mDiscardedFrames++;
Kevin DuBois413287f2019-02-25 08:46:47 -0800247 return;
248 }
John Dias84be7832019-06-18 17:05:26 -0700249 if (mDiscardedFrames < maxRegionSamplingSkips) {
250 // If there is relatively little time left for surfaceflinger
251 // until the next vsync deadline, defer this sampling work
252 // to a later frame, when hopefully there will be more time.
253 DisplayStatInfo stats;
Ady Abraham8cb21882020-08-26 18:22:05 -0700254 mScheduler.getDisplayStatInfo(&stats, systemTime());
John Dias84be7832019-06-18 17:05:26 -0700255 if (std::chrono::nanoseconds(stats.vsyncTime) - now < timeForRegionSampling) {
256 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::waitForQuietFrame));
257 mDiscardedFrames++;
258 return;
259 }
260 }
Kevin DuBois413287f2019-02-25 08:46:47 -0800261
262 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::sample));
263
John Dias84be7832019-06-18 17:05:26 -0700264 mDiscardedFrames = 0;
Kevin DuBois413287f2019-02-25 08:46:47 -0800265 lastSampleTime = now;
266
267 mIdleTimer.reset();
268 mPhaseCallback->stopVsyncListener();
269
Dan Stozaec460082018-12-17 15:35:09 -0800270 mSampleRequested = true;
271 mCondition.notify_one();
272}
273
274void RegionSamplingThread::binderDied(const wp<IBinder>& who) {
Kevin DuBois26afc782019-05-06 16:46:45 -0700275 std::lock_guard lock(mSamplingMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800276 mDescriptors.erase(who);
277}
278
Kevin DuBoisb325c932019-05-21 08:34:09 -0700279float sampleArea(const uint32_t* data, int32_t width, int32_t height, int32_t stride,
280 uint32_t orientation, const Rect& sample_area) {
281 if (!sample_area.isValid() || (sample_area.getWidth() > width) ||
282 (sample_area.getHeight() > height)) {
283 ALOGE("invalid sampling region requested");
284 return 0.0f;
285 }
286
287 // (b/133849373) ROT_90 screencap images produced upside down
288 auto area = sample_area;
289 if (orientation & ui::Transform::ROT_90) {
290 area.top = height - area.top;
291 area.bottom = height - area.bottom;
292 std::swap(area.top, area.bottom);
Kevin DuBois69162d02019-06-04 20:22:43 -0700293
294 area.left = width - area.left;
295 area.right = width - area.right;
296 std::swap(area.left, area.right);
Kevin DuBoisb325c932019-05-21 08:34:09 -0700297 }
298
Collin Fijalkovicha95e1702019-10-28 14:46:13 -0700299 const uint32_t pixelCount = (area.bottom - area.top) * (area.right - area.left);
300 uint32_t accumulatedLuma = 0;
Dan Stozaec460082018-12-17 15:35:09 -0800301
Collin Fijalkovicha95e1702019-10-28 14:46:13 -0700302 // Calculates luma with approximation of Rec. 709 primaries
Dan Stozaec460082018-12-17 15:35:09 -0800303 for (int32_t row = area.top; row < area.bottom; ++row) {
304 const uint32_t* rowBase = data + row * stride;
305 for (int32_t column = area.left; column < area.right; ++column) {
306 uint32_t pixel = rowBase[column];
Collin Fijalkovicha95e1702019-10-28 14:46:13 -0700307 const uint32_t r = pixel & 0xFF;
308 const uint32_t g = (pixel >> 8) & 0xFF;
309 const uint32_t b = (pixel >> 16) & 0xFF;
310 const uint32_t luma = (r * 7 + b * 2 + g * 23) >> 5;
311 accumulatedLuma += luma;
Dan Stozaec460082018-12-17 15:35:09 -0800312 }
313 }
314
Collin Fijalkovicha95e1702019-10-28 14:46:13 -0700315 return accumulatedLuma / (255.0f * pixelCount);
Dan Stozaec460082018-12-17 15:35:09 -0800316}
Dan Stozaec460082018-12-17 15:35:09 -0800317
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800318std::vector<float> RegionSamplingThread::sampleBuffer(
319 const sp<GraphicBuffer>& buffer, const Point& leftTop,
Kevin DuBoisb325c932019-05-21 08:34:09 -0700320 const std::vector<RegionSamplingThread::Descriptor>& descriptors, uint32_t orientation) {
Dan Stozaec460082018-12-17 15:35:09 -0800321 void* data_raw = nullptr;
322 buffer->lock(GRALLOC_USAGE_SW_READ_OFTEN, &data_raw);
323 std::shared_ptr<uint32_t> data(reinterpret_cast<uint32_t*>(data_raw),
324 [&buffer](auto) { buffer->unlock(); });
325 if (!data) return {};
326
Kevin DuBoisb325c932019-05-21 08:34:09 -0700327 const int32_t width = buffer->getWidth();
328 const int32_t height = buffer->getHeight();
Dan Stozaec460082018-12-17 15:35:09 -0800329 const int32_t stride = buffer->getStride();
330 std::vector<float> lumas(descriptors.size());
331 std::transform(descriptors.begin(), descriptors.end(), lumas.begin(),
332 [&](auto const& descriptor) {
Kevin DuBoisb325c932019-05-21 08:34:09 -0700333 return sampleArea(data.get(), width, height, stride, orientation,
334 descriptor.area - leftTop);
Dan Stozaec460082018-12-17 15:35:09 -0800335 });
336 return lumas;
337}
338
339void RegionSamplingThread::captureSample() {
340 ATRACE_CALL();
Kevin DuBois26afc782019-05-06 16:46:45 -0700341 std::lock_guard lock(mSamplingMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800342
343 if (mDescriptors.empty()) {
344 return;
345 }
346
Marin Shalamanov1c434292020-06-12 01:47:29 +0200347 wp<const DisplayDevice> displayWeak;
348
349 ui::LayerStack layerStack;
350 ui::Transform::RotationFlags orientation;
351 ui::Size displaySize;
352
353 {
354 // TODO(b/159112860): Don't keep sp<DisplayDevice> outside of SF main thread
355 const sp<const DisplayDevice> display = mFlinger.getDefaultDisplayDevice();
356 displayWeak = display;
357 layerStack = display->getLayerStack();
358 orientation = ui::Transform::toRotationFlags(display->getOrientation());
359 displaySize = display->getSize();
360 }
Kevin DuBoisb325c932019-05-21 08:34:09 -0700361
Dan Stozaec460082018-12-17 15:35:09 -0800362 std::vector<RegionSamplingThread::Descriptor> descriptors;
363 Region sampleRegion;
364 for (const auto& [listener, descriptor] : mDescriptors) {
365 sampleRegion.orSelf(descriptor.area);
366 descriptors.emplace_back(descriptor);
367 }
368
Kevin DuBoisb325c932019-05-21 08:34:09 -0700369 auto dx = 0;
370 auto dy = 0;
371 switch (orientation) {
372 case ui::Transform::ROT_90:
Marin Shalamanov1c434292020-06-12 01:47:29 +0200373 dx = displaySize.getWidth();
Kevin DuBoisb325c932019-05-21 08:34:09 -0700374 break;
375 case ui::Transform::ROT_180:
Marin Shalamanov1c434292020-06-12 01:47:29 +0200376 dx = displaySize.getWidth();
377 dy = displaySize.getHeight();
Kevin DuBoisb325c932019-05-21 08:34:09 -0700378 break;
379 case ui::Transform::ROT_270:
Marin Shalamanov1c434292020-06-12 01:47:29 +0200380 dy = displaySize.getHeight();
Kevin DuBoisb325c932019-05-21 08:34:09 -0700381 break;
382 default:
383 break;
384 }
385
386 ui::Transform t(orientation);
387 auto screencapRegion = t.transform(sampleRegion);
388 screencapRegion = screencapRegion.translate(dx, dy);
Marin Shalamanov1c434292020-06-12 01:47:29 +0200389
390 const Rect sampledBounds = sampleRegion.bounds();
391
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -0800392 SurfaceFlinger::RenderAreaFuture renderAreaFuture = ftl::defer([=] {
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200393 return DisplayRenderArea::create(displayWeak, screencapRegion.bounds(),
394 sampledBounds.getSize(), ui::Dataspace::V0_SRGB,
395 orientation);
Marin Shalamanov1c434292020-06-12 01:47:29 +0200396 });
Dan Stozaec460082018-12-17 15:35:09 -0800397
398 std::unordered_set<sp<IRegionSamplingListener>, SpHash<IRegionSamplingListener>> listeners;
399
400 auto traverseLayers = [&](const LayerVector::Visitor& visitor) {
401 bool stopLayerFound = false;
402 auto filterVisitor = [&](Layer* layer) {
403 // We don't want to capture any layers beyond the stop layer
404 if (stopLayerFound) return;
405
406 // Likewise if we just found a stop layer, set the flag and abort
407 for (const auto& [area, stopLayer, listener] : descriptors) {
408 if (layer == stopLayer.promote().get()) {
409 stopLayerFound = true;
410 return;
411 }
412 }
413
414 // Compute the layer's position on the screen
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800415 const Rect bounds = Rect(layer->getBounds());
416 const ui::Transform transform = layer->getTransform();
Dan Stozaec460082018-12-17 15:35:09 -0800417 constexpr bool roundOutwards = true;
418 Rect transformed = transform.transform(bounds, roundOutwards);
419
Marin Shalamanov1c434292020-06-12 01:47:29 +0200420 // If this layer doesn't intersect with the larger sampledBounds, skip capturing it
Dan Stozaec460082018-12-17 15:35:09 -0800421 Rect ignore;
Marin Shalamanov1c434292020-06-12 01:47:29 +0200422 if (!transformed.intersect(sampledBounds, &ignore)) return;
Dan Stozaec460082018-12-17 15:35:09 -0800423
424 // If the layer doesn't intersect a sampling area, skip capturing it
425 bool intersectsAnyArea = false;
426 for (const auto& [area, stopLayer, listener] : descriptors) {
427 if (transformed.intersect(area, &ignore)) {
428 intersectsAnyArea = true;
429 listeners.insert(listener);
430 }
431 }
432 if (!intersectsAnyArea) return;
433
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700434 ALOGV("Traversing [%s] [%d, %d, %d, %d]", layer->getDebugName(), bounds.left,
Dan Stozaec460082018-12-17 15:35:09 -0800435 bounds.top, bounds.right, bounds.bottom);
436 visitor(layer);
437 };
chaviw4b9d5e12020-08-04 18:30:35 -0700438 mFlinger.traverseLayersInLayerStack(layerStack, CaptureArgs::UNSET_UID, filterVisitor);
Dan Stozaec460082018-12-17 15:35:09 -0800439 };
440
Kevin DuBois4efd1f52019-04-29 10:09:43 -0700441 sp<GraphicBuffer> buffer = nullptr;
Marin Shalamanov1c434292020-06-12 01:47:29 +0200442 if (mCachedBuffer && mCachedBuffer->getWidth() == sampledBounds.getWidth() &&
443 mCachedBuffer->getHeight() == sampledBounds.getHeight()) {
Kevin DuBois4efd1f52019-04-29 10:09:43 -0700444 buffer = mCachedBuffer;
445 } else {
John Reck67b1e2b2020-08-26 13:17:24 -0700446 const uint32_t usage =
447 GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Marin Shalamanov1c434292020-06-12 01:47:29 +0200448 buffer = new GraphicBuffer(sampledBounds.getWidth(), sampledBounds.getHeight(),
Kevin DuBois4efd1f52019-04-29 10:09:43 -0700449 PIXEL_FORMAT_RGBA_8888, 1, usage, "RegionSamplingThread");
450 }
Dan Stozaec460082018-12-17 15:35:09 -0800451
chaviw03900772020-08-18 12:34:51 -0700452 const sp<SyncScreenCaptureListener> captureListener = new SyncScreenCaptureListener();
Marin Shalamanov1c434292020-06-12 01:47:29 +0200453 mFlinger.captureScreenCommon(std::move(renderAreaFuture), traverseLayers, buffer,
chaviw03900772020-08-18 12:34:51 -0700454 true /* regionSampling */, captureListener);
455 ScreenCaptureResults captureResults = captureListener->waitForResults();
Dan Stozaec460082018-12-17 15:35:09 -0800456
457 std::vector<Descriptor> activeDescriptors;
458 for (const auto& descriptor : descriptors) {
459 if (listeners.count(descriptor.listener) != 0) {
460 activeDescriptors.emplace_back(descriptor);
461 }
462 }
463
464 ALOGV("Sampling %zu descriptors", activeDescriptors.size());
Kevin DuBoisb325c932019-05-21 08:34:09 -0700465 std::vector<float> lumas =
Marin Shalamanov1c434292020-06-12 01:47:29 +0200466 sampleBuffer(buffer, sampledBounds.leftTop(), activeDescriptors, orientation);
Dan Stozaec460082018-12-17 15:35:09 -0800467 if (lumas.size() != activeDescriptors.size()) {
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800468 ALOGW("collected %zu median luma values for %zu descriptors", lumas.size(),
469 activeDescriptors.size());
Dan Stozaec460082018-12-17 15:35:09 -0800470 return;
471 }
472
473 for (size_t d = 0; d < activeDescriptors.size(); ++d) {
474 activeDescriptors[d].listener->onSampleCollected(lumas[d]);
475 }
Kevin DuBois4efd1f52019-04-29 10:09:43 -0700476
477 // Extend the lifetime of mCachedBuffer from the previous frame to here to ensure that:
478 // 1) The region sampling thread is the last owner of the buffer, and the freeing of the buffer
479 // happens in this thread, as opposed to the main thread.
480 // 2) The listener(s) receive their notifications prior to freeing the buffer.
481 mCachedBuffer = buffer;
Kevin DuBois413287f2019-02-25 08:46:47 -0800482 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::noWorkNeeded));
Dan Stozaec460082018-12-17 15:35:09 -0800483}
484
Kevin DuBois26afc782019-05-06 16:46:45 -0700485// NO_THREAD_SAFETY_ANALYSIS is because std::unique_lock presently lacks thread safety annotations.
486void RegionSamplingThread::threadMain() NO_THREAD_SAFETY_ANALYSIS {
487 std::unique_lock<std::mutex> lock(mThreadControlMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800488 while (mRunning) {
489 if (mSampleRequested) {
490 mSampleRequested = false;
Kevin DuBois26afc782019-05-06 16:46:45 -0700491 lock.unlock();
Dan Stozaec460082018-12-17 15:35:09 -0800492 captureSample();
Kevin DuBois26afc782019-05-06 16:46:45 -0700493 lock.lock();
Dan Stozaec460082018-12-17 15:35:09 -0800494 }
Kevin DuBois26afc782019-05-06 16:46:45 -0700495 mCondition.wait(lock, [this]() REQUIRES(mThreadControlMutex) {
496 return mSampleRequested || !mRunning;
497 });
Dan Stozaec460082018-12-17 15:35:09 -0800498 }
499}
500
501} // namespace android
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800502
503// TODO(b/129481165): remove the #pragma below and fix conversion issues
504#pragma clang diagnostic pop // ignored "-Wconversion"