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