blob: cbc7ada9b0817389bf77acdb7ca587eb1bc7df2d [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
24#include <gui/IRegionSamplingListener.h>
25#include <utils/Trace.h>
26
27#include "DisplayDevice.h"
28#include "Layer.h"
29#include "SurfaceFlinger.h"
30
31namespace android {
32
33template <typename T>
34struct SpHash {
35 size_t operator()(const sp<T>& p) const { return std::hash<T*>()(p.get()); }
36};
37
38RegionSamplingThread::RegionSamplingThread(SurfaceFlinger& flinger) : mFlinger(flinger) {
39 std::lock_guard threadLock(mThreadMutex);
40 mThread = std::thread([this]() { threadMain(); });
41 pthread_setname_np(mThread.native_handle(), "RegionSamplingThread");
42}
43
44RegionSamplingThread::~RegionSamplingThread() {
45 {
46 std::lock_guard lock(mMutex);
47 mRunning = false;
48 mCondition.notify_one();
49 }
50
51 std::lock_guard threadLock(mThreadMutex);
52 if (mThread.joinable()) {
53 mThread.join();
54 }
55}
56
57void RegionSamplingThread::addListener(const Rect& samplingArea, const sp<IBinder>& stopLayerHandle,
58 const sp<IRegionSamplingListener>& listener) {
59 wp<Layer> stopLayer = stopLayerHandle != nullptr
60 ? static_cast<Layer::Handle*>(stopLayerHandle.get())->owner
61 : nullptr;
62
63 sp<IBinder> asBinder = IInterface::asBinder(listener);
64 asBinder->linkToDeath(this);
65 std::lock_guard lock(mMutex);
66 mDescriptors.emplace(wp<IBinder>(asBinder), Descriptor{samplingArea, stopLayer, listener});
67}
68
69void RegionSamplingThread::removeListener(const sp<IRegionSamplingListener>& listener) {
70 std::lock_guard lock(mMutex);
71 mDescriptors.erase(wp<IBinder>(IInterface::asBinder(listener)));
72}
73
74void RegionSamplingThread::sampleNow() {
75 std::lock_guard lock(mMutex);
76 mSampleRequested = true;
77 mCondition.notify_one();
78}
79
80void RegionSamplingThread::binderDied(const wp<IBinder>& who) {
81 std::lock_guard lock(mMutex);
82 mDescriptors.erase(who);
83}
84
85namespace {
86// Using Rec. 709 primaries
87float getLuma(float r, float g, float b) {
88 constexpr auto rec709_red_primary = 0.2126f;
89 constexpr auto rec709_green_primary = 0.7152f;
90 constexpr auto rec709_blue_primary = 0.0722f;
91 return rec709_red_primary * r + rec709_green_primary * g + rec709_blue_primary * b;
92}
93
94float sampleArea(const uint32_t* data, int32_t stride, const Rect& area) {
95 std::array<int32_t, 256> brightnessBuckets = {};
96 const int32_t majoritySampleNum = area.getWidth() * area.getHeight() / 2;
97
98 for (int32_t row = area.top; row < area.bottom; ++row) {
99 const uint32_t* rowBase = data + row * stride;
100 for (int32_t column = area.left; column < area.right; ++column) {
101 uint32_t pixel = rowBase[column];
102 const float r = (pixel & 0xFF) / 255.0f;
103 const float g = ((pixel >> 8) & 0xFF) / 255.0f;
104 const float b = ((pixel >> 16) & 0xFF) / 255.0f;
105 const uint8_t luma = std::round(getLuma(r, g, b) * 255.0f);
106 ++brightnessBuckets[luma];
107 if (brightnessBuckets[luma] > majoritySampleNum) return luma / 255.0f;
108 }
109 }
110
111 int32_t accumulated = 0;
112 size_t bucket = 0;
113 while (bucket++ < brightnessBuckets.size()) {
114 accumulated += brightnessBuckets[bucket];
115 if (accumulated > majoritySampleNum) break;
116 }
117
118 return bucket / 255.0f;
119}
120} // anonymous namespace
121
122std::vector<float> sampleBuffer(const sp<GraphicBuffer>& buffer, const Point& leftTop,
123 const std::vector<RegionSamplingThread::Descriptor>& descriptors) {
124 void* data_raw = nullptr;
125 buffer->lock(GRALLOC_USAGE_SW_READ_OFTEN, &data_raw);
126 std::shared_ptr<uint32_t> data(reinterpret_cast<uint32_t*>(data_raw),
127 [&buffer](auto) { buffer->unlock(); });
128 if (!data) return {};
129
130 const int32_t stride = buffer->getStride();
131 std::vector<float> lumas(descriptors.size());
132 std::transform(descriptors.begin(), descriptors.end(), lumas.begin(),
133 [&](auto const& descriptor) {
134 return sampleArea(data.get(), stride, descriptor.area - leftTop);
135 });
136 return lumas;
137}
138
139void RegionSamplingThread::captureSample() {
140 ATRACE_CALL();
141
142 if (mDescriptors.empty()) {
143 return;
144 }
145
146 std::vector<RegionSamplingThread::Descriptor> descriptors;
147 Region sampleRegion;
148 for (const auto& [listener, descriptor] : mDescriptors) {
149 sampleRegion.orSelf(descriptor.area);
150 descriptors.emplace_back(descriptor);
151 }
152
153 Rect sampledArea = sampleRegion.bounds();
154
155 sp<const DisplayDevice> device = mFlinger.getDefaultDisplayDevice();
156 DisplayRenderArea renderArea(device, sampledArea, sampledArea.getWidth(),
157 sampledArea.getHeight(), ui::Dataspace::V0_SRGB,
158 ui::Transform::ROT_0);
159
160 std::unordered_set<sp<IRegionSamplingListener>, SpHash<IRegionSamplingListener>> listeners;
161
162 auto traverseLayers = [&](const LayerVector::Visitor& visitor) {
163 bool stopLayerFound = false;
164 auto filterVisitor = [&](Layer* layer) {
165 // We don't want to capture any layers beyond the stop layer
166 if (stopLayerFound) return;
167
168 // Likewise if we just found a stop layer, set the flag and abort
169 for (const auto& [area, stopLayer, listener] : descriptors) {
170 if (layer == stopLayer.promote().get()) {
171 stopLayerFound = true;
172 return;
173 }
174 }
175
176 // Compute the layer's position on the screen
177 Rect bounds = Rect(layer->getBounds());
178 ui::Transform transform = layer->getTransform();
179 constexpr bool roundOutwards = true;
180 Rect transformed = transform.transform(bounds, roundOutwards);
181
182 // If this layer doesn't intersect with the larger sampledArea, skip capturing it
183 Rect ignore;
184 if (!transformed.intersect(sampledArea, &ignore)) return;
185
186 // If the layer doesn't intersect a sampling area, skip capturing it
187 bool intersectsAnyArea = false;
188 for (const auto& [area, stopLayer, listener] : descriptors) {
189 if (transformed.intersect(area, &ignore)) {
190 intersectsAnyArea = true;
191 listeners.insert(listener);
192 }
193 }
194 if (!intersectsAnyArea) return;
195
196 ALOGV("Traversing [%s] [%d, %d, %d, %d]", layer->getName().string(), bounds.left,
197 bounds.top, bounds.right, bounds.bottom);
198 visitor(layer);
199 };
200 mFlinger.traverseLayersInDisplay(device, filterVisitor);
201 };
202
203 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_HW_RENDER;
204 sp<GraphicBuffer> buffer =
205 new GraphicBuffer(sampledArea.getWidth(), sampledArea.getHeight(),
206 PIXEL_FORMAT_RGBA_8888, 1, usage, "RegionSamplingThread");
207
208 // When calling into SF, we post a message into the SF message queue (so the
209 // screen capture runs on the main thread). This message blocks until the
210 // screenshot is actually captured, but before the capture occurs, the main
211 // thread may perform a normal refresh cycle. At the end of this cycle, it
212 // can request another sample (because layers changed), which triggers a
213 // call into sampleNow. When sampleNow attempts to grab the mutex, we can
214 // deadlock.
215 //
216 // To avoid this, we drop the mutex while we call into SF.
217 mMutex.unlock();
218 mFlinger.captureScreenCore(renderArea, traverseLayers, buffer, false);
219 mMutex.lock();
220
221 std::vector<Descriptor> activeDescriptors;
222 for (const auto& descriptor : descriptors) {
223 if (listeners.count(descriptor.listener) != 0) {
224 activeDescriptors.emplace_back(descriptor);
225 }
226 }
227
228 ALOGV("Sampling %zu descriptors", activeDescriptors.size());
229 std::vector<float> lumas = sampleBuffer(buffer, sampledArea.leftTop(), activeDescriptors);
230
231 if (lumas.size() != activeDescriptors.size()) {
232 return;
233 }
234
235 for (size_t d = 0; d < activeDescriptors.size(); ++d) {
236 activeDescriptors[d].listener->onSampleCollected(lumas[d]);
237 }
238}
239
240void RegionSamplingThread::threadMain() {
241 std::lock_guard lock(mMutex);
242 while (mRunning) {
243 if (mSampleRequested) {
244 mSampleRequested = false;
245 captureSample();
246 }
247 mCondition.wait(mMutex,
248 [this]() REQUIRES(mMutex) { return mSampleRequested || !mRunning; });
249 }
250}
251
252} // namespace android