blob: 2ec20ad5c2157a3bb555aecb952fd82766bc4294 [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>
Huihong Luoa339d0a2022-02-05 09:42:42 -080033#include <gui/SpHash.h>
chaviwe7b9f272020-08-18 16:08:59 -070034#include <gui/SyncScreenCaptureListener.h>
Vishnu Nairdbbe3852022-01-12 20:22:11 -080035#include <renderengine/impl/ExternalTexture.h>
Dominik Laskowski98041832019-08-01 18:35:59 -070036#include <ui/DisplayStatInfo.h>
37#include <utils/Trace.h>
38
39#include <string>
40
Dan Stozaec460082018-12-17 15:35:09 -080041#include "DisplayDevice.h"
Marin Shalamanovf6b5d182020-06-12 02:08:51 +020042#include "DisplayRenderArea.h"
Vishnu Nair9d77a5c2022-10-28 06:31:21 +000043#include "FrontEnd/LayerCreationArgs.h"
Dan Stozaec460082018-12-17 15:35:09 -080044#include "Layer.h"
Melody Hsu41ade202024-05-03 01:25:50 +000045#include "RenderAreaBuilder.h"
Ady Abraham8cb21882020-08-26 18:22:05 -070046#include "Scheduler/VsyncController.h"
Dan Stozaec460082018-12-17 15:35:09 -080047#include "SurfaceFlinger.h"
48
49namespace android {
Kevin DuBois413287f2019-02-25 08:46:47 -080050using namespace std::chrono_literals;
Dan Stozaec460082018-12-17 15:35:09 -080051
Huihong Luoa339d0a2022-02-05 09:42:42 -080052using gui::SpHash;
Dan Stozaec460082018-12-17 15:35:09 -080053
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 waitForSamplePhase,
60 sample
61};
62
Ady Abraham9c53ee72020-07-22 21:16:18 -070063constexpr auto defaultRegionSamplingWorkDuration = 3ms;
Kevin DuBois413287f2019-02-25 08:46:47 -080064constexpr auto defaultRegionSamplingPeriod = 100ms;
65constexpr auto defaultRegionSamplingTimerTimeout = 100ms;
Ady Abraham562c2712021-05-07 15:10:42 -070066constexpr auto maxRegionSamplingDelay = 100ms;
Kevin DuBois413287f2019-02-25 08:46:47 -080067// TODO: (b/127403193) duration to string conversion could probably be constexpr
68template <typename Rep, typename Per>
69inline std::string toNsString(std::chrono::duration<Rep, Per> t) {
70 return std::to_string(std::chrono::duration_cast<std::chrono::nanoseconds>(t).count());
Dan Stozaec460082018-12-17 15:35:09 -080071}
72
Kevin DuBois413287f2019-02-25 08:46:47 -080073RegionSamplingThread::EnvironmentTimingTunables::EnvironmentTimingTunables() {
74 char value[PROPERTY_VALUE_MAX] = {};
75
Ady Abraham9c53ee72020-07-22 21:16:18 -070076 property_get("debug.sf.region_sampling_duration_ns", value,
77 toNsString(defaultRegionSamplingWorkDuration).c_str());
78 int const samplingDurationNsRaw = atoi(value);
Kevin DuBois413287f2019-02-25 08:46:47 -080079
80 property_get("debug.sf.region_sampling_period_ns", value,
81 toNsString(defaultRegionSamplingPeriod).c_str());
82 int const samplingPeriodNsRaw = atoi(value);
83
84 property_get("debug.sf.region_sampling_timer_timeout_ns", value,
85 toNsString(defaultRegionSamplingTimerTimeout).c_str());
86 int const samplingTimerTimeoutNsRaw = atoi(value);
87
88 if ((samplingPeriodNsRaw < 0) || (samplingTimerTimeoutNsRaw < 0)) {
89 ALOGW("User-specified sampling tuning options nonsensical. Using defaults");
Ady Abraham9c53ee72020-07-22 21:16:18 -070090 mSamplingDuration = defaultRegionSamplingWorkDuration;
Kevin DuBois413287f2019-02-25 08:46:47 -080091 mSamplingPeriod = defaultRegionSamplingPeriod;
92 mSamplingTimerTimeout = defaultRegionSamplingTimerTimeout;
93 } else {
Ady Abraham9c53ee72020-07-22 21:16:18 -070094 mSamplingDuration = std::chrono::nanoseconds(samplingDurationNsRaw);
Kevin DuBois413287f2019-02-25 08:46:47 -080095 mSamplingPeriod = std::chrono::nanoseconds(samplingPeriodNsRaw);
96 mSamplingTimerTimeout = std::chrono::nanoseconds(samplingTimerTimeoutNsRaw);
97 }
98}
99
Ady Abraham562c2712021-05-07 15:10:42 -0700100RegionSamplingThread::RegionSamplingThread(SurfaceFlinger& flinger, const TimingTunables& tunables)
Kevin DuBois413287f2019-02-25 08:46:47 -0800101 : mFlinger(flinger),
Kevin DuBois413287f2019-02-25 08:46:47 -0800102 mTunables(tunables),
Ady Abraham9c53ee72020-07-22 21:16:18 -0700103 mIdleTimer(
Ady Abrahamdde984b2021-03-18 12:47:36 -0700104 "RegSampIdle",
Ady Abraham9c53ee72020-07-22 21:16:18 -0700105 std::chrono::duration_cast<std::chrono::milliseconds>(
106 mTunables.mSamplingTimerTimeout),
107 [] {}, [this] { checkForStaleLuma(); }),
Ady Abraham562c2712021-05-07 15:10:42 -0700108 mLastSampleTime(0ns) {
Kevin DuBois26afc782019-05-06 16:46:45 -0700109 mThread = std::thread([this]() { threadMain(); });
Ady Abrahamdde984b2021-03-18 12:47:36 -0700110 pthread_setname_np(mThread.native_handle(), "RegionSampling");
Kevin DuBois413287f2019-02-25 08:46:47 -0800111 mIdleTimer.start();
112}
113
Ady Abraham562c2712021-05-07 15:10:42 -0700114RegionSamplingThread::RegionSamplingThread(SurfaceFlinger& flinger)
115 : RegionSamplingThread(flinger,
Ady Abraham9c53ee72020-07-22 21:16:18 -0700116 TimingTunables{defaultRegionSamplingWorkDuration,
Kevin DuBois413287f2019-02-25 08:46:47 -0800117 defaultRegionSamplingPeriod,
118 defaultRegionSamplingTimerTimeout}) {}
119
Dan Stozaec460082018-12-17 15:35:09 -0800120RegionSamplingThread::~RegionSamplingThread() {
Kevin DuBois413287f2019-02-25 08:46:47 -0800121 mIdleTimer.stop();
122
Dan Stozaec460082018-12-17 15:35:09 -0800123 {
Kevin DuBois26afc782019-05-06 16:46:45 -0700124 std::lock_guard lock(mThreadControlMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800125 mRunning = false;
126 mCondition.notify_one();
127 }
128
Dan Stozaec460082018-12-17 15:35:09 -0800129 if (mThread.joinable()) {
130 mThread.join();
131 }
132}
133
Vishnu Nair9d77a5c2022-10-28 06:31:21 +0000134void RegionSamplingThread::addListener(const Rect& samplingArea, uint32_t stopLayerId,
Dan Stozaec460082018-12-17 15:35:09 -0800135 const sp<IRegionSamplingListener>& listener) {
Dan Stozaec460082018-12-17 15:35:09 -0800136 sp<IBinder> asBinder = IInterface::asBinder(listener);
Ady Abrahamd11bade2022-08-01 16:18:03 -0700137 asBinder->linkToDeath(sp<DeathRecipient>::fromExisting(this));
Kevin DuBois26afc782019-05-06 16:46:45 -0700138 std::lock_guard lock(mSamplingMutex);
Vishnu Nair9d77a5c2022-10-28 06:31:21 +0000139 mDescriptors.emplace(wp<IBinder>(asBinder), Descriptor{samplingArea, stopLayerId, listener});
Dan Stozaec460082018-12-17 15:35:09 -0800140}
141
142void RegionSamplingThread::removeListener(const sp<IRegionSamplingListener>& listener) {
Kevin DuBois26afc782019-05-06 16:46:45 -0700143 std::lock_guard lock(mSamplingMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800144 mDescriptors.erase(wp<IBinder>(IInterface::asBinder(listener)));
145}
146
Kevin DuBois413287f2019-02-25 08:46:47 -0800147void RegionSamplingThread::checkForStaleLuma() {
Kevin DuBois26afc782019-05-06 16:46:45 -0700148 std::lock_guard lock(mThreadControlMutex);
Kevin DuBois413287f2019-02-25 08:46:47 -0800149
Ady Abraham562c2712021-05-07 15:10:42 -0700150 if (mSampleRequestTime.has_value()) {
151 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::waitForSamplePhase));
152 mSampleRequestTime.reset();
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -0700153 mFlinger.scheduleSample();
Kevin DuBois413287f2019-02-25 08:46:47 -0800154 }
155}
156
Ady Abraham562c2712021-05-07 15:10:42 -0700157void RegionSamplingThread::onCompositionComplete(
158 std::optional<std::chrono::steady_clock::time_point> samplingDeadline) {
159 doSample(samplingDeadline);
Kevin DuBois413287f2019-02-25 08:46:47 -0800160}
161
Ady Abraham562c2712021-05-07 15:10:42 -0700162void RegionSamplingThread::doSample(
163 std::optional<std::chrono::steady_clock::time_point> samplingDeadline) {
Kevin DuBois26afc782019-05-06 16:46:45 -0700164 std::lock_guard lock(mThreadControlMutex);
Ady Abraham562c2712021-05-07 15:10:42 -0700165 const auto now = std::chrono::steady_clock::now();
166 if (mLastSampleTime + mTunables.mSamplingPeriod > now) {
167 // content changed, but we sampled not too long ago, so we need to sample some time in the
168 // future.
Kevin DuBois413287f2019-02-25 08:46:47 -0800169 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::idleTimerWaiting));
Ady Abraham562c2712021-05-07 15:10:42 -0700170 mSampleRequestTime = now;
Kevin DuBois413287f2019-02-25 08:46:47 -0800171 return;
172 }
Ady Abraham562c2712021-05-07 15:10:42 -0700173 if (!mSampleRequestTime.has_value() || now - *mSampleRequestTime < maxRegionSamplingDelay) {
John Dias84be7832019-06-18 17:05:26 -0700174 // If there is relatively little time left for surfaceflinger
175 // until the next vsync deadline, defer this sampling work
176 // to a later frame, when hopefully there will be more time.
Ady Abraham562c2712021-05-07 15:10:42 -0700177 if (samplingDeadline.has_value() && now + mTunables.mSamplingDuration > *samplingDeadline) {
John Dias84be7832019-06-18 17:05:26 -0700178 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::waitForQuietFrame));
Ady Abraham562c2712021-05-07 15:10:42 -0700179 mSampleRequestTime = mSampleRequestTime.value_or(now);
John Dias84be7832019-06-18 17:05:26 -0700180 return;
181 }
182 }
Kevin DuBois413287f2019-02-25 08:46:47 -0800183
184 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::sample));
185
Ady Abraham562c2712021-05-07 15:10:42 -0700186 mSampleRequestTime.reset();
187 mLastSampleTime = now;
Kevin DuBois413287f2019-02-25 08:46:47 -0800188
189 mIdleTimer.reset();
Kevin DuBois413287f2019-02-25 08:46:47 -0800190
Dan Stozaec460082018-12-17 15:35:09 -0800191 mSampleRequested = true;
192 mCondition.notify_one();
193}
194
195void RegionSamplingThread::binderDied(const wp<IBinder>& who) {
Kevin DuBois26afc782019-05-06 16:46:45 -0700196 std::lock_guard lock(mSamplingMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800197 mDescriptors.erase(who);
198}
199
Kevin DuBoisb325c932019-05-21 08:34:09 -0700200float sampleArea(const uint32_t* data, int32_t width, int32_t height, int32_t stride,
201 uint32_t orientation, const Rect& sample_area) {
202 if (!sample_area.isValid() || (sample_area.getWidth() > width) ||
203 (sample_area.getHeight() > height)) {
204 ALOGE("invalid sampling region requested");
205 return 0.0f;
206 }
207
Alec Mouri439b6092022-09-14 22:24:17 +0000208 const uint32_t pixelCount =
209 (sample_area.bottom - sample_area.top) * (sample_area.right - sample_area.left);
Collin Fijalkovicha95e1702019-10-28 14:46:13 -0700210 uint32_t accumulatedLuma = 0;
Dan Stozaec460082018-12-17 15:35:09 -0800211
Collin Fijalkovicha95e1702019-10-28 14:46:13 -0700212 // Calculates luma with approximation of Rec. 709 primaries
Alec Mouri439b6092022-09-14 22:24:17 +0000213 for (int32_t row = sample_area.top; row < sample_area.bottom; ++row) {
Dan Stozaec460082018-12-17 15:35:09 -0800214 const uint32_t* rowBase = data + row * stride;
Alec Mouri439b6092022-09-14 22:24:17 +0000215 for (int32_t column = sample_area.left; column < sample_area.right; ++column) {
Dan Stozaec460082018-12-17 15:35:09 -0800216 uint32_t pixel = rowBase[column];
Collin Fijalkovicha95e1702019-10-28 14:46:13 -0700217 const uint32_t r = pixel & 0xFF;
218 const uint32_t g = (pixel >> 8) & 0xFF;
219 const uint32_t b = (pixel >> 16) & 0xFF;
220 const uint32_t luma = (r * 7 + b * 2 + g * 23) >> 5;
221 accumulatedLuma += luma;
Dan Stozaec460082018-12-17 15:35:09 -0800222 }
223 }
224
Collin Fijalkovicha95e1702019-10-28 14:46:13 -0700225 return accumulatedLuma / (255.0f * pixelCount);
Dan Stozaec460082018-12-17 15:35:09 -0800226}
Dan Stozaec460082018-12-17 15:35:09 -0800227
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800228std::vector<float> RegionSamplingThread::sampleBuffer(
229 const sp<GraphicBuffer>& buffer, const Point& leftTop,
Kevin DuBoisb325c932019-05-21 08:34:09 -0700230 const std::vector<RegionSamplingThread::Descriptor>& descriptors, uint32_t orientation) {
Dan Stozaec460082018-12-17 15:35:09 -0800231 void* data_raw = nullptr;
232 buffer->lock(GRALLOC_USAGE_SW_READ_OFTEN, &data_raw);
233 std::shared_ptr<uint32_t> data(reinterpret_cast<uint32_t*>(data_raw),
234 [&buffer](auto) { buffer->unlock(); });
235 if (!data) return {};
236
Kevin DuBoisb325c932019-05-21 08:34:09 -0700237 const int32_t width = buffer->getWidth();
238 const int32_t height = buffer->getHeight();
Dan Stozaec460082018-12-17 15:35:09 -0800239 const int32_t stride = buffer->getStride();
240 std::vector<float> lumas(descriptors.size());
241 std::transform(descriptors.begin(), descriptors.end(), lumas.begin(),
242 [&](auto const& descriptor) {
Kevin DuBoisb325c932019-05-21 08:34:09 -0700243 return sampleArea(data.get(), width, height, stride, orientation,
244 descriptor.area - leftTop);
Dan Stozaec460082018-12-17 15:35:09 -0800245 });
246 return lumas;
247}
248
249void RegionSamplingThread::captureSample() {
250 ATRACE_CALL();
Kevin DuBois26afc782019-05-06 16:46:45 -0700251 std::lock_guard lock(mSamplingMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800252
253 if (mDescriptors.empty()) {
254 return;
255 }
256
Marin Shalamanov1c434292020-06-12 01:47:29 +0200257 wp<const DisplayDevice> displayWeak;
258
259 ui::LayerStack layerStack;
260 ui::Transform::RotationFlags orientation;
261 ui::Size displaySize;
262
263 {
264 // TODO(b/159112860): Don't keep sp<DisplayDevice> outside of SF main thread
265 const sp<const DisplayDevice> display = mFlinger.getDefaultDisplayDevice();
266 displayWeak = display;
267 layerStack = display->getLayerStack();
268 orientation = ui::Transform::toRotationFlags(display->getOrientation());
269 displaySize = display->getSize();
270 }
Kevin DuBoisb325c932019-05-21 08:34:09 -0700271
Dan Stozaec460082018-12-17 15:35:09 -0800272 std::vector<RegionSamplingThread::Descriptor> descriptors;
273 Region sampleRegion;
274 for (const auto& [listener, descriptor] : mDescriptors) {
275 sampleRegion.orSelf(descriptor.area);
276 descriptors.emplace_back(descriptor);
277 }
278
Marin Shalamanov1c434292020-06-12 01:47:29 +0200279 const Rect sampledBounds = sampleRegion.bounds();
Alec Mouri3e5965f2023-04-07 18:00:58 +0000280 constexpr bool kHintForSeamlessTransition = false;
Marin Shalamanov1c434292020-06-12 01:47:29 +0200281
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -0800282 SurfaceFlinger::RenderAreaFuture renderAreaFuture = ftl::defer([=] {
Melody Hsu41ade202024-05-03 01:25:50 +0000283 DisplayRenderAreaBuilder displayRenderArea(sampledBounds, sampledBounds.getSize(),
284 ui::Dataspace::V0_SRGB,
285 kHintForSeamlessTransition,
286 true /* captureSecureLayers */, displayWeak);
287 return displayRenderArea.build();
Marin Shalamanov1c434292020-06-12 01:47:29 +0200288 });
Dan Stozaec460082018-12-17 15:35:09 -0800289
290 std::unordered_set<sp<IRegionSamplingListener>, SpHash<IRegionSamplingListener>> listeners;
291
Vishnu Nairc5a5b6e2023-02-28 00:19:07 +0000292 auto layerFilterFn = [&](const char* layerName, uint32_t layerId, const Rect& bounds,
293 const ui::Transform transform, bool& outStopTraversal) -> bool {
294 // Likewise if we just found a stop layer, set the flag and abort
295 for (const auto& [area, stopLayerId, listener] : descriptors) {
296 if (stopLayerId != UNASSIGNED_LAYER_ID && layerId == stopLayerId) {
297 outStopTraversal = true;
298 return false;
299 }
300 }
Dan Stozaec460082018-12-17 15:35:09 -0800301
Vishnu Nairc5a5b6e2023-02-28 00:19:07 +0000302 // Compute the layer's position on the screen
303 constexpr bool roundOutwards = true;
304 Rect transformed = transform.transform(bounds, roundOutwards);
305
306 // If this layer doesn't intersect with the larger sampledBounds, skip capturing it
307 Rect ignore;
308 if (!transformed.intersect(sampledBounds, &ignore)) return false;
309
310 // If the layer doesn't intersect a sampling area, skip capturing it
311 bool intersectsAnyArea = false;
312 for (const auto& [area, stopLayer, listener] : descriptors) {
313 if (transformed.intersect(area, &ignore)) {
314 intersectsAnyArea = true;
315 listeners.insert(listener);
316 }
317 }
318 if (!intersectsAnyArea) return false;
319
320 ALOGV("Traversing [%s] [%d, %d, %d, %d]", layerName, bounds.left, bounds.top, bounds.right,
321 bounds.bottom);
322
323 return true;
324 };
325
326 std::function<std::vector<std::pair<Layer*, sp<LayerFE>>>()> getLayerSnapshots;
Lloyd Pique30db6402023-06-26 18:56:51 +0000327 if (mFlinger.mLayerLifecycleManagerEnabled) {
Vishnu Nairc5a5b6e2023-02-28 00:19:07 +0000328 auto filterFn = [&](const frontend::LayerSnapshot& snapshot,
329 bool& outStopTraversal) -> bool {
330 const Rect bounds =
331 frontend::RequestedLayerState::reduce(Rect(snapshot.geomLayerBounds),
332 snapshot.transparentRegionHint);
333 const ui::Transform transform = snapshot.geomLayerTransform;
334 return layerFilterFn(snapshot.name.c_str(), snapshot.path.id, bounds, transform,
335 outStopTraversal);
336 };
337 getLayerSnapshots =
338 mFlinger.getLayerSnapshotsForScreenshots(layerStack, CaptureArgs::UNSET_UID,
339 filterFn);
340 } else {
341 auto traverseLayers = [&](const LayerVector::Visitor& visitor) {
342 bool stopLayerFound = false;
343 auto filterVisitor = [&](Layer* layer) {
344 // We don't want to capture any layers beyond the stop layer
345 if (stopLayerFound) return;
346
347 if (!layerFilterFn(layer->getDebugName(), layer->getSequence(),
348 Rect(layer->getBounds()), layer->getTransform(),
349 stopLayerFound)) {
Dan Stozaec460082018-12-17 15:35:09 -0800350 return;
351 }
Vishnu Nairc5a5b6e2023-02-28 00:19:07 +0000352 visitor(layer);
353 };
Ajinkya Chalke02844632023-03-01 12:10:14 +0000354 mFlinger.traverseLayersInLayerStack(layerStack, CaptureArgs::UNSET_UID, {},
355 filterVisitor);
Dan Stozaec460082018-12-17 15:35:09 -0800356 };
Vishnu Nairc5a5b6e2023-02-28 00:19:07 +0000357 getLayerSnapshots = RenderArea::fromTraverseLayersLambda(traverseLayers);
358 }
Dan Stozaec460082018-12-17 15:35:09 -0800359
Alec Mouria90a5702021-04-16 16:36:21 +0000360 std::shared_ptr<renderengine::ExternalTexture> buffer = nullptr;
361 if (mCachedBuffer && mCachedBuffer->getBuffer()->getWidth() == sampledBounds.getWidth() &&
362 mCachedBuffer->getBuffer()->getHeight() == sampledBounds.getHeight()) {
Kevin DuBois4efd1f52019-04-29 10:09:43 -0700363 buffer = mCachedBuffer;
364 } else {
John Reck67b1e2b2020-08-26 13:17:24 -0700365 const uint32_t usage =
366 GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Alec Mouria90a5702021-04-16 16:36:21 +0000367 sp<GraphicBuffer> graphicBuffer =
Ady Abrahamd11bade2022-08-01 16:18:03 -0700368 sp<GraphicBuffer>::make(sampledBounds.getWidth(), sampledBounds.getHeight(),
369 PIXEL_FORMAT_RGBA_8888, 1, usage, "RegionSamplingThread");
Alec Mouria90a5702021-04-16 16:36:21 +0000370 const status_t bufferStatus = graphicBuffer->initCheck();
Alec Mouri7013b6f2021-02-12 11:16:54 -0800371 LOG_ALWAYS_FATAL_IF(bufferStatus != OK, "captureSample: Buffer failed to allocate: %d",
372 bufferStatus);
Alec Mouria90a5702021-04-16 16:36:21 +0000373 buffer = std::make_shared<
Vishnu Nairdbbe3852022-01-12 20:22:11 -0800374 renderengine::impl::ExternalTexture>(graphicBuffer, mFlinger.getRenderEngine(),
375 renderengine::impl::ExternalTexture::Usage::
376 WRITEABLE);
Kevin DuBois4efd1f52019-04-29 10:09:43 -0700377 }
Dan Stozaec460082018-12-17 15:35:09 -0800378
Dominik Laskowskibb448ce2022-05-07 15:52:55 -0700379 constexpr bool kRegionSampling = true;
380 constexpr bool kGrayscale = false;
Chavi Weingarten18fa7c62023-11-28 21:16:03 +0000381 constexpr bool kIsProtected = false;
Dominik Laskowskibb448ce2022-05-07 15:52:55 -0700382
383 if (const auto fenceResult =
Melody Hsu82d524e2024-02-23 02:37:38 +0000384 mFlinger.captureScreenshot(std::move(renderAreaFuture), getLayerSnapshots, buffer,
385 kRegionSampling, kGrayscale, kIsProtected, nullptr)
Dominik Laskowskibb448ce2022-05-07 15:52:55 -0700386 .get();
387 fenceResult.ok()) {
388 fenceResult.value()->waitForever(LOG_TAG);
Sally Qi59a9f502021-10-12 18:53:23 +0000389 }
Dan Stozaec460082018-12-17 15:35:09 -0800390
391 std::vector<Descriptor> activeDescriptors;
392 for (const auto& descriptor : descriptors) {
393 if (listeners.count(descriptor.listener) != 0) {
394 activeDescriptors.emplace_back(descriptor);
395 }
396 }
397
398 ALOGV("Sampling %zu descriptors", activeDescriptors.size());
Alec Mouria90a5702021-04-16 16:36:21 +0000399 std::vector<float> lumas = sampleBuffer(buffer->getBuffer(), sampledBounds.leftTop(),
400 activeDescriptors, orientation);
Dan Stozaec460082018-12-17 15:35:09 -0800401 if (lumas.size() != activeDescriptors.size()) {
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800402 ALOGW("collected %zu median luma values for %zu descriptors", lumas.size(),
403 activeDescriptors.size());
Dan Stozaec460082018-12-17 15:35:09 -0800404 return;
405 }
406
407 for (size_t d = 0; d < activeDescriptors.size(); ++d) {
408 activeDescriptors[d].listener->onSampleCollected(lumas[d]);
409 }
Kevin DuBois4efd1f52019-04-29 10:09:43 -0700410
Kevin DuBois4efd1f52019-04-29 10:09:43 -0700411 mCachedBuffer = buffer;
Kevin DuBois413287f2019-02-25 08:46:47 -0800412 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::noWorkNeeded));
Dan Stozaec460082018-12-17 15:35:09 -0800413}
414
Kevin DuBois26afc782019-05-06 16:46:45 -0700415// NO_THREAD_SAFETY_ANALYSIS is because std::unique_lock presently lacks thread safety annotations.
416void RegionSamplingThread::threadMain() NO_THREAD_SAFETY_ANALYSIS {
417 std::unique_lock<std::mutex> lock(mThreadControlMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800418 while (mRunning) {
419 if (mSampleRequested) {
420 mSampleRequested = false;
Kevin DuBois26afc782019-05-06 16:46:45 -0700421 lock.unlock();
Dan Stozaec460082018-12-17 15:35:09 -0800422 captureSample();
Kevin DuBois26afc782019-05-06 16:46:45 -0700423 lock.lock();
Dan Stozaec460082018-12-17 15:35:09 -0800424 }
Kevin DuBois26afc782019-05-06 16:46:45 -0700425 mCondition.wait(lock, [this]() REQUIRES(mThreadControlMutex) {
426 return mSampleRequested || !mRunning;
427 });
Dan Stozaec460082018-12-17 15:35:09 -0800428 }
429}
430
431} // namespace android
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800432
433// TODO(b/129481165): remove the #pragma below and fix conversion issues
Marin Shalamanovbed7fd32020-12-21 20:02:20 +0100434#pragma clang diagnostic pop // ignored "-Wconversion -Wextra"