blob: 718e996dae2483fafb70bff1994b6a12aa5f30f2 [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) {
171 {
172 std::lock_guard threadLock(mThreadMutex);
173 mThread = std::thread([this]() { threadMain(); });
174 pthread_setname_np(mThread.native_handle(), "RegionSamplingThread");
175 }
176 mIdleTimer.start();
177}
178
179RegionSamplingThread::RegionSamplingThread(SurfaceFlinger& flinger, Scheduler& scheduler)
180 : RegionSamplingThread(flinger, scheduler,
181 TimingTunables{defaultRegionSamplingOffset,
182 defaultRegionSamplingPeriod,
183 defaultRegionSamplingTimerTimeout}) {}
184
Dan Stozaec460082018-12-17 15:35:09 -0800185RegionSamplingThread::~RegionSamplingThread() {
Kevin DuBois413287f2019-02-25 08:46:47 -0800186 mIdleTimer.stop();
187
Dan Stozaec460082018-12-17 15:35:09 -0800188 {
189 std::lock_guard lock(mMutex);
190 mRunning = false;
191 mCondition.notify_one();
192 }
193
194 std::lock_guard threadLock(mThreadMutex);
195 if (mThread.joinable()) {
196 mThread.join();
197 }
198}
199
200void RegionSamplingThread::addListener(const Rect& samplingArea, const sp<IBinder>& stopLayerHandle,
201 const sp<IRegionSamplingListener>& listener) {
202 wp<Layer> stopLayer = stopLayerHandle != nullptr
203 ? static_cast<Layer::Handle*>(stopLayerHandle.get())->owner
204 : nullptr;
205
206 sp<IBinder> asBinder = IInterface::asBinder(listener);
207 asBinder->linkToDeath(this);
208 std::lock_guard lock(mMutex);
209 mDescriptors.emplace(wp<IBinder>(asBinder), Descriptor{samplingArea, stopLayer, listener});
210}
211
212void RegionSamplingThread::removeListener(const sp<IRegionSamplingListener>& listener) {
213 std::lock_guard lock(mMutex);
214 mDescriptors.erase(wp<IBinder>(IInterface::asBinder(listener)));
215}
216
Kevin DuBois413287f2019-02-25 08:46:47 -0800217void RegionSamplingThread::checkForStaleLuma() {
Dan Stozaec460082018-12-17 15:35:09 -0800218 std::lock_guard lock(mMutex);
Kevin DuBois413287f2019-02-25 08:46:47 -0800219
220 if (mDiscardedFrames) {
221 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::waitForZeroPhase));
222 mDiscardedFrames = false;
223 mPhaseCallback->startVsyncListener();
224 }
225}
226
227void RegionSamplingThread::notifyNewContent() {
228 doSample();
229}
230
231void RegionSamplingThread::notifySamplingOffset() {
232 doSample();
233}
234
235void RegionSamplingThread::doSample() {
236 std::lock_guard lock(mMutex);
237 auto now = std::chrono::nanoseconds(systemTime(SYSTEM_TIME_MONOTONIC));
238 if (lastSampleTime + mTunables.mSamplingPeriod > now) {
239 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::idleTimerWaiting));
240 mDiscardedFrames = true;
241 return;
242 }
243
244 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::sample));
245
246 mDiscardedFrames = false;
247 lastSampleTime = now;
248
249 mIdleTimer.reset();
250 mPhaseCallback->stopVsyncListener();
251
Dan Stozaec460082018-12-17 15:35:09 -0800252 mSampleRequested = true;
253 mCondition.notify_one();
254}
255
256void RegionSamplingThread::binderDied(const wp<IBinder>& who) {
257 std::lock_guard lock(mMutex);
258 mDescriptors.erase(who);
259}
260
261namespace {
262// Using Rec. 709 primaries
263float getLuma(float r, float g, float b) {
264 constexpr auto rec709_red_primary = 0.2126f;
265 constexpr auto rec709_green_primary = 0.7152f;
266 constexpr auto rec709_blue_primary = 0.0722f;
267 return rec709_red_primary * r + rec709_green_primary * g + rec709_blue_primary * b;
268}
269
270float sampleArea(const uint32_t* data, int32_t stride, const Rect& area) {
271 std::array<int32_t, 256> brightnessBuckets = {};
272 const int32_t majoritySampleNum = area.getWidth() * area.getHeight() / 2;
273
274 for (int32_t row = area.top; row < area.bottom; ++row) {
275 const uint32_t* rowBase = data + row * stride;
276 for (int32_t column = area.left; column < area.right; ++column) {
277 uint32_t pixel = rowBase[column];
278 const float r = (pixel & 0xFF) / 255.0f;
279 const float g = ((pixel >> 8) & 0xFF) / 255.0f;
280 const float b = ((pixel >> 16) & 0xFF) / 255.0f;
281 const uint8_t luma = std::round(getLuma(r, g, b) * 255.0f);
282 ++brightnessBuckets[luma];
283 if (brightnessBuckets[luma] > majoritySampleNum) return luma / 255.0f;
284 }
285 }
286
287 int32_t accumulated = 0;
288 size_t bucket = 0;
289 while (bucket++ < brightnessBuckets.size()) {
290 accumulated += brightnessBuckets[bucket];
291 if (accumulated > majoritySampleNum) break;
292 }
293
294 return bucket / 255.0f;
295}
296} // anonymous namespace
297
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800298std::vector<float> RegionSamplingThread::sampleBuffer(
299 const sp<GraphicBuffer>& buffer, const Point& leftTop,
300 const std::vector<RegionSamplingThread::Descriptor>& descriptors) {
Dan Stozaec460082018-12-17 15:35:09 -0800301 void* data_raw = nullptr;
302 buffer->lock(GRALLOC_USAGE_SW_READ_OFTEN, &data_raw);
303 std::shared_ptr<uint32_t> data(reinterpret_cast<uint32_t*>(data_raw),
304 [&buffer](auto) { buffer->unlock(); });
305 if (!data) return {};
306
307 const int32_t stride = buffer->getStride();
308 std::vector<float> lumas(descriptors.size());
309 std::transform(descriptors.begin(), descriptors.end(), lumas.begin(),
310 [&](auto const& descriptor) {
311 return sampleArea(data.get(), stride, descriptor.area - leftTop);
312 });
313 return lumas;
314}
315
316void RegionSamplingThread::captureSample() {
317 ATRACE_CALL();
318
319 if (mDescriptors.empty()) {
320 return;
321 }
322
323 std::vector<RegionSamplingThread::Descriptor> descriptors;
324 Region sampleRegion;
325 for (const auto& [listener, descriptor] : mDescriptors) {
326 sampleRegion.orSelf(descriptor.area);
327 descriptors.emplace_back(descriptor);
328 }
329
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800330 const Rect sampledArea = sampleRegion.bounds();
Dan Stozaec460082018-12-17 15:35:09 -0800331
332 sp<const DisplayDevice> device = mFlinger.getDefaultDisplayDevice();
333 DisplayRenderArea renderArea(device, sampledArea, sampledArea.getWidth(),
334 sampledArea.getHeight(), ui::Dataspace::V0_SRGB,
335 ui::Transform::ROT_0);
336
337 std::unordered_set<sp<IRegionSamplingListener>, SpHash<IRegionSamplingListener>> listeners;
338
339 auto traverseLayers = [&](const LayerVector::Visitor& visitor) {
340 bool stopLayerFound = false;
341 auto filterVisitor = [&](Layer* layer) {
342 // We don't want to capture any layers beyond the stop layer
343 if (stopLayerFound) return;
344
345 // Likewise if we just found a stop layer, set the flag and abort
346 for (const auto& [area, stopLayer, listener] : descriptors) {
347 if (layer == stopLayer.promote().get()) {
348 stopLayerFound = true;
349 return;
350 }
351 }
352
353 // Compute the layer's position on the screen
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800354 const Rect bounds = Rect(layer->getBounds());
355 const ui::Transform transform = layer->getTransform();
Dan Stozaec460082018-12-17 15:35:09 -0800356 constexpr bool roundOutwards = true;
357 Rect transformed = transform.transform(bounds, roundOutwards);
358
359 // If this layer doesn't intersect with the larger sampledArea, skip capturing it
360 Rect ignore;
361 if (!transformed.intersect(sampledArea, &ignore)) return;
362
363 // If the layer doesn't intersect a sampling area, skip capturing it
364 bool intersectsAnyArea = false;
365 for (const auto& [area, stopLayer, listener] : descriptors) {
366 if (transformed.intersect(area, &ignore)) {
367 intersectsAnyArea = true;
368 listeners.insert(listener);
369 }
370 }
371 if (!intersectsAnyArea) return;
372
373 ALOGV("Traversing [%s] [%d, %d, %d, %d]", layer->getName().string(), bounds.left,
374 bounds.top, bounds.right, bounds.bottom);
375 visitor(layer);
376 };
377 mFlinger.traverseLayersInDisplay(device, filterVisitor);
378 };
379
380 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_HW_RENDER;
381 sp<GraphicBuffer> buffer =
382 new GraphicBuffer(sampledArea.getWidth(), sampledArea.getHeight(),
383 PIXEL_FORMAT_RGBA_8888, 1, usage, "RegionSamplingThread");
384
385 // When calling into SF, we post a message into the SF message queue (so the
386 // screen capture runs on the main thread). This message blocks until the
387 // screenshot is actually captured, but before the capture occurs, the main
388 // thread may perform a normal refresh cycle. At the end of this cycle, it
389 // can request another sample (because layers changed), which triggers a
390 // call into sampleNow. When sampleNow attempts to grab the mutex, we can
391 // deadlock.
392 //
393 // To avoid this, we drop the mutex while we call into SF.
394 mMutex.unlock();
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800395 mFlinger.captureScreenCommon(renderArea, traverseLayers, buffer, false);
Dan Stozaec460082018-12-17 15:35:09 -0800396 mMutex.lock();
397
398 std::vector<Descriptor> activeDescriptors;
399 for (const auto& descriptor : descriptors) {
400 if (listeners.count(descriptor.listener) != 0) {
401 activeDescriptors.emplace_back(descriptor);
402 }
403 }
404
405 ALOGV("Sampling %zu descriptors", activeDescriptors.size());
406 std::vector<float> lumas = sampleBuffer(buffer, sampledArea.leftTop(), activeDescriptors);
407
408 if (lumas.size() != activeDescriptors.size()) {
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800409 ALOGW("collected %zu median luma values for %zu descriptors", lumas.size(),
410 activeDescriptors.size());
Dan Stozaec460082018-12-17 15:35:09 -0800411 return;
412 }
413
414 for (size_t d = 0; d < activeDescriptors.size(); ++d) {
415 activeDescriptors[d].listener->onSampleCollected(lumas[d]);
416 }
Kevin DuBois413287f2019-02-25 08:46:47 -0800417 ATRACE_INT(lumaSamplingStepTag, static_cast<int>(samplingStep::noWorkNeeded));
Dan Stozaec460082018-12-17 15:35:09 -0800418}
419
420void RegionSamplingThread::threadMain() {
421 std::lock_guard lock(mMutex);
422 while (mRunning) {
423 if (mSampleRequested) {
424 mSampleRequested = false;
425 captureSample();
426 }
427 mCondition.wait(mMutex,
428 [this]() REQUIRES(mMutex) { return mSampleRequested || !mRunning; });
429 }
430}
431
432} // namespace android