blob: b7e772d917452dc94918f6323d33a7ffe47f3bfe [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
17//#define LOG_NDEBUG 0
18#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19#undef LOG_TAG
20#define LOG_TAG "RegionSamplingThread"
21
22#include "RegionSamplingThread.h"
23
Kevin DuBoisb325c932019-05-21 08:34:09 -070024#include <compositionengine/Display.h>
25#include <compositionengine/impl/OutputCompositionState.h>
Dominik Laskowski98041832019-08-01 18:35:59 -070026#include <cutils/properties.h>
27#include <gui/IRegionSamplingListener.h>
28#include <ui/DisplayStatInfo.h>
29#include <utils/Trace.h>
30
31#include <string>
32
Dan Stozaec460082018-12-17 15:35:09 -080033#include "DisplayDevice.h"
34#include "Layer.h"
Dominik Laskowski98041832019-08-01 18:35:59 -070035#include "Scheduler/DispSync.h"
Dan Stozaec460082018-12-17 15:35:09 -080036#include "SurfaceFlinger.h"
37
38namespace android {
Kevin DuBois413287f2019-02-25 08:46:47 -080039using namespace std::chrono_literals;
Dan Stozaec460082018-12-17 15:35:09 -080040
41template <typename T>
42struct SpHash {
43 size_t operator()(const sp<T>& p) const { return std::hash<T*>()(p.get()); }
44};
45
Kevin DuBois413287f2019-02-25 08:46:47 -080046constexpr auto lumaSamplingStepTag = "LumaSamplingStep";
47enum class samplingStep {
48 noWorkNeeded,
49 idleTimerWaiting,
John Dias84be7832019-06-18 17:05:26 -070050 waitForQuietFrame,
Kevin DuBois413287f2019-02-25 08:46:47 -080051 waitForZeroPhase,
52 waitForSamplePhase,
53 sample
54};
55
John Dias84be7832019-06-18 17:05:26 -070056constexpr auto timeForRegionSampling = 5000000ns;
57constexpr auto maxRegionSamplingSkips = 10;
Kevin DuBois413287f2019-02-25 08:46:47 -080058constexpr auto defaultRegionSamplingOffset = -3ms;
59constexpr auto defaultRegionSamplingPeriod = 100ms;
60constexpr auto defaultRegionSamplingTimerTimeout = 100ms;
61// TODO: (b/127403193) duration to string conversion could probably be constexpr
62template <typename Rep, typename Per>
63inline std::string toNsString(std::chrono::duration<Rep, Per> t) {
64 return std::to_string(std::chrono::duration_cast<std::chrono::nanoseconds>(t).count());
Dan Stozaec460082018-12-17 15:35:09 -080065}
66
Kevin DuBois413287f2019-02-25 08:46:47 -080067RegionSamplingThread::EnvironmentTimingTunables::EnvironmentTimingTunables() {
68 char value[PROPERTY_VALUE_MAX] = {};
69
70 property_get("debug.sf.region_sampling_offset_ns", value,
71 toNsString(defaultRegionSamplingOffset).c_str());
72 int const samplingOffsetNsRaw = atoi(value);
73
74 property_get("debug.sf.region_sampling_period_ns", value,
75 toNsString(defaultRegionSamplingPeriod).c_str());
76 int const samplingPeriodNsRaw = atoi(value);
77
78 property_get("debug.sf.region_sampling_timer_timeout_ns", value,
79 toNsString(defaultRegionSamplingTimerTimeout).c_str());
80 int const samplingTimerTimeoutNsRaw = atoi(value);
81
82 if ((samplingPeriodNsRaw < 0) || (samplingTimerTimeoutNsRaw < 0)) {
83 ALOGW("User-specified sampling tuning options nonsensical. Using defaults");
84 mSamplingOffset = defaultRegionSamplingOffset;
85 mSamplingPeriod = defaultRegionSamplingPeriod;
86 mSamplingTimerTimeout = defaultRegionSamplingTimerTimeout;
87 } else {
88 mSamplingOffset = std::chrono::nanoseconds(samplingOffsetNsRaw);
89 mSamplingPeriod = std::chrono::nanoseconds(samplingPeriodNsRaw);
90 mSamplingTimerTimeout = std::chrono::nanoseconds(samplingTimerTimeoutNsRaw);
91 }
92}
93
94struct SamplingOffsetCallback : DispSync::Callback {
95 SamplingOffsetCallback(RegionSamplingThread& samplingThread, Scheduler& scheduler,
96 std::chrono::nanoseconds targetSamplingOffset)
97 : mRegionSamplingThread(samplingThread),
98 mScheduler(scheduler),
99 mTargetSamplingOffset(targetSamplingOffset) {}
100
101 ~SamplingOffsetCallback() { stopVsyncListener(); }
102
103 SamplingOffsetCallback(const SamplingOffsetCallback&) = delete;
104 SamplingOffsetCallback& operator=(const SamplingOffsetCallback&) = delete;
105
106 void startVsyncListener() {
107 std::lock_guard lock(mMutex);
108 if (mVsyncListening) return;
109
110 mPhaseIntervalSetting = Phase::ZERO;
Dominik Laskowski98041832019-08-01 18:35:59 -0700111 mScheduler.getPrimaryDispSync().addEventListener("SamplingThreadDispSyncListener", 0, this,
112 mLastCallbackTime);
Kevin DuBois413287f2019-02-25 08:46:47 -0800113 mVsyncListening = true;
114 }
115
116 void stopVsyncListener() {
117 std::lock_guard lock(mMutex);
118 stopVsyncListenerLocked();
119 }
120
121private:
122 void stopVsyncListenerLocked() /*REQUIRES(mMutex)*/ {
123 if (!mVsyncListening) return;
124
Dominik Laskowski98041832019-08-01 18:35:59 -0700125 mScheduler.getPrimaryDispSync().removeEventListener(this, &mLastCallbackTime);
Kevin DuBois413287f2019-02-25 08:46:47 -0800126 mVsyncListening = false;
127 }
128
129 void onDispSyncEvent(nsecs_t /* when */) final {
130 std::unique_lock<decltype(mMutex)> lock(mMutex);
131
132 if (mPhaseIntervalSetting == Phase::ZERO) {
133 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::waitForSamplePhase));
134 mPhaseIntervalSetting = Phase::SAMPLING;
Dominik Laskowski98041832019-08-01 18:35:59 -0700135 mScheduler.getPrimaryDispSync().changePhaseOffset(this, mTargetSamplingOffset.count());
Kevin DuBois413287f2019-02-25 08:46:47 -0800136 return;
137 }
138
139 if (mPhaseIntervalSetting == Phase::SAMPLING) {
140 mPhaseIntervalSetting = Phase::ZERO;
Dominik Laskowski98041832019-08-01 18:35:59 -0700141 mScheduler.getPrimaryDispSync().changePhaseOffset(this, 0);
Kevin DuBois413287f2019-02-25 08:46:47 -0800142 stopVsyncListenerLocked();
143 lock.unlock();
144 mRegionSamplingThread.notifySamplingOffset();
145 return;
146 }
147 }
148
149 RegionSamplingThread& mRegionSamplingThread;
150 Scheduler& mScheduler;
151 const std::chrono::nanoseconds mTargetSamplingOffset;
152 mutable std::mutex mMutex;
Alec Mouri7355eb22019-03-05 14:19:10 -0800153 nsecs_t mLastCallbackTime = 0;
Kevin DuBois413287f2019-02-25 08:46:47 -0800154 enum class Phase {
155 ZERO,
156 SAMPLING
157 } mPhaseIntervalSetting /*GUARDED_BY(mMutex) macro doesnt work with unique_lock?*/
158 = Phase::ZERO;
159 bool mVsyncListening /*GUARDED_BY(mMutex)*/ = false;
160};
161
162RegionSamplingThread::RegionSamplingThread(SurfaceFlinger& flinger, Scheduler& scheduler,
163 const TimingTunables& tunables)
164 : mFlinger(flinger),
165 mScheduler(scheduler),
166 mTunables(tunables),
167 mIdleTimer(std::chrono::duration_cast<std::chrono::milliseconds>(
168 mTunables.mSamplingTimerTimeout),
169 [] {}, [this] { checkForStaleLuma(); }),
170 mPhaseCallback(std::make_unique<SamplingOffsetCallback>(*this, mScheduler,
171 tunables.mSamplingOffset)),
172 lastSampleTime(0ns) {
Kevin DuBois26afc782019-05-06 16:46:45 -0700173 mThread = std::thread([this]() { threadMain(); });
174 pthread_setname_np(mThread.native_handle(), "RegionSamplingThread");
Kevin DuBois413287f2019-02-25 08:46:47 -0800175 mIdleTimer.start();
176}
177
178RegionSamplingThread::RegionSamplingThread(SurfaceFlinger& flinger, Scheduler& scheduler)
179 : RegionSamplingThread(flinger, scheduler,
180 TimingTunables{defaultRegionSamplingOffset,
181 defaultRegionSamplingPeriod,
182 defaultRegionSamplingTimerTimeout}) {}
183
Dan Stozaec460082018-12-17 15:35:09 -0800184RegionSamplingThread::~RegionSamplingThread() {
Kevin DuBois413287f2019-02-25 08:46:47 -0800185 mIdleTimer.stop();
186
Dan Stozaec460082018-12-17 15:35:09 -0800187 {
Kevin DuBois26afc782019-05-06 16:46:45 -0700188 std::lock_guard lock(mThreadControlMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800189 mRunning = false;
190 mCondition.notify_one();
191 }
192
Dan Stozaec460082018-12-17 15:35:09 -0800193 if (mThread.joinable()) {
194 mThread.join();
195 }
196}
197
198void RegionSamplingThread::addListener(const Rect& samplingArea, const sp<IBinder>& stopLayerHandle,
199 const sp<IRegionSamplingListener>& listener) {
200 wp<Layer> stopLayer = stopLayerHandle != nullptr
201 ? static_cast<Layer::Handle*>(stopLayerHandle.get())->owner
202 : nullptr;
203
204 sp<IBinder> asBinder = IInterface::asBinder(listener);
205 asBinder->linkToDeath(this);
Kevin DuBois26afc782019-05-06 16:46:45 -0700206 std::lock_guard lock(mSamplingMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800207 mDescriptors.emplace(wp<IBinder>(asBinder), Descriptor{samplingArea, stopLayer, listener});
208}
209
210void RegionSamplingThread::removeListener(const sp<IRegionSamplingListener>& listener) {
Kevin DuBois26afc782019-05-06 16:46:45 -0700211 std::lock_guard lock(mSamplingMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800212 mDescriptors.erase(wp<IBinder>(IInterface::asBinder(listener)));
213}
214
Kevin DuBois413287f2019-02-25 08:46:47 -0800215void RegionSamplingThread::checkForStaleLuma() {
Kevin DuBois26afc782019-05-06 16:46:45 -0700216 std::lock_guard lock(mThreadControlMutex);
Kevin DuBois413287f2019-02-25 08:46:47 -0800217
John Dias84be7832019-06-18 17:05:26 -0700218 if (mDiscardedFrames > 0) {
Kevin DuBois413287f2019-02-25 08:46:47 -0800219 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::waitForZeroPhase));
John Dias84be7832019-06-18 17:05:26 -0700220 mDiscardedFrames = 0;
Kevin DuBois413287f2019-02-25 08:46:47 -0800221 mPhaseCallback->startVsyncListener();
222 }
223}
224
225void RegionSamplingThread::notifyNewContent() {
226 doSample();
227}
228
229void RegionSamplingThread::notifySamplingOffset() {
230 doSample();
231}
232
233void RegionSamplingThread::doSample() {
Kevin DuBois26afc782019-05-06 16:46:45 -0700234 std::lock_guard lock(mThreadControlMutex);
Kevin DuBois413287f2019-02-25 08:46:47 -0800235 auto now = std::chrono::nanoseconds(systemTime(SYSTEM_TIME_MONOTONIC));
236 if (lastSampleTime + mTunables.mSamplingPeriod > now) {
237 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::idleTimerWaiting));
John Dias84be7832019-06-18 17:05:26 -0700238 if (mDiscardedFrames == 0) mDiscardedFrames++;
Kevin DuBois413287f2019-02-25 08:46:47 -0800239 return;
240 }
John Dias84be7832019-06-18 17:05:26 -0700241 if (mDiscardedFrames < maxRegionSamplingSkips) {
242 // If there is relatively little time left for surfaceflinger
243 // until the next vsync deadline, defer this sampling work
244 // to a later frame, when hopefully there will be more time.
245 DisplayStatInfo stats;
246 mScheduler.getDisplayStatInfo(&stats);
247 if (std::chrono::nanoseconds(stats.vsyncTime) - now < timeForRegionSampling) {
248 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::waitForQuietFrame));
249 mDiscardedFrames++;
250 return;
251 }
252 }
Kevin DuBois413287f2019-02-25 08:46:47 -0800253
254 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::sample));
255
John Dias84be7832019-06-18 17:05:26 -0700256 mDiscardedFrames = 0;
Kevin DuBois413287f2019-02-25 08:46:47 -0800257 lastSampleTime = now;
258
259 mIdleTimer.reset();
260 mPhaseCallback->stopVsyncListener();
261
Dan Stozaec460082018-12-17 15:35:09 -0800262 mSampleRequested = true;
263 mCondition.notify_one();
264}
265
266void RegionSamplingThread::binderDied(const wp<IBinder>& who) {
Kevin DuBois26afc782019-05-06 16:46:45 -0700267 std::lock_guard lock(mSamplingMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800268 mDescriptors.erase(who);
269}
270
Kevin DuBoisb325c932019-05-21 08:34:09 -0700271float sampleArea(const uint32_t* data, int32_t width, int32_t height, int32_t stride,
272 uint32_t orientation, const Rect& sample_area) {
273 if (!sample_area.isValid() || (sample_area.getWidth() > width) ||
274 (sample_area.getHeight() > height)) {
275 ALOGE("invalid sampling region requested");
276 return 0.0f;
277 }
278
279 // (b/133849373) ROT_90 screencap images produced upside down
280 auto area = sample_area;
281 if (orientation & ui::Transform::ROT_90) {
282 area.top = height - area.top;
283 area.bottom = height - area.bottom;
284 std::swap(area.top, area.bottom);
Kevin DuBois69162d02019-06-04 20:22:43 -0700285
286 area.left = width - area.left;
287 area.right = width - area.right;
288 std::swap(area.left, area.right);
Kevin DuBoisb325c932019-05-21 08:34:09 -0700289 }
290
Collin Fijalkovicha95e1702019-10-28 14:46:13 -0700291 const uint32_t pixelCount = (area.bottom - area.top) * (area.right - area.left);
292 uint32_t accumulatedLuma = 0;
Dan Stozaec460082018-12-17 15:35:09 -0800293
Collin Fijalkovicha95e1702019-10-28 14:46:13 -0700294 // Calculates luma with approximation of Rec. 709 primaries
Dan Stozaec460082018-12-17 15:35:09 -0800295 for (int32_t row = area.top; row < area.bottom; ++row) {
296 const uint32_t* rowBase = data + row * stride;
297 for (int32_t column = area.left; column < area.right; ++column) {
298 uint32_t pixel = rowBase[column];
Collin Fijalkovicha95e1702019-10-28 14:46:13 -0700299 const uint32_t r = pixel & 0xFF;
300 const uint32_t g = (pixel >> 8) & 0xFF;
301 const uint32_t b = (pixel >> 16) & 0xFF;
302 const uint32_t luma = (r * 7 + b * 2 + g * 23) >> 5;
303 accumulatedLuma += luma;
Dan Stozaec460082018-12-17 15:35:09 -0800304 }
305 }
306
Collin Fijalkovicha95e1702019-10-28 14:46:13 -0700307 return accumulatedLuma / (255.0f * pixelCount);
Dan Stozaec460082018-12-17 15:35:09 -0800308}
Dan Stozaec460082018-12-17 15:35:09 -0800309
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800310std::vector<float> RegionSamplingThread::sampleBuffer(
311 const sp<GraphicBuffer>& buffer, const Point& leftTop,
Kevin DuBoisb325c932019-05-21 08:34:09 -0700312 const std::vector<RegionSamplingThread::Descriptor>& descriptors, uint32_t orientation) {
Dan Stozaec460082018-12-17 15:35:09 -0800313 void* data_raw = nullptr;
314 buffer->lock(GRALLOC_USAGE_SW_READ_OFTEN, &data_raw);
315 std::shared_ptr<uint32_t> data(reinterpret_cast<uint32_t*>(data_raw),
316 [&buffer](auto) { buffer->unlock(); });
317 if (!data) return {};
318
Kevin DuBoisb325c932019-05-21 08:34:09 -0700319 const int32_t width = buffer->getWidth();
320 const int32_t height = buffer->getHeight();
Dan Stozaec460082018-12-17 15:35:09 -0800321 const int32_t stride = buffer->getStride();
322 std::vector<float> lumas(descriptors.size());
323 std::transform(descriptors.begin(), descriptors.end(), lumas.begin(),
324 [&](auto const& descriptor) {
Kevin DuBoisb325c932019-05-21 08:34:09 -0700325 return sampleArea(data.get(), width, height, stride, orientation,
326 descriptor.area - leftTop);
Dan Stozaec460082018-12-17 15:35:09 -0800327 });
328 return lumas;
329}
330
331void RegionSamplingThread::captureSample() {
332 ATRACE_CALL();
Kevin DuBois26afc782019-05-06 16:46:45 -0700333 std::lock_guard lock(mSamplingMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800334
335 if (mDescriptors.empty()) {
336 return;
337 }
338
Kevin DuBoisb325c932019-05-21 08:34:09 -0700339 const auto device = mFlinger.getDefaultDisplayDevice();
Kevin DuBois769ab6f2019-06-19 08:13:28 -0700340 const auto orientation = [](uint32_t orientation) {
341 switch (orientation) {
342 default:
343 case DisplayState::eOrientationDefault:
344 return ui::Transform::ROT_0;
345 case DisplayState::eOrientation90:
346 return ui::Transform::ROT_90;
347 case DisplayState::eOrientation180:
348 return ui::Transform::ROT_180;
349 case DisplayState::eOrientation270:
350 return ui::Transform::ROT_270;
351 }
352 }(device->getOrientation());
Kevin DuBoisb325c932019-05-21 08:34:09 -0700353
Dan Stozaec460082018-12-17 15:35:09 -0800354 std::vector<RegionSamplingThread::Descriptor> descriptors;
355 Region sampleRegion;
356 for (const auto& [listener, descriptor] : mDescriptors) {
357 sampleRegion.orSelf(descriptor.area);
358 descriptors.emplace_back(descriptor);
359 }
360
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800361 const Rect sampledArea = sampleRegion.bounds();
Dan Stozaec460082018-12-17 15:35:09 -0800362
Kevin DuBoisb325c932019-05-21 08:34:09 -0700363 auto dx = 0;
364 auto dy = 0;
365 switch (orientation) {
366 case ui::Transform::ROT_90:
367 dx = device->getWidth();
368 break;
369 case ui::Transform::ROT_180:
370 dx = device->getWidth();
371 dy = device->getHeight();
372 break;
373 case ui::Transform::ROT_270:
374 dy = device->getHeight();
375 break;
376 default:
377 break;
378 }
379
380 ui::Transform t(orientation);
381 auto screencapRegion = t.transform(sampleRegion);
382 screencapRegion = screencapRegion.translate(dx, dy);
383 DisplayRenderArea renderArea(device, screencapRegion.bounds(), sampledArea.getWidth(),
384 sampledArea.getHeight(), ui::Dataspace::V0_SRGB, orientation);
Dan Stozaec460082018-12-17 15:35:09 -0800385
386 std::unordered_set<sp<IRegionSamplingListener>, SpHash<IRegionSamplingListener>> listeners;
387
388 auto traverseLayers = [&](const LayerVector::Visitor& visitor) {
389 bool stopLayerFound = false;
390 auto filterVisitor = [&](Layer* layer) {
391 // We don't want to capture any layers beyond the stop layer
392 if (stopLayerFound) return;
393
394 // Likewise if we just found a stop layer, set the flag and abort
395 for (const auto& [area, stopLayer, listener] : descriptors) {
396 if (layer == stopLayer.promote().get()) {
397 stopLayerFound = true;
398 return;
399 }
400 }
401
402 // Compute the layer's position on the screen
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800403 const Rect bounds = Rect(layer->getBounds());
404 const ui::Transform transform = layer->getTransform();
Dan Stozaec460082018-12-17 15:35:09 -0800405 constexpr bool roundOutwards = true;
406 Rect transformed = transform.transform(bounds, roundOutwards);
407
408 // If this layer doesn't intersect with the larger sampledArea, skip capturing it
409 Rect ignore;
410 if (!transformed.intersect(sampledArea, &ignore)) return;
411
412 // If the layer doesn't intersect a sampling area, skip capturing it
413 bool intersectsAnyArea = false;
414 for (const auto& [area, stopLayer, listener] : descriptors) {
415 if (transformed.intersect(area, &ignore)) {
416 intersectsAnyArea = true;
417 listeners.insert(listener);
418 }
419 }
420 if (!intersectsAnyArea) return;
421
422 ALOGV("Traversing [%s] [%d, %d, %d, %d]", layer->getName().string(), bounds.left,
423 bounds.top, bounds.right, bounds.bottom);
424 visitor(layer);
425 };
426 mFlinger.traverseLayersInDisplay(device, filterVisitor);
427 };
428
Kevin DuBois4efd1f52019-04-29 10:09:43 -0700429 sp<GraphicBuffer> buffer = nullptr;
430 if (mCachedBuffer && mCachedBuffer->getWidth() == sampledArea.getWidth() &&
431 mCachedBuffer->getHeight() == sampledArea.getHeight()) {
432 buffer = mCachedBuffer;
433 } else {
434 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_HW_RENDER;
435 buffer = new GraphicBuffer(sampledArea.getWidth(), sampledArea.getHeight(),
436 PIXEL_FORMAT_RGBA_8888, 1, usage, "RegionSamplingThread");
437 }
Dan Stozaec460082018-12-17 15:35:09 -0800438
Robert Carr108b2c72019-04-02 16:32:58 -0700439 bool ignored;
440 mFlinger.captureScreenCommon(renderArea, traverseLayers, buffer, false, ignored);
Dan Stozaec460082018-12-17 15:35:09 -0800441
442 std::vector<Descriptor> activeDescriptors;
443 for (const auto& descriptor : descriptors) {
444 if (listeners.count(descriptor.listener) != 0) {
445 activeDescriptors.emplace_back(descriptor);
446 }
447 }
448
449 ALOGV("Sampling %zu descriptors", activeDescriptors.size());
Kevin DuBoisb325c932019-05-21 08:34:09 -0700450 std::vector<float> lumas =
451 sampleBuffer(buffer, sampledArea.leftTop(), activeDescriptors, orientation);
Dan Stozaec460082018-12-17 15:35:09 -0800452 if (lumas.size() != activeDescriptors.size()) {
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800453 ALOGW("collected %zu median luma values for %zu descriptors", lumas.size(),
454 activeDescriptors.size());
Dan Stozaec460082018-12-17 15:35:09 -0800455 return;
456 }
457
458 for (size_t d = 0; d < activeDescriptors.size(); ++d) {
459 activeDescriptors[d].listener->onSampleCollected(lumas[d]);
460 }
Kevin DuBois4efd1f52019-04-29 10:09:43 -0700461
462 // Extend the lifetime of mCachedBuffer from the previous frame to here to ensure that:
463 // 1) The region sampling thread is the last owner of the buffer, and the freeing of the buffer
464 // happens in this thread, as opposed to the main thread.
465 // 2) The listener(s) receive their notifications prior to freeing the buffer.
466 mCachedBuffer = buffer;
Kevin DuBois413287f2019-02-25 08:46:47 -0800467 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::noWorkNeeded));
Dan Stozaec460082018-12-17 15:35:09 -0800468}
469
Kevin DuBois26afc782019-05-06 16:46:45 -0700470// NO_THREAD_SAFETY_ANALYSIS is because std::unique_lock presently lacks thread safety annotations.
471void RegionSamplingThread::threadMain() NO_THREAD_SAFETY_ANALYSIS {
472 std::unique_lock<std::mutex> lock(mThreadControlMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800473 while (mRunning) {
474 if (mSampleRequested) {
475 mSampleRequested = false;
Kevin DuBois26afc782019-05-06 16:46:45 -0700476 lock.unlock();
Dan Stozaec460082018-12-17 15:35:09 -0800477 captureSample();
Kevin DuBois26afc782019-05-06 16:46:45 -0700478 lock.lock();
Dan Stozaec460082018-12-17 15:35:09 -0800479 }
Kevin DuBois26afc782019-05-06 16:46:45 -0700480 mCondition.wait(lock, [this]() REQUIRES(mThreadControlMutex) {
481 return mSampleRequested || !mRunning;
482 });
Dan Stozaec460082018-12-17 15:35:09 -0800483 }
484}
485
486} // namespace android