blob: bd8548c8da0e05fd4a15c4639dbf64b1e60cd303 [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
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800122std::vector<float> RegionSamplingThread::sampleBuffer(
123 const sp<GraphicBuffer>& buffer, const Point& leftTop,
124 const std::vector<RegionSamplingThread::Descriptor>& descriptors) {
Dan Stozaec460082018-12-17 15:35:09 -0800125 void* data_raw = nullptr;
126 buffer->lock(GRALLOC_USAGE_SW_READ_OFTEN, &data_raw);
127 std::shared_ptr<uint32_t> data(reinterpret_cast<uint32_t*>(data_raw),
128 [&buffer](auto) { buffer->unlock(); });
129 if (!data) return {};
130
131 const int32_t stride = buffer->getStride();
132 std::vector<float> lumas(descriptors.size());
133 std::transform(descriptors.begin(), descriptors.end(), lumas.begin(),
134 [&](auto const& descriptor) {
135 return sampleArea(data.get(), stride, descriptor.area - leftTop);
136 });
137 return lumas;
138}
139
140void RegionSamplingThread::captureSample() {
141 ATRACE_CALL();
142
143 if (mDescriptors.empty()) {
144 return;
145 }
146
147 std::vector<RegionSamplingThread::Descriptor> descriptors;
148 Region sampleRegion;
149 for (const auto& [listener, descriptor] : mDescriptors) {
150 sampleRegion.orSelf(descriptor.area);
151 descriptors.emplace_back(descriptor);
152 }
153
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800154 const Rect sampledArea = sampleRegion.bounds();
Dan Stozaec460082018-12-17 15:35:09 -0800155
156 sp<const DisplayDevice> device = mFlinger.getDefaultDisplayDevice();
157 DisplayRenderArea renderArea(device, sampledArea, sampledArea.getWidth(),
158 sampledArea.getHeight(), ui::Dataspace::V0_SRGB,
159 ui::Transform::ROT_0);
160
161 std::unordered_set<sp<IRegionSamplingListener>, SpHash<IRegionSamplingListener>> listeners;
162
163 auto traverseLayers = [&](const LayerVector::Visitor& visitor) {
164 bool stopLayerFound = false;
165 auto filterVisitor = [&](Layer* layer) {
166 // We don't want to capture any layers beyond the stop layer
167 if (stopLayerFound) return;
168
169 // Likewise if we just found a stop layer, set the flag and abort
170 for (const auto& [area, stopLayer, listener] : descriptors) {
171 if (layer == stopLayer.promote().get()) {
172 stopLayerFound = true;
173 return;
174 }
175 }
176
177 // Compute the layer's position on the screen
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800178 const Rect bounds = Rect(layer->getBounds());
179 const ui::Transform transform = layer->getTransform();
Dan Stozaec460082018-12-17 15:35:09 -0800180 constexpr bool roundOutwards = true;
181 Rect transformed = transform.transform(bounds, roundOutwards);
182
183 // If this layer doesn't intersect with the larger sampledArea, skip capturing it
184 Rect ignore;
185 if (!transformed.intersect(sampledArea, &ignore)) return;
186
187 // If the layer doesn't intersect a sampling area, skip capturing it
188 bool intersectsAnyArea = false;
189 for (const auto& [area, stopLayer, listener] : descriptors) {
190 if (transformed.intersect(area, &ignore)) {
191 intersectsAnyArea = true;
192 listeners.insert(listener);
193 }
194 }
195 if (!intersectsAnyArea) return;
196
197 ALOGV("Traversing [%s] [%d, %d, %d, %d]", layer->getName().string(), bounds.left,
198 bounds.top, bounds.right, bounds.bottom);
199 visitor(layer);
200 };
201 mFlinger.traverseLayersInDisplay(device, filterVisitor);
202 };
203
204 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_HW_RENDER;
205 sp<GraphicBuffer> buffer =
206 new GraphicBuffer(sampledArea.getWidth(), sampledArea.getHeight(),
207 PIXEL_FORMAT_RGBA_8888, 1, usage, "RegionSamplingThread");
208
209 // When calling into SF, we post a message into the SF message queue (so the
210 // screen capture runs on the main thread). This message blocks until the
211 // screenshot is actually captured, but before the capture occurs, the main
212 // thread may perform a normal refresh cycle. At the end of this cycle, it
213 // can request another sample (because layers changed), which triggers a
214 // call into sampleNow. When sampleNow attempts to grab the mutex, we can
215 // deadlock.
216 //
217 // To avoid this, we drop the mutex while we call into SF.
218 mMutex.unlock();
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800219 mFlinger.captureScreenCommon(renderArea, traverseLayers, buffer, false);
Dan Stozaec460082018-12-17 15:35:09 -0800220 mMutex.lock();
221
222 std::vector<Descriptor> activeDescriptors;
223 for (const auto& descriptor : descriptors) {
224 if (listeners.count(descriptor.listener) != 0) {
225 activeDescriptors.emplace_back(descriptor);
226 }
227 }
228
229 ALOGV("Sampling %zu descriptors", activeDescriptors.size());
230 std::vector<float> lumas = sampleBuffer(buffer, sampledArea.leftTop(), activeDescriptors);
231
232 if (lumas.size() != activeDescriptors.size()) {
Kevin DuBois7cbcc372019-02-25 14:53:28 -0800233 ALOGW("collected %zu median luma values for %zu descriptors", lumas.size(),
234 activeDescriptors.size());
Dan Stozaec460082018-12-17 15:35:09 -0800235 return;
236 }
237
238 for (size_t d = 0; d < activeDescriptors.size(); ++d) {
239 activeDescriptors[d].listener->onSampleCollected(lumas[d]);
240 }
241}
242
243void RegionSamplingThread::threadMain() {
244 std::lock_guard lock(mMutex);
245 while (mRunning) {
246 if (mSampleRequested) {
247 mSampleRequested = false;
248 captureSample();
249 }
250 mCondition.wait(mMutex,
251 [this]() REQUIRES(mMutex) { return mSampleRequested || !mRunning; });
252 }
253}
254
255} // namespace android