blob: 4dc20c44b87588200d8f899a8e0b0602929ed7e6 [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>
chaviwe7b9f272020-08-18 16:08:59 -070032#include <gui/SyncScreenCaptureListener.h>
Dominik Laskowski98041832019-08-01 18:35:59 -070033#include <ui/DisplayStatInfo.h>
34#include <utils/Trace.h>
35
36#include <string>
37
Dan Stozaec460082018-12-17 15:35:09 -080038#include "DisplayDevice.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +020039#include "DisplayRenderArea.h"
Dan Stozaec460082018-12-17 15:35:09 -080040#include "Layer.h"
Marin Shalamanov1c434292020-06-12 01:47:29 +020041#include "Promise.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(
178 std::chrono::duration_cast<std::chrono::milliseconds>(
179 mTunables.mSamplingTimerTimeout),
180 [] {}, [this] { checkForStaleLuma(); }),
Kevin DuBois413287f2019-02-25 08:46:47 -0800181 mPhaseCallback(std::make_unique<SamplingOffsetCallback>(*this, mScheduler,
Ady Abraham9c53ee72020-07-22 21:16:18 -0700182 tunables.mSamplingDuration)),
Kevin DuBois413287f2019-02-25 08:46:47 -0800183 lastSampleTime(0ns) {
Kevin DuBois26afc782019-05-06 16:46:45 -0700184 mThread = std::thread([this]() { threadMain(); });
185 pthread_setname_np(mThread.native_handle(), "RegionSamplingThread");
Kevin DuBois413287f2019-02-25 08:46:47 -0800186 mIdleTimer.start();
187}
188
189RegionSamplingThread::RegionSamplingThread(SurfaceFlinger& flinger, Scheduler& scheduler)
190 : RegionSamplingThread(flinger, scheduler,
Ady Abraham9c53ee72020-07-22 21:16:18 -0700191 TimingTunables{defaultRegionSamplingWorkDuration,
Kevin DuBois413287f2019-02-25 08:46:47 -0800192 defaultRegionSamplingPeriod,
193 defaultRegionSamplingTimerTimeout}) {}
194
Dan Stozaec460082018-12-17 15:35:09 -0800195RegionSamplingThread::~RegionSamplingThread() {
Kevin DuBois413287f2019-02-25 08:46:47 -0800196 mIdleTimer.stop();
197
Dan Stozaec460082018-12-17 15:35:09 -0800198 {
Kevin DuBois26afc782019-05-06 16:46:45 -0700199 std::lock_guard lock(mThreadControlMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800200 mRunning = false;
201 mCondition.notify_one();
202 }
203
Dan Stozaec460082018-12-17 15:35:09 -0800204 if (mThread.joinable()) {
205 mThread.join();
206 }
207}
208
Alec Mouri9a02eda2020-04-21 17:39:34 -0700209void RegionSamplingThread::addListener(const Rect& samplingArea, const wp<Layer>& stopLayer,
Dan Stozaec460082018-12-17 15:35:09 -0800210 const sp<IRegionSamplingListener>& listener) {
Dan Stozaec460082018-12-17 15:35:09 -0800211 sp<IBinder> asBinder = IInterface::asBinder(listener);
212 asBinder->linkToDeath(this);
Kevin DuBois26afc782019-05-06 16:46:45 -0700213 std::lock_guard lock(mSamplingMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800214 mDescriptors.emplace(wp<IBinder>(asBinder), Descriptor{samplingArea, stopLayer, listener});
215}
216
217void RegionSamplingThread::removeListener(const sp<IRegionSamplingListener>& listener) {
Kevin DuBois26afc782019-05-06 16:46:45 -0700218 std::lock_guard lock(mSamplingMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800219 mDescriptors.erase(wp<IBinder>(IInterface::asBinder(listener)));
220}
221
Kevin DuBois413287f2019-02-25 08:46:47 -0800222void RegionSamplingThread::checkForStaleLuma() {
Kevin DuBois26afc782019-05-06 16:46:45 -0700223 std::lock_guard lock(mThreadControlMutex);
Kevin DuBois413287f2019-02-25 08:46:47 -0800224
John Dias84be7832019-06-18 17:05:26 -0700225 if (mDiscardedFrames > 0) {
Kevin DuBois413287f2019-02-25 08:46:47 -0800226 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::waitForZeroPhase));
John Dias84be7832019-06-18 17:05:26 -0700227 mDiscardedFrames = 0;
Kevin DuBois413287f2019-02-25 08:46:47 -0800228 mPhaseCallback->startVsyncListener();
229 }
230}
231
232void RegionSamplingThread::notifyNewContent() {
233 doSample();
234}
235
236void RegionSamplingThread::notifySamplingOffset() {
237 doSample();
238}
239
240void RegionSamplingThread::doSample() {
Kevin DuBois26afc782019-05-06 16:46:45 -0700241 std::lock_guard lock(mThreadControlMutex);
Kevin DuBois413287f2019-02-25 08:46:47 -0800242 auto now = std::chrono::nanoseconds(systemTime(SYSTEM_TIME_MONOTONIC));
243 if (lastSampleTime + mTunables.mSamplingPeriod > now) {
244 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::idleTimerWaiting));
John Dias84be7832019-06-18 17:05:26 -0700245 if (mDiscardedFrames == 0) mDiscardedFrames++;
Kevin DuBois413287f2019-02-25 08:46:47 -0800246 return;
247 }
John Dias84be7832019-06-18 17:05:26 -0700248 if (mDiscardedFrames < maxRegionSamplingSkips) {
249 // If there is relatively little time left for surfaceflinger
250 // until the next vsync deadline, defer this sampling work
251 // to a later frame, when hopefully there will be more time.
252 DisplayStatInfo stats;
Ady Abraham8cb21882020-08-26 18:22:05 -0700253 mScheduler.getDisplayStatInfo(&stats, systemTime());
John Dias84be7832019-06-18 17:05:26 -0700254 if (std::chrono::nanoseconds(stats.vsyncTime) - now < timeForRegionSampling) {
255 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::waitForQuietFrame));
256 mDiscardedFrames++;
257 return;
258 }
259 }
Kevin DuBois413287f2019-02-25 08:46:47 -0800260
261 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::sample));
262
John Dias84be7832019-06-18 17:05:26 -0700263 mDiscardedFrames = 0;
Kevin DuBois413287f2019-02-25 08:46:47 -0800264 lastSampleTime = now;
265
266 mIdleTimer.reset();
267 mPhaseCallback->stopVsyncListener();
268
Dan Stozaec460082018-12-17 15:35:09 -0800269 mSampleRequested = true;
270 mCondition.notify_one();
271}
272
273void RegionSamplingThread::binderDied(const wp<IBinder>& who) {
Kevin DuBois26afc782019-05-06 16:46:45 -0700274 std::lock_guard lock(mSamplingMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800275 mDescriptors.erase(who);
276}
277
Kevin DuBoisb325c932019-05-21 08:34:09 -0700278float sampleArea(const uint32_t* data, int32_t width, int32_t height, int32_t stride,
279 uint32_t orientation, const Rect& sample_area) {
280 if (!sample_area.isValid() || (sample_area.getWidth() > width) ||
281 (sample_area.getHeight() > height)) {
282 ALOGE("invalid sampling region requested");
283 return 0.0f;
284 }
285
286 // (b/133849373) ROT_90 screencap images produced upside down
287 auto area = sample_area;
288 if (orientation & ui::Transform::ROT_90) {
289 area.top = height - area.top;
290 area.bottom = height - area.bottom;
291 std::swap(area.top, area.bottom);
Kevin DuBois69162d02019-06-04 20:22:43 -0700292
293 area.left = width - area.left;
294 area.right = width - area.right;
295 std::swap(area.left, area.right);
Kevin DuBoisb325c932019-05-21 08:34:09 -0700296 }
297
Collin Fijalkovicha95e1702019-10-28 14:46:13 -0700298 const uint32_t pixelCount = (area.bottom - area.top) * (area.right - area.left);
299 uint32_t accumulatedLuma = 0;
Dan Stozaec460082018-12-17 15:35:09 -0800300
Collin Fijalkovicha95e1702019-10-28 14:46:13 -0700301 // Calculates luma with approximation of Rec. 709 primaries
Dan Stozaec460082018-12-17 15:35:09 -0800302 for (int32_t row = area.top; row < area.bottom; ++row) {
303 const uint32_t* rowBase = data + row * stride;
304 for (int32_t column = area.left; column < area.right; ++column) {
305 uint32_t pixel = rowBase[column];
Collin Fijalkovicha95e1702019-10-28 14:46:13 -0700306 const uint32_t r = pixel & 0xFF;
307 const uint32_t g = (pixel >> 8) & 0xFF;
308 const uint32_t b = (pixel >> 16) & 0xFF;
309 const uint32_t luma = (r * 7 + b * 2 + g * 23) >> 5;
310 accumulatedLuma += luma;
Dan Stozaec460082018-12-17 15:35:09 -0800311 }
312 }
313
Collin Fijalkovicha95e1702019-10-28 14:46:13 -0700314 return accumulatedLuma / (255.0f * pixelCount);
Dan Stozaec460082018-12-17 15:35:09 -0800315}
Dan Stozaec460082018-12-17 15:35:09 -0800316
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800317std::vector<float> RegionSamplingThread::sampleBuffer(
318 const sp<GraphicBuffer>& buffer, const Point& leftTop,
Kevin DuBoisb325c932019-05-21 08:34:09 -0700319 const std::vector<RegionSamplingThread::Descriptor>& descriptors, uint32_t orientation) {
Dan Stozaec460082018-12-17 15:35:09 -0800320 void* data_raw = nullptr;
321 buffer->lock(GRALLOC_USAGE_SW_READ_OFTEN, &data_raw);
322 std::shared_ptr<uint32_t> data(reinterpret_cast<uint32_t*>(data_raw),
323 [&buffer](auto) { buffer->unlock(); });
324 if (!data) return {};
325
Kevin DuBoisb325c932019-05-21 08:34:09 -0700326 const int32_t width = buffer->getWidth();
327 const int32_t height = buffer->getHeight();
Dan Stozaec460082018-12-17 15:35:09 -0800328 const int32_t stride = buffer->getStride();
329 std::vector<float> lumas(descriptors.size());
330 std::transform(descriptors.begin(), descriptors.end(), lumas.begin(),
331 [&](auto const& descriptor) {
Kevin DuBoisb325c932019-05-21 08:34:09 -0700332 return sampleArea(data.get(), width, height, stride, orientation,
333 descriptor.area - leftTop);
Dan Stozaec460082018-12-17 15:35:09 -0800334 });
335 return lumas;
336}
337
338void RegionSamplingThread::captureSample() {
339 ATRACE_CALL();
Kevin DuBois26afc782019-05-06 16:46:45 -0700340 std::lock_guard lock(mSamplingMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800341
342 if (mDescriptors.empty()) {
343 return;
344 }
345
Marin Shalamanov1c434292020-06-12 01:47:29 +0200346 wp<const DisplayDevice> displayWeak;
347
348 ui::LayerStack layerStack;
349 ui::Transform::RotationFlags orientation;
350 ui::Size displaySize;
351
352 {
353 // TODO(b/159112860): Don't keep sp<DisplayDevice> outside of SF main thread
354 const sp<const DisplayDevice> display = mFlinger.getDefaultDisplayDevice();
355 displayWeak = display;
356 layerStack = display->getLayerStack();
357 orientation = ui::Transform::toRotationFlags(display->getOrientation());
358 displaySize = display->getSize();
359 }
Kevin DuBoisb325c932019-05-21 08:34:09 -0700360
Dan Stozaec460082018-12-17 15:35:09 -0800361 std::vector<RegionSamplingThread::Descriptor> descriptors;
362 Region sampleRegion;
363 for (const auto& [listener, descriptor] : mDescriptors) {
364 sampleRegion.orSelf(descriptor.area);
365 descriptors.emplace_back(descriptor);
366 }
367
Kevin DuBoisb325c932019-05-21 08:34:09 -0700368 auto dx = 0;
369 auto dy = 0;
370 switch (orientation) {
371 case ui::Transform::ROT_90:
Marin Shalamanov1c434292020-06-12 01:47:29 +0200372 dx = displaySize.getWidth();
Kevin DuBoisb325c932019-05-21 08:34:09 -0700373 break;
374 case ui::Transform::ROT_180:
Marin Shalamanov1c434292020-06-12 01:47:29 +0200375 dx = displaySize.getWidth();
376 dy = displaySize.getHeight();
Kevin DuBoisb325c932019-05-21 08:34:09 -0700377 break;
378 case ui::Transform::ROT_270:
Marin Shalamanov1c434292020-06-12 01:47:29 +0200379 dy = displaySize.getHeight();
Kevin DuBoisb325c932019-05-21 08:34:09 -0700380 break;
381 default:
382 break;
383 }
384
385 ui::Transform t(orientation);
386 auto screencapRegion = t.transform(sampleRegion);
387 screencapRegion = screencapRegion.translate(dx, dy);
Marin Shalamanov1c434292020-06-12 01:47:29 +0200388
389 const Rect sampledBounds = sampleRegion.bounds();
390
391 SurfaceFlinger::RenderAreaFuture renderAreaFuture = promise::defer([=] {
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200392 return DisplayRenderArea::create(displayWeak, screencapRegion.bounds(),
393 sampledBounds.getSize(), ui::Dataspace::V0_SRGB,
394 orientation);
Marin Shalamanov1c434292020-06-12 01:47:29 +0200395 });
Dan Stozaec460082018-12-17 15:35:09 -0800396
397 std::unordered_set<sp<IRegionSamplingListener>, SpHash<IRegionSamplingListener>> listeners;
398
399 auto traverseLayers = [&](const LayerVector::Visitor& visitor) {
400 bool stopLayerFound = false;
401 auto filterVisitor = [&](Layer* layer) {
402 // We don't want to capture any layers beyond the stop layer
403 if (stopLayerFound) return;
404
405 // Likewise if we just found a stop layer, set the flag and abort
406 for (const auto& [area, stopLayer, listener] : descriptors) {
407 if (layer == stopLayer.promote().get()) {
408 stopLayerFound = true;
409 return;
410 }
411 }
412
413 // Compute the layer's position on the screen
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800414 const Rect bounds = Rect(layer->getBounds());
415 const ui::Transform transform = layer->getTransform();
Dan Stozaec460082018-12-17 15:35:09 -0800416 constexpr bool roundOutwards = true;
417 Rect transformed = transform.transform(bounds, roundOutwards);
418
Marin Shalamanov1c434292020-06-12 01:47:29 +0200419 // If this layer doesn't intersect with the larger sampledBounds, skip capturing it
Dan Stozaec460082018-12-17 15:35:09 -0800420 Rect ignore;
Marin Shalamanov1c434292020-06-12 01:47:29 +0200421 if (!transformed.intersect(sampledBounds, &ignore)) return;
Dan Stozaec460082018-12-17 15:35:09 -0800422
423 // If the layer doesn't intersect a sampling area, skip capturing it
424 bool intersectsAnyArea = false;
425 for (const auto& [area, stopLayer, listener] : descriptors) {
426 if (transformed.intersect(area, &ignore)) {
427 intersectsAnyArea = true;
428 listeners.insert(listener);
429 }
430 }
431 if (!intersectsAnyArea) return;
432
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700433 ALOGV("Traversing [%s] [%d, %d, %d, %d]", layer->getDebugName(), bounds.left,
Dan Stozaec460082018-12-17 15:35:09 -0800434 bounds.top, bounds.right, bounds.bottom);
435 visitor(layer);
436 };
chaviw4b9d5e12020-08-04 18:30:35 -0700437 mFlinger.traverseLayersInLayerStack(layerStack, CaptureArgs::UNSET_UID, filterVisitor);
Dan Stozaec460082018-12-17 15:35:09 -0800438 };
439
Kevin DuBois4efd1f52019-04-29 10:09:43 -0700440 sp<GraphicBuffer> buffer = nullptr;
Marin Shalamanov1c434292020-06-12 01:47:29 +0200441 if (mCachedBuffer && mCachedBuffer->getWidth() == sampledBounds.getWidth() &&
442 mCachedBuffer->getHeight() == sampledBounds.getHeight()) {
Kevin DuBois4efd1f52019-04-29 10:09:43 -0700443 buffer = mCachedBuffer;
444 } else {
445 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_HW_RENDER;
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
chaviw03900772020-08-18 12:34:51 -0700450 const sp<SyncScreenCaptureListener> captureListener = new SyncScreenCaptureListener();
Marin Shalamanov1c434292020-06-12 01:47:29 +0200451 mFlinger.captureScreenCommon(std::move(renderAreaFuture), traverseLayers, buffer,
chaviw03900772020-08-18 12:34:51 -0700452 true /* regionSampling */, captureListener);
453 ScreenCaptureResults captureResults = captureListener->waitForResults();
Dan Stozaec460082018-12-17 15:35:09 -0800454
455 std::vector<Descriptor> activeDescriptors;
456 for (const auto& descriptor : descriptors) {
457 if (listeners.count(descriptor.listener) != 0) {
458 activeDescriptors.emplace_back(descriptor);
459 }
460 }
461
462 ALOGV("Sampling %zu descriptors", activeDescriptors.size());
Kevin DuBoisb325c932019-05-21 08:34:09 -0700463 std::vector<float> lumas =
Marin Shalamanov1c434292020-06-12 01:47:29 +0200464 sampleBuffer(buffer, sampledBounds.leftTop(), activeDescriptors, orientation);
Dan Stozaec460082018-12-17 15:35:09 -0800465 if (lumas.size() != activeDescriptors.size()) {
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800466 ALOGW("collected %zu median luma values for %zu descriptors", lumas.size(),
467 activeDescriptors.size());
Dan Stozaec460082018-12-17 15:35:09 -0800468 return;
469 }
470
471 for (size_t d = 0; d < activeDescriptors.size(); ++d) {
472 activeDescriptors[d].listener->onSampleCollected(lumas[d]);
473 }
Kevin DuBois4efd1f52019-04-29 10:09:43 -0700474
475 // Extend the lifetime of mCachedBuffer from the previous frame to here to ensure that:
476 // 1) The region sampling thread is the last owner of the buffer, and the freeing of the buffer
477 // happens in this thread, as opposed to the main thread.
478 // 2) The listener(s) receive their notifications prior to freeing the buffer.
479 mCachedBuffer = buffer;
Kevin DuBois413287f2019-02-25 08:46:47 -0800480 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::noWorkNeeded));
Dan Stozaec460082018-12-17 15:35:09 -0800481}
482
Kevin DuBois26afc782019-05-06 16:46:45 -0700483// NO_THREAD_SAFETY_ANALYSIS is because std::unique_lock presently lacks thread safety annotations.
484void RegionSamplingThread::threadMain() NO_THREAD_SAFETY_ANALYSIS {
485 std::unique_lock<std::mutex> lock(mThreadControlMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800486 while (mRunning) {
487 if (mSampleRequested) {
488 mSampleRequested = false;
Kevin DuBois26afc782019-05-06 16:46:45 -0700489 lock.unlock();
Dan Stozaec460082018-12-17 15:35:09 -0800490 captureSample();
Kevin DuBois26afc782019-05-06 16:46:45 -0700491 lock.lock();
Dan Stozaec460082018-12-17 15:35:09 -0800492 }
Kevin DuBois26afc782019-05-06 16:46:45 -0700493 mCondition.wait(lock, [this]() REQUIRES(mThreadControlMutex) {
494 return mSampleRequested || !mRunning;
495 });
Dan Stozaec460082018-12-17 15:35:09 -0800496 }
497}
498
499} // namespace android
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800500
501// TODO(b/129481165): remove the #pragma below and fix conversion issues
502#pragma clang diagnostic pop // ignored "-Wconversion"