blob: f450ea5f2f047cca8df8e15cdd5648146dbc346d [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"
Marin Shalamanovbed7fd32020-12-21 20:02:20 +010020#pragma clang diagnostic ignored "-Wextra"
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080021
Dan Stozaec460082018-12-17 15:35:09 -080022//#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
Kevin DuBoisb325c932019-05-21 08:34:09 -070029#include <compositionengine/Display.h>
30#include <compositionengine/impl/OutputCompositionState.h>
Dominik Laskowski98041832019-08-01 18:35:59 -070031#include <cutils/properties.h>
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -080032#include <ftl/future.h>
Dominik Laskowski98041832019-08-01 18:35:59 -070033#include <gui/IRegionSamplingListener.h>
chaviwe7b9f272020-08-18 16:08:59 -070034#include <gui/SyncScreenCaptureListener.h>
Dominik Laskowski98041832019-08-01 18:35:59 -070035#include <ui/DisplayStatInfo.h>
36#include <utils/Trace.h>
37
38#include <string>
39
Dan Stozaec460082018-12-17 15:35:09 -080040#include "DisplayDevice.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +020041#include "DisplayRenderArea.h"
Dan Stozaec460082018-12-17 15:35:09 -080042#include "Layer.h"
Ady Abraham8cb21882020-08-26 18:22:05 -070043#include "Scheduler/VsyncController.h"
Dan Stozaec460082018-12-17 15:35:09 -080044#include "SurfaceFlinger.h"
45
46namespace android {
Kevin DuBois413287f2019-02-25 08:46:47 -080047using namespace std::chrono_literals;
Dan Stozaec460082018-12-17 15:35:09 -080048
49template <typename T>
50struct SpHash {
51 size_t operator()(const sp<T>& p) const { return std::hash<T*>()(p.get()); }
52};
53
Kevin DuBois413287f2019-02-25 08:46:47 -080054constexpr auto lumaSamplingStepTag = "LumaSamplingStep";
55enum class samplingStep {
56 noWorkNeeded,
57 idleTimerWaiting,
John Dias84be7832019-06-18 17:05:26 -070058 waitForQuietFrame,
Kevin DuBois413287f2019-02-25 08:46:47 -080059 waitForZeroPhase,
60 waitForSamplePhase,
61 sample
62};
63
John Dias84be7832019-06-18 17:05:26 -070064constexpr auto timeForRegionSampling = 5000000ns;
65constexpr auto maxRegionSamplingSkips = 10;
Ady Abraham9c53ee72020-07-22 21:16:18 -070066constexpr auto defaultRegionSamplingWorkDuration = 3ms;
Kevin DuBois413287f2019-02-25 08:46:47 -080067constexpr auto defaultRegionSamplingPeriod = 100ms;
68constexpr auto defaultRegionSamplingTimerTimeout = 100ms;
69// TODO: (b/127403193) duration to string conversion could probably be constexpr
70template <typename Rep, typename Per>
71inline std::string toNsString(std::chrono::duration<Rep, Per> t) {
72 return std::to_string(std::chrono::duration_cast<std::chrono::nanoseconds>(t).count());
Dan Stozaec460082018-12-17 15:35:09 -080073}
74
Kevin DuBois413287f2019-02-25 08:46:47 -080075RegionSamplingThread::EnvironmentTimingTunables::EnvironmentTimingTunables() {
76 char value[PROPERTY_VALUE_MAX] = {};
77
Ady Abraham9c53ee72020-07-22 21:16:18 -070078 property_get("debug.sf.region_sampling_duration_ns", value,
79 toNsString(defaultRegionSamplingWorkDuration).c_str());
80 int const samplingDurationNsRaw = atoi(value);
Kevin DuBois413287f2019-02-25 08:46:47 -080081
82 property_get("debug.sf.region_sampling_period_ns", value,
83 toNsString(defaultRegionSamplingPeriod).c_str());
84 int const samplingPeriodNsRaw = atoi(value);
85
86 property_get("debug.sf.region_sampling_timer_timeout_ns", value,
87 toNsString(defaultRegionSamplingTimerTimeout).c_str());
88 int const samplingTimerTimeoutNsRaw = atoi(value);
89
90 if ((samplingPeriodNsRaw < 0) || (samplingTimerTimeoutNsRaw < 0)) {
91 ALOGW("User-specified sampling tuning options nonsensical. Using defaults");
Ady Abraham9c53ee72020-07-22 21:16:18 -070092 mSamplingDuration = defaultRegionSamplingWorkDuration;
Kevin DuBois413287f2019-02-25 08:46:47 -080093 mSamplingPeriod = defaultRegionSamplingPeriod;
94 mSamplingTimerTimeout = defaultRegionSamplingTimerTimeout;
95 } else {
Ady Abraham9c53ee72020-07-22 21:16:18 -070096 mSamplingDuration = std::chrono::nanoseconds(samplingDurationNsRaw);
Kevin DuBois413287f2019-02-25 08:46:47 -080097 mSamplingPeriod = std::chrono::nanoseconds(samplingPeriodNsRaw);
98 mSamplingTimerTimeout = std::chrono::nanoseconds(samplingTimerTimeoutNsRaw);
99 }
100}
101
Ady Abraham9c53ee72020-07-22 21:16:18 -0700102struct SamplingOffsetCallback : VSyncSource::Callback {
Kevin DuBois413287f2019-02-25 08:46:47 -0800103 SamplingOffsetCallback(RegionSamplingThread& samplingThread, Scheduler& scheduler,
Ady Abraham9c53ee72020-07-22 21:16:18 -0700104 std::chrono::nanoseconds targetSamplingWorkDuration)
Kevin DuBois413287f2019-02-25 08:46:47 -0800105 : mRegionSamplingThread(samplingThread),
Ady Abraham9c53ee72020-07-22 21:16:18 -0700106 mTargetSamplingWorkDuration(targetSamplingWorkDuration),
107 mVSyncSource(scheduler.makePrimaryDispSyncSource("SamplingThreadDispSyncListener", 0ns,
108 0ns,
109 /*traceVsync=*/false)) {
110 mVSyncSource->setCallback(this);
111 }
Kevin DuBois413287f2019-02-25 08:46:47 -0800112
113 ~SamplingOffsetCallback() { stopVsyncListener(); }
114
115 SamplingOffsetCallback(const SamplingOffsetCallback&) = delete;
116 SamplingOffsetCallback& operator=(const SamplingOffsetCallback&) = delete;
117
118 void startVsyncListener() {
119 std::lock_guard lock(mMutex);
120 if (mVsyncListening) return;
121
122 mPhaseIntervalSetting = Phase::ZERO;
Ady Abraham9c53ee72020-07-22 21:16:18 -0700123 mVSyncSource->setVSyncEnabled(true);
Kevin DuBois413287f2019-02-25 08:46:47 -0800124 mVsyncListening = true;
125 }
126
127 void stopVsyncListener() {
128 std::lock_guard lock(mMutex);
129 stopVsyncListenerLocked();
130 }
131
132private:
133 void stopVsyncListenerLocked() /*REQUIRES(mMutex)*/ {
134 if (!mVsyncListening) return;
135
Ady Abraham9c53ee72020-07-22 21:16:18 -0700136 mVSyncSource->setVSyncEnabled(false);
Kevin DuBois413287f2019-02-25 08:46:47 -0800137 mVsyncListening = false;
138 }
139
Ady Abraham9c53ee72020-07-22 21:16:18 -0700140 void onVSyncEvent(nsecs_t /*when*/, nsecs_t /*expectedVSyncTimestamp*/,
141 nsecs_t /*deadlineTimestamp*/) final {
Kevin DuBois413287f2019-02-25 08:46:47 -0800142 std::unique_lock<decltype(mMutex)> lock(mMutex);
143
144 if (mPhaseIntervalSetting == Phase::ZERO) {
145 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::waitForSamplePhase));
146 mPhaseIntervalSetting = Phase::SAMPLING;
Ady Abraham9c53ee72020-07-22 21:16:18 -0700147 mVSyncSource->setDuration(mTargetSamplingWorkDuration, 0ns);
Kevin DuBois413287f2019-02-25 08:46:47 -0800148 return;
149 }
150
151 if (mPhaseIntervalSetting == Phase::SAMPLING) {
152 mPhaseIntervalSetting = Phase::ZERO;
Ady Abraham9c53ee72020-07-22 21:16:18 -0700153 mVSyncSource->setDuration(0ns, 0ns);
Kevin DuBois413287f2019-02-25 08:46:47 -0800154 stopVsyncListenerLocked();
155 lock.unlock();
156 mRegionSamplingThread.notifySamplingOffset();
157 return;
158 }
159 }
160
161 RegionSamplingThread& mRegionSamplingThread;
Ady Abraham9c53ee72020-07-22 21:16:18 -0700162 const std::chrono::nanoseconds mTargetSamplingWorkDuration;
Kevin DuBois413287f2019-02-25 08:46:47 -0800163 mutable std::mutex mMutex;
164 enum class Phase {
165 ZERO,
166 SAMPLING
167 } mPhaseIntervalSetting /*GUARDED_BY(mMutex) macro doesnt work with unique_lock?*/
168 = Phase::ZERO;
169 bool mVsyncListening /*GUARDED_BY(mMutex)*/ = false;
Ady Abraham9c53ee72020-07-22 21:16:18 -0700170 std::unique_ptr<VSyncSource> mVSyncSource;
Kevin DuBois413287f2019-02-25 08:46:47 -0800171};
172
173RegionSamplingThread::RegionSamplingThread(SurfaceFlinger& flinger, Scheduler& scheduler,
174 const TimingTunables& tunables)
175 : mFlinger(flinger),
176 mScheduler(scheduler),
177 mTunables(tunables),
Ady Abraham9c53ee72020-07-22 21:16:18 -0700178 mIdleTimer(
Ady Abrahamdb3dfee2020-11-17 17:07:12 -0800179 "RegionSamplingIdleTimer",
Ady Abraham9c53ee72020-07-22 21:16:18 -0700180 std::chrono::duration_cast<std::chrono::milliseconds>(
181 mTunables.mSamplingTimerTimeout),
182 [] {}, [this] { checkForStaleLuma(); }),
Kevin DuBois413287f2019-02-25 08:46:47 -0800183 mPhaseCallback(std::make_unique<SamplingOffsetCallback>(*this, mScheduler,
Ady Abraham9c53ee72020-07-22 21:16:18 -0700184 tunables.mSamplingDuration)),
Kevin DuBois413287f2019-02-25 08:46:47 -0800185 lastSampleTime(0ns) {
Kevin DuBois26afc782019-05-06 16:46:45 -0700186 mThread = std::thread([this]() { threadMain(); });
187 pthread_setname_np(mThread.native_handle(), "RegionSamplingThread");
Kevin DuBois413287f2019-02-25 08:46:47 -0800188 mIdleTimer.start();
189}
190
191RegionSamplingThread::RegionSamplingThread(SurfaceFlinger& flinger, Scheduler& scheduler)
192 : RegionSamplingThread(flinger, scheduler,
Ady Abraham9c53ee72020-07-22 21:16:18 -0700193 TimingTunables{defaultRegionSamplingWorkDuration,
Kevin DuBois413287f2019-02-25 08:46:47 -0800194 defaultRegionSamplingPeriod,
195 defaultRegionSamplingTimerTimeout}) {}
196
Dan Stozaec460082018-12-17 15:35:09 -0800197RegionSamplingThread::~RegionSamplingThread() {
Kevin DuBois413287f2019-02-25 08:46:47 -0800198 mIdleTimer.stop();
199
Dan Stozaec460082018-12-17 15:35:09 -0800200 {
Kevin DuBois26afc782019-05-06 16:46:45 -0700201 std::lock_guard lock(mThreadControlMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800202 mRunning = false;
203 mCondition.notify_one();
204 }
205
Dan Stozaec460082018-12-17 15:35:09 -0800206 if (mThread.joinable()) {
207 mThread.join();
208 }
209}
210
Alec Mouri9a02eda2020-04-21 17:39:34 -0700211void RegionSamplingThread::addListener(const Rect& samplingArea, const wp<Layer>& stopLayer,
Dan Stozaec460082018-12-17 15:35:09 -0800212 const sp<IRegionSamplingListener>& listener) {
Dan Stozaec460082018-12-17 15:35:09 -0800213 sp<IBinder> asBinder = IInterface::asBinder(listener);
214 asBinder->linkToDeath(this);
Kevin DuBois26afc782019-05-06 16:46:45 -0700215 std::lock_guard lock(mSamplingMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800216 mDescriptors.emplace(wp<IBinder>(asBinder), Descriptor{samplingArea, stopLayer, listener});
217}
218
219void RegionSamplingThread::removeListener(const sp<IRegionSamplingListener>& listener) {
Kevin DuBois26afc782019-05-06 16:46:45 -0700220 std::lock_guard lock(mSamplingMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800221 mDescriptors.erase(wp<IBinder>(IInterface::asBinder(listener)));
222}
223
Kevin DuBois413287f2019-02-25 08:46:47 -0800224void RegionSamplingThread::checkForStaleLuma() {
Kevin DuBois26afc782019-05-06 16:46:45 -0700225 std::lock_guard lock(mThreadControlMutex);
Kevin DuBois413287f2019-02-25 08:46:47 -0800226
John Dias84be7832019-06-18 17:05:26 -0700227 if (mDiscardedFrames > 0) {
Kevin DuBois413287f2019-02-25 08:46:47 -0800228 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::waitForZeroPhase));
John Dias84be7832019-06-18 17:05:26 -0700229 mDiscardedFrames = 0;
Kevin DuBois413287f2019-02-25 08:46:47 -0800230 mPhaseCallback->startVsyncListener();
231 }
232}
233
234void RegionSamplingThread::notifyNewContent() {
235 doSample();
236}
237
238void RegionSamplingThread::notifySamplingOffset() {
239 doSample();
240}
241
242void RegionSamplingThread::doSample() {
Kevin DuBois26afc782019-05-06 16:46:45 -0700243 std::lock_guard lock(mThreadControlMutex);
Kevin DuBois413287f2019-02-25 08:46:47 -0800244 auto now = std::chrono::nanoseconds(systemTime(SYSTEM_TIME_MONOTONIC));
245 if (lastSampleTime + mTunables.mSamplingPeriod > now) {
246 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::idleTimerWaiting));
John Dias84be7832019-06-18 17:05:26 -0700247 if (mDiscardedFrames == 0) mDiscardedFrames++;
Kevin DuBois413287f2019-02-25 08:46:47 -0800248 return;
249 }
John Dias84be7832019-06-18 17:05:26 -0700250 if (mDiscardedFrames < maxRegionSamplingSkips) {
251 // If there is relatively little time left for surfaceflinger
252 // until the next vsync deadline, defer this sampling work
253 // to a later frame, when hopefully there will be more time.
254 DisplayStatInfo stats;
Ady Abraham8cb21882020-08-26 18:22:05 -0700255 mScheduler.getDisplayStatInfo(&stats, systemTime());
John Dias84be7832019-06-18 17:05:26 -0700256 if (std::chrono::nanoseconds(stats.vsyncTime) - now < timeForRegionSampling) {
257 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::waitForQuietFrame));
258 mDiscardedFrames++;
259 return;
260 }
261 }
Kevin DuBois413287f2019-02-25 08:46:47 -0800262
263 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::sample));
264
John Dias84be7832019-06-18 17:05:26 -0700265 mDiscardedFrames = 0;
Kevin DuBois413287f2019-02-25 08:46:47 -0800266 lastSampleTime = now;
267
268 mIdleTimer.reset();
269 mPhaseCallback->stopVsyncListener();
270
Dan Stozaec460082018-12-17 15:35:09 -0800271 mSampleRequested = true;
272 mCondition.notify_one();
273}
274
275void RegionSamplingThread::binderDied(const wp<IBinder>& who) {
Kevin DuBois26afc782019-05-06 16:46:45 -0700276 std::lock_guard lock(mSamplingMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800277 mDescriptors.erase(who);
278}
279
Kevin DuBoisb325c932019-05-21 08:34:09 -0700280float sampleArea(const uint32_t* data, int32_t width, int32_t height, int32_t stride,
281 uint32_t orientation, const Rect& sample_area) {
282 if (!sample_area.isValid() || (sample_area.getWidth() > width) ||
283 (sample_area.getHeight() > height)) {
284 ALOGE("invalid sampling region requested");
285 return 0.0f;
286 }
287
288 // (b/133849373) ROT_90 screencap images produced upside down
289 auto area = sample_area;
290 if (orientation & ui::Transform::ROT_90) {
291 area.top = height - area.top;
292 area.bottom = height - area.bottom;
293 std::swap(area.top, area.bottom);
Kevin DuBois69162d02019-06-04 20:22:43 -0700294
295 area.left = width - area.left;
296 area.right = width - area.right;
297 std::swap(area.left, area.right);
Kevin DuBoisb325c932019-05-21 08:34:09 -0700298 }
299
Collin Fijalkovicha95e1702019-10-28 14:46:13 -0700300 const uint32_t pixelCount = (area.bottom - area.top) * (area.right - area.left);
301 uint32_t accumulatedLuma = 0;
Dan Stozaec460082018-12-17 15:35:09 -0800302
Collin Fijalkovicha95e1702019-10-28 14:46:13 -0700303 // Calculates luma with approximation of Rec. 709 primaries
Dan Stozaec460082018-12-17 15:35:09 -0800304 for (int32_t row = area.top; row < area.bottom; ++row) {
305 const uint32_t* rowBase = data + row * stride;
306 for (int32_t column = area.left; column < area.right; ++column) {
307 uint32_t pixel = rowBase[column];
Collin Fijalkovicha95e1702019-10-28 14:46:13 -0700308 const uint32_t r = pixel & 0xFF;
309 const uint32_t g = (pixel >> 8) & 0xFF;
310 const uint32_t b = (pixel >> 16) & 0xFF;
311 const uint32_t luma = (r * 7 + b * 2 + g * 23) >> 5;
312 accumulatedLuma += luma;
Dan Stozaec460082018-12-17 15:35:09 -0800313 }
314 }
315
Collin Fijalkovicha95e1702019-10-28 14:46:13 -0700316 return accumulatedLuma / (255.0f * pixelCount);
Dan Stozaec460082018-12-17 15:35:09 -0800317}
Dan Stozaec460082018-12-17 15:35:09 -0800318
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800319std::vector<float> RegionSamplingThread::sampleBuffer(
320 const sp<GraphicBuffer>& buffer, const Point& leftTop,
Kevin DuBoisb325c932019-05-21 08:34:09 -0700321 const std::vector<RegionSamplingThread::Descriptor>& descriptors, uint32_t orientation) {
Dan Stozaec460082018-12-17 15:35:09 -0800322 void* data_raw = nullptr;
323 buffer->lock(GRALLOC_USAGE_SW_READ_OFTEN, &data_raw);
324 std::shared_ptr<uint32_t> data(reinterpret_cast<uint32_t*>(data_raw),
325 [&buffer](auto) { buffer->unlock(); });
326 if (!data) return {};
327
Kevin DuBoisb325c932019-05-21 08:34:09 -0700328 const int32_t width = buffer->getWidth();
329 const int32_t height = buffer->getHeight();
Dan Stozaec460082018-12-17 15:35:09 -0800330 const int32_t stride = buffer->getStride();
331 std::vector<float> lumas(descriptors.size());
332 std::transform(descriptors.begin(), descriptors.end(), lumas.begin(),
333 [&](auto const& descriptor) {
Kevin DuBoisb325c932019-05-21 08:34:09 -0700334 return sampleArea(data.get(), width, height, stride, orientation,
335 descriptor.area - leftTop);
Dan Stozaec460082018-12-17 15:35:09 -0800336 });
337 return lumas;
338}
339
340void RegionSamplingThread::captureSample() {
341 ATRACE_CALL();
Kevin DuBois26afc782019-05-06 16:46:45 -0700342 std::lock_guard lock(mSamplingMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800343
344 if (mDescriptors.empty()) {
345 return;
346 }
347
Marin Shalamanov1c434292020-06-12 01:47:29 +0200348 wp<const DisplayDevice> displayWeak;
349
350 ui::LayerStack layerStack;
351 ui::Transform::RotationFlags orientation;
352 ui::Size displaySize;
353
354 {
355 // TODO(b/159112860): Don't keep sp<DisplayDevice> outside of SF main thread
356 const sp<const DisplayDevice> display = mFlinger.getDefaultDisplayDevice();
357 displayWeak = display;
358 layerStack = display->getLayerStack();
359 orientation = ui::Transform::toRotationFlags(display->getOrientation());
360 displaySize = display->getSize();
361 }
Kevin DuBoisb325c932019-05-21 08:34:09 -0700362
Dan Stozaec460082018-12-17 15:35:09 -0800363 std::vector<RegionSamplingThread::Descriptor> descriptors;
364 Region sampleRegion;
365 for (const auto& [listener, descriptor] : mDescriptors) {
366 sampleRegion.orSelf(descriptor.area);
367 descriptors.emplace_back(descriptor);
368 }
369
Kevin DuBoisb325c932019-05-21 08:34:09 -0700370 auto dx = 0;
371 auto dy = 0;
372 switch (orientation) {
373 case ui::Transform::ROT_90:
Marin Shalamanov1c434292020-06-12 01:47:29 +0200374 dx = displaySize.getWidth();
Kevin DuBoisb325c932019-05-21 08:34:09 -0700375 break;
376 case ui::Transform::ROT_180:
Marin Shalamanov1c434292020-06-12 01:47:29 +0200377 dx = displaySize.getWidth();
378 dy = displaySize.getHeight();
Kevin DuBoisb325c932019-05-21 08:34:09 -0700379 break;
380 case ui::Transform::ROT_270:
Marin Shalamanov1c434292020-06-12 01:47:29 +0200381 dy = displaySize.getHeight();
Kevin DuBoisb325c932019-05-21 08:34:09 -0700382 break;
383 default:
384 break;
385 }
386
387 ui::Transform t(orientation);
388 auto screencapRegion = t.transform(sampleRegion);
389 screencapRegion = screencapRegion.translate(dx, dy);
Marin Shalamanov1c434292020-06-12 01:47:29 +0200390
391 const Rect sampledBounds = sampleRegion.bounds();
392
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -0800393 SurfaceFlinger::RenderAreaFuture renderAreaFuture = ftl::defer([=] {
Marin Shalamanovf6b5d182020-06-12 02:08:51 +0200394 return DisplayRenderArea::create(displayWeak, screencapRegion.bounds(),
395 sampledBounds.getSize(), ui::Dataspace::V0_SRGB,
396 orientation);
Marin Shalamanov1c434292020-06-12 01:47:29 +0200397 });
Dan Stozaec460082018-12-17 15:35:09 -0800398
399 std::unordered_set<sp<IRegionSamplingListener>, SpHash<IRegionSamplingListener>> listeners;
400
401 auto traverseLayers = [&](const LayerVector::Visitor& visitor) {
402 bool stopLayerFound = false;
403 auto filterVisitor = [&](Layer* layer) {
404 // We don't want to capture any layers beyond the stop layer
405 if (stopLayerFound) return;
406
407 // Likewise if we just found a stop layer, set the flag and abort
408 for (const auto& [area, stopLayer, listener] : descriptors) {
409 if (layer == stopLayer.promote().get()) {
410 stopLayerFound = true;
411 return;
412 }
413 }
414
415 // Compute the layer's position on the screen
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800416 const Rect bounds = Rect(layer->getBounds());
417 const ui::Transform transform = layer->getTransform();
Dan Stozaec460082018-12-17 15:35:09 -0800418 constexpr bool roundOutwards = true;
419 Rect transformed = transform.transform(bounds, roundOutwards);
420
Marin Shalamanov1c434292020-06-12 01:47:29 +0200421 // If this layer doesn't intersect with the larger sampledBounds, skip capturing it
Dan Stozaec460082018-12-17 15:35:09 -0800422 Rect ignore;
Marin Shalamanov1c434292020-06-12 01:47:29 +0200423 if (!transformed.intersect(sampledBounds, &ignore)) return;
Dan Stozaec460082018-12-17 15:35:09 -0800424
425 // If the layer doesn't intersect a sampling area, skip capturing it
426 bool intersectsAnyArea = false;
427 for (const auto& [area, stopLayer, listener] : descriptors) {
428 if (transformed.intersect(area, &ignore)) {
429 intersectsAnyArea = true;
430 listeners.insert(listener);
431 }
432 }
433 if (!intersectsAnyArea) return;
434
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700435 ALOGV("Traversing [%s] [%d, %d, %d, %d]", layer->getDebugName(), bounds.left,
Dan Stozaec460082018-12-17 15:35:09 -0800436 bounds.top, bounds.right, bounds.bottom);
437 visitor(layer);
438 };
chaviw4b9d5e12020-08-04 18:30:35 -0700439 mFlinger.traverseLayersInLayerStack(layerStack, CaptureArgs::UNSET_UID, filterVisitor);
Dan Stozaec460082018-12-17 15:35:09 -0800440 };
441
Kevin DuBois4efd1f52019-04-29 10:09:43 -0700442 sp<GraphicBuffer> buffer = nullptr;
Marin Shalamanov1c434292020-06-12 01:47:29 +0200443 if (mCachedBuffer && mCachedBuffer->getWidth() == sampledBounds.getWidth() &&
444 mCachedBuffer->getHeight() == sampledBounds.getHeight()) {
Kevin DuBois4efd1f52019-04-29 10:09:43 -0700445 buffer = mCachedBuffer;
446 } else {
John Reck67b1e2b2020-08-26 13:17:24 -0700447 const uint32_t usage =
448 GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Marin Shalamanov1c434292020-06-12 01:47:29 +0200449 buffer = new GraphicBuffer(sampledBounds.getWidth(), sampledBounds.getHeight(),
Kevin DuBois4efd1f52019-04-29 10:09:43 -0700450 PIXEL_FORMAT_RGBA_8888, 1, usage, "RegionSamplingThread");
451 }
Dan Stozaec460082018-12-17 15:35:09 -0800452
chaviw03900772020-08-18 12:34:51 -0700453 const sp<SyncScreenCaptureListener> captureListener = new SyncScreenCaptureListener();
Marin Shalamanov1c434292020-06-12 01:47:29 +0200454 mFlinger.captureScreenCommon(std::move(renderAreaFuture), traverseLayers, buffer,
chaviw03900772020-08-18 12:34:51 -0700455 true /* regionSampling */, captureListener);
456 ScreenCaptureResults captureResults = captureListener->waitForResults();
Dan Stozaec460082018-12-17 15:35:09 -0800457
458 std::vector<Descriptor> activeDescriptors;
459 for (const auto& descriptor : descriptors) {
460 if (listeners.count(descriptor.listener) != 0) {
461 activeDescriptors.emplace_back(descriptor);
462 }
463 }
464
465 ALOGV("Sampling %zu descriptors", activeDescriptors.size());
Kevin DuBoisb325c932019-05-21 08:34:09 -0700466 std::vector<float> lumas =
Marin Shalamanov1c434292020-06-12 01:47:29 +0200467 sampleBuffer(buffer, sampledBounds.leftTop(), activeDescriptors, orientation);
Dan Stozaec460082018-12-17 15:35:09 -0800468 if (lumas.size() != activeDescriptors.size()) {
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800469 ALOGW("collected %zu median luma values for %zu descriptors", lumas.size(),
470 activeDescriptors.size());
Dan Stozaec460082018-12-17 15:35:09 -0800471 return;
472 }
473
474 for (size_t d = 0; d < activeDescriptors.size(); ++d) {
475 activeDescriptors[d].listener->onSampleCollected(lumas[d]);
476 }
Kevin DuBois4efd1f52019-04-29 10:09:43 -0700477
478 // Extend the lifetime of mCachedBuffer from the previous frame to here to ensure that:
479 // 1) The region sampling thread is the last owner of the buffer, and the freeing of the buffer
480 // happens in this thread, as opposed to the main thread.
481 // 2) The listener(s) receive their notifications prior to freeing the buffer.
482 mCachedBuffer = buffer;
Kevin DuBois413287f2019-02-25 08:46:47 -0800483 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::noWorkNeeded));
Dan Stozaec460082018-12-17 15:35:09 -0800484}
485
Kevin DuBois26afc782019-05-06 16:46:45 -0700486// NO_THREAD_SAFETY_ANALYSIS is because std::unique_lock presently lacks thread safety annotations.
487void RegionSamplingThread::threadMain() NO_THREAD_SAFETY_ANALYSIS {
488 std::unique_lock<std::mutex> lock(mThreadControlMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800489 while (mRunning) {
490 if (mSampleRequested) {
491 mSampleRequested = false;
Kevin DuBois26afc782019-05-06 16:46:45 -0700492 lock.unlock();
Dan Stozaec460082018-12-17 15:35:09 -0800493 captureSample();
Kevin DuBois26afc782019-05-06 16:46:45 -0700494 lock.lock();
Dan Stozaec460082018-12-17 15:35:09 -0800495 }
Kevin DuBois26afc782019-05-06 16:46:45 -0700496 mCondition.wait(lock, [this]() REQUIRES(mThreadControlMutex) {
497 return mSampleRequested || !mRunning;
498 });
Dan Stozaec460082018-12-17 15:35:09 -0800499 }
500}
501
502} // namespace android
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800503
504// TODO(b/129481165): remove the #pragma below and fix conversion issues
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100505#pragma clang diagnostic pop // ignored "-Wconversion -Wextra"