blob: 368426018b9af32398007690e112288ba181edeb [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 DuBois413287f2019-02-25 08:46:47 -080024#include <cutils/properties.h>
Dan Stozaec460082018-12-17 15:35:09 -080025#include <gui/IRegionSamplingListener.h>
26#include <utils/Trace.h>
Kevin DuBois413287f2019-02-25 08:46:47 -080027#include <string>
Dan Stozaec460082018-12-17 15:35:09 -080028
29#include "DisplayDevice.h"
30#include "Layer.h"
31#include "SurfaceFlinger.h"
32
33namespace android {
Kevin DuBois413287f2019-02-25 08:46:47 -080034using namespace std::chrono_literals;
Dan Stozaec460082018-12-17 15:35:09 -080035
36template <typename T>
37struct SpHash {
38 size_t operator()(const sp<T>& p) const { return std::hash<T*>()(p.get()); }
39};
40
Kevin DuBois413287f2019-02-25 08:46:47 -080041constexpr auto lumaSamplingStepTag = "LumaSamplingStep";
42enum class samplingStep {
43 noWorkNeeded,
44 idleTimerWaiting,
45 waitForZeroPhase,
46 waitForSamplePhase,
47 sample
48};
49
50constexpr auto defaultRegionSamplingOffset = -3ms;
51constexpr auto defaultRegionSamplingPeriod = 100ms;
52constexpr auto defaultRegionSamplingTimerTimeout = 100ms;
53// TODO: (b/127403193) duration to string conversion could probably be constexpr
54template <typename Rep, typename Per>
55inline std::string toNsString(std::chrono::duration<Rep, Per> t) {
56 return std::to_string(std::chrono::duration_cast<std::chrono::nanoseconds>(t).count());
Dan Stozaec460082018-12-17 15:35:09 -080057}
58
Kevin DuBois413287f2019-02-25 08:46:47 -080059RegionSamplingThread::EnvironmentTimingTunables::EnvironmentTimingTunables() {
60 char value[PROPERTY_VALUE_MAX] = {};
61
62 property_get("debug.sf.region_sampling_offset_ns", value,
63 toNsString(defaultRegionSamplingOffset).c_str());
64 int const samplingOffsetNsRaw = atoi(value);
65
66 property_get("debug.sf.region_sampling_period_ns", value,
67 toNsString(defaultRegionSamplingPeriod).c_str());
68 int const samplingPeriodNsRaw = atoi(value);
69
70 property_get("debug.sf.region_sampling_timer_timeout_ns", value,
71 toNsString(defaultRegionSamplingTimerTimeout).c_str());
72 int const samplingTimerTimeoutNsRaw = atoi(value);
73
74 if ((samplingPeriodNsRaw < 0) || (samplingTimerTimeoutNsRaw < 0)) {
75 ALOGW("User-specified sampling tuning options nonsensical. Using defaults");
76 mSamplingOffset = defaultRegionSamplingOffset;
77 mSamplingPeriod = defaultRegionSamplingPeriod;
78 mSamplingTimerTimeout = defaultRegionSamplingTimerTimeout;
79 } else {
80 mSamplingOffset = std::chrono::nanoseconds(samplingOffsetNsRaw);
81 mSamplingPeriod = std::chrono::nanoseconds(samplingPeriodNsRaw);
82 mSamplingTimerTimeout = std::chrono::nanoseconds(samplingTimerTimeoutNsRaw);
83 }
84}
85
86struct SamplingOffsetCallback : DispSync::Callback {
87 SamplingOffsetCallback(RegionSamplingThread& samplingThread, Scheduler& scheduler,
88 std::chrono::nanoseconds targetSamplingOffset)
89 : mRegionSamplingThread(samplingThread),
90 mScheduler(scheduler),
91 mTargetSamplingOffset(targetSamplingOffset) {}
92
93 ~SamplingOffsetCallback() { stopVsyncListener(); }
94
95 SamplingOffsetCallback(const SamplingOffsetCallback&) = delete;
96 SamplingOffsetCallback& operator=(const SamplingOffsetCallback&) = delete;
97
98 void startVsyncListener() {
99 std::lock_guard lock(mMutex);
100 if (mVsyncListening) return;
101
102 mPhaseIntervalSetting = Phase::ZERO;
103 mScheduler.withPrimaryDispSync([this](android::DispSync& sync) {
Alec Mouri7355eb22019-03-05 14:19:10 -0800104 sync.addEventListener("SamplingThreadDispSyncListener", 0, this, mLastCallbackTime);
Kevin DuBois413287f2019-02-25 08:46:47 -0800105 });
106 mVsyncListening = true;
107 }
108
109 void stopVsyncListener() {
110 std::lock_guard lock(mMutex);
111 stopVsyncListenerLocked();
112 }
113
114private:
115 void stopVsyncListenerLocked() /*REQUIRES(mMutex)*/ {
116 if (!mVsyncListening) return;
117
Alec Mouri7355eb22019-03-05 14:19:10 -0800118 mScheduler.withPrimaryDispSync([this](android::DispSync& sync) {
119 sync.removeEventListener(this, &mLastCallbackTime);
120 });
Kevin DuBois413287f2019-02-25 08:46:47 -0800121 mVsyncListening = false;
122 }
123
124 void onDispSyncEvent(nsecs_t /* when */) final {
125 std::unique_lock<decltype(mMutex)> lock(mMutex);
126
127 if (mPhaseIntervalSetting == Phase::ZERO) {
128 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::waitForSamplePhase));
129 mPhaseIntervalSetting = Phase::SAMPLING;
130 mScheduler.withPrimaryDispSync([this](android::DispSync& sync) {
131 sync.changePhaseOffset(this, mTargetSamplingOffset.count());
132 });
133 return;
134 }
135
136 if (mPhaseIntervalSetting == Phase::SAMPLING) {
137 mPhaseIntervalSetting = Phase::ZERO;
138 mScheduler.withPrimaryDispSync(
139 [this](android::DispSync& sync) { sync.changePhaseOffset(this, 0); });
140 stopVsyncListenerLocked();
141 lock.unlock();
142 mRegionSamplingThread.notifySamplingOffset();
143 return;
144 }
145 }
146
147 RegionSamplingThread& mRegionSamplingThread;
148 Scheduler& mScheduler;
149 const std::chrono::nanoseconds mTargetSamplingOffset;
150 mutable std::mutex mMutex;
Alec Mouri7355eb22019-03-05 14:19:10 -0800151 nsecs_t mLastCallbackTime = 0;
Kevin DuBois413287f2019-02-25 08:46:47 -0800152 enum class Phase {
153 ZERO,
154 SAMPLING
155 } mPhaseIntervalSetting /*GUARDED_BY(mMutex) macro doesnt work with unique_lock?*/
156 = Phase::ZERO;
157 bool mVsyncListening /*GUARDED_BY(mMutex)*/ = false;
158};
159
160RegionSamplingThread::RegionSamplingThread(SurfaceFlinger& flinger, Scheduler& scheduler,
161 const TimingTunables& tunables)
162 : mFlinger(flinger),
163 mScheduler(scheduler),
164 mTunables(tunables),
165 mIdleTimer(std::chrono::duration_cast<std::chrono::milliseconds>(
166 mTunables.mSamplingTimerTimeout),
167 [] {}, [this] { checkForStaleLuma(); }),
168 mPhaseCallback(std::make_unique<SamplingOffsetCallback>(*this, mScheduler,
169 tunables.mSamplingOffset)),
170 lastSampleTime(0ns) {
Kevin DuBois26afc782019-05-06 16:46:45 -0700171 mThread = std::thread([this]() { threadMain(); });
172 pthread_setname_np(mThread.native_handle(), "RegionSamplingThread");
Kevin DuBois413287f2019-02-25 08:46:47 -0800173 mIdleTimer.start();
174}
175
176RegionSamplingThread::RegionSamplingThread(SurfaceFlinger& flinger, Scheduler& scheduler)
177 : RegionSamplingThread(flinger, scheduler,
178 TimingTunables{defaultRegionSamplingOffset,
179 defaultRegionSamplingPeriod,
180 defaultRegionSamplingTimerTimeout}) {}
181
Dan Stozaec460082018-12-17 15:35:09 -0800182RegionSamplingThread::~RegionSamplingThread() {
Kevin DuBois413287f2019-02-25 08:46:47 -0800183 mIdleTimer.stop();
184
Dan Stozaec460082018-12-17 15:35:09 -0800185 {
Kevin DuBois26afc782019-05-06 16:46:45 -0700186 std::lock_guard lock(mThreadControlMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800187 mRunning = false;
188 mCondition.notify_one();
189 }
190
Dan Stozaec460082018-12-17 15:35:09 -0800191 if (mThread.joinable()) {
192 mThread.join();
193 }
194}
195
196void RegionSamplingThread::addListener(const Rect& samplingArea, const sp<IBinder>& stopLayerHandle,
197 const sp<IRegionSamplingListener>& listener) {
198 wp<Layer> stopLayer = stopLayerHandle != nullptr
199 ? static_cast<Layer::Handle*>(stopLayerHandle.get())->owner
200 : nullptr;
201
202 sp<IBinder> asBinder = IInterface::asBinder(listener);
203 asBinder->linkToDeath(this);
Kevin DuBois26afc782019-05-06 16:46:45 -0700204 std::lock_guard lock(mSamplingMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800205 mDescriptors.emplace(wp<IBinder>(asBinder), Descriptor{samplingArea, stopLayer, listener});
206}
207
208void RegionSamplingThread::removeListener(const sp<IRegionSamplingListener>& listener) {
Kevin DuBois26afc782019-05-06 16:46:45 -0700209 std::lock_guard lock(mSamplingMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800210 mDescriptors.erase(wp<IBinder>(IInterface::asBinder(listener)));
211}
212
Kevin DuBois413287f2019-02-25 08:46:47 -0800213void RegionSamplingThread::checkForStaleLuma() {
Kevin DuBois26afc782019-05-06 16:46:45 -0700214 std::lock_guard lock(mThreadControlMutex);
Kevin DuBois413287f2019-02-25 08:46:47 -0800215
216 if (mDiscardedFrames) {
217 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::waitForZeroPhase));
218 mDiscardedFrames = false;
219 mPhaseCallback->startVsyncListener();
220 }
221}
222
223void RegionSamplingThread::notifyNewContent() {
224 doSample();
225}
226
227void RegionSamplingThread::notifySamplingOffset() {
228 doSample();
229}
230
231void RegionSamplingThread::doSample() {
Kevin DuBois26afc782019-05-06 16:46:45 -0700232 std::lock_guard lock(mThreadControlMutex);
Kevin DuBois413287f2019-02-25 08:46:47 -0800233 auto now = std::chrono::nanoseconds(systemTime(SYSTEM_TIME_MONOTONIC));
234 if (lastSampleTime + mTunables.mSamplingPeriod > now) {
235 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::idleTimerWaiting));
236 mDiscardedFrames = true;
237 return;
238 }
239
240 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::sample));
241
242 mDiscardedFrames = false;
243 lastSampleTime = now;
244
245 mIdleTimer.reset();
246 mPhaseCallback->stopVsyncListener();
247
Dan Stozaec460082018-12-17 15:35:09 -0800248 mSampleRequested = true;
249 mCondition.notify_one();
250}
251
252void RegionSamplingThread::binderDied(const wp<IBinder>& who) {
Kevin DuBois26afc782019-05-06 16:46:45 -0700253 std::lock_guard lock(mSamplingMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800254 mDescriptors.erase(who);
255}
256
257namespace {
258// Using Rec. 709 primaries
259float getLuma(float r, float g, float b) {
260 constexpr auto rec709_red_primary = 0.2126f;
261 constexpr auto rec709_green_primary = 0.7152f;
262 constexpr auto rec709_blue_primary = 0.0722f;
263 return rec709_red_primary * r + rec709_green_primary * g + rec709_blue_primary * b;
264}
Kevin DuBoisbb27bcd2019-04-02 14:34:35 -0700265} // anonymous namespace
Dan Stozaec460082018-12-17 15:35:09 -0800266
267float sampleArea(const uint32_t* data, int32_t stride, const Rect& area) {
268 std::array<int32_t, 256> brightnessBuckets = {};
269 const int32_t majoritySampleNum = area.getWidth() * area.getHeight() / 2;
270
271 for (int32_t row = area.top; row < area.bottom; ++row) {
272 const uint32_t* rowBase = data + row * stride;
273 for (int32_t column = area.left; column < area.right; ++column) {
274 uint32_t pixel = rowBase[column];
275 const float r = (pixel & 0xFF) / 255.0f;
276 const float g = ((pixel >> 8) & 0xFF) / 255.0f;
277 const float b = ((pixel >> 16) & 0xFF) / 255.0f;
278 const uint8_t luma = std::round(getLuma(r, g, b) * 255.0f);
279 ++brightnessBuckets[luma];
280 if (brightnessBuckets[luma] > majoritySampleNum) return luma / 255.0f;
281 }
282 }
283
284 int32_t accumulated = 0;
285 size_t bucket = 0;
Kevin DuBoisbb27bcd2019-04-02 14:34:35 -0700286 for (; bucket < brightnessBuckets.size(); bucket++) {
Dan Stozaec460082018-12-17 15:35:09 -0800287 accumulated += brightnessBuckets[bucket];
288 if (accumulated > majoritySampleNum) break;
289 }
290
291 return bucket / 255.0f;
292}
Dan Stozaec460082018-12-17 15:35:09 -0800293
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800294std::vector<float> RegionSamplingThread::sampleBuffer(
295 const sp<GraphicBuffer>& buffer, const Point& leftTop,
296 const std::vector<RegionSamplingThread::Descriptor>& descriptors) {
Dan Stozaec460082018-12-17 15:35:09 -0800297 void* data_raw = nullptr;
298 buffer->lock(GRALLOC_USAGE_SW_READ_OFTEN, &data_raw);
299 std::shared_ptr<uint32_t> data(reinterpret_cast<uint32_t*>(data_raw),
300 [&buffer](auto) { buffer->unlock(); });
301 if (!data) return {};
302
303 const int32_t stride = buffer->getStride();
304 std::vector<float> lumas(descriptors.size());
305 std::transform(descriptors.begin(), descriptors.end(), lumas.begin(),
306 [&](auto const& descriptor) {
307 return sampleArea(data.get(), stride, descriptor.area - leftTop);
308 });
309 return lumas;
310}
311
312void RegionSamplingThread::captureSample() {
313 ATRACE_CALL();
Kevin DuBois26afc782019-05-06 16:46:45 -0700314 std::lock_guard lock(mSamplingMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800315
316 if (mDescriptors.empty()) {
317 return;
318 }
319
320 std::vector<RegionSamplingThread::Descriptor> descriptors;
321 Region sampleRegion;
322 for (const auto& [listener, descriptor] : mDescriptors) {
323 sampleRegion.orSelf(descriptor.area);
324 descriptors.emplace_back(descriptor);
325 }
326
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800327 const Rect sampledArea = sampleRegion.bounds();
Dan Stozaec460082018-12-17 15:35:09 -0800328
329 sp<const DisplayDevice> device = mFlinger.getDefaultDisplayDevice();
330 DisplayRenderArea renderArea(device, sampledArea, sampledArea.getWidth(),
331 sampledArea.getHeight(), ui::Dataspace::V0_SRGB,
332 ui::Transform::ROT_0);
333
334 std::unordered_set<sp<IRegionSamplingListener>, SpHash<IRegionSamplingListener>> listeners;
335
336 auto traverseLayers = [&](const LayerVector::Visitor& visitor) {
337 bool stopLayerFound = false;
338 auto filterVisitor = [&](Layer* layer) {
339 // We don't want to capture any layers beyond the stop layer
340 if (stopLayerFound) return;
341
342 // Likewise if we just found a stop layer, set the flag and abort
343 for (const auto& [area, stopLayer, listener] : descriptors) {
344 if (layer == stopLayer.promote().get()) {
345 stopLayerFound = true;
346 return;
347 }
348 }
349
350 // Compute the layer's position on the screen
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800351 const Rect bounds = Rect(layer->getBounds());
352 const ui::Transform transform = layer->getTransform();
Dan Stozaec460082018-12-17 15:35:09 -0800353 constexpr bool roundOutwards = true;
354 Rect transformed = transform.transform(bounds, roundOutwards);
355
356 // If this layer doesn't intersect with the larger sampledArea, skip capturing it
357 Rect ignore;
358 if (!transformed.intersect(sampledArea, &ignore)) return;
359
360 // If the layer doesn't intersect a sampling area, skip capturing it
361 bool intersectsAnyArea = false;
362 for (const auto& [area, stopLayer, listener] : descriptors) {
363 if (transformed.intersect(area, &ignore)) {
364 intersectsAnyArea = true;
365 listeners.insert(listener);
366 }
367 }
368 if (!intersectsAnyArea) return;
369
370 ALOGV("Traversing [%s] [%d, %d, %d, %d]", layer->getName().string(), bounds.left,
371 bounds.top, bounds.right, bounds.bottom);
372 visitor(layer);
373 };
374 mFlinger.traverseLayersInDisplay(device, filterVisitor);
375 };
376
Kevin DuBois4efd1f52019-04-29 10:09:43 -0700377 sp<GraphicBuffer> buffer = nullptr;
378 if (mCachedBuffer && mCachedBuffer->getWidth() == sampledArea.getWidth() &&
379 mCachedBuffer->getHeight() == sampledArea.getHeight()) {
380 buffer = mCachedBuffer;
381 } else {
382 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_HW_RENDER;
383 buffer = new GraphicBuffer(sampledArea.getWidth(), sampledArea.getHeight(),
384 PIXEL_FORMAT_RGBA_8888, 1, usage, "RegionSamplingThread");
385 }
Dan Stozaec460082018-12-17 15:35:09 -0800386
Robert Carr108b2c72019-04-02 16:32:58 -0700387 bool ignored;
388 mFlinger.captureScreenCommon(renderArea, traverseLayers, buffer, false, ignored);
Dan Stozaec460082018-12-17 15:35:09 -0800389
390 std::vector<Descriptor> activeDescriptors;
391 for (const auto& descriptor : descriptors) {
392 if (listeners.count(descriptor.listener) != 0) {
393 activeDescriptors.emplace_back(descriptor);
394 }
395 }
396
397 ALOGV("Sampling %zu descriptors", activeDescriptors.size());
398 std::vector<float> lumas = sampleBuffer(buffer, sampledArea.leftTop(), activeDescriptors);
399
400 if (lumas.size() != activeDescriptors.size()) {
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800401 ALOGW("collected %zu median luma values for %zu descriptors", lumas.size(),
402 activeDescriptors.size());
Dan Stozaec460082018-12-17 15:35:09 -0800403 return;
404 }
405
406 for (size_t d = 0; d < activeDescriptors.size(); ++d) {
407 activeDescriptors[d].listener->onSampleCollected(lumas[d]);
408 }
Kevin DuBois4efd1f52019-04-29 10:09:43 -0700409
410 // Extend the lifetime of mCachedBuffer from the previous frame to here to ensure that:
411 // 1) The region sampling thread is the last owner of the buffer, and the freeing of the buffer
412 // happens in this thread, as opposed to the main thread.
413 // 2) The listener(s) receive their notifications prior to freeing the buffer.
414 mCachedBuffer = buffer;
Kevin DuBois413287f2019-02-25 08:46:47 -0800415 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::noWorkNeeded));
Dan Stozaec460082018-12-17 15:35:09 -0800416}
417
Kevin DuBois26afc782019-05-06 16:46:45 -0700418// NO_THREAD_SAFETY_ANALYSIS is because std::unique_lock presently lacks thread safety annotations.
419void RegionSamplingThread::threadMain() NO_THREAD_SAFETY_ANALYSIS {
420 std::unique_lock<std::mutex> lock(mThreadControlMutex);
Dan Stozaec460082018-12-17 15:35:09 -0800421 while (mRunning) {
422 if (mSampleRequested) {
423 mSampleRequested = false;
Kevin DuBois26afc782019-05-06 16:46:45 -0700424 lock.unlock();
Dan Stozaec460082018-12-17 15:35:09 -0800425 captureSample();
Kevin DuBois26afc782019-05-06 16:46:45 -0700426 lock.lock();
Dan Stozaec460082018-12-17 15:35:09 -0800427 }
Kevin DuBois26afc782019-05-06 16:46:45 -0700428 mCondition.wait(lock, [this]() REQUIRES(mThreadControlMutex) {
429 return mSampleRequested || !mRunning;
430 });
Dan Stozaec460082018-12-17 15:35:09 -0800431 }
432}
433
434} // namespace android