blob: 398fd4044252b60c99cb52597d0ee46263b779ea [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"
38#include "Layer.h"
Marin Shalamanov1c434292020-06-12 01:47:29 +020039#include "Promise.h"
Dominik Laskowski98041832019-08-01 18:35:59 -070040#include "Scheduler/DispSync.h"
Dan Stozaec460082018-12-17 15:35:09 -080041#include "SurfaceFlinger.h"
42
43namespace android {
Kevin DuBois413287f2019-02-25 08:46:47 -080044using namespace std::chrono_literals;
Dan Stozaec460082018-12-17 15:35:09 -080045
46template <typename T>
47struct SpHash {
48 size_t operator()(const sp<T>& p) const { return std::hash<T*>()(p.get()); }
49};
50
Kevin DuBois413287f2019-02-25 08:46:47 -080051constexpr auto lumaSamplingStepTag = "LumaSamplingStep";
52enum class samplingStep {
53 noWorkNeeded,
54 idleTimerWaiting,
John Dias84be7832019-06-18 17:05:26 -070055 waitForQuietFrame,
Kevin DuBois413287f2019-02-25 08:46:47 -080056 waitForZeroPhase,
57 waitForSamplePhase,
58 sample
59};
60
John Dias84be7832019-06-18 17:05:26 -070061constexpr auto timeForRegionSampling = 5000000ns;
62constexpr auto maxRegionSamplingSkips = 10;
Kevin DuBois413287f2019-02-25 08:46:47 -080063constexpr auto defaultRegionSamplingOffset = -3ms;
64constexpr auto defaultRegionSamplingPeriod = 100ms;
65constexpr auto defaultRegionSamplingTimerTimeout = 100ms;
66// TODO: (b/127403193) duration to string conversion could probably be constexpr
67template <typename Rep, typename Per>
68inline std::string toNsString(std::chrono::duration<Rep, Per> t) {
69 return std::to_string(std::chrono::duration_cast<std::chrono::nanoseconds>(t).count());
Dan Stozaec460082018-12-17 15:35:09 -080070}
71
Kevin DuBois413287f2019-02-25 08:46:47 -080072RegionSamplingThread::EnvironmentTimingTunables::EnvironmentTimingTunables() {
73 char value[PROPERTY_VALUE_MAX] = {};
74
75 property_get("debug.sf.region_sampling_offset_ns", value,
76 toNsString(defaultRegionSamplingOffset).c_str());
77 int const samplingOffsetNsRaw = atoi(value);
78
79 property_get("debug.sf.region_sampling_period_ns", value,
80 toNsString(defaultRegionSamplingPeriod).c_str());
81 int const samplingPeriodNsRaw = atoi(value);
82
83 property_get("debug.sf.region_sampling_timer_timeout_ns", value,
84 toNsString(defaultRegionSamplingTimerTimeout).c_str());
85 int const samplingTimerTimeoutNsRaw = atoi(value);
86
87 if ((samplingPeriodNsRaw < 0) || (samplingTimerTimeoutNsRaw < 0)) {
88 ALOGW("User-specified sampling tuning options nonsensical. Using defaults");
89 mSamplingOffset = defaultRegionSamplingOffset;
90 mSamplingPeriod = defaultRegionSamplingPeriod;
91 mSamplingTimerTimeout = defaultRegionSamplingTimerTimeout;
92 } else {
93 mSamplingOffset = std::chrono::nanoseconds(samplingOffsetNsRaw);
94 mSamplingPeriod = std::chrono::nanoseconds(samplingPeriodNsRaw);
95 mSamplingTimerTimeout = std::chrono::nanoseconds(samplingTimerTimeoutNsRaw);
96 }
97}
98
99struct SamplingOffsetCallback : DispSync::Callback {
100 SamplingOffsetCallback(RegionSamplingThread& samplingThread, Scheduler& scheduler,
101 std::chrono::nanoseconds targetSamplingOffset)
102 : mRegionSamplingThread(samplingThread),
103 mScheduler(scheduler),
104 mTargetSamplingOffset(targetSamplingOffset) {}
105
106 ~SamplingOffsetCallback() { stopVsyncListener(); }
107
108 SamplingOffsetCallback(const SamplingOffsetCallback&) = delete;
109 SamplingOffsetCallback& operator=(const SamplingOffsetCallback&) = delete;
110
111 void startVsyncListener() {
112 std::lock_guard lock(mMutex);
113 if (mVsyncListening) return;
114
115 mPhaseIntervalSetting = Phase::ZERO;
Dominik Laskowski98041832019-08-01 18:35:59 -0700116 mScheduler.getPrimaryDispSync().addEventListener("SamplingThreadDispSyncListener", 0, this,
117 mLastCallbackTime);
Kevin DuBois413287f2019-02-25 08:46:47 -0800118 mVsyncListening = true;
119 }
120
121 void stopVsyncListener() {
122 std::lock_guard lock(mMutex);
123 stopVsyncListenerLocked();
124 }
125
126private:
127 void stopVsyncListenerLocked() /*REQUIRES(mMutex)*/ {
128 if (!mVsyncListening) return;
129
Dominik Laskowski98041832019-08-01 18:35:59 -0700130 mScheduler.getPrimaryDispSync().removeEventListener(this, &mLastCallbackTime);
Kevin DuBois413287f2019-02-25 08:46:47 -0800131 mVsyncListening = false;
132 }
133
Ady Abraham5facfb12020-04-22 15:18:31 -0700134 void onDispSyncEvent(nsecs_t /*when*/, nsecs_t /*expectedVSyncTimestamp*/) final {
Kevin DuBois413287f2019-02-25 08:46:47 -0800135 std::unique_lock<decltype(mMutex)> lock(mMutex);
136
137 if (mPhaseIntervalSetting == Phase::ZERO) {
138 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::waitForSamplePhase));
139 mPhaseIntervalSetting = Phase::SAMPLING;
Dominik Laskowski98041832019-08-01 18:35:59 -0700140 mScheduler.getPrimaryDispSync().changePhaseOffset(this, mTargetSamplingOffset.count());
Kevin DuBois413287f2019-02-25 08:46:47 -0800141 return;
142 }
143
144 if (mPhaseIntervalSetting == Phase::SAMPLING) {
145 mPhaseIntervalSetting = Phase::ZERO;
Dominik Laskowski98041832019-08-01 18:35:59 -0700146 mScheduler.getPrimaryDispSync().changePhaseOffset(this, 0);
Kevin DuBois413287f2019-02-25 08:46:47 -0800147 stopVsyncListenerLocked();
148 lock.unlock();
149 mRegionSamplingThread.notifySamplingOffset();
150 return;
151 }
152 }
153
154 RegionSamplingThread& mRegionSamplingThread;
155 Scheduler& mScheduler;
156 const std::chrono::nanoseconds mTargetSamplingOffset;
157 mutable std::mutex mMutex;
Alec Mouri7355eb22019-03-05 14:19:10 -0800158 nsecs_t mLastCallbackTime = 0;
Kevin DuBois413287f2019-02-25 08:46:47 -0800159 enum class Phase {
160 ZERO,
161 SAMPLING
162 } mPhaseIntervalSetting /*GUARDED_BY(mMutex) macro doesnt work with unique_lock?*/
163 = Phase::ZERO;
164 bool mVsyncListening /*GUARDED_BY(mMutex)*/ = false;
165};
166
167RegionSamplingThread::RegionSamplingThread(SurfaceFlinger& flinger, Scheduler& scheduler,
168 const TimingTunables& tunables)
169 : mFlinger(flinger),
170 mScheduler(scheduler),
171 mTunables(tunables),
172 mIdleTimer(std::chrono::duration_cast<std::chrono::milliseconds>(
173 mTunables.mSamplingTimerTimeout),
174 [] {}, [this] { checkForStaleLuma(); }),
175 mPhaseCallback(std::make_unique<SamplingOffsetCallback>(*this, mScheduler,
176 tunables.mSamplingOffset)),
177 lastSampleTime(0ns) {
Kevin DuBois26afc782019-05-06 16:46:45 -0700178 mThread = std::thread([this]() { threadMain(); });
179 pthread_setname_np(mThread.native_handle(), "RegionSamplingThread");
Kevin DuBois413287f2019-02-25 08:46:47 -0800180 mIdleTimer.start();
181}
182
183RegionSamplingThread::RegionSamplingThread(SurfaceFlinger& flinger, Scheduler& scheduler)
184 : RegionSamplingThread(flinger, scheduler,
185 TimingTunables{defaultRegionSamplingOffset,
186 defaultRegionSamplingPeriod,
187 defaultRegionSamplingTimerTimeout}) {}
188
Dan Stozaec460082018-12-17 15:35:09 -0800189RegionSamplingThread::~RegionSamplingThread() {
Kevin DuBois413287f2019-02-25 08:46:47 -0800190 mIdleTimer.stop();
191
Dan Stozaec460082018-12-17 15:35:09 -0800192 {
Kevin DuBois26afc782019-05-06 16:46:45 -0700193 std::lock_guard lock(mThreadControlMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800194 mRunning = false;
195 mCondition.notify_one();
196 }
197
Dan Stozaec460082018-12-17 15:35:09 -0800198 if (mThread.joinable()) {
199 mThread.join();
200 }
201}
202
Alec Mouri9a02eda2020-04-21 17:39:34 -0700203void RegionSamplingThread::addListener(const Rect& samplingArea, const wp<Layer>& stopLayer,
Dan Stozaec460082018-12-17 15:35:09 -0800204 const sp<IRegionSamplingListener>& listener) {
Dan Stozaec460082018-12-17 15:35:09 -0800205 sp<IBinder> asBinder = IInterface::asBinder(listener);
206 asBinder->linkToDeath(this);
Kevin DuBois26afc782019-05-06 16:46:45 -0700207 std::lock_guard lock(mSamplingMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800208 mDescriptors.emplace(wp<IBinder>(asBinder), Descriptor{samplingArea, stopLayer, listener});
209}
210
211void RegionSamplingThread::removeListener(const sp<IRegionSamplingListener>& listener) {
Kevin DuBois26afc782019-05-06 16:46:45 -0700212 std::lock_guard lock(mSamplingMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800213 mDescriptors.erase(wp<IBinder>(IInterface::asBinder(listener)));
214}
215
Kevin DuBois413287f2019-02-25 08:46:47 -0800216void RegionSamplingThread::checkForStaleLuma() {
Kevin DuBois26afc782019-05-06 16:46:45 -0700217 std::lock_guard lock(mThreadControlMutex);
Kevin DuBois413287f2019-02-25 08:46:47 -0800218
John Dias84be7832019-06-18 17:05:26 -0700219 if (mDiscardedFrames > 0) {
Kevin DuBois413287f2019-02-25 08:46:47 -0800220 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::waitForZeroPhase));
John Dias84be7832019-06-18 17:05:26 -0700221 mDiscardedFrames = 0;
Kevin DuBois413287f2019-02-25 08:46:47 -0800222 mPhaseCallback->startVsyncListener();
223 }
224}
225
226void RegionSamplingThread::notifyNewContent() {
227 doSample();
228}
229
230void RegionSamplingThread::notifySamplingOffset() {
231 doSample();
232}
233
234void RegionSamplingThread::doSample() {
Kevin DuBois26afc782019-05-06 16:46:45 -0700235 std::lock_guard lock(mThreadControlMutex);
Kevin DuBois413287f2019-02-25 08:46:47 -0800236 auto now = std::chrono::nanoseconds(systemTime(SYSTEM_TIME_MONOTONIC));
237 if (lastSampleTime + mTunables.mSamplingPeriod > now) {
238 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::idleTimerWaiting));
John Dias84be7832019-06-18 17:05:26 -0700239 if (mDiscardedFrames == 0) mDiscardedFrames++;
Kevin DuBois413287f2019-02-25 08:46:47 -0800240 return;
241 }
John Dias84be7832019-06-18 17:05:26 -0700242 if (mDiscardedFrames < maxRegionSamplingSkips) {
243 // If there is relatively little time left for surfaceflinger
244 // until the next vsync deadline, defer this sampling work
245 // to a later frame, when hopefully there will be more time.
246 DisplayStatInfo stats;
247 mScheduler.getDisplayStatInfo(&stats);
248 if (std::chrono::nanoseconds(stats.vsyncTime) - now < timeForRegionSampling) {
249 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::waitForQuietFrame));
250 mDiscardedFrames++;
251 return;
252 }
253 }
Kevin DuBois413287f2019-02-25 08:46:47 -0800254
255 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::sample));
256
John Dias84be7832019-06-18 17:05:26 -0700257 mDiscardedFrames = 0;
Kevin DuBois413287f2019-02-25 08:46:47 -0800258 lastSampleTime = now;
259
260 mIdleTimer.reset();
261 mPhaseCallback->stopVsyncListener();
262
Dan Stozaec460082018-12-17 15:35:09 -0800263 mSampleRequested = true;
264 mCondition.notify_one();
265}
266
267void RegionSamplingThread::binderDied(const wp<IBinder>& who) {
Kevin DuBois26afc782019-05-06 16:46:45 -0700268 std::lock_guard lock(mSamplingMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800269 mDescriptors.erase(who);
270}
271
Kevin DuBoisb325c932019-05-21 08:34:09 -0700272float sampleArea(const uint32_t* data, int32_t width, int32_t height, int32_t stride,
273 uint32_t orientation, const Rect& sample_area) {
274 if (!sample_area.isValid() || (sample_area.getWidth() > width) ||
275 (sample_area.getHeight() > height)) {
276 ALOGE("invalid sampling region requested");
277 return 0.0f;
278 }
279
280 // (b/133849373) ROT_90 screencap images produced upside down
281 auto area = sample_area;
282 if (orientation & ui::Transform::ROT_90) {
283 area.top = height - area.top;
284 area.bottom = height - area.bottom;
285 std::swap(area.top, area.bottom);
Kevin DuBois69162d02019-06-04 20:22:43 -0700286
287 area.left = width - area.left;
288 area.right = width - area.right;
289 std::swap(area.left, area.right);
Kevin DuBoisb325c932019-05-21 08:34:09 -0700290 }
291
Collin Fijalkovicha95e1702019-10-28 14:46:13 -0700292 const uint32_t pixelCount = (area.bottom - area.top) * (area.right - area.left);
293 uint32_t accumulatedLuma = 0;
Dan Stozaec460082018-12-17 15:35:09 -0800294
Collin Fijalkovicha95e1702019-10-28 14:46:13 -0700295 // Calculates luma with approximation of Rec. 709 primaries
Dan Stozaec460082018-12-17 15:35:09 -0800296 for (int32_t row = area.top; row < area.bottom; ++row) {
297 const uint32_t* rowBase = data + row * stride;
298 for (int32_t column = area.left; column < area.right; ++column) {
299 uint32_t pixel = rowBase[column];
Collin Fijalkovicha95e1702019-10-28 14:46:13 -0700300 const uint32_t r = pixel & 0xFF;
301 const uint32_t g = (pixel >> 8) & 0xFF;
302 const uint32_t b = (pixel >> 16) & 0xFF;
303 const uint32_t luma = (r * 7 + b * 2 + g * 23) >> 5;
304 accumulatedLuma += luma;
Dan Stozaec460082018-12-17 15:35:09 -0800305 }
306 }
307
Collin Fijalkovicha95e1702019-10-28 14:46:13 -0700308 return accumulatedLuma / (255.0f * pixelCount);
Dan Stozaec460082018-12-17 15:35:09 -0800309}
Dan Stozaec460082018-12-17 15:35:09 -0800310
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800311std::vector<float> RegionSamplingThread::sampleBuffer(
312 const sp<GraphicBuffer>& buffer, const Point& leftTop,
Kevin DuBoisb325c932019-05-21 08:34:09 -0700313 const std::vector<RegionSamplingThread::Descriptor>& descriptors, uint32_t orientation) {
Dan Stozaec460082018-12-17 15:35:09 -0800314 void* data_raw = nullptr;
315 buffer->lock(GRALLOC_USAGE_SW_READ_OFTEN, &data_raw);
316 std::shared_ptr<uint32_t> data(reinterpret_cast<uint32_t*>(data_raw),
317 [&buffer](auto) { buffer->unlock(); });
318 if (!data) return {};
319
Kevin DuBoisb325c932019-05-21 08:34:09 -0700320 const int32_t width = buffer->getWidth();
321 const int32_t height = buffer->getHeight();
Dan Stozaec460082018-12-17 15:35:09 -0800322 const int32_t stride = buffer->getStride();
323 std::vector<float> lumas(descriptors.size());
324 std::transform(descriptors.begin(), descriptors.end(), lumas.begin(),
325 [&](auto const& descriptor) {
Kevin DuBoisb325c932019-05-21 08:34:09 -0700326 return sampleArea(data.get(), width, height, stride, orientation,
327 descriptor.area - leftTop);
Dan Stozaec460082018-12-17 15:35:09 -0800328 });
329 return lumas;
330}
331
332void RegionSamplingThread::captureSample() {
333 ATRACE_CALL();
Kevin DuBois26afc782019-05-06 16:46:45 -0700334 std::lock_guard lock(mSamplingMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800335
336 if (mDescriptors.empty()) {
337 return;
338 }
339
Marin Shalamanov1c434292020-06-12 01:47:29 +0200340 wp<const DisplayDevice> displayWeak;
341
342 ui::LayerStack layerStack;
343 ui::Transform::RotationFlags orientation;
344 ui::Size displaySize;
345
346 {
347 // TODO(b/159112860): Don't keep sp<DisplayDevice> outside of SF main thread
348 const sp<const DisplayDevice> display = mFlinger.getDefaultDisplayDevice();
349 displayWeak = display;
350 layerStack = display->getLayerStack();
351 orientation = ui::Transform::toRotationFlags(display->getOrientation());
352 displaySize = display->getSize();
353 }
Kevin DuBoisb325c932019-05-21 08:34:09 -0700354
Dan Stozaec460082018-12-17 15:35:09 -0800355 std::vector<RegionSamplingThread::Descriptor> descriptors;
356 Region sampleRegion;
357 for (const auto& [listener, descriptor] : mDescriptors) {
358 sampleRegion.orSelf(descriptor.area);
359 descriptors.emplace_back(descriptor);
360 }
361
Kevin DuBoisb325c932019-05-21 08:34:09 -0700362 auto dx = 0;
363 auto dy = 0;
364 switch (orientation) {
365 case ui::Transform::ROT_90:
Marin Shalamanov1c434292020-06-12 01:47:29 +0200366 dx = displaySize.getWidth();
Kevin DuBoisb325c932019-05-21 08:34:09 -0700367 break;
368 case ui::Transform::ROT_180:
Marin Shalamanov1c434292020-06-12 01:47:29 +0200369 dx = displaySize.getWidth();
370 dy = displaySize.getHeight();
Kevin DuBoisb325c932019-05-21 08:34:09 -0700371 break;
372 case ui::Transform::ROT_270:
Marin Shalamanov1c434292020-06-12 01:47:29 +0200373 dy = displaySize.getHeight();
Kevin DuBoisb325c932019-05-21 08:34:09 -0700374 break;
375 default:
376 break;
377 }
378
379 ui::Transform t(orientation);
380 auto screencapRegion = t.transform(sampleRegion);
381 screencapRegion = screencapRegion.translate(dx, dy);
Marin Shalamanov1c434292020-06-12 01:47:29 +0200382
383 const Rect sampledBounds = sampleRegion.bounds();
384
385 SurfaceFlinger::RenderAreaFuture renderAreaFuture = promise::defer([=] {
386 return DisplayRenderArea::create(displayWeak, sampledBounds, sampledBounds.getSize(),
387 ui::Dataspace::V0_SRGB, orientation);
388 });
Dan Stozaec460082018-12-17 15:35:09 -0800389
390 std::unordered_set<sp<IRegionSamplingListener>, SpHash<IRegionSamplingListener>> listeners;
391
392 auto traverseLayers = [&](const LayerVector::Visitor& visitor) {
393 bool stopLayerFound = false;
394 auto filterVisitor = [&](Layer* layer) {
395 // We don't want to capture any layers beyond the stop layer
396 if (stopLayerFound) return;
397
398 // Likewise if we just found a stop layer, set the flag and abort
399 for (const auto& [area, stopLayer, listener] : descriptors) {
400 if (layer == stopLayer.promote().get()) {
401 stopLayerFound = true;
402 return;
403 }
404 }
405
406 // Compute the layer's position on the screen
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800407 const Rect bounds = Rect(layer->getBounds());
408 const ui::Transform transform = layer->getTransform();
Dan Stozaec460082018-12-17 15:35:09 -0800409 constexpr bool roundOutwards = true;
410 Rect transformed = transform.transform(bounds, roundOutwards);
411
Marin Shalamanov1c434292020-06-12 01:47:29 +0200412 // If this layer doesn't intersect with the larger sampledBounds, skip capturing it
Dan Stozaec460082018-12-17 15:35:09 -0800413 Rect ignore;
Marin Shalamanov1c434292020-06-12 01:47:29 +0200414 if (!transformed.intersect(sampledBounds, &ignore)) return;
Dan Stozaec460082018-12-17 15:35:09 -0800415
416 // If the layer doesn't intersect a sampling area, skip capturing it
417 bool intersectsAnyArea = false;
418 for (const auto& [area, stopLayer, listener] : descriptors) {
419 if (transformed.intersect(area, &ignore)) {
420 intersectsAnyArea = true;
421 listeners.insert(listener);
422 }
423 }
424 if (!intersectsAnyArea) return;
425
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700426 ALOGV("Traversing [%s] [%d, %d, %d, %d]", layer->getDebugName(), bounds.left,
Dan Stozaec460082018-12-17 15:35:09 -0800427 bounds.top, bounds.right, bounds.bottom);
428 visitor(layer);
429 };
Marin Shalamanov1c434292020-06-12 01:47:29 +0200430 mFlinger.traverseLayersInLayerStack(layerStack, filterVisitor);
Dan Stozaec460082018-12-17 15:35:09 -0800431 };
432
Kevin DuBois4efd1f52019-04-29 10:09:43 -0700433 sp<GraphicBuffer> buffer = nullptr;
Marin Shalamanov1c434292020-06-12 01:47:29 +0200434 if (mCachedBuffer && mCachedBuffer->getWidth() == sampledBounds.getWidth() &&
435 mCachedBuffer->getHeight() == sampledBounds.getHeight()) {
Kevin DuBois4efd1f52019-04-29 10:09:43 -0700436 buffer = mCachedBuffer;
437 } else {
438 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_HW_RENDER;
Marin Shalamanov1c434292020-06-12 01:47:29 +0200439 buffer = new GraphicBuffer(sampledBounds.getWidth(), sampledBounds.getHeight(),
Kevin DuBois4efd1f52019-04-29 10:09:43 -0700440 PIXEL_FORMAT_RGBA_8888, 1, usage, "RegionSamplingThread");
441 }
Dan Stozaec460082018-12-17 15:35:09 -0800442
Robert Carr108b2c72019-04-02 16:32:58 -0700443 bool ignored;
Marin Shalamanov1c434292020-06-12 01:47:29 +0200444 mFlinger.captureScreenCommon(std::move(renderAreaFuture), traverseLayers, buffer,
445 false /* identityTransform */, true /* regionSampling */, ignored);
Dan Stozaec460082018-12-17 15:35:09 -0800446
447 std::vector<Descriptor> activeDescriptors;
448 for (const auto& descriptor : descriptors) {
449 if (listeners.count(descriptor.listener) != 0) {
450 activeDescriptors.emplace_back(descriptor);
451 }
452 }
453
454 ALOGV("Sampling %zu descriptors", activeDescriptors.size());
Kevin DuBoisb325c932019-05-21 08:34:09 -0700455 std::vector<float> lumas =
Marin Shalamanov1c434292020-06-12 01:47:29 +0200456 sampleBuffer(buffer, sampledBounds.leftTop(), activeDescriptors, orientation);
Dan Stozaec460082018-12-17 15:35:09 -0800457 if (lumas.size() != activeDescriptors.size()) {
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800458 ALOGW("collected %zu median luma values for %zu descriptors", lumas.size(),
459 activeDescriptors.size());
Dan Stozaec460082018-12-17 15:35:09 -0800460 return;
461 }
462
463 for (size_t d = 0; d < activeDescriptors.size(); ++d) {
464 activeDescriptors[d].listener->onSampleCollected(lumas[d]);
465 }
Kevin DuBois4efd1f52019-04-29 10:09:43 -0700466
467 // Extend the lifetime of mCachedBuffer from the previous frame to here to ensure that:
468 // 1) The region sampling thread is the last owner of the buffer, and the freeing of the buffer
469 // happens in this thread, as opposed to the main thread.
470 // 2) The listener(s) receive their notifications prior to freeing the buffer.
471 mCachedBuffer = buffer;
Kevin DuBois413287f2019-02-25 08:46:47 -0800472 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::noWorkNeeded));
Dan Stozaec460082018-12-17 15:35:09 -0800473}
474
Kevin DuBois26afc782019-05-06 16:46:45 -0700475// NO_THREAD_SAFETY_ANALYSIS is because std::unique_lock presently lacks thread safety annotations.
476void RegionSamplingThread::threadMain() NO_THREAD_SAFETY_ANALYSIS {
477 std::unique_lock<std::mutex> lock(mThreadControlMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800478 while (mRunning) {
479 if (mSampleRequested) {
480 mSampleRequested = false;
Kevin DuBois26afc782019-05-06 16:46:45 -0700481 lock.unlock();
Dan Stozaec460082018-12-17 15:35:09 -0800482 captureSample();
Kevin DuBois26afc782019-05-06 16:46:45 -0700483 lock.lock();
Dan Stozaec460082018-12-17 15:35:09 -0800484 }
Kevin DuBois26afc782019-05-06 16:46:45 -0700485 mCondition.wait(lock, [this]() REQUIRES(mThreadControlMutex) {
486 return mSampleRequested || !mRunning;
487 });
Dan Stozaec460082018-12-17 15:35:09 -0800488 }
489}
490
491} // namespace android
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800492
493// TODO(b/129481165): remove the #pragma below and fix conversion issues
494#pragma clang diagnostic pop // ignored "-Wconversion"