1 /*
2 * Copyright (C) 2007 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_TAG "SurfaceComposerClient"
18
19 #include <semaphore.h>
20 #include <stdint.h>
21 #include <sys/types.h>
22
23 #include <android/gui/BnWindowInfosReportedListener.h>
24 #include <android/gui/DisplayState.h>
25 #include <android/gui/ISurfaceComposerClient.h>
26 #include <android/gui/IWindowInfosListener.h>
27 #include <android/gui/TrustedPresentationThresholds.h>
28 #include <android/os/IInputConstants.h>
29 #include <gui/TraceUtils.h>
30 #include <utils/Errors.h>
31 #include <utils/Log.h>
32 #include <utils/SortedVector.h>
33 #include <utils/String8.h>
34 #include <utils/threads.h>
35
36 #include <binder/IPCThreadState.h>
37 #include <binder/IServiceManager.h>
38 #include <binder/ProcessState.h>
39
40 #include <system/graphics.h>
41
42 #include <gui/AidlStatusUtil.h>
43 #include <gui/BufferItemConsumer.h>
44 #include <gui/CpuConsumer.h>
45 #include <gui/IGraphicBufferProducer.h>
46 #include <gui/ISurfaceComposer.h>
47 #include <gui/LayerState.h>
48 #include <gui/Surface.h>
49 #include <gui/SurfaceComposerClient.h>
50 #include <gui/WindowInfo.h>
51 #include <private/gui/ParcelUtils.h>
52 #include <ui/DisplayMode.h>
53 #include <ui/DisplayState.h>
54 #include <ui/DynamicDisplayInfo.h>
55
56 #include <android-base/thread_annotations.h>
57 #include <gui/LayerStatePermissions.h>
58 #include <private/gui/ComposerService.h>
59 #include <private/gui/ComposerServiceAIDL.h>
60
61 // This server size should always be smaller than the server cache size
62 #define BUFFER_CACHE_MAX_SIZE 4096
63
64 namespace android {
65
66 using aidl::android::hardware::graphics::common::DisplayDecorationSupport;
67 using gui::FocusRequest;
68 using gui::IRegionSamplingListener;
69 using gui::TrustedPresentationThresholds;
70 using gui::WindowInfo;
71 using gui::WindowInfoHandle;
72 using gui::WindowInfosListener;
73 using gui::aidl_utils::statusTFromBinderStatus;
74 using ui::ColorMode;
75 // ---------------------------------------------------------------------------
76
77 ANDROID_SINGLETON_STATIC_INSTANCE(ComposerService);
78 ANDROID_SINGLETON_STATIC_INSTANCE(ComposerServiceAIDL);
79
80 namespace {
81 // Initialize transaction id counter used to generate transaction ids
82 std::atomic<uint32_t> idCounter = 0;
generateId()83 int64_t generateId() {
84 return (((int64_t)getpid()) << 32) | ++idCounter;
85 }
86
emptyCallback(nsecs_t,const sp<Fence> &,const std::vector<SurfaceControlStats> &)87 void emptyCallback(nsecs_t, const sp<Fence>&, const std::vector<SurfaceControlStats>&) {}
88 } // namespace
89
ComposerService()90 ComposerService::ComposerService()
91 : Singleton<ComposerService>() {
92 Mutex::Autolock _l(mLock);
93 connectLocked();
94 }
95
connectLocked()96 bool ComposerService::connectLocked() {
97 const String16 name("SurfaceFlinger");
98 mComposerService = waitForService<ISurfaceComposer>(name);
99 if (mComposerService == nullptr) {
100 return false; // fatal error or permission problem
101 }
102
103 // Create the death listener.
104 class DeathObserver : public IBinder::DeathRecipient {
105 ComposerService& mComposerService;
106 virtual void binderDied(const wp<IBinder>& who) {
107 ALOGW("ComposerService remote (surfaceflinger) died [%p]",
108 who.unsafe_get());
109 mComposerService.composerServiceDied();
110 }
111 public:
112 explicit DeathObserver(ComposerService& mgr) : mComposerService(mgr) { }
113 };
114
115 mDeathObserver = new DeathObserver(*const_cast<ComposerService*>(this));
116 IInterface::asBinder(mComposerService)->linkToDeath(mDeathObserver);
117 return true;
118 }
119
getComposerService()120 /*static*/ sp<ISurfaceComposer> ComposerService::getComposerService() {
121 ComposerService& instance = ComposerService::getInstance();
122 Mutex::Autolock _l(instance.mLock);
123 if (instance.mComposerService == nullptr) {
124 if (ComposerService::getInstance().connectLocked()) {
125 ALOGD("ComposerService reconnected");
126 }
127 }
128 return instance.mComposerService;
129 }
130
composerServiceDied()131 void ComposerService::composerServiceDied()
132 {
133 Mutex::Autolock _l(mLock);
134 mComposerService = nullptr;
135 mDeathObserver = nullptr;
136 }
137
ComposerServiceAIDL()138 ComposerServiceAIDL::ComposerServiceAIDL() : Singleton<ComposerServiceAIDL>() {
139 std::scoped_lock lock(mMutex);
140 connectLocked();
141 }
142
connectLocked()143 bool ComposerServiceAIDL::connectLocked() {
144 const String16 name("SurfaceFlingerAIDL");
145 mComposerService = waitForService<gui::ISurfaceComposer>(name);
146 if (mComposerService == nullptr) {
147 return false; // fatal error or permission problem
148 }
149
150 // Create the death listener.
151 class DeathObserver : public IBinder::DeathRecipient {
152 ComposerServiceAIDL& mComposerService;
153 virtual void binderDied(const wp<IBinder>& who) {
154 ALOGW("ComposerService aidl remote (surfaceflinger) died [%p]", who.unsafe_get());
155 mComposerService.composerServiceDied();
156 }
157
158 public:
159 explicit DeathObserver(ComposerServiceAIDL& mgr) : mComposerService(mgr) {}
160 };
161
162 mDeathObserver = new DeathObserver(*const_cast<ComposerServiceAIDL*>(this));
163 IInterface::asBinder(mComposerService)->linkToDeath(mDeathObserver);
164 return true;
165 }
166
getComposerService()167 /*static*/ sp<gui::ISurfaceComposer> ComposerServiceAIDL::getComposerService() {
168 ComposerServiceAIDL& instance = ComposerServiceAIDL::getInstance();
169 std::scoped_lock lock(instance.mMutex);
170 if (instance.mComposerService == nullptr) {
171 if (ComposerServiceAIDL::getInstance().connectLocked()) {
172 ALOGD("ComposerServiceAIDL reconnected");
173 WindowInfosListenerReporter::getInstance()->reconnect(instance.mComposerService);
174 }
175 }
176 return instance.mComposerService;
177 }
178
composerServiceDied()179 void ComposerServiceAIDL::composerServiceDied() {
180 std::scoped_lock lock(mMutex);
181 mComposerService = nullptr;
182 mDeathObserver = nullptr;
183 }
184
185 class DefaultComposerClient: public Singleton<DefaultComposerClient> {
186 Mutex mLock;
187 sp<SurfaceComposerClient> mClient;
188 friend class Singleton<ComposerService>;
189 public:
getComposerClient()190 static sp<SurfaceComposerClient> getComposerClient() {
191 DefaultComposerClient& dc = DefaultComposerClient::getInstance();
192 Mutex::Autolock _l(dc.mLock);
193 if (dc.mClient == nullptr) {
194 dc.mClient = new SurfaceComposerClient;
195 }
196 return dc.mClient;
197 }
198 };
199 ANDROID_SINGLETON_STATIC_INSTANCE(DefaultComposerClient);
200
201
getDefault()202 sp<SurfaceComposerClient> SurfaceComposerClient::getDefault() {
203 return DefaultComposerClient::getComposerClient();
204 }
205
~JankDataListener()206 JankDataListener::~JankDataListener() {
207 }
208
209 // ---------------------------------------------------------------------------
210
211 // TransactionCompletedListener does not use ANDROID_SINGLETON_STATIC_INSTANCE because it needs
212 // to be able to return a sp<> to its instance to pass to SurfaceFlinger.
213 // ANDROID_SINGLETON_STATIC_INSTANCE only allows a reference to an instance.
214
215 // 0 is an invalid callback id
TransactionCompletedListener()216 TransactionCompletedListener::TransactionCompletedListener() : mCallbackIdCounter(1) {}
217
getNextIdLocked()218 int64_t TransactionCompletedListener::getNextIdLocked() {
219 return mCallbackIdCounter++;
220 }
221
222 sp<TransactionCompletedListener> TransactionCompletedListener::sInstance = nullptr;
223 static std::mutex sListenerInstanceMutex;
224
setInstance(const sp<TransactionCompletedListener> & listener)225 void TransactionCompletedListener::setInstance(const sp<TransactionCompletedListener>& listener) {
226 sInstance = listener;
227 }
228
getInstance()229 sp<TransactionCompletedListener> TransactionCompletedListener::getInstance() {
230 std::lock_guard<std::mutex> lock(sListenerInstanceMutex);
231 if (sInstance == nullptr) {
232 sInstance = new TransactionCompletedListener;
233 }
234 return sInstance;
235 }
236
getIInstance()237 sp<ITransactionCompletedListener> TransactionCompletedListener::getIInstance() {
238 return static_cast<sp<ITransactionCompletedListener>>(getInstance());
239 }
240
startListeningLocked()241 void TransactionCompletedListener::startListeningLocked() {
242 if (mListening) {
243 return;
244 }
245 ProcessState::self()->startThreadPool();
246 mListening = true;
247 }
248
addCallbackFunction(const TransactionCompletedCallback & callbackFunction,const std::unordered_set<sp<SurfaceControl>,SurfaceComposerClient::SCHash> & surfaceControls,CallbackId::Type callbackType)249 CallbackId TransactionCompletedListener::addCallbackFunction(
250 const TransactionCompletedCallback& callbackFunction,
251 const std::unordered_set<sp<SurfaceControl>, SurfaceComposerClient::SCHash>&
252 surfaceControls,
253 CallbackId::Type callbackType) {
254 std::lock_guard<std::mutex> lock(mMutex);
255 return addCallbackFunctionLocked(callbackFunction, surfaceControls, callbackType);
256 }
257
addCallbackFunctionLocked(const TransactionCompletedCallback & callbackFunction,const std::unordered_set<sp<SurfaceControl>,SurfaceComposerClient::SCHash> & surfaceControls,CallbackId::Type callbackType)258 CallbackId TransactionCompletedListener::addCallbackFunctionLocked(
259 const TransactionCompletedCallback& callbackFunction,
260 const std::unordered_set<sp<SurfaceControl>, SurfaceComposerClient::SCHash>&
261 surfaceControls,
262 CallbackId::Type callbackType) {
263 startListeningLocked();
264
265 CallbackId callbackId(getNextIdLocked(), callbackType);
266 mCallbacks[callbackId].callbackFunction = callbackFunction;
267 auto& callbackSurfaceControls = mCallbacks[callbackId].surfaceControls;
268
269 for (const auto& surfaceControl : surfaceControls) {
270 callbackSurfaceControls[surfaceControl->getHandle()] = surfaceControl;
271
272 if (callbackType == CallbackId::Type::ON_COMPLETE &&
273 mJankListeners.count(surfaceControl->getLayerId()) != 0) {
274 callbackId.includeJankData = true;
275 }
276 }
277
278 return callbackId;
279 }
280
addJankListener(const sp<JankDataListener> & listener,sp<SurfaceControl> surfaceControl)281 void TransactionCompletedListener::addJankListener(const sp<JankDataListener>& listener,
282 sp<SurfaceControl> surfaceControl) {
283 std::lock_guard<std::mutex> lock(mMutex);
284 mJankListeners.insert({surfaceControl->getLayerId(), listener});
285 }
286
removeJankListener(const sp<JankDataListener> & listener)287 void TransactionCompletedListener::removeJankListener(const sp<JankDataListener>& listener) {
288 std::lock_guard<std::mutex> lock(mMutex);
289 for (auto it = mJankListeners.begin(); it != mJankListeners.end();) {
290 if (it->second == listener) {
291 it = mJankListeners.erase(it);
292 } else {
293 it++;
294 }
295 }
296 }
297
setReleaseBufferCallback(const ReleaseCallbackId & callbackId,ReleaseBufferCallback listener)298 void TransactionCompletedListener::setReleaseBufferCallback(const ReleaseCallbackId& callbackId,
299 ReleaseBufferCallback listener) {
300 std::scoped_lock<std::mutex> lock(mMutex);
301 mReleaseBufferCallbacks[callbackId] = listener;
302 }
303
addSurfaceStatsListener(void * context,void * cookie,sp<SurfaceControl> surfaceControl,SurfaceStatsCallback listener)304 void TransactionCompletedListener::addSurfaceStatsListener(void* context, void* cookie,
305 sp<SurfaceControl> surfaceControl, SurfaceStatsCallback listener) {
306 std::scoped_lock<std::recursive_mutex> lock(mSurfaceStatsListenerMutex);
307 mSurfaceStatsListeners.insert(
308 {surfaceControl->getLayerId(), SurfaceStatsCallbackEntry(context, cookie, listener)});
309 }
310
removeSurfaceStatsListener(void * context,void * cookie)311 void TransactionCompletedListener::removeSurfaceStatsListener(void* context, void* cookie) {
312 std::scoped_lock<std::recursive_mutex> lock(mSurfaceStatsListenerMutex);
313 for (auto it = mSurfaceStatsListeners.begin(); it != mSurfaceStatsListeners.end();) {
314 auto [itContext, itCookie, itListener] = it->second;
315 if (itContext == context && itCookie == cookie) {
316 it = mSurfaceStatsListeners.erase(it);
317 } else {
318 it++;
319 }
320 }
321 }
322
addSurfaceControlToCallbacks(SurfaceComposerClient::CallbackInfo & callbackInfo,const sp<SurfaceControl> & surfaceControl)323 void TransactionCompletedListener::addSurfaceControlToCallbacks(
324 SurfaceComposerClient::CallbackInfo& callbackInfo,
325 const sp<SurfaceControl>& surfaceControl) {
326 std::lock_guard<std::mutex> lock(mMutex);
327
328 bool includingJankData = false;
329 for (auto callbackId : callbackInfo.callbackIds) {
330 mCallbacks[callbackId].surfaceControls.emplace(std::piecewise_construct,
331 std::forward_as_tuple(
332 surfaceControl->getHandle()),
333 std::forward_as_tuple(surfaceControl));
334 includingJankData = includingJankData || callbackId.includeJankData;
335 }
336
337 // If no registered callback is requesting jank data, but there is a jank listener registered
338 // on the new surface control, add a synthetic callback that requests the jank data.
339 if (!includingJankData && mJankListeners.count(surfaceControl->getLayerId()) != 0) {
340 CallbackId callbackId =
341 addCallbackFunctionLocked(&emptyCallback, callbackInfo.surfaceControls,
342 CallbackId::Type::ON_COMPLETE);
343 callbackInfo.callbackIds.emplace(callbackId);
344 }
345 }
346
onTransactionCompleted(ListenerStats listenerStats)347 void TransactionCompletedListener::onTransactionCompleted(ListenerStats listenerStats) {
348 std::unordered_map<CallbackId, CallbackTranslation, CallbackIdHash> callbacksMap;
349 std::multimap<int32_t, sp<JankDataListener>> jankListenersMap;
350 {
351 std::lock_guard<std::mutex> lock(mMutex);
352
353 /* This listener knows all the sp<IBinder> to sp<SurfaceControl> for all its registered
354 * callbackIds, except for when Transactions are merged together. This probably cannot be
355 * solved before this point because the Transactions could be merged together and applied in
356 * a different process.
357 *
358 * Fortunately, we get all the callbacks for this listener for the same frame together at
359 * the same time. This means if any Transactions were merged together, we will get their
360 * callbacks at the same time. We can combine all the sp<IBinder> to sp<SurfaceControl> maps
361 * for all the callbackIds to generate one super map that contains all the sp<IBinder> to
362 * sp<SurfaceControl> that could possibly exist for the callbacks.
363 */
364 callbacksMap = mCallbacks;
365 jankListenersMap = mJankListeners;
366 for (const auto& transactionStats : listenerStats.transactionStats) {
367 for (auto& callbackId : transactionStats.callbackIds) {
368 mCallbacks.erase(callbackId);
369 }
370 }
371 }
372 for (const auto& transactionStats : listenerStats.transactionStats) {
373 // handle on commit callbacks
374 for (auto callbackId : transactionStats.callbackIds) {
375 if (callbackId.type != CallbackId::Type::ON_COMMIT) {
376 continue;
377 }
378 auto& [callbackFunction, callbackSurfaceControls] = callbacksMap[callbackId];
379 if (!callbackFunction) {
380 ALOGE("cannot call null callback function, skipping");
381 continue;
382 }
383 std::vector<SurfaceControlStats> surfaceControlStats;
384 for (const auto& surfaceStats : transactionStats.surfaceStats) {
385 surfaceControlStats
386 .emplace_back(callbacksMap[callbackId]
387 .surfaceControls[surfaceStats.surfaceControl],
388 transactionStats.latchTime, surfaceStats.acquireTimeOrFence,
389 transactionStats.presentFence,
390 surfaceStats.previousReleaseFence, surfaceStats.transformHint,
391 surfaceStats.eventStats,
392 surfaceStats.currentMaxAcquiredBufferCount);
393 }
394
395 callbackFunction(transactionStats.latchTime, transactionStats.presentFence,
396 surfaceControlStats);
397 }
398
399 // handle on complete callbacks
400 for (auto callbackId : transactionStats.callbackIds) {
401 if (callbackId.type != CallbackId::Type::ON_COMPLETE) {
402 continue;
403 }
404 auto& [callbackFunction, callbackSurfaceControls] = callbacksMap[callbackId];
405 if (!callbackFunction) {
406 ALOGE("cannot call null callback function, skipping");
407 continue;
408 }
409 std::vector<SurfaceControlStats> surfaceControlStats;
410 for (const auto& surfaceStats : transactionStats.surfaceStats) {
411 surfaceControlStats
412 .emplace_back(callbacksMap[callbackId]
413 .surfaceControls[surfaceStats.surfaceControl],
414 transactionStats.latchTime, surfaceStats.acquireTimeOrFence,
415 transactionStats.presentFence,
416 surfaceStats.previousReleaseFence, surfaceStats.transformHint,
417 surfaceStats.eventStats,
418 surfaceStats.currentMaxAcquiredBufferCount);
419 if (callbacksMap[callbackId].surfaceControls[surfaceStats.surfaceControl] &&
420 surfaceStats.transformHint.has_value()) {
421 callbacksMap[callbackId]
422 .surfaceControls[surfaceStats.surfaceControl]
423 ->setTransformHint(*surfaceStats.transformHint);
424 }
425 // If there is buffer id set, we look up any pending client release buffer callbacks
426 // and call them. This is a performance optimization when we have a transaction
427 // callback and a release buffer callback happening at the same time to avoid an
428 // additional ipc call from the server.
429 if (surfaceStats.previousReleaseCallbackId != ReleaseCallbackId::INVALID_ID) {
430 ReleaseBufferCallback callback;
431 {
432 std::scoped_lock<std::mutex> lock(mMutex);
433 callback = popReleaseBufferCallbackLocked(
434 surfaceStats.previousReleaseCallbackId);
435 }
436 if (callback) {
437 callback(surfaceStats.previousReleaseCallbackId,
438 surfaceStats.previousReleaseFence
439 ? surfaceStats.previousReleaseFence
440 : Fence::NO_FENCE,
441 surfaceStats.currentMaxAcquiredBufferCount);
442 }
443 }
444 }
445
446 callbackFunction(transactionStats.latchTime, transactionStats.presentFence,
447 surfaceControlStats);
448 }
449
450 for (const auto& surfaceStats : transactionStats.surfaceStats) {
451 // The callbackMap contains the SurfaceControl object, which we need to look up the
452 // layerId. Since we don't know which callback contains the SurfaceControl, iterate
453 // through all until the SC is found.
454 int32_t layerId = -1;
455 for (auto callbackId : transactionStats.callbackIds) {
456 if (callbackId.type != CallbackId::Type::ON_COMPLETE) {
457 // We only want to run the stats callback for ON_COMPLETE
458 continue;
459 }
460 sp<SurfaceControl> sc =
461 callbacksMap[callbackId].surfaceControls[surfaceStats.surfaceControl];
462 if (sc != nullptr) {
463 layerId = sc->getLayerId();
464 break;
465 }
466 }
467
468 if (layerId != -1) {
469 // Acquire surface stats listener lock such that we guarantee that after calling
470 // unregister, there won't be any further callback.
471 std::scoped_lock<std::recursive_mutex> lock(mSurfaceStatsListenerMutex);
472 auto listenerRange = mSurfaceStatsListeners.equal_range(layerId);
473 for (auto it = listenerRange.first; it != listenerRange.second; it++) {
474 auto entry = it->second;
475 entry.callback(entry.context, transactionStats.latchTime,
476 transactionStats.presentFence, surfaceStats);
477 }
478 }
479
480 if (surfaceStats.jankData.empty()) continue;
481 auto jankRange = jankListenersMap.equal_range(layerId);
482 for (auto it = jankRange.first; it != jankRange.second; it++) {
483 it->second->onJankDataAvailable(surfaceStats.jankData);
484 }
485 }
486 }
487 }
488
onTransactionQueueStalled(const String8 & reason)489 void TransactionCompletedListener::onTransactionQueueStalled(const String8& reason) {
490 std::unordered_map<void*, std::function<void(const std::string&)>> callbackCopy;
491 {
492 std::scoped_lock<std::mutex> lock(mMutex);
493 callbackCopy = mQueueStallListeners;
494 }
495 for (auto const& it : callbackCopy) {
496 it.second(reason.c_str());
497 }
498 }
499
addQueueStallListener(std::function<void (const std::string &)> stallListener,void * id)500 void TransactionCompletedListener::addQueueStallListener(
501 std::function<void(const std::string&)> stallListener, void* id) {
502 std::scoped_lock<std::mutex> lock(mMutex);
503 mQueueStallListeners[id] = stallListener;
504 }
505
removeQueueStallListener(void * id)506 void TransactionCompletedListener::removeQueueStallListener(void* id) {
507 std::scoped_lock<std::mutex> lock(mMutex);
508 mQueueStallListeners.erase(id);
509 }
510
onReleaseBuffer(ReleaseCallbackId callbackId,sp<Fence> releaseFence,uint32_t currentMaxAcquiredBufferCount)511 void TransactionCompletedListener::onReleaseBuffer(ReleaseCallbackId callbackId,
512 sp<Fence> releaseFence,
513 uint32_t currentMaxAcquiredBufferCount) {
514 ReleaseBufferCallback callback;
515 {
516 std::scoped_lock<std::mutex> lock(mMutex);
517 callback = popReleaseBufferCallbackLocked(callbackId);
518 }
519 if (!callback) {
520 ALOGE("Could not call release buffer callback, buffer not found %s",
521 callbackId.to_string().c_str());
522 return;
523 }
524 std::optional<uint32_t> optionalMaxAcquiredBufferCount =
525 currentMaxAcquiredBufferCount == UINT_MAX
526 ? std::nullopt
527 : std::make_optional<uint32_t>(currentMaxAcquiredBufferCount);
528 callback(callbackId, releaseFence, optionalMaxAcquiredBufferCount);
529 }
530
popReleaseBufferCallbackLocked(const ReleaseCallbackId & callbackId)531 ReleaseBufferCallback TransactionCompletedListener::popReleaseBufferCallbackLocked(
532 const ReleaseCallbackId& callbackId) {
533 ReleaseBufferCallback callback;
534 auto itr = mReleaseBufferCallbacks.find(callbackId);
535 if (itr == mReleaseBufferCallbacks.end()) {
536 return nullptr;
537 }
538 callback = itr->second;
539 mReleaseBufferCallbacks.erase(itr);
540 return callback;
541 }
542
removeReleaseBufferCallback(const ReleaseCallbackId & callbackId)543 void TransactionCompletedListener::removeReleaseBufferCallback(
544 const ReleaseCallbackId& callbackId) {
545 {
546 std::scoped_lock<std::mutex> lock(mMutex);
547 popReleaseBufferCallbackLocked(callbackId);
548 }
549 }
550
PresentationCallbackRAII(TransactionCompletedListener * tcl,int id)551 SurfaceComposerClient::PresentationCallbackRAII::PresentationCallbackRAII(
552 TransactionCompletedListener* tcl, int id) {
553 mTcl = tcl;
554 mId = id;
555 }
556
~PresentationCallbackRAII()557 SurfaceComposerClient::PresentationCallbackRAII::~PresentationCallbackRAII() {
558 mTcl->clearTrustedPresentationCallback(mId);
559 }
560
561 sp<SurfaceComposerClient::PresentationCallbackRAII>
addTrustedPresentationCallback(TrustedPresentationCallback tpc,int id,void * context)562 TransactionCompletedListener::addTrustedPresentationCallback(TrustedPresentationCallback tpc,
563 int id, void* context) {
564 std::scoped_lock<std::mutex> lock(mMutex);
565 mTrustedPresentationCallbacks[id] =
566 std::tuple<TrustedPresentationCallback, void*>(tpc, context);
567 return new SurfaceComposerClient::PresentationCallbackRAII(this, id);
568 }
569
clearTrustedPresentationCallback(int id)570 void TransactionCompletedListener::clearTrustedPresentationCallback(int id) {
571 std::scoped_lock<std::mutex> lock(mMutex);
572 mTrustedPresentationCallbacks.erase(id);
573 }
574
onTrustedPresentationChanged(int id,bool presentedWithinThresholds)575 void TransactionCompletedListener::onTrustedPresentationChanged(int id,
576 bool presentedWithinThresholds) {
577 TrustedPresentationCallback tpc;
578 void* context;
579 {
580 std::scoped_lock<std::mutex> lock(mMutex);
581 auto it = mTrustedPresentationCallbacks.find(id);
582 if (it == mTrustedPresentationCallbacks.end()) {
583 return;
584 }
585 std::tie(tpc, context) = it->second;
586 }
587 tpc(context, presentedWithinThresholds);
588 }
589
590 // ---------------------------------------------------------------------------
591
592 void removeDeadBufferCallback(void* /*context*/, uint64_t graphicBufferId);
593
594 /**
595 * We use the BufferCache to reduce the overhead of exchanging GraphicBuffers with
596 * the server. If we were to simply parcel the GraphicBuffer we would pay two overheads
597 * 1. Cost of sending the FD
598 * 2. Cost of importing the GraphicBuffer with the mapper in the receiving process.
599 * To ease this cost we implement the following scheme of caching buffers to integers,
600 * or said-otherwise, naming them with integers. This is the scheme known as slots in
601 * the legacy BufferQueue system.
602 * 1. When sending Buffers to SurfaceFlinger we look up the Buffer in the cache.
603 * 2. If there is a cache-hit we remove the Buffer from the Transaction and instead
604 * send the cached integer.
605 * 3. If there is a cache miss, we cache the new buffer and send the integer
606 * along with the Buffer, SurfaceFlinger on it's side creates a new cache
607 * entry, and we use the integer for further communication.
608 * A few details about lifetime:
609 * 1. The cache evicts by LRU. The server side cache is keyed by BufferCache::getToken
610 * which is per process Unique. The server side cache is larger than the client side
611 * cache so that the server will never evict entries before the client.
612 * 2. When the client evicts an entry it notifies the server via an uncacheBuffer
613 * transaction.
614 * 3. The client only references the Buffers by ID, and uses buffer->addDeathCallback
615 * to auto-evict destroyed buffers.
616 */
617 class BufferCache : public Singleton<BufferCache> {
618 public:
BufferCache()619 BufferCache() : token(new BBinder()) {}
620
getToken()621 sp<IBinder> getToken() {
622 return IInterface::asBinder(TransactionCompletedListener::getIInstance());
623 }
624
getCacheId(const sp<GraphicBuffer> & buffer,uint64_t * cacheId)625 status_t getCacheId(const sp<GraphicBuffer>& buffer, uint64_t* cacheId) {
626 std::lock_guard<std::mutex> lock(mMutex);
627
628 auto itr = mBuffers.find(buffer->getId());
629 if (itr == mBuffers.end()) {
630 return BAD_VALUE;
631 }
632 itr->second = getCounter();
633 *cacheId = buffer->getId();
634 return NO_ERROR;
635 }
636
cache(const sp<GraphicBuffer> & buffer,std::optional<client_cache_t> & outUncacheBuffer)637 uint64_t cache(const sp<GraphicBuffer>& buffer,
638 std::optional<client_cache_t>& outUncacheBuffer) {
639 std::lock_guard<std::mutex> lock(mMutex);
640
641 if (mBuffers.size() >= BUFFER_CACHE_MAX_SIZE) {
642 outUncacheBuffer = findLeastRecentlyUsedBuffer();
643 mBuffers.erase(outUncacheBuffer->id);
644 }
645
646 buffer->addDeathCallback(removeDeadBufferCallback, nullptr);
647
648 mBuffers[buffer->getId()] = getCounter();
649 return buffer->getId();
650 }
651
uncache(uint64_t cacheId)652 void uncache(uint64_t cacheId) {
653 std::lock_guard<std::mutex> lock(mMutex);
654 if (mBuffers.erase(cacheId)) {
655 SurfaceComposerClient::doUncacheBufferTransaction(cacheId);
656 }
657 }
658
659 private:
findLeastRecentlyUsedBuffer()660 client_cache_t findLeastRecentlyUsedBuffer() REQUIRES(mMutex) {
661 auto itr = mBuffers.begin();
662 uint64_t minCounter = itr->second;
663 auto minBuffer = itr;
664 itr++;
665
666 while (itr != mBuffers.end()) {
667 uint64_t counter = itr->second;
668 if (counter < minCounter) {
669 minCounter = counter;
670 minBuffer = itr;
671 }
672 itr++;
673 }
674
675 return {.token = getToken(), .id = minBuffer->first};
676 }
677
getCounter()678 uint64_t getCounter() REQUIRES(mMutex) {
679 static uint64_t counter = 0;
680 return counter++;
681 }
682
683 std::mutex mMutex;
684 std::map<uint64_t /*Cache id*/, uint64_t /*counter*/> mBuffers GUARDED_BY(mMutex);
685
686 // Used by ISurfaceComposer to identify which process is sending the cached buffer.
687 sp<IBinder> token;
688 };
689
690 ANDROID_SINGLETON_STATIC_INSTANCE(BufferCache);
691
removeDeadBufferCallback(void *,uint64_t graphicBufferId)692 void removeDeadBufferCallback(void* /*context*/, uint64_t graphicBufferId) {
693 // GraphicBuffer id's are used as the cache ids.
694 BufferCache::getInstance().uncache(graphicBufferId);
695 }
696
697 // ---------------------------------------------------------------------------
698
Transaction()699 SurfaceComposerClient::Transaction::Transaction() {
700 mId = generateId();
701 }
702
Transaction(const Transaction & other)703 SurfaceComposerClient::Transaction::Transaction(const Transaction& other)
704 : mId(other.mId),
705 mTransactionNestCount(other.mTransactionNestCount),
706 mAnimation(other.mAnimation),
707 mEarlyWakeupStart(other.mEarlyWakeupStart),
708 mEarlyWakeupEnd(other.mEarlyWakeupEnd),
709 mMayContainBuffer(other.mMayContainBuffer),
710 mDesiredPresentTime(other.mDesiredPresentTime),
711 mIsAutoTimestamp(other.mIsAutoTimestamp),
712 mFrameTimelineInfo(other.mFrameTimelineInfo),
713 mApplyToken(other.mApplyToken) {
714 mDisplayStates = other.mDisplayStates;
715 mComposerStates = other.mComposerStates;
716 mInputWindowCommands = other.mInputWindowCommands;
717 mListenerCallbacks = other.mListenerCallbacks;
718 }
719
sanitize(int pid,int uid)720 void SurfaceComposerClient::Transaction::sanitize(int pid, int uid) {
721 uint32_t permissions = LayerStatePermissions::getTransactionPermissions(pid, uid);
722 for (auto & [handle, composerState] : mComposerStates) {
723 composerState.state.sanitize(permissions);
724 }
725 if (!mInputWindowCommands.empty() &&
726 (permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) == 0) {
727 ALOGE("Only privileged callers are allowed to send input commands.");
728 mInputWindowCommands.clear();
729 }
730 }
731
732 std::unique_ptr<SurfaceComposerClient::Transaction>
createFromParcel(const Parcel * parcel)733 SurfaceComposerClient::Transaction::createFromParcel(const Parcel* parcel) {
734 auto transaction = std::make_unique<Transaction>();
735 if (transaction->readFromParcel(parcel) == NO_ERROR) {
736 return transaction;
737 }
738 return nullptr;
739 }
740
741
readFromParcel(const Parcel * parcel)742 status_t SurfaceComposerClient::Transaction::readFromParcel(const Parcel* parcel) {
743 const uint64_t transactionId = parcel->readUint64();
744 const uint32_t transactionNestCount = parcel->readUint32();
745 const bool animation = parcel->readBool();
746 const bool earlyWakeupStart = parcel->readBool();
747 const bool earlyWakeupEnd = parcel->readBool();
748 const int64_t desiredPresentTime = parcel->readInt64();
749 const bool isAutoTimestamp = parcel->readBool();
750 FrameTimelineInfo frameTimelineInfo;
751 frameTimelineInfo.readFromParcel(parcel);
752
753 sp<IBinder> applyToken;
754 parcel->readNullableStrongBinder(&applyToken);
755 size_t count = static_cast<size_t>(parcel->readUint32());
756 if (count > parcel->dataSize()) {
757 return BAD_VALUE;
758 }
759 SortedVector<DisplayState> displayStates;
760 displayStates.setCapacity(count);
761 for (size_t i = 0; i < count; i++) {
762 DisplayState displayState;
763 if (displayState.read(*parcel) == BAD_VALUE) {
764 return BAD_VALUE;
765 }
766 displayStates.add(displayState);
767 }
768
769 count = static_cast<size_t>(parcel->readUint32());
770 if (count > parcel->dataSize()) {
771 return BAD_VALUE;
772 }
773 std::unordered_map<sp<ITransactionCompletedListener>, CallbackInfo, TCLHash> listenerCallbacks;
774 listenerCallbacks.reserve(count);
775 for (size_t i = 0; i < count; i++) {
776 sp<ITransactionCompletedListener> listener =
777 interface_cast<ITransactionCompletedListener>(parcel->readStrongBinder());
778 size_t numCallbackIds = parcel->readUint32();
779 if (numCallbackIds > parcel->dataSize()) {
780 return BAD_VALUE;
781 }
782 for (size_t j = 0; j < numCallbackIds; j++) {
783 CallbackId id;
784 parcel->readParcelable(&id);
785 listenerCallbacks[listener].callbackIds.insert(id);
786 }
787 size_t numSurfaces = parcel->readUint32();
788 if (numSurfaces > parcel->dataSize()) {
789 return BAD_VALUE;
790 }
791 for (size_t j = 0; j < numSurfaces; j++) {
792 sp<SurfaceControl> surface;
793 SAFE_PARCEL(SurfaceControl::readFromParcel, *parcel, &surface);
794 listenerCallbacks[listener].surfaceControls.insert(surface);
795 }
796 }
797
798 count = static_cast<size_t>(parcel->readUint32());
799 if (count > parcel->dataSize()) {
800 return BAD_VALUE;
801 }
802 std::unordered_map<sp<IBinder>, ComposerState, IBinderHash> composerStates;
803 composerStates.reserve(count);
804 for (size_t i = 0; i < count; i++) {
805 sp<IBinder> surfaceControlHandle;
806 SAFE_PARCEL(parcel->readStrongBinder, &surfaceControlHandle);
807
808 ComposerState composerState;
809 if (composerState.read(*parcel) == BAD_VALUE) {
810 return BAD_VALUE;
811 }
812 composerStates[surfaceControlHandle] = composerState;
813 }
814
815 InputWindowCommands inputWindowCommands;
816 inputWindowCommands.read(*parcel);
817
818 count = static_cast<size_t>(parcel->readUint32());
819 if (count > parcel->dataSize()) {
820 return BAD_VALUE;
821 }
822 std::vector<client_cache_t> uncacheBuffers(count);
823 for (size_t i = 0; i < count; i++) {
824 sp<IBinder> tmpBinder;
825 SAFE_PARCEL(parcel->readStrongBinder, &tmpBinder);
826 uncacheBuffers[i].token = tmpBinder;
827 SAFE_PARCEL(parcel->readUint64, &uncacheBuffers[i].id);
828 }
829
830 count = static_cast<size_t>(parcel->readUint32());
831 if (count > parcel->dataSize()) {
832 return BAD_VALUE;
833 }
834 std::vector<uint64_t> mergedTransactionIds(count);
835 for (size_t i = 0; i < count; i++) {
836 SAFE_PARCEL(parcel->readUint64, &mergedTransactionIds[i]);
837 }
838
839 // Parsing was successful. Update the object.
840 mId = transactionId;
841 mTransactionNestCount = transactionNestCount;
842 mAnimation = animation;
843 mEarlyWakeupStart = earlyWakeupStart;
844 mEarlyWakeupEnd = earlyWakeupEnd;
845 mDesiredPresentTime = desiredPresentTime;
846 mIsAutoTimestamp = isAutoTimestamp;
847 mFrameTimelineInfo = frameTimelineInfo;
848 mDisplayStates = displayStates;
849 mListenerCallbacks = listenerCallbacks;
850 mComposerStates = composerStates;
851 mInputWindowCommands = inputWindowCommands;
852 mApplyToken = applyToken;
853 mUncacheBuffers = std::move(uncacheBuffers);
854 mMergedTransactionIds = std::move(mergedTransactionIds);
855 return NO_ERROR;
856 }
857
writeToParcel(Parcel * parcel) const858 status_t SurfaceComposerClient::Transaction::writeToParcel(Parcel* parcel) const {
859 // If we write the Transaction to a parcel, we want to ensure the Buffers are cached
860 // before crossing the IPC boundary. Otherwise the receiving party will cache the buffers
861 // but is unlikely to use them again as they are owned by the other process.
862 // You may be asking yourself, is this const cast safe? Const cast is safe up
863 // until the point where you try and write to an object that was originally const at which
864 // point we enter undefined behavior. In this case we are safe though, because there are
865 // two possibilities:
866 // 1. The SurfaceComposerClient::Transaction was originally non-const. Safe.
867 // 2. It was originall const! In this case not only was it useless, but it by definition
868 // contains no composer states and so cacheBuffers will not perform any writes.
869
870 const_cast<SurfaceComposerClient::Transaction*>(this)->cacheBuffers();
871
872 parcel->writeUint64(mId);
873 parcel->writeUint32(mTransactionNestCount);
874 parcel->writeBool(mAnimation);
875 parcel->writeBool(mEarlyWakeupStart);
876 parcel->writeBool(mEarlyWakeupEnd);
877 parcel->writeInt64(mDesiredPresentTime);
878 parcel->writeBool(mIsAutoTimestamp);
879 mFrameTimelineInfo.writeToParcel(parcel);
880 parcel->writeStrongBinder(mApplyToken);
881 parcel->writeUint32(static_cast<uint32_t>(mDisplayStates.size()));
882 for (auto const& displayState : mDisplayStates) {
883 displayState.write(*parcel);
884 }
885
886 parcel->writeUint32(static_cast<uint32_t>(mListenerCallbacks.size()));
887 for (auto const& [listener, callbackInfo] : mListenerCallbacks) {
888 parcel->writeStrongBinder(ITransactionCompletedListener::asBinder(listener));
889 parcel->writeUint32(static_cast<uint32_t>(callbackInfo.callbackIds.size()));
890 for (auto callbackId : callbackInfo.callbackIds) {
891 parcel->writeParcelable(callbackId);
892 }
893 parcel->writeUint32(static_cast<uint32_t>(callbackInfo.surfaceControls.size()));
894 for (auto surfaceControl : callbackInfo.surfaceControls) {
895 SAFE_PARCEL(surfaceControl->writeToParcel, *parcel);
896 }
897 }
898
899 parcel->writeUint32(static_cast<uint32_t>(mComposerStates.size()));
900 for (auto const& [handle, composerState] : mComposerStates) {
901 SAFE_PARCEL(parcel->writeStrongBinder, handle);
902 composerState.write(*parcel);
903 }
904
905 mInputWindowCommands.write(*parcel);
906
907 SAFE_PARCEL(parcel->writeUint32, static_cast<uint32_t>(mUncacheBuffers.size()));
908 for (const client_cache_t& uncacheBuffer : mUncacheBuffers) {
909 SAFE_PARCEL(parcel->writeStrongBinder, uncacheBuffer.token.promote());
910 SAFE_PARCEL(parcel->writeUint64, uncacheBuffer.id);
911 }
912
913 SAFE_PARCEL(parcel->writeUint32, static_cast<uint32_t>(mMergedTransactionIds.size()));
914 for (auto mergedTransactionId : mMergedTransactionIds) {
915 SAFE_PARCEL(parcel->writeUint64, mergedTransactionId);
916 }
917
918 return NO_ERROR;
919 }
920
releaseBufferIfOverwriting(const layer_state_t & state)921 void SurfaceComposerClient::Transaction::releaseBufferIfOverwriting(const layer_state_t& state) {
922 if (!(state.what & layer_state_t::eBufferChanged) || !state.bufferData->hasBuffer()) {
923 return;
924 }
925
926 auto listener = state.bufferData->releaseBufferListener;
927 sp<Fence> fence =
928 state.bufferData->acquireFence ? state.bufferData->acquireFence : Fence::NO_FENCE;
929 if (state.bufferData->releaseBufferEndpoint ==
930 IInterface::asBinder(TransactionCompletedListener::getIInstance())) {
931 // if the callback is in process, run on a different thread to avoid any lock contigency
932 // issues in the client.
933 SurfaceComposerClient::getDefault()
934 ->mReleaseCallbackThread
935 .addReleaseCallback(state.bufferData->generateReleaseCallbackId(), fence);
936 } else {
937 listener->onReleaseBuffer(state.bufferData->generateReleaseCallbackId(), fence, UINT_MAX);
938 }
939 }
940
merge(Transaction && other)941 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::merge(Transaction&& other) {
942 while (mMergedTransactionIds.size() + other.mMergedTransactionIds.size() >
943 MAX_MERGE_HISTORY_LENGTH - 1 &&
944 mMergedTransactionIds.size() > 0) {
945 mMergedTransactionIds.pop_back();
946 }
947 if (other.mMergedTransactionIds.size() == MAX_MERGE_HISTORY_LENGTH) {
948 mMergedTransactionIds.insert(mMergedTransactionIds.begin(),
949 other.mMergedTransactionIds.begin(),
950 other.mMergedTransactionIds.end() - 1);
951 } else if (other.mMergedTransactionIds.size() > 0u) {
952 mMergedTransactionIds.insert(mMergedTransactionIds.begin(),
953 other.mMergedTransactionIds.begin(),
954 other.mMergedTransactionIds.end());
955 }
956 mMergedTransactionIds.insert(mMergedTransactionIds.begin(), other.mId);
957
958 for (auto const& [handle, composerState] : other.mComposerStates) {
959 if (mComposerStates.count(handle) == 0) {
960 mComposerStates[handle] = composerState;
961 } else {
962 if (composerState.state.what & layer_state_t::eBufferChanged) {
963 releaseBufferIfOverwriting(mComposerStates[handle].state);
964 }
965 mComposerStates[handle].state.merge(composerState.state);
966 }
967 }
968
969 for (auto const& state : other.mDisplayStates) {
970 ssize_t index = mDisplayStates.indexOf(state);
971 if (index < 0) {
972 mDisplayStates.add(state);
973 } else {
974 mDisplayStates.editItemAt(static_cast<size_t>(index)).merge(state);
975 }
976 }
977
978 for (const auto& [listener, callbackInfo] : other.mListenerCallbacks) {
979 auto& [callbackIds, surfaceControls] = callbackInfo;
980 mListenerCallbacks[listener].callbackIds.insert(std::make_move_iterator(
981 callbackIds.begin()),
982 std::make_move_iterator(callbackIds.end()));
983
984 mListenerCallbacks[listener].surfaceControls.insert(surfaceControls.begin(),
985 surfaceControls.end());
986
987 auto& currentProcessCallbackInfo =
988 mListenerCallbacks[TransactionCompletedListener::getIInstance()];
989 currentProcessCallbackInfo.surfaceControls
990 .insert(std::make_move_iterator(surfaceControls.begin()),
991 std::make_move_iterator(surfaceControls.end()));
992
993 // register all surface controls for all callbackIds for this listener that is merging
994 for (const auto& surfaceControl : currentProcessCallbackInfo.surfaceControls) {
995 TransactionCompletedListener::getInstance()
996 ->addSurfaceControlToCallbacks(currentProcessCallbackInfo, surfaceControl);
997 }
998 }
999
1000 for (const auto& cacheId : other.mUncacheBuffers) {
1001 mUncacheBuffers.push_back(cacheId);
1002 }
1003
1004 mInputWindowCommands.merge(other.mInputWindowCommands);
1005
1006 mMayContainBuffer |= other.mMayContainBuffer;
1007 mEarlyWakeupStart = mEarlyWakeupStart || other.mEarlyWakeupStart;
1008 mEarlyWakeupEnd = mEarlyWakeupEnd || other.mEarlyWakeupEnd;
1009 mApplyToken = other.mApplyToken;
1010
1011 mergeFrameTimelineInfo(mFrameTimelineInfo, other.mFrameTimelineInfo);
1012
1013 other.clear();
1014 return *this;
1015 }
1016
clear()1017 void SurfaceComposerClient::Transaction::clear() {
1018 mComposerStates.clear();
1019 mDisplayStates.clear();
1020 mListenerCallbacks.clear();
1021 mInputWindowCommands.clear();
1022 mUncacheBuffers.clear();
1023 mMayContainBuffer = false;
1024 mTransactionNestCount = 0;
1025 mAnimation = false;
1026 mEarlyWakeupStart = false;
1027 mEarlyWakeupEnd = false;
1028 mDesiredPresentTime = 0;
1029 mIsAutoTimestamp = true;
1030 mFrameTimelineInfo = {};
1031 mApplyToken = nullptr;
1032 mMergedTransactionIds.clear();
1033 }
1034
getId()1035 uint64_t SurfaceComposerClient::Transaction::getId() {
1036 return mId;
1037 }
1038
getMergedTransactionIds()1039 std::vector<uint64_t> SurfaceComposerClient::Transaction::getMergedTransactionIds() {
1040 return mMergedTransactionIds;
1041 }
1042
doUncacheBufferTransaction(uint64_t cacheId)1043 void SurfaceComposerClient::doUncacheBufferTransaction(uint64_t cacheId) {
1044 sp<ISurfaceComposer> sf(ComposerService::getComposerService());
1045
1046 client_cache_t uncacheBuffer;
1047 uncacheBuffer.token = BufferCache::getInstance().getToken();
1048 uncacheBuffer.id = cacheId;
1049 Vector<ComposerState> composerStates;
1050 status_t status = sf->setTransactionState(FrameTimelineInfo{}, composerStates, {},
1051 ISurfaceComposer::eOneWay,
1052 Transaction::getDefaultApplyToken(), {}, systemTime(),
1053 true, {uncacheBuffer}, false, {}, generateId(), {});
1054 if (status != NO_ERROR) {
1055 ALOGE_AND_TRACE("SurfaceComposerClient::doUncacheBufferTransaction - %s",
1056 strerror(-status));
1057 }
1058 }
1059
cacheBuffers()1060 void SurfaceComposerClient::Transaction::cacheBuffers() {
1061 if (!mMayContainBuffer) {
1062 return;
1063 }
1064
1065 size_t count = 0;
1066 for (auto& [handle, cs] : mComposerStates) {
1067 layer_state_t* s = &(mComposerStates[handle].state);
1068 if (!(s->what & layer_state_t::eBufferChanged)) {
1069 continue;
1070 } else if (s->bufferData &&
1071 s->bufferData->flags.test(BufferData::BufferDataChange::cachedBufferChanged)) {
1072 // If eBufferChanged and eCachedBufferChanged are both trued then that means
1073 // we already cached the buffer in a previous call to cacheBuffers, perhaps
1074 // from writeToParcel on a Transaction that was merged in to this one.
1075 continue;
1076 }
1077
1078 // Don't try to cache a null buffer. Sending null buffers is cheap so we shouldn't waste
1079 // time trying to cache them.
1080 if (!s->bufferData || !s->bufferData->buffer) {
1081 continue;
1082 }
1083
1084 uint64_t cacheId = 0;
1085 status_t ret = BufferCache::getInstance().getCacheId(s->bufferData->buffer, &cacheId);
1086 if (ret == NO_ERROR) {
1087 // Cache-hit. Strip the buffer and send only the id.
1088 s->bufferData->buffer = nullptr;
1089 } else {
1090 // Cache-miss. Include the buffer and send the new cacheId.
1091 std::optional<client_cache_t> uncacheBuffer;
1092 cacheId = BufferCache::getInstance().cache(s->bufferData->buffer, uncacheBuffer);
1093 if (uncacheBuffer) {
1094 mUncacheBuffers.push_back(*uncacheBuffer);
1095 }
1096 }
1097 s->bufferData->flags |= BufferData::BufferDataChange::cachedBufferChanged;
1098 s->bufferData->cachedBuffer.token = BufferCache::getInstance().getToken();
1099 s->bufferData->cachedBuffer.id = cacheId;
1100
1101 // If we have more buffers than the size of the cache, we should stop caching so we don't
1102 // evict other buffers in this transaction
1103 count++;
1104 if (count >= BUFFER_CACHE_MAX_SIZE) {
1105 break;
1106 }
1107 }
1108 }
1109
1110 class SyncCallback {
1111 public:
getCallback(std::shared_ptr<SyncCallback> & callbackContext)1112 static auto getCallback(std::shared_ptr<SyncCallback>& callbackContext) {
1113 return [callbackContext](void* /* unused context */, nsecs_t /* latchTime */,
1114 const sp<Fence>& /* presentFence */,
1115 const std::vector<SurfaceControlStats>& /* stats */) {
1116 if (!callbackContext) {
1117 ALOGE("failed to get callback context for SyncCallback");
1118 return;
1119 }
1120 LOG_ALWAYS_FATAL_IF(sem_post(&callbackContext->mSemaphore), "sem_post failed");
1121 };
1122 }
~SyncCallback()1123 ~SyncCallback() {
1124 if (mInitialized) {
1125 LOG_ALWAYS_FATAL_IF(sem_destroy(&mSemaphore), "sem_destroy failed");
1126 }
1127 }
init()1128 void init() {
1129 LOG_ALWAYS_FATAL_IF(clock_gettime(CLOCK_MONOTONIC, &mTimeoutTimespec) == -1,
1130 "clock_gettime() fail! in SyncCallback::init");
1131 mTimeoutTimespec.tv_sec += 4;
1132 LOG_ALWAYS_FATAL_IF(sem_init(&mSemaphore, 0, 0), "sem_init failed");
1133 mInitialized = true;
1134 }
wait()1135 void wait() {
1136 int result = sem_clockwait(&mSemaphore, CLOCK_MONOTONIC, &mTimeoutTimespec);
1137 if (result && errno != ETIMEDOUT && errno != EINTR) {
1138 LOG_ALWAYS_FATAL("sem_clockwait failed(%d)", errno);
1139 } else if (errno == ETIMEDOUT) {
1140 ALOGW("Sync transaction timed out waiting for commit callback.");
1141 }
1142 }
getContext()1143 void* getContext() { return static_cast<void*>(this); }
1144
1145 private:
1146 sem_t mSemaphore;
1147 bool mInitialized = false;
1148 timespec mTimeoutTimespec;
1149 };
1150
apply(bool synchronous,bool oneWay)1151 status_t SurfaceComposerClient::Transaction::apply(bool synchronous, bool oneWay) {
1152 if (mStatus != NO_ERROR) {
1153 return mStatus;
1154 }
1155
1156 std::shared_ptr<SyncCallback> syncCallback = std::make_shared<SyncCallback>();
1157 if (synchronous) {
1158 syncCallback->init();
1159 addTransactionCommittedCallback(SyncCallback::getCallback(syncCallback),
1160 /*callbackContext=*/nullptr);
1161 }
1162
1163 bool hasListenerCallbacks = !mListenerCallbacks.empty();
1164 std::vector<ListenerCallbacks> listenerCallbacks;
1165 // For every listener with registered callbacks
1166 for (const auto& [listener, callbackInfo] : mListenerCallbacks) {
1167 auto& [callbackIds, surfaceControls] = callbackInfo;
1168 if (callbackIds.empty()) {
1169 continue;
1170 }
1171
1172 if (surfaceControls.empty()) {
1173 listenerCallbacks.emplace_back(IInterface::asBinder(listener), std::move(callbackIds));
1174 } else {
1175 // If the listener has any SurfaceControls set on this Transaction update the surface
1176 // state
1177 for (const auto& surfaceControl : surfaceControls) {
1178 layer_state_t* s = getLayerState(surfaceControl);
1179 if (!s) {
1180 ALOGE("failed to get layer state");
1181 continue;
1182 }
1183 std::vector<CallbackId> callbacks(callbackIds.begin(), callbackIds.end());
1184 s->what |= layer_state_t::eHasListenerCallbacksChanged;
1185 s->listeners.emplace_back(IInterface::asBinder(listener), callbacks);
1186 }
1187 }
1188 }
1189
1190 cacheBuffers();
1191
1192 Vector<ComposerState> composerStates;
1193 Vector<DisplayState> displayStates;
1194 uint32_t flags = 0;
1195
1196 for (auto const& kv : mComposerStates) {
1197 composerStates.add(kv.second);
1198 }
1199
1200 displayStates = std::move(mDisplayStates);
1201
1202 if (mAnimation) {
1203 flags |= ISurfaceComposer::eAnimation;
1204 }
1205 if (oneWay) {
1206 if (synchronous) {
1207 ALOGE("Transaction attempted to set synchronous and one way at the same time"
1208 " this is an invalid request. Synchronous will win for safety");
1209 } else {
1210 flags |= ISurfaceComposer::eOneWay;
1211 }
1212 }
1213
1214 // If both mEarlyWakeupStart and mEarlyWakeupEnd are set
1215 // it is equivalent for none
1216 if (mEarlyWakeupStart && !mEarlyWakeupEnd) {
1217 flags |= ISurfaceComposer::eEarlyWakeupStart;
1218 }
1219 if (mEarlyWakeupEnd && !mEarlyWakeupStart) {
1220 flags |= ISurfaceComposer::eEarlyWakeupEnd;
1221 }
1222
1223 sp<IBinder> applyToken = mApplyToken ? mApplyToken : sApplyToken;
1224
1225 sp<ISurfaceComposer> sf(ComposerService::getComposerService());
1226 sf->setTransactionState(mFrameTimelineInfo, composerStates, displayStates, flags, applyToken,
1227 mInputWindowCommands, mDesiredPresentTime, mIsAutoTimestamp,
1228 mUncacheBuffers, hasListenerCallbacks, listenerCallbacks, mId,
1229 mMergedTransactionIds);
1230 mId = generateId();
1231
1232 // Clear the current states and flags
1233 clear();
1234
1235 if (synchronous) {
1236 syncCallback->wait();
1237 }
1238
1239 mStatus = NO_ERROR;
1240 return NO_ERROR;
1241 }
1242
1243 sp<IBinder> SurfaceComposerClient::Transaction::sApplyToken = new BBinder();
1244
getDefaultApplyToken()1245 sp<IBinder> SurfaceComposerClient::Transaction::getDefaultApplyToken() {
1246 return sApplyToken;
1247 }
1248
setDefaultApplyToken(sp<IBinder> applyToken)1249 void SurfaceComposerClient::Transaction::setDefaultApplyToken(sp<IBinder> applyToken) {
1250 sApplyToken = applyToken;
1251 }
1252
sendSurfaceFlushJankDataTransaction(const sp<SurfaceControl> & sc)1253 status_t SurfaceComposerClient::Transaction::sendSurfaceFlushJankDataTransaction(
1254 const sp<SurfaceControl>& sc) {
1255 Transaction t;
1256 layer_state_t* s = t.getLayerState(sc);
1257 if (!s) {
1258 return BAD_INDEX;
1259 }
1260
1261 s->what |= layer_state_t::eFlushJankData;
1262 t.registerSurfaceControlForCallback(sc);
1263 return t.apply(/*sync=*/false, /* oneWay=*/true);
1264 }
1265 // ---------------------------------------------------------------------------
1266
createDisplay(const String8 & displayName,bool secure,float requestedRefereshRate)1267 sp<IBinder> SurfaceComposerClient::createDisplay(const String8& displayName, bool secure,
1268 float requestedRefereshRate) {
1269 sp<IBinder> display = nullptr;
1270 binder::Status status =
1271 ComposerServiceAIDL::getComposerService()->createDisplay(std::string(
1272 displayName.string()),
1273 secure, requestedRefereshRate,
1274 &display);
1275 return status.isOk() ? display : nullptr;
1276 }
1277
destroyDisplay(const sp<IBinder> & display)1278 void SurfaceComposerClient::destroyDisplay(const sp<IBinder>& display) {
1279 ComposerServiceAIDL::getComposerService()->destroyDisplay(display);
1280 }
1281
getPhysicalDisplayIds()1282 std::vector<PhysicalDisplayId> SurfaceComposerClient::getPhysicalDisplayIds() {
1283 std::vector<int64_t> displayIds;
1284 std::vector<PhysicalDisplayId> physicalDisplayIds;
1285 binder::Status status =
1286 ComposerServiceAIDL::getComposerService()->getPhysicalDisplayIds(&displayIds);
1287 if (status.isOk()) {
1288 physicalDisplayIds.reserve(displayIds.size());
1289 for (auto item : displayIds) {
1290 auto id = DisplayId::fromValue<PhysicalDisplayId>(static_cast<uint64_t>(item));
1291 physicalDisplayIds.push_back(*id);
1292 }
1293 }
1294 return physicalDisplayIds;
1295 }
1296
getPhysicalDisplayToken(PhysicalDisplayId displayId)1297 sp<IBinder> SurfaceComposerClient::getPhysicalDisplayToken(PhysicalDisplayId displayId) {
1298 sp<IBinder> display = nullptr;
1299 binder::Status status =
1300 ComposerServiceAIDL::getComposerService()->getPhysicalDisplayToken(displayId.value,
1301 &display);
1302 return status.isOk() ? display : nullptr;
1303 }
1304
getStalledTransactionInfo(pid_t pid)1305 std::optional<gui::StalledTransactionInfo> SurfaceComposerClient::getStalledTransactionInfo(
1306 pid_t pid) {
1307 std::optional<gui::StalledTransactionInfo> result;
1308 ComposerServiceAIDL::getComposerService()->getStalledTransactionInfo(pid, &result);
1309 return result;
1310 }
1311
setAnimationTransaction()1312 void SurfaceComposerClient::Transaction::setAnimationTransaction() {
1313 mAnimation = true;
1314 }
1315
setEarlyWakeupStart()1316 void SurfaceComposerClient::Transaction::setEarlyWakeupStart() {
1317 mEarlyWakeupStart = true;
1318 }
1319
setEarlyWakeupEnd()1320 void SurfaceComposerClient::Transaction::setEarlyWakeupEnd() {
1321 mEarlyWakeupEnd = true;
1322 }
1323
getLayerState(const sp<SurfaceControl> & sc)1324 layer_state_t* SurfaceComposerClient::Transaction::getLayerState(const sp<SurfaceControl>& sc) {
1325 auto handle = sc->getLayerStateHandle();
1326
1327 if (mComposerStates.count(handle) == 0) {
1328 // we don't have it, add an initialized layer_state to our list
1329 ComposerState s;
1330
1331 s.state.surface = handle;
1332 s.state.layerId = sc->getLayerId();
1333
1334 mComposerStates[handle] = s;
1335 }
1336
1337 return &(mComposerStates[handle].state);
1338 }
1339
registerSurfaceControlForCallback(const sp<SurfaceControl> & sc)1340 void SurfaceComposerClient::Transaction::registerSurfaceControlForCallback(
1341 const sp<SurfaceControl>& sc) {
1342 auto& callbackInfo = mListenerCallbacks[TransactionCompletedListener::getIInstance()];
1343 callbackInfo.surfaceControls.insert(sc);
1344
1345 TransactionCompletedListener::getInstance()->addSurfaceControlToCallbacks(callbackInfo, sc);
1346 }
1347
setPosition(const sp<SurfaceControl> & sc,float x,float y)1348 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setPosition(
1349 const sp<SurfaceControl>& sc, float x, float y) {
1350 layer_state_t* s = getLayerState(sc);
1351 if (!s) {
1352 mStatus = BAD_INDEX;
1353 return *this;
1354 }
1355 s->what |= layer_state_t::ePositionChanged;
1356 s->x = x;
1357 s->y = y;
1358
1359 registerSurfaceControlForCallback(sc);
1360 return *this;
1361 }
1362
show(const sp<SurfaceControl> & sc)1363 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::show(
1364 const sp<SurfaceControl>& sc) {
1365 return setFlags(sc, 0, layer_state_t::eLayerHidden);
1366 }
1367
hide(const sp<SurfaceControl> & sc)1368 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::hide(
1369 const sp<SurfaceControl>& sc) {
1370 return setFlags(sc, layer_state_t::eLayerHidden, layer_state_t::eLayerHidden);
1371 }
1372
setLayer(const sp<SurfaceControl> & sc,int32_t z)1373 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setLayer(
1374 const sp<SurfaceControl>& sc, int32_t z) {
1375 layer_state_t* s = getLayerState(sc);
1376 if (!s) {
1377 mStatus = BAD_INDEX;
1378 return *this;
1379 }
1380 s->what |= layer_state_t::eLayerChanged;
1381 s->what &= ~layer_state_t::eRelativeLayerChanged;
1382 s->z = z;
1383
1384 registerSurfaceControlForCallback(sc);
1385 return *this;
1386 }
1387
setRelativeLayer(const sp<SurfaceControl> & sc,const sp<SurfaceControl> & relativeTo,int32_t z)1388 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setRelativeLayer(
1389 const sp<SurfaceControl>& sc, const sp<SurfaceControl>& relativeTo, int32_t z) {
1390 layer_state_t* s = getLayerState(sc);
1391 if (!s) {
1392 mStatus = BAD_INDEX;
1393 return *this;
1394 }
1395 s->what |= layer_state_t::eRelativeLayerChanged;
1396 s->what &= ~layer_state_t::eLayerChanged;
1397 s->relativeLayerSurfaceControl = relativeTo;
1398 s->z = z;
1399
1400 registerSurfaceControlForCallback(sc);
1401 return *this;
1402 }
1403
setFlags(const sp<SurfaceControl> & sc,uint32_t flags,uint32_t mask)1404 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setFlags(
1405 const sp<SurfaceControl>& sc, uint32_t flags,
1406 uint32_t mask) {
1407 layer_state_t* s = getLayerState(sc);
1408 if (!s) {
1409 mStatus = BAD_INDEX;
1410 return *this;
1411 }
1412 if ((mask & layer_state_t::eLayerOpaque) || (mask & layer_state_t::eLayerHidden) ||
1413 (mask & layer_state_t::eLayerSecure) || (mask & layer_state_t::eLayerSkipScreenshot) ||
1414 (mask & layer_state_t::eEnableBackpressure) ||
1415 (mask & layer_state_t::eIgnoreDestinationFrame) ||
1416 (mask & layer_state_t::eLayerIsDisplayDecoration) ||
1417 (mask & layer_state_t::eLayerIsRefreshRateIndicator)) {
1418 s->what |= layer_state_t::eFlagsChanged;
1419 }
1420 s->flags &= ~mask;
1421 s->flags |= (flags & mask);
1422 s->mask |= mask;
1423
1424 registerSurfaceControlForCallback(sc);
1425 return *this;
1426 }
1427
setTransparentRegionHint(const sp<SurfaceControl> & sc,const Region & transparentRegion)1428 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setTransparentRegionHint(
1429 const sp<SurfaceControl>& sc,
1430 const Region& transparentRegion) {
1431 layer_state_t* s = getLayerState(sc);
1432 if (!s) {
1433 mStatus = BAD_INDEX;
1434 return *this;
1435 }
1436 s->what |= layer_state_t::eTransparentRegionChanged;
1437 s->transparentRegion = transparentRegion;
1438
1439 registerSurfaceControlForCallback(sc);
1440 return *this;
1441 }
1442
setDimmingEnabled(const sp<SurfaceControl> & sc,bool dimmingEnabled)1443 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setDimmingEnabled(
1444 const sp<SurfaceControl>& sc, bool dimmingEnabled) {
1445 layer_state_t* s = getLayerState(sc);
1446 if (!s) {
1447 mStatus = BAD_INDEX;
1448 return *this;
1449 }
1450 s->what |= layer_state_t::eDimmingEnabledChanged;
1451 s->dimmingEnabled = dimmingEnabled;
1452
1453 registerSurfaceControlForCallback(sc);
1454 return *this;
1455 }
1456
setAlpha(const sp<SurfaceControl> & sc,float alpha)1457 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setAlpha(
1458 const sp<SurfaceControl>& sc, float alpha) {
1459 layer_state_t* s = getLayerState(sc);
1460 if (!s) {
1461 mStatus = BAD_INDEX;
1462 return *this;
1463 }
1464 if (alpha < 0.0f || alpha > 1.0f) {
1465 ALOGE("SurfaceComposerClient::Transaction::setAlpha: invalid alpha %f, clamping", alpha);
1466 }
1467 s->what |= layer_state_t::eAlphaChanged;
1468 s->color.a = std::clamp(alpha, 0.f, 1.f);
1469
1470 registerSurfaceControlForCallback(sc);
1471 return *this;
1472 }
1473
setLayerStack(const sp<SurfaceControl> & sc,ui::LayerStack layerStack)1474 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setLayerStack(
1475 const sp<SurfaceControl>& sc, ui::LayerStack layerStack) {
1476 layer_state_t* s = getLayerState(sc);
1477 if (!s) {
1478 mStatus = BAD_INDEX;
1479 return *this;
1480 }
1481 s->what |= layer_state_t::eLayerStackChanged;
1482 s->layerStack = layerStack;
1483
1484 registerSurfaceControlForCallback(sc);
1485 return *this;
1486 }
1487
setMetadata(const sp<SurfaceControl> & sc,uint32_t key,const Parcel & p)1488 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setMetadata(
1489 const sp<SurfaceControl>& sc, uint32_t key, const Parcel& p) {
1490 layer_state_t* s = getLayerState(sc);
1491 if (!s) {
1492 mStatus = BAD_INDEX;
1493 return *this;
1494 }
1495 s->what |= layer_state_t::eMetadataChanged;
1496
1497 s->metadata.mMap[key] = {p.data(), p.data() + p.dataSize()};
1498
1499 registerSurfaceControlForCallback(sc);
1500 return *this;
1501 }
1502
setMatrix(const sp<SurfaceControl> & sc,float dsdx,float dtdx,float dtdy,float dsdy)1503 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setMatrix(
1504 const sp<SurfaceControl>& sc, float dsdx, float dtdx,
1505 float dtdy, float dsdy) {
1506 layer_state_t* s = getLayerState(sc);
1507 if (!s) {
1508 mStatus = BAD_INDEX;
1509 return *this;
1510 }
1511 s->what |= layer_state_t::eMatrixChanged;
1512 layer_state_t::matrix22_t matrix;
1513 matrix.dsdx = dsdx;
1514 matrix.dtdx = dtdx;
1515 matrix.dsdy = dsdy;
1516 matrix.dtdy = dtdy;
1517 s->matrix = matrix;
1518
1519 registerSurfaceControlForCallback(sc);
1520 return *this;
1521 }
1522
setCrop(const sp<SurfaceControl> & sc,const Rect & crop)1523 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setCrop(
1524 const sp<SurfaceControl>& sc, const Rect& crop) {
1525 layer_state_t* s = getLayerState(sc);
1526 if (!s) {
1527 mStatus = BAD_INDEX;
1528 return *this;
1529 }
1530 s->what |= layer_state_t::eCropChanged;
1531 s->crop = crop;
1532
1533 registerSurfaceControlForCallback(sc);
1534 return *this;
1535 }
1536
setCornerRadius(const sp<SurfaceControl> & sc,float cornerRadius)1537 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setCornerRadius(
1538 const sp<SurfaceControl>& sc, float cornerRadius) {
1539 layer_state_t* s = getLayerState(sc);
1540 if (!s) {
1541 mStatus = BAD_INDEX;
1542 return *this;
1543 }
1544 s->what |= layer_state_t::eCornerRadiusChanged;
1545 s->cornerRadius = cornerRadius;
1546 return *this;
1547 }
1548
setBackgroundBlurRadius(const sp<SurfaceControl> & sc,int backgroundBlurRadius)1549 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setBackgroundBlurRadius(
1550 const sp<SurfaceControl>& sc, int backgroundBlurRadius) {
1551 layer_state_t* s = getLayerState(sc);
1552 if (!s) {
1553 mStatus = BAD_INDEX;
1554 return *this;
1555 }
1556 s->what |= layer_state_t::eBackgroundBlurRadiusChanged;
1557 s->backgroundBlurRadius = backgroundBlurRadius;
1558 return *this;
1559 }
1560
setBlurRegions(const sp<SurfaceControl> & sc,const std::vector<BlurRegion> & blurRegions)1561 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setBlurRegions(
1562 const sp<SurfaceControl>& sc, const std::vector<BlurRegion>& blurRegions) {
1563 layer_state_t* s = getLayerState(sc);
1564 if (!s) {
1565 mStatus = BAD_INDEX;
1566 return *this;
1567 }
1568 s->what |= layer_state_t::eBlurRegionsChanged;
1569 s->blurRegions = blurRegions;
1570 return *this;
1571 }
1572
reparent(const sp<SurfaceControl> & sc,const sp<SurfaceControl> & newParent)1573 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::reparent(
1574 const sp<SurfaceControl>& sc, const sp<SurfaceControl>& newParent) {
1575 layer_state_t* s = getLayerState(sc);
1576 if (!s) {
1577 mStatus = BAD_INDEX;
1578 return *this;
1579 }
1580 if (SurfaceControl::isSameSurface(sc, newParent)) {
1581 return *this;
1582 }
1583 s->what |= layer_state_t::eReparent;
1584 s->parentSurfaceControlForChild = newParent ? newParent->getParentingLayer() : nullptr;
1585
1586 registerSurfaceControlForCallback(sc);
1587 return *this;
1588 }
1589
setColor(const sp<SurfaceControl> & sc,const half3 & color)1590 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setColor(
1591 const sp<SurfaceControl>& sc,
1592 const half3& color) {
1593 layer_state_t* s = getLayerState(sc);
1594 if (!s) {
1595 mStatus = BAD_INDEX;
1596 return *this;
1597 }
1598 s->what |= layer_state_t::eColorChanged;
1599 s->color.rgb = color;
1600
1601 registerSurfaceControlForCallback(sc);
1602 return *this;
1603 }
1604
setBackgroundColor(const sp<SurfaceControl> & sc,const half3 & color,float alpha,ui::Dataspace dataspace)1605 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setBackgroundColor(
1606 const sp<SurfaceControl>& sc, const half3& color, float alpha, ui::Dataspace dataspace) {
1607 layer_state_t* s = getLayerState(sc);
1608 if (!s) {
1609 mStatus = BAD_INDEX;
1610 return *this;
1611 }
1612
1613 s->what |= layer_state_t::eBackgroundColorChanged;
1614 s->bgColor.rgb = color;
1615 s->bgColor.a = alpha;
1616 s->bgColorDataspace = dataspace;
1617
1618 registerSurfaceControlForCallback(sc);
1619 return *this;
1620 }
1621
setTransform(const sp<SurfaceControl> & sc,uint32_t transform)1622 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setTransform(
1623 const sp<SurfaceControl>& sc, uint32_t transform) {
1624 layer_state_t* s = getLayerState(sc);
1625 if (!s) {
1626 mStatus = BAD_INDEX;
1627 return *this;
1628 }
1629 s->what |= layer_state_t::eBufferTransformChanged;
1630 s->bufferTransform = transform;
1631
1632 registerSurfaceControlForCallback(sc);
1633 return *this;
1634 }
1635
1636 SurfaceComposerClient::Transaction&
setTransformToDisplayInverse(const sp<SurfaceControl> & sc,bool transformToDisplayInverse)1637 SurfaceComposerClient::Transaction::setTransformToDisplayInverse(const sp<SurfaceControl>& sc,
1638 bool transformToDisplayInverse) {
1639 layer_state_t* s = getLayerState(sc);
1640 if (!s) {
1641 mStatus = BAD_INDEX;
1642 return *this;
1643 }
1644 s->what |= layer_state_t::eTransformToDisplayInverseChanged;
1645 s->transformToDisplayInverse = transformToDisplayInverse;
1646
1647 registerSurfaceControlForCallback(sc);
1648 return *this;
1649 }
1650
getAndClearBuffer(const sp<SurfaceControl> & sc)1651 std::shared_ptr<BufferData> SurfaceComposerClient::Transaction::getAndClearBuffer(
1652 const sp<SurfaceControl>& sc) {
1653 layer_state_t* s = getLayerState(sc);
1654 if (!s) {
1655 return nullptr;
1656 }
1657 if (!(s->what & layer_state_t::eBufferChanged)) {
1658 return nullptr;
1659 }
1660
1661 std::shared_ptr<BufferData> bufferData = std::move(s->bufferData);
1662
1663 TransactionCompletedListener::getInstance()->removeReleaseBufferCallback(
1664 bufferData->generateReleaseCallbackId());
1665 s->what &= ~layer_state_t::eBufferChanged;
1666 s->bufferData = nullptr;
1667
1668 return bufferData;
1669 }
1670
setBufferHasBarrier(const sp<SurfaceControl> & sc,uint64_t barrierFrameNumber)1671 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setBufferHasBarrier(
1672 const sp<SurfaceControl>& sc, uint64_t barrierFrameNumber) {
1673 layer_state_t* s = getLayerState(sc);
1674 if (!s) {
1675 mStatus = BAD_INDEX;
1676 return *this;
1677 }
1678 s->bufferData->hasBarrier = true;
1679 s->bufferData->barrierFrameNumber = barrierFrameNumber;
1680 return *this;
1681 }
1682
setBuffer(const sp<SurfaceControl> & sc,const sp<GraphicBuffer> & buffer,const std::optional<sp<Fence>> & fence,const std::optional<uint64_t> & optFrameNumber,uint32_t producerId,ReleaseBufferCallback callback)1683 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setBuffer(
1684 const sp<SurfaceControl>& sc, const sp<GraphicBuffer>& buffer,
1685 const std::optional<sp<Fence>>& fence, const std::optional<uint64_t>& optFrameNumber,
1686 uint32_t producerId, ReleaseBufferCallback callback) {
1687 layer_state_t* s = getLayerState(sc);
1688 if (!s) {
1689 mStatus = BAD_INDEX;
1690 return *this;
1691 }
1692
1693 releaseBufferIfOverwriting(*s);
1694
1695 std::shared_ptr<BufferData> bufferData = std::make_shared<BufferData>();
1696 bufferData->buffer = buffer;
1697 if (buffer) {
1698 uint64_t frameNumber = sc->resolveFrameNumber(optFrameNumber);
1699 bufferData->frameNumber = frameNumber;
1700 bufferData->producerId = producerId;
1701 bufferData->flags |= BufferData::BufferDataChange::frameNumberChanged;
1702 if (fence) {
1703 bufferData->acquireFence = *fence;
1704 bufferData->flags |= BufferData::BufferDataChange::fenceChanged;
1705 }
1706 bufferData->releaseBufferEndpoint =
1707 IInterface::asBinder(TransactionCompletedListener::getIInstance());
1708 setReleaseBufferCallback(bufferData.get(), callback);
1709 }
1710
1711 if (mIsAutoTimestamp) {
1712 mDesiredPresentTime = systemTime();
1713 }
1714 s->what |= layer_state_t::eBufferChanged;
1715 s->bufferData = std::move(bufferData);
1716 registerSurfaceControlForCallback(sc);
1717
1718 // With the current infrastructure, a release callback will not be invoked if there's no
1719 // transaction callback in the case when a buffer is latched and not released early. This is
1720 // because the legacy implementation didn't have a release callback and sent releases in the
1721 // transaction callback. Because of this, we need to make sure to have a transaction callback
1722 // set up when a buffer is sent in a transaction to ensure the caller gets the release
1723 // callback, regardless if they set up a transaction callback.
1724 //
1725 // TODO (b/230380821): Remove when release callbacks are separated from transaction callbacks
1726 addTransactionCompletedCallback([](void*, nsecs_t, const sp<Fence>&,
1727 const std::vector<SurfaceControlStats>&) {},
1728 nullptr);
1729
1730 mMayContainBuffer = true;
1731 return *this;
1732 }
1733
unsetBuffer(const sp<SurfaceControl> & sc)1734 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::unsetBuffer(
1735 const sp<SurfaceControl>& sc) {
1736 layer_state_t* s = getLayerState(sc);
1737 if (!s) {
1738 mStatus = BAD_INDEX;
1739 return *this;
1740 }
1741
1742 if (!(s->what & layer_state_t::eBufferChanged)) {
1743 return *this;
1744 }
1745
1746 releaseBufferIfOverwriting(*s);
1747
1748 s->what &= ~layer_state_t::eBufferChanged;
1749 s->bufferData = nullptr;
1750 return *this;
1751 }
1752
setReleaseBufferCallback(BufferData * bufferData,ReleaseBufferCallback callback)1753 void SurfaceComposerClient::Transaction::setReleaseBufferCallback(BufferData* bufferData,
1754 ReleaseBufferCallback callback) {
1755 if (!callback) {
1756 return;
1757 }
1758
1759 if (!bufferData->buffer) {
1760 ALOGW("Transaction::setReleaseBufferCallback"
1761 "ignored trying to set a callback on a null buffer.");
1762 return;
1763 }
1764
1765 bufferData->releaseBufferListener = TransactionCompletedListener::getIInstance();
1766 auto listener = TransactionCompletedListener::getInstance();
1767 listener->setReleaseBufferCallback(bufferData->generateReleaseCallbackId(), callback);
1768 }
1769
setDataspace(const sp<SurfaceControl> & sc,ui::Dataspace dataspace)1770 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setDataspace(
1771 const sp<SurfaceControl>& sc, ui::Dataspace dataspace) {
1772 layer_state_t* s = getLayerState(sc);
1773 if (!s) {
1774 mStatus = BAD_INDEX;
1775 return *this;
1776 }
1777 s->what |= layer_state_t::eDataspaceChanged;
1778 s->dataspace = dataspace;
1779
1780 registerSurfaceControlForCallback(sc);
1781 return *this;
1782 }
1783
setExtendedRangeBrightness(const sp<SurfaceControl> & sc,float currentBufferRatio,float desiredRatio)1784 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setExtendedRangeBrightness(
1785 const sp<SurfaceControl>& sc, float currentBufferRatio, float desiredRatio) {
1786 layer_state_t* s = getLayerState(sc);
1787 if (!s) {
1788 mStatus = BAD_INDEX;
1789 return *this;
1790 }
1791 s->what |= layer_state_t::eExtendedRangeBrightnessChanged;
1792 s->currentHdrSdrRatio = currentBufferRatio;
1793 s->desiredHdrSdrRatio = desiredRatio;
1794
1795 registerSurfaceControlForCallback(sc);
1796 return *this;
1797 }
1798
setCachingHint(const sp<SurfaceControl> & sc,gui::CachingHint cachingHint)1799 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setCachingHint(
1800 const sp<SurfaceControl>& sc, gui::CachingHint cachingHint) {
1801 layer_state_t* s = getLayerState(sc);
1802 if (!s) {
1803 mStatus = BAD_INDEX;
1804 return *this;
1805 }
1806 s->what |= layer_state_t::eCachingHintChanged;
1807 s->cachingHint = cachingHint;
1808
1809 registerSurfaceControlForCallback(sc);
1810 return *this;
1811 }
1812
setHdrMetadata(const sp<SurfaceControl> & sc,const HdrMetadata & hdrMetadata)1813 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setHdrMetadata(
1814 const sp<SurfaceControl>& sc, const HdrMetadata& hdrMetadata) {
1815 layer_state_t* s = getLayerState(sc);
1816 if (!s) {
1817 mStatus = BAD_INDEX;
1818 return *this;
1819 }
1820 s->what |= layer_state_t::eHdrMetadataChanged;
1821 s->hdrMetadata = hdrMetadata;
1822
1823 registerSurfaceControlForCallback(sc);
1824 return *this;
1825 }
1826
setSurfaceDamageRegion(const sp<SurfaceControl> & sc,const Region & surfaceDamageRegion)1827 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setSurfaceDamageRegion(
1828 const sp<SurfaceControl>& sc, const Region& surfaceDamageRegion) {
1829 layer_state_t* s = getLayerState(sc);
1830 if (!s) {
1831 mStatus = BAD_INDEX;
1832 return *this;
1833 }
1834 s->what |= layer_state_t::eSurfaceDamageRegionChanged;
1835 s->surfaceDamageRegion = surfaceDamageRegion;
1836
1837 registerSurfaceControlForCallback(sc);
1838 return *this;
1839 }
1840
setApi(const sp<SurfaceControl> & sc,int32_t api)1841 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setApi(
1842 const sp<SurfaceControl>& sc, int32_t api) {
1843 layer_state_t* s = getLayerState(sc);
1844 if (!s) {
1845 mStatus = BAD_INDEX;
1846 return *this;
1847 }
1848 s->what |= layer_state_t::eApiChanged;
1849 s->api = api;
1850
1851 registerSurfaceControlForCallback(sc);
1852 return *this;
1853 }
1854
setSidebandStream(const sp<SurfaceControl> & sc,const sp<NativeHandle> & sidebandStream)1855 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setSidebandStream(
1856 const sp<SurfaceControl>& sc, const sp<NativeHandle>& sidebandStream) {
1857 layer_state_t* s = getLayerState(sc);
1858 if (!s) {
1859 mStatus = BAD_INDEX;
1860 return *this;
1861 }
1862 s->what |= layer_state_t::eSidebandStreamChanged;
1863 s->sidebandStream = sidebandStream;
1864
1865 registerSurfaceControlForCallback(sc);
1866 return *this;
1867 }
1868
setDesiredPresentTime(nsecs_t desiredPresentTime)1869 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setDesiredPresentTime(
1870 nsecs_t desiredPresentTime) {
1871 mDesiredPresentTime = desiredPresentTime;
1872 mIsAutoTimestamp = false;
1873 return *this;
1874 }
1875
setColorSpaceAgnostic(const sp<SurfaceControl> & sc,const bool agnostic)1876 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setColorSpaceAgnostic(
1877 const sp<SurfaceControl>& sc, const bool agnostic) {
1878 layer_state_t* s = getLayerState(sc);
1879 if (!s) {
1880 mStatus = BAD_INDEX;
1881 return *this;
1882 }
1883 s->what |= layer_state_t::eColorSpaceAgnosticChanged;
1884 s->colorSpaceAgnostic = agnostic;
1885
1886 registerSurfaceControlForCallback(sc);
1887 return *this;
1888 }
1889
1890 SurfaceComposerClient::Transaction&
setFrameRateSelectionPriority(const sp<SurfaceControl> & sc,int32_t priority)1891 SurfaceComposerClient::Transaction::setFrameRateSelectionPriority(const sp<SurfaceControl>& sc,
1892 int32_t priority) {
1893 layer_state_t* s = getLayerState(sc);
1894 if (!s) {
1895 mStatus = BAD_INDEX;
1896 return *this;
1897 }
1898
1899 s->what |= layer_state_t::eFrameRateSelectionPriority;
1900 s->frameRateSelectionPriority = priority;
1901
1902 registerSurfaceControlForCallback(sc);
1903 return *this;
1904 }
1905
addTransactionCallback(TransactionCompletedCallbackTakesContext callback,void * callbackContext,CallbackId::Type callbackType)1906 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::addTransactionCallback(
1907 TransactionCompletedCallbackTakesContext callback, void* callbackContext,
1908 CallbackId::Type callbackType) {
1909 auto listener = TransactionCompletedListener::getInstance();
1910
1911 auto callbackWithContext = std::bind(callback, callbackContext, std::placeholders::_1,
1912 std::placeholders::_2, std::placeholders::_3);
1913 const auto& surfaceControls =
1914 mListenerCallbacks[TransactionCompletedListener::getIInstance()].surfaceControls;
1915
1916 CallbackId callbackId =
1917 listener->addCallbackFunction(callbackWithContext, surfaceControls, callbackType);
1918
1919 mListenerCallbacks[TransactionCompletedListener::getIInstance()].callbackIds.emplace(
1920 callbackId);
1921 return *this;
1922 }
1923
1924 SurfaceComposerClient::Transaction&
addTransactionCompletedCallback(TransactionCompletedCallbackTakesContext callback,void * callbackContext)1925 SurfaceComposerClient::Transaction::addTransactionCompletedCallback(
1926 TransactionCompletedCallbackTakesContext callback, void* callbackContext) {
1927 return addTransactionCallback(callback, callbackContext, CallbackId::Type::ON_COMPLETE);
1928 }
1929
1930 SurfaceComposerClient::Transaction&
addTransactionCommittedCallback(TransactionCompletedCallbackTakesContext callback,void * callbackContext)1931 SurfaceComposerClient::Transaction::addTransactionCommittedCallback(
1932 TransactionCompletedCallbackTakesContext callback, void* callbackContext) {
1933 return addTransactionCallback(callback, callbackContext, CallbackId::Type::ON_COMMIT);
1934 }
1935
notifyProducerDisconnect(const sp<SurfaceControl> & sc)1936 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::notifyProducerDisconnect(
1937 const sp<SurfaceControl>& sc) {
1938 layer_state_t* s = getLayerState(sc);
1939 if (!s) {
1940 mStatus = BAD_INDEX;
1941 return *this;
1942 }
1943
1944 s->what |= layer_state_t::eProducerDisconnect;
1945 return *this;
1946 }
1947
setInputWindowInfo(const sp<SurfaceControl> & sc,const WindowInfo & info)1948 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setInputWindowInfo(
1949 const sp<SurfaceControl>& sc, const WindowInfo& info) {
1950 layer_state_t* s = getLayerState(sc);
1951 if (!s) {
1952 mStatus = BAD_INDEX;
1953 return *this;
1954 }
1955 s->windowInfoHandle = new WindowInfoHandle(info);
1956 s->what |= layer_state_t::eInputInfoChanged;
1957 return *this;
1958 }
1959
setFocusedWindow(const FocusRequest & request)1960 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setFocusedWindow(
1961 const FocusRequest& request) {
1962 mInputWindowCommands.focusRequests.push_back(request);
1963 return *this;
1964 }
1965
1966 SurfaceComposerClient::Transaction&
addWindowInfosReportedListener(sp<gui::IWindowInfosReportedListener> windowInfosReportedListener)1967 SurfaceComposerClient::Transaction::addWindowInfosReportedListener(
1968 sp<gui::IWindowInfosReportedListener> windowInfosReportedListener) {
1969 mInputWindowCommands.windowInfosReportedListeners.insert(windowInfosReportedListener);
1970 return *this;
1971 }
1972
setColorTransform(const sp<SurfaceControl> & sc,const mat3 & matrix,const vec3 & translation)1973 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setColorTransform(
1974 const sp<SurfaceControl>& sc, const mat3& matrix, const vec3& translation) {
1975 layer_state_t* s = getLayerState(sc);
1976 if (!s) {
1977 mStatus = BAD_INDEX;
1978 return *this;
1979 }
1980 s->what |= layer_state_t::eColorTransformChanged;
1981 s->colorTransform = mat4(matrix, translation);
1982
1983 registerSurfaceControlForCallback(sc);
1984 return *this;
1985 }
1986
setGeometry(const sp<SurfaceControl> & sc,const Rect & source,const Rect & dst,int transform)1987 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setGeometry(
1988 const sp<SurfaceControl>& sc, const Rect& source, const Rect& dst, int transform) {
1989 setCrop(sc, source);
1990
1991 int x = dst.left;
1992 int y = dst.top;
1993
1994 float sourceWidth = source.getWidth();
1995 float sourceHeight = source.getHeight();
1996
1997 float xScale = sourceWidth < 0 ? 1.0f : dst.getWidth() / sourceWidth;
1998 float yScale = sourceHeight < 0 ? 1.0f : dst.getHeight() / sourceHeight;
1999 float matrix[4] = {1, 0, 0, 1};
2000
2001 switch (transform) {
2002 case NATIVE_WINDOW_TRANSFORM_FLIP_H:
2003 matrix[0] = -xScale; matrix[1] = 0;
2004 matrix[2] = 0; matrix[3] = yScale;
2005 x += source.getWidth();
2006 break;
2007 case NATIVE_WINDOW_TRANSFORM_FLIP_V:
2008 matrix[0] = xScale; matrix[1] = 0;
2009 matrix[2] = 0; matrix[3] = -yScale;
2010 y += source.getHeight();
2011 break;
2012 case NATIVE_WINDOW_TRANSFORM_ROT_90:
2013 matrix[0] = 0; matrix[1] = -yScale;
2014 matrix[2] = xScale; matrix[3] = 0;
2015 x += source.getHeight();
2016 break;
2017 case NATIVE_WINDOW_TRANSFORM_ROT_180:
2018 matrix[0] = -xScale; matrix[1] = 0;
2019 matrix[2] = 0; matrix[3] = -yScale;
2020 x += source.getWidth();
2021 y += source.getHeight();
2022 break;
2023 case NATIVE_WINDOW_TRANSFORM_ROT_270:
2024 matrix[0] = 0; matrix[1] = yScale;
2025 matrix[2] = -xScale; matrix[3] = 0;
2026 y += source.getWidth();
2027 break;
2028 default:
2029 matrix[0] = xScale; matrix[1] = 0;
2030 matrix[2] = 0; matrix[3] = yScale;
2031 break;
2032 }
2033 setMatrix(sc, matrix[0], matrix[1], matrix[2], matrix[3]);
2034 float offsetX = xScale * source.left;
2035 float offsetY = yScale * source.top;
2036 setPosition(sc, x - offsetX, y - offsetY);
2037
2038 return *this;
2039 }
2040
setShadowRadius(const sp<SurfaceControl> & sc,float shadowRadius)2041 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setShadowRadius(
2042 const sp<SurfaceControl>& sc, float shadowRadius) {
2043 layer_state_t* s = getLayerState(sc);
2044 if (!s) {
2045 mStatus = BAD_INDEX;
2046 return *this;
2047 }
2048 s->what |= layer_state_t::eShadowRadiusChanged;
2049 s->shadowRadius = shadowRadius;
2050 return *this;
2051 }
2052
setFrameRate(const sp<SurfaceControl> & sc,float frameRate,int8_t compatibility,int8_t changeFrameRateStrategy)2053 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setFrameRate(
2054 const sp<SurfaceControl>& sc, float frameRate, int8_t compatibility,
2055 int8_t changeFrameRateStrategy) {
2056 layer_state_t* s = getLayerState(sc);
2057 if (!s) {
2058 mStatus = BAD_INDEX;
2059 return *this;
2060 }
2061 // Allow privileged values as well here, those will be ignored by SF if
2062 // the caller is not privileged
2063 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
2064 "Transaction::setFrameRate",
2065 /*privileged=*/true)) {
2066 mStatus = BAD_VALUE;
2067 return *this;
2068 }
2069 s->what |= layer_state_t::eFrameRateChanged;
2070 s->frameRate = frameRate;
2071 s->frameRateCompatibility = compatibility;
2072 s->changeFrameRateStrategy = changeFrameRateStrategy;
2073 return *this;
2074 }
2075
2076 SurfaceComposerClient::Transaction&
setDefaultFrameRateCompatibility(const sp<SurfaceControl> & sc,int8_t compatibility)2077 SurfaceComposerClient::Transaction::setDefaultFrameRateCompatibility(const sp<SurfaceControl>& sc,
2078 int8_t compatibility) {
2079 layer_state_t* s = getLayerState(sc);
2080 if (!s) {
2081 mStatus = BAD_INDEX;
2082 return *this;
2083 }
2084 s->what |= layer_state_t::eDefaultFrameRateCompatibilityChanged;
2085 s->defaultFrameRateCompatibility = compatibility;
2086 return *this;
2087 }
2088
setFixedTransformHint(const sp<SurfaceControl> & sc,int32_t fixedTransformHint)2089 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setFixedTransformHint(
2090 const sp<SurfaceControl>& sc, int32_t fixedTransformHint) {
2091 layer_state_t* s = getLayerState(sc);
2092 if (!s) {
2093 mStatus = BAD_INDEX;
2094 return *this;
2095 }
2096
2097 const ui::Transform::RotationFlags transform = fixedTransformHint == -1
2098 ? ui::Transform::ROT_INVALID
2099 : ui::Transform::toRotationFlags(static_cast<ui::Rotation>(fixedTransformHint));
2100 s->what |= layer_state_t::eFixedTransformHintChanged;
2101 s->fixedTransformHint = transform;
2102 return *this;
2103 }
2104
setFrameTimelineInfo(const FrameTimelineInfo & frameTimelineInfo)2105 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setFrameTimelineInfo(
2106 const FrameTimelineInfo& frameTimelineInfo) {
2107 mergeFrameTimelineInfo(mFrameTimelineInfo, frameTimelineInfo);
2108 return *this;
2109 }
2110
setAutoRefresh(const sp<SurfaceControl> & sc,bool autoRefresh)2111 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setAutoRefresh(
2112 const sp<SurfaceControl>& sc, bool autoRefresh) {
2113 layer_state_t* s = getLayerState(sc);
2114 if (!s) {
2115 mStatus = BAD_INDEX;
2116 return *this;
2117 }
2118
2119 s->what |= layer_state_t::eAutoRefreshChanged;
2120 s->autoRefresh = autoRefresh;
2121 return *this;
2122 }
2123
setTrustedOverlay(const sp<SurfaceControl> & sc,bool isTrustedOverlay)2124 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setTrustedOverlay(
2125 const sp<SurfaceControl>& sc, bool isTrustedOverlay) {
2126 layer_state_t* s = getLayerState(sc);
2127 if (!s) {
2128 mStatus = BAD_INDEX;
2129 return *this;
2130 }
2131
2132 s->what |= layer_state_t::eTrustedOverlayChanged;
2133 s->isTrustedOverlay = isTrustedOverlay;
2134 return *this;
2135 }
2136
setApplyToken(const sp<IBinder> & applyToken)2137 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setApplyToken(
2138 const sp<IBinder>& applyToken) {
2139 mApplyToken = applyToken;
2140 return *this;
2141 }
2142
setStretchEffect(const sp<SurfaceControl> & sc,const StretchEffect & stretchEffect)2143 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setStretchEffect(
2144 const sp<SurfaceControl>& sc, const StretchEffect& stretchEffect) {
2145 layer_state_t* s = getLayerState(sc);
2146 if (!s) {
2147 mStatus = BAD_INDEX;
2148 return *this;
2149 }
2150
2151 s->what |= layer_state_t::eStretchChanged;
2152 s->stretchEffect = stretchEffect;
2153 return *this;
2154 }
2155
setBufferCrop(const sp<SurfaceControl> & sc,const Rect & bufferCrop)2156 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setBufferCrop(
2157 const sp<SurfaceControl>& sc, const Rect& bufferCrop) {
2158 layer_state_t* s = getLayerState(sc);
2159 if (!s) {
2160 mStatus = BAD_INDEX;
2161 return *this;
2162 }
2163
2164 s->what |= layer_state_t::eBufferCropChanged;
2165 s->bufferCrop = bufferCrop;
2166
2167 registerSurfaceControlForCallback(sc);
2168 return *this;
2169 }
2170
setDestinationFrame(const sp<SurfaceControl> & sc,const Rect & destinationFrame)2171 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setDestinationFrame(
2172 const sp<SurfaceControl>& sc, const Rect& destinationFrame) {
2173 layer_state_t* s = getLayerState(sc);
2174 if (!s) {
2175 mStatus = BAD_INDEX;
2176 return *this;
2177 }
2178
2179 s->what |= layer_state_t::eDestinationFrameChanged;
2180 s->destinationFrame = destinationFrame;
2181
2182 registerSurfaceControlForCallback(sc);
2183 return *this;
2184 }
2185
setDropInputMode(const sp<SurfaceControl> & sc,gui::DropInputMode mode)2186 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setDropInputMode(
2187 const sp<SurfaceControl>& sc, gui::DropInputMode mode) {
2188 layer_state_t* s = getLayerState(sc);
2189 if (!s) {
2190 mStatus = BAD_INDEX;
2191 return *this;
2192 }
2193
2194 s->what |= layer_state_t::eDropInputModeChanged;
2195 s->dropInputMode = mode;
2196
2197 registerSurfaceControlForCallback(sc);
2198 return *this;
2199 }
2200
enableBorder(const sp<SurfaceControl> & sc,bool shouldEnable,float width,const half4 & color)2201 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::enableBorder(
2202 const sp<SurfaceControl>& sc, bool shouldEnable, float width, const half4& color) {
2203 layer_state_t* s = getLayerState(sc);
2204 if (!s) {
2205 mStatus = BAD_INDEX;
2206 return *this;
2207 }
2208
2209 s->what |= layer_state_t::eRenderBorderChanged;
2210 s->borderEnabled = shouldEnable;
2211 s->borderWidth = width;
2212 s->borderColor = color;
2213
2214 registerSurfaceControlForCallback(sc);
2215 return *this;
2216 }
2217
2218 // ---------------------------------------------------------------------------
2219
getDisplayState(const sp<IBinder> & token)2220 DisplayState& SurfaceComposerClient::Transaction::getDisplayState(const sp<IBinder>& token) {
2221 DisplayState s;
2222 s.token = token;
2223 ssize_t index = mDisplayStates.indexOf(s);
2224 if (index < 0) {
2225 // we don't have it, add an initialized layer_state to our list
2226 s.what = 0;
2227 index = mDisplayStates.add(s);
2228 }
2229 return mDisplayStates.editItemAt(static_cast<size_t>(index));
2230 }
2231
setDisplaySurface(const sp<IBinder> & token,const sp<IGraphicBufferProducer> & bufferProducer)2232 status_t SurfaceComposerClient::Transaction::setDisplaySurface(const sp<IBinder>& token,
2233 const sp<IGraphicBufferProducer>& bufferProducer) {
2234 if (bufferProducer.get() != nullptr) {
2235 // Make sure that composition can never be stalled by a virtual display
2236 // consumer that isn't processing buffers fast enough.
2237 status_t err = bufferProducer->setAsyncMode(true);
2238 if (err != NO_ERROR) {
2239 ALOGE("Composer::setDisplaySurface Failed to enable async mode on the "
2240 "BufferQueue. This BufferQueue cannot be used for virtual "
2241 "display. (%d)", err);
2242 return err;
2243 }
2244 }
2245 DisplayState& s(getDisplayState(token));
2246 s.surface = bufferProducer;
2247 s.what |= DisplayState::eSurfaceChanged;
2248 return NO_ERROR;
2249 }
2250
setDisplayLayerStack(const sp<IBinder> & token,ui::LayerStack layerStack)2251 void SurfaceComposerClient::Transaction::setDisplayLayerStack(const sp<IBinder>& token,
2252 ui::LayerStack layerStack) {
2253 DisplayState& s(getDisplayState(token));
2254 s.layerStack = layerStack;
2255 s.what |= DisplayState::eLayerStackChanged;
2256 }
2257
setDisplayFlags(const sp<IBinder> & token,uint32_t flags)2258 void SurfaceComposerClient::Transaction::setDisplayFlags(const sp<IBinder>& token, uint32_t flags) {
2259 DisplayState& s(getDisplayState(token));
2260 s.flags = flags;
2261 s.what |= DisplayState::eFlagsChanged;
2262 }
2263
setDisplayProjection(const sp<IBinder> & token,ui::Rotation orientation,const Rect & layerStackRect,const Rect & displayRect)2264 void SurfaceComposerClient::Transaction::setDisplayProjection(const sp<IBinder>& token,
2265 ui::Rotation orientation,
2266 const Rect& layerStackRect,
2267 const Rect& displayRect) {
2268 DisplayState& s(getDisplayState(token));
2269 s.orientation = orientation;
2270 s.layerStackSpaceRect = layerStackRect;
2271 s.orientedDisplaySpaceRect = displayRect;
2272 s.what |= DisplayState::eDisplayProjectionChanged;
2273 }
2274
setDisplaySize(const sp<IBinder> & token,uint32_t width,uint32_t height)2275 void SurfaceComposerClient::Transaction::setDisplaySize(const sp<IBinder>& token, uint32_t width, uint32_t height) {
2276 DisplayState& s(getDisplayState(token));
2277 s.width = width;
2278 s.height = height;
2279 s.what |= DisplayState::eDisplaySizeChanged;
2280 }
2281
2282 // copied from FrameTimelineInfo::merge()
mergeFrameTimelineInfo(FrameTimelineInfo & t,const FrameTimelineInfo & other)2283 void SurfaceComposerClient::Transaction::mergeFrameTimelineInfo(FrameTimelineInfo& t,
2284 const FrameTimelineInfo& other) {
2285 // When merging vsync Ids we take the oldest valid one
2286 if (t.vsyncId != FrameTimelineInfo::INVALID_VSYNC_ID &&
2287 other.vsyncId != FrameTimelineInfo::INVALID_VSYNC_ID) {
2288 if (other.vsyncId > t.vsyncId) {
2289 t = other;
2290 }
2291 } else if (t.vsyncId == FrameTimelineInfo::INVALID_VSYNC_ID) {
2292 t = other;
2293 }
2294 }
2295
2296 SurfaceComposerClient::Transaction&
setTrustedPresentationCallback(const sp<SurfaceControl> & sc,TrustedPresentationCallback cb,const TrustedPresentationThresholds & thresholds,void * context,sp<SurfaceComposerClient::PresentationCallbackRAII> & outCallbackRef)2297 SurfaceComposerClient::Transaction::setTrustedPresentationCallback(
2298 const sp<SurfaceControl>& sc, TrustedPresentationCallback cb,
2299 const TrustedPresentationThresholds& thresholds, void* context,
2300 sp<SurfaceComposerClient::PresentationCallbackRAII>& outCallbackRef) {
2301 auto listener = TransactionCompletedListener::getInstance();
2302 outCallbackRef = listener->addTrustedPresentationCallback(cb, sc->getLayerId(), context);
2303
2304 layer_state_t* s = getLayerState(sc);
2305 if (!s) {
2306 mStatus = BAD_INDEX;
2307 return *this;
2308 }
2309 s->what |= layer_state_t::eTrustedPresentationInfoChanged;
2310 s->trustedPresentationThresholds = thresholds;
2311 s->trustedPresentationListener.callbackInterface = TransactionCompletedListener::getIInstance();
2312 s->trustedPresentationListener.callbackId = sc->getLayerId();
2313
2314 return *this;
2315 }
2316
2317 SurfaceComposerClient::Transaction&
clearTrustedPresentationCallback(const sp<SurfaceControl> & sc)2318 SurfaceComposerClient::Transaction::clearTrustedPresentationCallback(const sp<SurfaceControl>& sc) {
2319 auto listener = TransactionCompletedListener::getInstance();
2320 listener->clearTrustedPresentationCallback(sc->getLayerId());
2321
2322 layer_state_t* s = getLayerState(sc);
2323 if (!s) {
2324 mStatus = BAD_INDEX;
2325 return *this;
2326 }
2327 s->what |= layer_state_t::eTrustedPresentationInfoChanged;
2328 s->trustedPresentationThresholds = TrustedPresentationThresholds();
2329 s->trustedPresentationListener.callbackInterface = nullptr;
2330 s->trustedPresentationListener.callbackId = -1;
2331
2332 return *this;
2333 }
2334
2335 // ---------------------------------------------------------------------------
2336
SurfaceComposerClient()2337 SurfaceComposerClient::SurfaceComposerClient() : mStatus(NO_INIT) {}
2338
SurfaceComposerClient(const sp<ISurfaceComposerClient> & client)2339 SurfaceComposerClient::SurfaceComposerClient(const sp<ISurfaceComposerClient>& client)
2340 : mStatus(NO_ERROR), mClient(client) {}
2341
onFirstRef()2342 void SurfaceComposerClient::onFirstRef() {
2343 sp<gui::ISurfaceComposer> sf(ComposerServiceAIDL::getComposerService());
2344 if (sf != nullptr && mStatus == NO_INIT) {
2345 sp<ISurfaceComposerClient> conn;
2346 binder::Status status = sf->createConnection(&conn);
2347 if (status.isOk() && conn != nullptr) {
2348 mClient = conn;
2349 mStatus = NO_ERROR;
2350 }
2351 }
2352 }
2353
~SurfaceComposerClient()2354 SurfaceComposerClient::~SurfaceComposerClient() {
2355 dispose();
2356 }
2357
initCheck() const2358 status_t SurfaceComposerClient::initCheck() const {
2359 return mStatus;
2360 }
2361
connection() const2362 sp<IBinder> SurfaceComposerClient::connection() const {
2363 return IInterface::asBinder(mClient);
2364 }
2365
linkToComposerDeath(const sp<IBinder::DeathRecipient> & recipient,void * cookie,uint32_t flags)2366 status_t SurfaceComposerClient::linkToComposerDeath(
2367 const sp<IBinder::DeathRecipient>& recipient,
2368 void* cookie, uint32_t flags) {
2369 sp<ISurfaceComposer> sf(ComposerService::getComposerService());
2370 return IInterface::asBinder(sf)->linkToDeath(recipient, cookie, flags);
2371 }
2372
dispose()2373 void SurfaceComposerClient::dispose() {
2374 // this can be called more than once.
2375 sp<ISurfaceComposerClient> client;
2376 Mutex::Autolock _lm(mLock);
2377 if (mClient != nullptr) {
2378 client = mClient; // hold ref while lock is held
2379 mClient.clear();
2380 }
2381 mStatus = NO_INIT;
2382 }
2383
bootFinished()2384 status_t SurfaceComposerClient::bootFinished() {
2385 sp<gui::ISurfaceComposer> sf(ComposerServiceAIDL::getComposerService());
2386 binder::Status status = sf->bootFinished();
2387 return statusTFromBinderStatus(status);
2388 }
2389
createSurface(const String8 & name,uint32_t w,uint32_t h,PixelFormat format,int32_t flags,const sp<IBinder> & parentHandle,LayerMetadata metadata,uint32_t * outTransformHint)2390 sp<SurfaceControl> SurfaceComposerClient::createSurface(const String8& name, uint32_t w, uint32_t h,
2391 PixelFormat format, int32_t flags,
2392 const sp<IBinder>& parentHandle,
2393 LayerMetadata metadata,
2394 uint32_t* outTransformHint) {
2395 sp<SurfaceControl> s;
2396 createSurfaceChecked(name, w, h, format, &s, flags, parentHandle, std::move(metadata),
2397 outTransformHint);
2398 return s;
2399 }
2400
toString(const String16 & string)2401 static std::string toString(const String16& string) {
2402 return std::string(String8(string).c_str());
2403 }
2404
createSurfaceChecked(const String8 & name,uint32_t w,uint32_t h,PixelFormat format,sp<SurfaceControl> * outSurface,int32_t flags,const sp<IBinder> & parentHandle,LayerMetadata metadata,uint32_t * outTransformHint)2405 status_t SurfaceComposerClient::createSurfaceChecked(const String8& name, uint32_t w, uint32_t h,
2406 PixelFormat format,
2407 sp<SurfaceControl>* outSurface, int32_t flags,
2408 const sp<IBinder>& parentHandle,
2409 LayerMetadata metadata,
2410 uint32_t* outTransformHint) {
2411 sp<SurfaceControl> sur;
2412 status_t err = mStatus;
2413
2414 if (mStatus == NO_ERROR) {
2415 gui::CreateSurfaceResult result;
2416 binder::Status status = mClient->createSurface(std::string(name.string()), flags,
2417 parentHandle, std::move(metadata), &result);
2418 err = statusTFromBinderStatus(status);
2419 if (outTransformHint) {
2420 *outTransformHint = result.transformHint;
2421 }
2422 ALOGE_IF(err, "SurfaceComposerClient::createSurface error %s", strerror(-err));
2423 if (err == NO_ERROR) {
2424 *outSurface = new SurfaceControl(this, result.handle, result.layerId,
2425 toString(result.layerName), w, h, format,
2426 result.transformHint, flags);
2427 }
2428 }
2429 return err;
2430 }
2431
mirrorSurface(SurfaceControl * mirrorFromSurface)2432 sp<SurfaceControl> SurfaceComposerClient::mirrorSurface(SurfaceControl* mirrorFromSurface) {
2433 if (mirrorFromSurface == nullptr) {
2434 return nullptr;
2435 }
2436
2437 sp<IBinder> mirrorFromHandle = mirrorFromSurface->getHandle();
2438 gui::CreateSurfaceResult result;
2439 const binder::Status status = mClient->mirrorSurface(mirrorFromHandle, &result);
2440 const status_t err = statusTFromBinderStatus(status);
2441 if (err == NO_ERROR) {
2442 return new SurfaceControl(this, result.handle, result.layerId, toString(result.layerName));
2443 }
2444 return nullptr;
2445 }
2446
mirrorDisplay(DisplayId displayId)2447 sp<SurfaceControl> SurfaceComposerClient::mirrorDisplay(DisplayId displayId) {
2448 gui::CreateSurfaceResult result;
2449 const binder::Status status = mClient->mirrorDisplay(displayId.value, &result);
2450 const status_t err = statusTFromBinderStatus(status);
2451 if (err == NO_ERROR) {
2452 return new SurfaceControl(this, result.handle, result.layerId, toString(result.layerName));
2453 }
2454 return nullptr;
2455 }
2456
clearLayerFrameStats(const sp<IBinder> & token) const2457 status_t SurfaceComposerClient::clearLayerFrameStats(const sp<IBinder>& token) const {
2458 if (mStatus != NO_ERROR) {
2459 return mStatus;
2460 }
2461 const binder::Status status = mClient->clearLayerFrameStats(token);
2462 return statusTFromBinderStatus(status);
2463 }
2464
getLayerFrameStats(const sp<IBinder> & token,FrameStats * outStats) const2465 status_t SurfaceComposerClient::getLayerFrameStats(const sp<IBinder>& token,
2466 FrameStats* outStats) const {
2467 if (mStatus != NO_ERROR) {
2468 return mStatus;
2469 }
2470 gui::FrameStats stats;
2471 const binder::Status status = mClient->getLayerFrameStats(token, &stats);
2472 if (status.isOk()) {
2473 outStats->refreshPeriodNano = stats.refreshPeriodNano;
2474 outStats->desiredPresentTimesNano.setCapacity(stats.desiredPresentTimesNano.size());
2475 for (const auto& t : stats.desiredPresentTimesNano) {
2476 outStats->desiredPresentTimesNano.add(t);
2477 }
2478 outStats->actualPresentTimesNano.setCapacity(stats.actualPresentTimesNano.size());
2479 for (const auto& t : stats.actualPresentTimesNano) {
2480 outStats->actualPresentTimesNano.add(t);
2481 }
2482 outStats->frameReadyTimesNano.setCapacity(stats.frameReadyTimesNano.size());
2483 for (const auto& t : stats.frameReadyTimesNano) {
2484 outStats->frameReadyTimesNano.add(t);
2485 }
2486 }
2487 return statusTFromBinderStatus(status);
2488 }
2489
2490 // ----------------------------------------------------------------------------
2491
getDisplayState(const sp<IBinder> & display,ui::DisplayState * state)2492 status_t SurfaceComposerClient::getDisplayState(const sp<IBinder>& display,
2493 ui::DisplayState* state) {
2494 gui::DisplayState ds;
2495 binder::Status status =
2496 ComposerServiceAIDL::getComposerService()->getDisplayState(display, &ds);
2497 if (status.isOk()) {
2498 state->layerStack = ui::LayerStack::fromValue(ds.layerStack);
2499 state->orientation = static_cast<ui::Rotation>(ds.orientation);
2500 state->layerStackSpaceRect =
2501 ui::Size(ds.layerStackSpaceRect.width, ds.layerStackSpaceRect.height);
2502 }
2503 return statusTFromBinderStatus(status);
2504 }
2505
getStaticDisplayInfo(int64_t displayId,ui::StaticDisplayInfo * outInfo)2506 status_t SurfaceComposerClient::getStaticDisplayInfo(int64_t displayId,
2507 ui::StaticDisplayInfo* outInfo) {
2508 using Tag = android::gui::DeviceProductInfo::ManufactureOrModelDate::Tag;
2509 gui::StaticDisplayInfo ginfo;
2510 binder::Status status =
2511 ComposerServiceAIDL::getComposerService()->getStaticDisplayInfo(displayId, &ginfo);
2512 if (status.isOk()) {
2513 // convert gui::StaticDisplayInfo to ui::StaticDisplayInfo
2514 outInfo->connectionType = static_cast<ui::DisplayConnectionType>(ginfo.connectionType);
2515 outInfo->density = ginfo.density;
2516 outInfo->secure = ginfo.secure;
2517 outInfo->installOrientation = static_cast<ui::Rotation>(ginfo.installOrientation);
2518
2519 if (const std::optional<gui::DeviceProductInfo> dpi = ginfo.deviceProductInfo) {
2520 DeviceProductInfo info;
2521 info.name = dpi->name;
2522 if (dpi->manufacturerPnpId.size() > 0) {
2523 // copid from PnpId = std::array<char, 4> in ui/DeviceProductInfo.h
2524 constexpr int kMaxPnpIdSize = 4;
2525 size_t count = std::max<size_t>(kMaxPnpIdSize, dpi->manufacturerPnpId.size());
2526 std::copy_n(dpi->manufacturerPnpId.begin(), count, info.manufacturerPnpId.begin());
2527 }
2528 if (dpi->relativeAddress.size() > 0) {
2529 std::copy(dpi->relativeAddress.begin(), dpi->relativeAddress.end(),
2530 std::back_inserter(info.relativeAddress));
2531 }
2532 info.productId = dpi->productId;
2533
2534 const gui::DeviceProductInfo::ManufactureOrModelDate& date =
2535 dpi->manufactureOrModelDate;
2536 if (date.getTag() == Tag::modelYear) {
2537 DeviceProductInfo::ModelYear modelYear;
2538 modelYear.year = static_cast<uint32_t>(date.get<Tag::modelYear>().year);
2539 info.manufactureOrModelDate = modelYear;
2540 } else if (date.getTag() == Tag::manufactureYear) {
2541 DeviceProductInfo::ManufactureYear manufactureYear;
2542 manufactureYear.year = date.get<Tag::manufactureYear>().modelYear.year;
2543 info.manufactureOrModelDate = manufactureYear;
2544 } else if (date.getTag() == Tag::manufactureWeekAndYear) {
2545 DeviceProductInfo::ManufactureWeekAndYear weekAndYear;
2546 weekAndYear.year =
2547 date.get<Tag::manufactureWeekAndYear>().manufactureYear.modelYear.year;
2548 weekAndYear.week = date.get<Tag::manufactureWeekAndYear>().week;
2549 info.manufactureOrModelDate = weekAndYear;
2550 }
2551
2552 outInfo->deviceProductInfo = info;
2553 }
2554 }
2555 return statusTFromBinderStatus(status);
2556 }
2557
getDynamicDisplayInfoInternal(gui::DynamicDisplayInfo & ginfo,ui::DynamicDisplayInfo * & outInfo)2558 void SurfaceComposerClient::getDynamicDisplayInfoInternal(gui::DynamicDisplayInfo& ginfo,
2559 ui::DynamicDisplayInfo*& outInfo) {
2560 // convert gui::DynamicDisplayInfo to ui::DynamicDisplayInfo
2561 outInfo->supportedDisplayModes.clear();
2562 outInfo->supportedDisplayModes.reserve(ginfo.supportedDisplayModes.size());
2563 for (const auto& mode : ginfo.supportedDisplayModes) {
2564 ui::DisplayMode outMode;
2565 outMode.id = mode.id;
2566 outMode.resolution.width = mode.resolution.width;
2567 outMode.resolution.height = mode.resolution.height;
2568 outMode.xDpi = mode.xDpi;
2569 outMode.yDpi = mode.yDpi;
2570 outMode.refreshRate = mode.refreshRate;
2571 outMode.appVsyncOffset = mode.appVsyncOffset;
2572 outMode.sfVsyncOffset = mode.sfVsyncOffset;
2573 outMode.presentationDeadline = mode.presentationDeadline;
2574 outMode.group = mode.group;
2575 std::transform(mode.supportedHdrTypes.begin(), mode.supportedHdrTypes.end(),
2576 std::back_inserter(outMode.supportedHdrTypes),
2577 [](const int32_t& value) { return static_cast<ui::Hdr>(value); });
2578 outInfo->supportedDisplayModes.push_back(outMode);
2579 }
2580
2581 outInfo->activeDisplayModeId = ginfo.activeDisplayModeId;
2582 outInfo->renderFrameRate = ginfo.renderFrameRate;
2583
2584 outInfo->supportedColorModes.clear();
2585 outInfo->supportedColorModes.reserve(ginfo.supportedColorModes.size());
2586 for (const auto& cmode : ginfo.supportedColorModes) {
2587 outInfo->supportedColorModes.push_back(static_cast<ui::ColorMode>(cmode));
2588 }
2589
2590 outInfo->activeColorMode = static_cast<ui::ColorMode>(ginfo.activeColorMode);
2591
2592 std::vector<ui::Hdr> types;
2593 types.reserve(ginfo.hdrCapabilities.supportedHdrTypes.size());
2594 for (const auto& hdr : ginfo.hdrCapabilities.supportedHdrTypes) {
2595 types.push_back(static_cast<ui::Hdr>(hdr));
2596 }
2597 outInfo->hdrCapabilities = HdrCapabilities(types, ginfo.hdrCapabilities.maxLuminance,
2598 ginfo.hdrCapabilities.maxAverageLuminance,
2599 ginfo.hdrCapabilities.minLuminance);
2600
2601 outInfo->autoLowLatencyModeSupported = ginfo.autoLowLatencyModeSupported;
2602 outInfo->gameContentTypeSupported = ginfo.gameContentTypeSupported;
2603 outInfo->preferredBootDisplayMode = ginfo.preferredBootDisplayMode;
2604 }
2605
getDynamicDisplayInfoFromId(int64_t displayId,ui::DynamicDisplayInfo * outInfo)2606 status_t SurfaceComposerClient::getDynamicDisplayInfoFromId(int64_t displayId,
2607 ui::DynamicDisplayInfo* outInfo) {
2608 gui::DynamicDisplayInfo ginfo;
2609 binder::Status status =
2610 ComposerServiceAIDL::getComposerService()->getDynamicDisplayInfoFromId(displayId,
2611 &ginfo);
2612 if (status.isOk()) {
2613 getDynamicDisplayInfoInternal(ginfo, outInfo);
2614 }
2615 return statusTFromBinderStatus(status);
2616 }
2617
getDynamicDisplayInfoFromToken(const sp<IBinder> & display,ui::DynamicDisplayInfo * outInfo)2618 status_t SurfaceComposerClient::getDynamicDisplayInfoFromToken(const sp<IBinder>& display,
2619 ui::DynamicDisplayInfo* outInfo) {
2620 gui::DynamicDisplayInfo ginfo;
2621 binder::Status status =
2622 ComposerServiceAIDL::getComposerService()->getDynamicDisplayInfoFromToken(display,
2623 &ginfo);
2624 if (status.isOk()) {
2625 getDynamicDisplayInfoInternal(ginfo, outInfo);
2626 }
2627 return statusTFromBinderStatus(status);
2628 }
2629
getActiveDisplayMode(const sp<IBinder> & display,ui::DisplayMode * mode)2630 status_t SurfaceComposerClient::getActiveDisplayMode(const sp<IBinder>& display,
2631 ui::DisplayMode* mode) {
2632 ui::DynamicDisplayInfo info;
2633
2634 status_t result = getDynamicDisplayInfoFromToken(display, &info);
2635 if (result != NO_ERROR) {
2636 return result;
2637 }
2638
2639 if (const auto activeMode = info.getActiveDisplayMode()) {
2640 *mode = *activeMode;
2641 return NO_ERROR;
2642 }
2643
2644 ALOGE("Active display mode not found.");
2645 return NAME_NOT_FOUND;
2646 }
2647
setDesiredDisplayModeSpecs(const sp<IBinder> & displayToken,const gui::DisplayModeSpecs & specs)2648 status_t SurfaceComposerClient::setDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
2649 const gui::DisplayModeSpecs& specs) {
2650 binder::Status status =
2651 ComposerServiceAIDL::getComposerService()->setDesiredDisplayModeSpecs(displayToken,
2652 specs);
2653 return statusTFromBinderStatus(status);
2654 }
2655
getDesiredDisplayModeSpecs(const sp<IBinder> & displayToken,gui::DisplayModeSpecs * outSpecs)2656 status_t SurfaceComposerClient::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
2657 gui::DisplayModeSpecs* outSpecs) {
2658 if (!outSpecs) {
2659 return BAD_VALUE;
2660 }
2661 binder::Status status =
2662 ComposerServiceAIDL::getComposerService()->getDesiredDisplayModeSpecs(displayToken,
2663 outSpecs);
2664 return statusTFromBinderStatus(status);
2665 }
2666
getDisplayNativePrimaries(const sp<IBinder> & display,ui::DisplayPrimaries & outPrimaries)2667 status_t SurfaceComposerClient::getDisplayNativePrimaries(const sp<IBinder>& display,
2668 ui::DisplayPrimaries& outPrimaries) {
2669 gui::DisplayPrimaries primaries;
2670 binder::Status status =
2671 ComposerServiceAIDL::getComposerService()->getDisplayNativePrimaries(display,
2672 &primaries);
2673 if (status.isOk()) {
2674 outPrimaries.red.X = primaries.red.X;
2675 outPrimaries.red.Y = primaries.red.Y;
2676 outPrimaries.red.Z = primaries.red.Z;
2677
2678 outPrimaries.green.X = primaries.green.X;
2679 outPrimaries.green.Y = primaries.green.Y;
2680 outPrimaries.green.Z = primaries.green.Z;
2681
2682 outPrimaries.blue.X = primaries.blue.X;
2683 outPrimaries.blue.Y = primaries.blue.Y;
2684 outPrimaries.blue.Z = primaries.blue.Z;
2685
2686 outPrimaries.white.X = primaries.white.X;
2687 outPrimaries.white.Y = primaries.white.Y;
2688 outPrimaries.white.Z = primaries.white.Z;
2689 }
2690 return statusTFromBinderStatus(status);
2691 }
2692
setActiveColorMode(const sp<IBinder> & display,ColorMode colorMode)2693 status_t SurfaceComposerClient::setActiveColorMode(const sp<IBinder>& display,
2694 ColorMode colorMode) {
2695 binder::Status status = ComposerServiceAIDL::getComposerService()
2696 ->setActiveColorMode(display, static_cast<int>(colorMode));
2697 return statusTFromBinderStatus(status);
2698 }
2699
getBootDisplayModeSupport(bool * support)2700 status_t SurfaceComposerClient::getBootDisplayModeSupport(bool* support) {
2701 binder::Status status =
2702 ComposerServiceAIDL::getComposerService()->getBootDisplayModeSupport(support);
2703 return statusTFromBinderStatus(status);
2704 }
2705
getOverlaySupport(gui::OverlayProperties * outProperties)2706 status_t SurfaceComposerClient::getOverlaySupport(gui::OverlayProperties* outProperties) {
2707 binder::Status status =
2708 ComposerServiceAIDL::getComposerService()->getOverlaySupport(outProperties);
2709 return statusTFromBinderStatus(status);
2710 }
2711
setBootDisplayMode(const sp<IBinder> & display,ui::DisplayModeId displayModeId)2712 status_t SurfaceComposerClient::setBootDisplayMode(const sp<IBinder>& display,
2713 ui::DisplayModeId displayModeId) {
2714 binder::Status status = ComposerServiceAIDL::getComposerService()
2715 ->setBootDisplayMode(display, static_cast<int>(displayModeId));
2716 return statusTFromBinderStatus(status);
2717 }
2718
clearBootDisplayMode(const sp<IBinder> & display)2719 status_t SurfaceComposerClient::clearBootDisplayMode(const sp<IBinder>& display) {
2720 binder::Status status =
2721 ComposerServiceAIDL::getComposerService()->clearBootDisplayMode(display);
2722 return statusTFromBinderStatus(status);
2723 }
2724
getHdrConversionCapabilities(std::vector<gui::HdrConversionCapability> * hdrConversionCapabilities)2725 status_t SurfaceComposerClient::getHdrConversionCapabilities(
2726 std::vector<gui::HdrConversionCapability>* hdrConversionCapabilities) {
2727 binder::Status status = ComposerServiceAIDL::getComposerService()->getHdrConversionCapabilities(
2728 hdrConversionCapabilities);
2729 return statusTFromBinderStatus(status);
2730 }
2731
setHdrConversionStrategy(gui::HdrConversionStrategy hdrConversionStrategy,ui::Hdr * outPreferredHdrOutputType)2732 status_t SurfaceComposerClient::setHdrConversionStrategy(
2733 gui::HdrConversionStrategy hdrConversionStrategy, ui::Hdr* outPreferredHdrOutputType) {
2734 int hdrType;
2735 binder::Status status = ComposerServiceAIDL::getComposerService()
2736 ->setHdrConversionStrategy(hdrConversionStrategy, &hdrType);
2737 *outPreferredHdrOutputType = static_cast<ui::Hdr>(hdrType);
2738 return statusTFromBinderStatus(status);
2739 }
2740
getHdrOutputConversionSupport(bool * isSupported)2741 status_t SurfaceComposerClient::getHdrOutputConversionSupport(bool* isSupported) {
2742 binder::Status status =
2743 ComposerServiceAIDL::getComposerService()->getHdrOutputConversionSupport(isSupported);
2744 return statusTFromBinderStatus(status);
2745 }
2746
setOverrideFrameRate(uid_t uid,float frameRate)2747 status_t SurfaceComposerClient::setOverrideFrameRate(uid_t uid, float frameRate) {
2748 binder::Status status =
2749 ComposerServiceAIDL::getComposerService()->setOverrideFrameRate(uid, frameRate);
2750 return statusTFromBinderStatus(status);
2751 }
2752
updateSmallAreaDetection(std::vector<int32_t> & uids,std::vector<float> & thresholds)2753 status_t SurfaceComposerClient::updateSmallAreaDetection(std::vector<int32_t>& uids,
2754 std::vector<float>& thresholds) {
2755 binder::Status status =
2756 ComposerServiceAIDL::getComposerService()->updateSmallAreaDetection(uids, thresholds);
2757 return statusTFromBinderStatus(status);
2758 }
2759
setSmallAreaDetectionThreshold(uid_t uid,float threshold)2760 status_t SurfaceComposerClient::setSmallAreaDetectionThreshold(uid_t uid, float threshold) {
2761 binder::Status status =
2762 ComposerServiceAIDL::getComposerService()->setSmallAreaDetectionThreshold(uid,
2763 threshold);
2764 return statusTFromBinderStatus(status);
2765 }
2766
setAutoLowLatencyMode(const sp<IBinder> & display,bool on)2767 void SurfaceComposerClient::setAutoLowLatencyMode(const sp<IBinder>& display, bool on) {
2768 ComposerServiceAIDL::getComposerService()->setAutoLowLatencyMode(display, on);
2769 }
2770
setGameContentType(const sp<IBinder> & display,bool on)2771 void SurfaceComposerClient::setGameContentType(const sp<IBinder>& display, bool on) {
2772 ComposerServiceAIDL::getComposerService()->setGameContentType(display, on);
2773 }
2774
setDisplayPowerMode(const sp<IBinder> & token,int mode)2775 void SurfaceComposerClient::setDisplayPowerMode(const sp<IBinder>& token,
2776 int mode) {
2777 ComposerServiceAIDL::getComposerService()->setPowerMode(token, mode);
2778 }
2779
getCompositionPreference(ui::Dataspace * defaultDataspace,ui::PixelFormat * defaultPixelFormat,ui::Dataspace * wideColorGamutDataspace,ui::PixelFormat * wideColorGamutPixelFormat)2780 status_t SurfaceComposerClient::getCompositionPreference(
2781 ui::Dataspace* defaultDataspace, ui::PixelFormat* defaultPixelFormat,
2782 ui::Dataspace* wideColorGamutDataspace, ui::PixelFormat* wideColorGamutPixelFormat) {
2783 gui::CompositionPreference pref;
2784 binder::Status status =
2785 ComposerServiceAIDL::getComposerService()->getCompositionPreference(&pref);
2786 if (status.isOk()) {
2787 *defaultDataspace = static_cast<ui::Dataspace>(pref.defaultDataspace);
2788 *defaultPixelFormat = static_cast<ui::PixelFormat>(pref.defaultPixelFormat);
2789 *wideColorGamutDataspace = static_cast<ui::Dataspace>(pref.wideColorGamutDataspace);
2790 *wideColorGamutPixelFormat = static_cast<ui::PixelFormat>(pref.wideColorGamutPixelFormat);
2791 }
2792 return statusTFromBinderStatus(status);
2793 }
2794
getProtectedContentSupport()2795 bool SurfaceComposerClient::getProtectedContentSupport() {
2796 bool supported = false;
2797 ComposerServiceAIDL::getComposerService()->getProtectedContentSupport(&supported);
2798 return supported;
2799 }
2800
clearAnimationFrameStats()2801 status_t SurfaceComposerClient::clearAnimationFrameStats() {
2802 binder::Status status = ComposerServiceAIDL::getComposerService()->clearAnimationFrameStats();
2803 return statusTFromBinderStatus(status);
2804 }
2805
getAnimationFrameStats(FrameStats * outStats)2806 status_t SurfaceComposerClient::getAnimationFrameStats(FrameStats* outStats) {
2807 gui::FrameStats stats;
2808 binder::Status status =
2809 ComposerServiceAIDL::getComposerService()->getAnimationFrameStats(&stats);
2810 if (status.isOk()) {
2811 outStats->refreshPeriodNano = stats.refreshPeriodNano;
2812 outStats->desiredPresentTimesNano.setCapacity(stats.desiredPresentTimesNano.size());
2813 for (const auto& t : stats.desiredPresentTimesNano) {
2814 outStats->desiredPresentTimesNano.add(t);
2815 }
2816 outStats->actualPresentTimesNano.setCapacity(stats.actualPresentTimesNano.size());
2817 for (const auto& t : stats.actualPresentTimesNano) {
2818 outStats->actualPresentTimesNano.add(t);
2819 }
2820 outStats->frameReadyTimesNano.setCapacity(stats.frameReadyTimesNano.size());
2821 for (const auto& t : stats.frameReadyTimesNano) {
2822 outStats->frameReadyTimesNano.add(t);
2823 }
2824 }
2825 return statusTFromBinderStatus(status);
2826 }
2827
overrideHdrTypes(const sp<IBinder> & display,const std::vector<ui::Hdr> & hdrTypes)2828 status_t SurfaceComposerClient::overrideHdrTypes(const sp<IBinder>& display,
2829 const std::vector<ui::Hdr>& hdrTypes) {
2830 std::vector<int32_t> hdrTypesVector;
2831 hdrTypesVector.reserve(hdrTypes.size());
2832 for (auto t : hdrTypes) {
2833 hdrTypesVector.push_back(static_cast<int32_t>(t));
2834 }
2835
2836 binder::Status status =
2837 ComposerServiceAIDL::getComposerService()->overrideHdrTypes(display, hdrTypesVector);
2838 return statusTFromBinderStatus(status);
2839 }
2840
onPullAtom(const int32_t atomId,std::string * outData,bool * success)2841 status_t SurfaceComposerClient::onPullAtom(const int32_t atomId, std::string* outData,
2842 bool* success) {
2843 gui::PullAtomData pad;
2844 binder::Status status = ComposerServiceAIDL::getComposerService()->onPullAtom(atomId, &pad);
2845 if (status.isOk()) {
2846 outData->assign(pad.data.begin(), pad.data.end());
2847 *success = pad.success;
2848 }
2849 return statusTFromBinderStatus(status);
2850 }
2851
getDisplayedContentSamplingAttributes(const sp<IBinder> & display,ui::PixelFormat * outFormat,ui::Dataspace * outDataspace,uint8_t * outComponentMask)2852 status_t SurfaceComposerClient::getDisplayedContentSamplingAttributes(const sp<IBinder>& display,
2853 ui::PixelFormat* outFormat,
2854 ui::Dataspace* outDataspace,
2855 uint8_t* outComponentMask) {
2856 if (!outFormat || !outDataspace || !outComponentMask) {
2857 return BAD_VALUE;
2858 }
2859
2860 gui::ContentSamplingAttributes attrs;
2861 binder::Status status = ComposerServiceAIDL::getComposerService()
2862 ->getDisplayedContentSamplingAttributes(display, &attrs);
2863 if (status.isOk()) {
2864 *outFormat = static_cast<ui::PixelFormat>(attrs.format);
2865 *outDataspace = static_cast<ui::Dataspace>(attrs.dataspace);
2866 *outComponentMask = static_cast<uint8_t>(attrs.componentMask);
2867 }
2868 return statusTFromBinderStatus(status);
2869 }
2870
setDisplayContentSamplingEnabled(const sp<IBinder> & display,bool enable,uint8_t componentMask,uint64_t maxFrames)2871 status_t SurfaceComposerClient::setDisplayContentSamplingEnabled(const sp<IBinder>& display,
2872 bool enable, uint8_t componentMask,
2873 uint64_t maxFrames) {
2874 binder::Status status =
2875 ComposerServiceAIDL::getComposerService()
2876 ->setDisplayContentSamplingEnabled(display, enable,
2877 static_cast<int8_t>(componentMask),
2878 static_cast<int64_t>(maxFrames));
2879 return statusTFromBinderStatus(status);
2880 }
2881
getDisplayedContentSample(const sp<IBinder> & display,uint64_t maxFrames,uint64_t timestamp,DisplayedFrameStats * outStats)2882 status_t SurfaceComposerClient::getDisplayedContentSample(const sp<IBinder>& display,
2883 uint64_t maxFrames, uint64_t timestamp,
2884 DisplayedFrameStats* outStats) {
2885 if (!outStats) {
2886 return BAD_VALUE;
2887 }
2888
2889 gui::DisplayedFrameStats stats;
2890 binder::Status status =
2891 ComposerServiceAIDL::getComposerService()->getDisplayedContentSample(display, maxFrames,
2892 timestamp, &stats);
2893 if (status.isOk()) {
2894 // convert gui::DisplayedFrameStats to ui::DisplayedFrameStats
2895 outStats->numFrames = static_cast<uint64_t>(stats.numFrames);
2896 outStats->component_0_sample.reserve(stats.component_0_sample.size());
2897 for (const auto& s : stats.component_0_sample) {
2898 outStats->component_0_sample.push_back(static_cast<uint64_t>(s));
2899 }
2900 outStats->component_1_sample.reserve(stats.component_1_sample.size());
2901 for (const auto& s : stats.component_1_sample) {
2902 outStats->component_1_sample.push_back(static_cast<uint64_t>(s));
2903 }
2904 outStats->component_2_sample.reserve(stats.component_2_sample.size());
2905 for (const auto& s : stats.component_2_sample) {
2906 outStats->component_2_sample.push_back(static_cast<uint64_t>(s));
2907 }
2908 outStats->component_3_sample.reserve(stats.component_3_sample.size());
2909 for (const auto& s : stats.component_3_sample) {
2910 outStats->component_3_sample.push_back(static_cast<uint64_t>(s));
2911 }
2912 }
2913 return statusTFromBinderStatus(status);
2914 }
2915
isWideColorDisplay(const sp<IBinder> & display,bool * outIsWideColorDisplay)2916 status_t SurfaceComposerClient::isWideColorDisplay(const sp<IBinder>& display,
2917 bool* outIsWideColorDisplay) {
2918 binder::Status status =
2919 ComposerServiceAIDL::getComposerService()->isWideColorDisplay(display,
2920 outIsWideColorDisplay);
2921 return statusTFromBinderStatus(status);
2922 }
2923
addRegionSamplingListener(const Rect & samplingArea,const sp<IBinder> & stopLayerHandle,const sp<IRegionSamplingListener> & listener)2924 status_t SurfaceComposerClient::addRegionSamplingListener(
2925 const Rect& samplingArea, const sp<IBinder>& stopLayerHandle,
2926 const sp<IRegionSamplingListener>& listener) {
2927 gui::ARect rect;
2928 rect.left = samplingArea.left;
2929 rect.top = samplingArea.top;
2930 rect.right = samplingArea.right;
2931 rect.bottom = samplingArea.bottom;
2932 binder::Status status =
2933 ComposerServiceAIDL::getComposerService()->addRegionSamplingListener(rect,
2934 stopLayerHandle,
2935 listener);
2936 return statusTFromBinderStatus(status);
2937 }
2938
removeRegionSamplingListener(const sp<IRegionSamplingListener> & listener)2939 status_t SurfaceComposerClient::removeRegionSamplingListener(
2940 const sp<IRegionSamplingListener>& listener) {
2941 binder::Status status =
2942 ComposerServiceAIDL::getComposerService()->removeRegionSamplingListener(listener);
2943 return statusTFromBinderStatus(status);
2944 }
2945
addFpsListener(int32_t taskId,const sp<gui::IFpsListener> & listener)2946 status_t SurfaceComposerClient::addFpsListener(int32_t taskId,
2947 const sp<gui::IFpsListener>& listener) {
2948 binder::Status status =
2949 ComposerServiceAIDL::getComposerService()->addFpsListener(taskId, listener);
2950 return statusTFromBinderStatus(status);
2951 }
2952
removeFpsListener(const sp<gui::IFpsListener> & listener)2953 status_t SurfaceComposerClient::removeFpsListener(const sp<gui::IFpsListener>& listener) {
2954 binder::Status status = ComposerServiceAIDL::getComposerService()->removeFpsListener(listener);
2955 return statusTFromBinderStatus(status);
2956 }
2957
addTunnelModeEnabledListener(const sp<gui::ITunnelModeEnabledListener> & listener)2958 status_t SurfaceComposerClient::addTunnelModeEnabledListener(
2959 const sp<gui::ITunnelModeEnabledListener>& listener) {
2960 binder::Status status =
2961 ComposerServiceAIDL::getComposerService()->addTunnelModeEnabledListener(listener);
2962 return statusTFromBinderStatus(status);
2963 }
2964
removeTunnelModeEnabledListener(const sp<gui::ITunnelModeEnabledListener> & listener)2965 status_t SurfaceComposerClient::removeTunnelModeEnabledListener(
2966 const sp<gui::ITunnelModeEnabledListener>& listener) {
2967 binder::Status status =
2968 ComposerServiceAIDL::getComposerService()->removeTunnelModeEnabledListener(listener);
2969 return statusTFromBinderStatus(status);
2970 }
2971
getDisplayBrightnessSupport(const sp<IBinder> & displayToken)2972 bool SurfaceComposerClient::getDisplayBrightnessSupport(const sp<IBinder>& displayToken) {
2973 bool support = false;
2974 binder::Status status =
2975 ComposerServiceAIDL::getComposerService()->getDisplayBrightnessSupport(displayToken,
2976 &support);
2977 return status.isOk() ? support : false;
2978 }
2979
setDisplayBrightness(const sp<IBinder> & displayToken,const gui::DisplayBrightness & brightness)2980 status_t SurfaceComposerClient::setDisplayBrightness(const sp<IBinder>& displayToken,
2981 const gui::DisplayBrightness& brightness) {
2982 binder::Status status =
2983 ComposerServiceAIDL::getComposerService()->setDisplayBrightness(displayToken,
2984 brightness);
2985 return statusTFromBinderStatus(status);
2986 }
2987
addHdrLayerInfoListener(const sp<IBinder> & displayToken,const sp<gui::IHdrLayerInfoListener> & listener)2988 status_t SurfaceComposerClient::addHdrLayerInfoListener(
2989 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
2990 binder::Status status =
2991 ComposerServiceAIDL::getComposerService()->addHdrLayerInfoListener(displayToken,
2992 listener);
2993 return statusTFromBinderStatus(status);
2994 }
2995
removeHdrLayerInfoListener(const sp<IBinder> & displayToken,const sp<gui::IHdrLayerInfoListener> & listener)2996 status_t SurfaceComposerClient::removeHdrLayerInfoListener(
2997 const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
2998 binder::Status status =
2999 ComposerServiceAIDL::getComposerService()->removeHdrLayerInfoListener(displayToken,
3000 listener);
3001 return statusTFromBinderStatus(status);
3002 }
3003
notifyPowerBoost(int32_t boostId)3004 status_t SurfaceComposerClient::notifyPowerBoost(int32_t boostId) {
3005 binder::Status status = ComposerServiceAIDL::getComposerService()->notifyPowerBoost(boostId);
3006 return statusTFromBinderStatus(status);
3007 }
3008
setGlobalShadowSettings(const half4 & ambientColor,const half4 & spotColor,float lightPosY,float lightPosZ,float lightRadius)3009 status_t SurfaceComposerClient::setGlobalShadowSettings(const half4& ambientColor,
3010 const half4& spotColor, float lightPosY,
3011 float lightPosZ, float lightRadius) {
3012 gui::Color ambientColorG, spotColorG;
3013 ambientColorG.r = ambientColor.r;
3014 ambientColorG.g = ambientColor.g;
3015 ambientColorG.b = ambientColor.b;
3016 ambientColorG.a = ambientColor.a;
3017 spotColorG.r = spotColor.r;
3018 spotColorG.g = spotColor.g;
3019 spotColorG.b = spotColor.b;
3020 spotColorG.a = spotColor.a;
3021 binder::Status status =
3022 ComposerServiceAIDL::getComposerService()->setGlobalShadowSettings(ambientColorG,
3023 spotColorG,
3024 lightPosY, lightPosZ,
3025 lightRadius);
3026 return statusTFromBinderStatus(status);
3027 }
3028
getDisplayDecorationSupport(const sp<IBinder> & displayToken)3029 std::optional<DisplayDecorationSupport> SurfaceComposerClient::getDisplayDecorationSupport(
3030 const sp<IBinder>& displayToken) {
3031 std::optional<gui::DisplayDecorationSupport> gsupport;
3032 binder::Status status =
3033 ComposerServiceAIDL::getComposerService()->getDisplayDecorationSupport(displayToken,
3034 &gsupport);
3035 std::optional<DisplayDecorationSupport> support;
3036 if (status.isOk() && gsupport.has_value()) {
3037 support.emplace(DisplayDecorationSupport{
3038 .format =
3039 static_cast<aidl::android::hardware::graphics::common::PixelFormat>(
3040 gsupport->format),
3041 .alphaInterpretation =
3042 static_cast<aidl::android::hardware::graphics::common::AlphaInterpretation>(
3043 gsupport->alphaInterpretation)
3044 });
3045 }
3046 return support;
3047 }
3048
getGpuContextPriority()3049 int SurfaceComposerClient::getGpuContextPriority() {
3050 int priority;
3051 binder::Status status =
3052 ComposerServiceAIDL::getComposerService()->getGpuContextPriority(&priority);
3053 if (!status.isOk()) {
3054 status_t err = statusTFromBinderStatus(status);
3055 ALOGE("getGpuContextPriority failed to read data: %s (%d)", strerror(-err), err);
3056 return 0;
3057 }
3058 return priority;
3059 }
3060
addWindowInfosListener(const sp<WindowInfosListener> & windowInfosListener,std::pair<std::vector<gui::WindowInfo>,std::vector<gui::DisplayInfo>> * outInitialInfo)3061 status_t SurfaceComposerClient::addWindowInfosListener(
3062 const sp<WindowInfosListener>& windowInfosListener,
3063 std::pair<std::vector<gui::WindowInfo>, std::vector<gui::DisplayInfo>>* outInitialInfo) {
3064 return WindowInfosListenerReporter::getInstance()
3065 ->addWindowInfosListener(windowInfosListener, ComposerServiceAIDL::getComposerService(),
3066 outInitialInfo);
3067 }
3068
removeWindowInfosListener(const sp<WindowInfosListener> & windowInfosListener)3069 status_t SurfaceComposerClient::removeWindowInfosListener(
3070 const sp<WindowInfosListener>& windowInfosListener) {
3071 return WindowInfosListenerReporter::getInstance()
3072 ->removeWindowInfosListener(windowInfosListener,
3073 ComposerServiceAIDL::getComposerService());
3074 }
3075
3076 // ----------------------------------------------------------------------------
3077
captureDisplay(const DisplayCaptureArgs & captureArgs,const sp<IScreenCaptureListener> & captureListener)3078 status_t ScreenshotClient::captureDisplay(const DisplayCaptureArgs& captureArgs,
3079 const sp<IScreenCaptureListener>& captureListener) {
3080 sp<gui::ISurfaceComposer> s(ComposerServiceAIDL::getComposerService());
3081 if (s == nullptr) return NO_INIT;
3082
3083 binder::Status status = s->captureDisplay(captureArgs, captureListener);
3084 return statusTFromBinderStatus(status);
3085 }
3086
captureDisplay(DisplayId displayId,const sp<IScreenCaptureListener> & captureListener)3087 status_t ScreenshotClient::captureDisplay(DisplayId displayId,
3088 const sp<IScreenCaptureListener>& captureListener) {
3089 sp<gui::ISurfaceComposer> s(ComposerServiceAIDL::getComposerService());
3090 if (s == nullptr) return NO_INIT;
3091
3092 binder::Status status = s->captureDisplayById(displayId.value, captureListener);
3093 return statusTFromBinderStatus(status);
3094 }
3095
captureLayers(const LayerCaptureArgs & captureArgs,const sp<IScreenCaptureListener> & captureListener)3096 status_t ScreenshotClient::captureLayers(const LayerCaptureArgs& captureArgs,
3097 const sp<IScreenCaptureListener>& captureListener) {
3098 sp<gui::ISurfaceComposer> s(ComposerServiceAIDL::getComposerService());
3099 if (s == nullptr) return NO_INIT;
3100
3101 binder::Status status = s->captureLayers(captureArgs, captureListener);
3102 return statusTFromBinderStatus(status);
3103 }
3104
3105 // ---------------------------------------------------------------------------------
3106
addReleaseCallback(const ReleaseCallbackId callbackId,sp<Fence> releaseFence)3107 void ReleaseCallbackThread::addReleaseCallback(const ReleaseCallbackId callbackId,
3108 sp<Fence> releaseFence) {
3109 std::scoped_lock<std::mutex> lock(mMutex);
3110 if (!mStarted) {
3111 mThread = std::thread(&ReleaseCallbackThread::threadMain, this);
3112 mStarted = true;
3113 }
3114
3115 mCallbackInfos.emplace(callbackId, std::move(releaseFence));
3116 mReleaseCallbackPending.notify_one();
3117 }
3118
threadMain()3119 void ReleaseCallbackThread::threadMain() {
3120 const auto listener = TransactionCompletedListener::getInstance();
3121 std::queue<std::tuple<const ReleaseCallbackId, const sp<Fence>>> callbackInfos;
3122 while (true) {
3123 {
3124 std::unique_lock<std::mutex> lock(mMutex);
3125 base::ScopedLockAssertion assumeLocked(mMutex);
3126 callbackInfos = std::move(mCallbackInfos);
3127 mCallbackInfos = {};
3128 }
3129
3130 while (!callbackInfos.empty()) {
3131 auto [callbackId, releaseFence] = callbackInfos.front();
3132 listener->onReleaseBuffer(callbackId, std::move(releaseFence), UINT_MAX);
3133 callbackInfos.pop();
3134 }
3135
3136 {
3137 std::unique_lock<std::mutex> lock(mMutex);
3138 base::ScopedLockAssertion assumeLocked(mMutex);
3139 if (mCallbackInfos.size() == 0) {
3140 mReleaseCallbackPending.wait(lock);
3141 }
3142 }
3143 }
3144 }
3145
3146 } // namespace android
3147