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 <stdint.h>
20 #include <sys/types.h>
21 
22 #include <android/gui/IWindowInfosListener.h>
23 #include <utils/Errors.h>
24 #include <utils/Log.h>
25 #include <utils/SortedVector.h>
26 #include <utils/String8.h>
27 #include <utils/threads.h>
28 
29 #include <binder/IPCThreadState.h>
30 #include <binder/IServiceManager.h>
31 #include <binder/ProcessState.h>
32 
33 #include <system/graphics.h>
34 
35 #include <gui/BufferItemConsumer.h>
36 #include <gui/CpuConsumer.h>
37 #include <gui/IGraphicBufferProducer.h>
38 #include <gui/ISurfaceComposer.h>
39 #include <gui/ISurfaceComposerClient.h>
40 #include <gui/LayerState.h>
41 #include <gui/Surface.h>
42 #include <gui/SurfaceComposerClient.h>
43 #include <gui/WindowInfo.h>
44 #include <private/gui/ParcelUtils.h>
45 #include <ui/DisplayMode.h>
46 #include <ui/DynamicDisplayInfo.h>
47 
48 #include <private/gui/ComposerService.h>
49 
50 // This server size should always be smaller than the server cache size
51 #define BUFFER_CACHE_MAX_SIZE 64
52 
53 namespace android {
54 
55 using gui::FocusRequest;
56 using gui::WindowInfo;
57 using gui::WindowInfoHandle;
58 using gui::WindowInfosListener;
59 using ui::ColorMode;
60 // ---------------------------------------------------------------------------
61 
62 ANDROID_SINGLETON_STATIC_INSTANCE(ComposerService);
63 
ComposerService()64 ComposerService::ComposerService()
65 : Singleton<ComposerService>() {
66     Mutex::Autolock _l(mLock);
67     connectLocked();
68 }
69 
connectLocked()70 bool ComposerService::connectLocked() {
71     const String16 name("SurfaceFlinger");
72     mComposerService = waitForService<ISurfaceComposer>(name);
73     if (mComposerService == nullptr) {
74         return false; // fatal error or permission problem
75     }
76 
77     // Create the death listener.
78     class DeathObserver : public IBinder::DeathRecipient {
79         ComposerService& mComposerService;
80         virtual void binderDied(const wp<IBinder>& who) {
81             ALOGW("ComposerService remote (surfaceflinger) died [%p]",
82                   who.unsafe_get());
83             mComposerService.composerServiceDied();
84         }
85      public:
86         explicit DeathObserver(ComposerService& mgr) : mComposerService(mgr) { }
87     };
88 
89     mDeathObserver = new DeathObserver(*const_cast<ComposerService*>(this));
90     IInterface::asBinder(mComposerService)->linkToDeath(mDeathObserver);
91     return true;
92 }
93 
getComposerService()94 /*static*/ sp<ISurfaceComposer> ComposerService::getComposerService() {
95     ComposerService& instance = ComposerService::getInstance();
96     Mutex::Autolock _l(instance.mLock);
97     if (instance.mComposerService == nullptr) {
98         if (ComposerService::getInstance().connectLocked()) {
99             ALOGD("ComposerService reconnected");
100             WindowInfosListenerReporter::getInstance()->reconnect(instance.mComposerService);
101         }
102     }
103     return instance.mComposerService;
104 }
105 
composerServiceDied()106 void ComposerService::composerServiceDied()
107 {
108     Mutex::Autolock _l(mLock);
109     mComposerService = nullptr;
110     mDeathObserver = nullptr;
111 }
112 
113 class DefaultComposerClient: public Singleton<DefaultComposerClient> {
114     Mutex mLock;
115     sp<SurfaceComposerClient> mClient;
116     friend class Singleton<ComposerService>;
117 public:
getComposerClient()118     static sp<SurfaceComposerClient> getComposerClient() {
119         DefaultComposerClient& dc = DefaultComposerClient::getInstance();
120         Mutex::Autolock _l(dc.mLock);
121         if (dc.mClient == nullptr) {
122             dc.mClient = new SurfaceComposerClient;
123         }
124         return dc.mClient;
125     }
126 };
127 ANDROID_SINGLETON_STATIC_INSTANCE(DefaultComposerClient);
128 
129 
getDefault()130 sp<SurfaceComposerClient> SurfaceComposerClient::getDefault() {
131     return DefaultComposerClient::getComposerClient();
132 }
133 
~JankDataListener()134 JankDataListener::~JankDataListener() {
135 }
136 
137 // ---------------------------------------------------------------------------
138 
139 // TransactionCompletedListener does not use ANDROID_SINGLETON_STATIC_INSTANCE because it needs
140 // to be able to return a sp<> to its instance to pass to SurfaceFlinger.
141 // ANDROID_SINGLETON_STATIC_INSTANCE only allows a reference to an instance.
142 
143 // 0 is an invalid callback id
TransactionCompletedListener()144 TransactionCompletedListener::TransactionCompletedListener() : mCallbackIdCounter(1) {}
145 
getNextIdLocked()146 int64_t TransactionCompletedListener::getNextIdLocked() {
147     return mCallbackIdCounter++;
148 }
149 
150 sp<TransactionCompletedListener> TransactionCompletedListener::sInstance = nullptr;
151 
setInstance(const sp<TransactionCompletedListener> & listener)152 void TransactionCompletedListener::setInstance(const sp<TransactionCompletedListener>& listener) {
153     sInstance = listener;
154 }
155 
getInstance()156 sp<TransactionCompletedListener> TransactionCompletedListener::getInstance() {
157     if (sInstance == nullptr) {
158         sInstance = new TransactionCompletedListener;
159     }
160     return sInstance;
161 }
162 
getIInstance()163 sp<ITransactionCompletedListener> TransactionCompletedListener::getIInstance() {
164     return static_cast<sp<ITransactionCompletedListener>>(getInstance());
165 }
166 
startListeningLocked()167 void TransactionCompletedListener::startListeningLocked() {
168     if (mListening) {
169         return;
170     }
171     ProcessState::self()->startThreadPool();
172     mListening = true;
173 }
174 
addCallbackFunction(const TransactionCompletedCallback & callbackFunction,const std::unordered_set<sp<SurfaceControl>,SurfaceComposerClient::SCHash> & surfaceControls,CallbackId::Type callbackType)175 CallbackId TransactionCompletedListener::addCallbackFunction(
176         const TransactionCompletedCallback& callbackFunction,
177         const std::unordered_set<sp<SurfaceControl>, SurfaceComposerClient::SCHash>&
178                 surfaceControls,
179         CallbackId::Type callbackType) {
180     std::lock_guard<std::mutex> lock(mMutex);
181     startListeningLocked();
182 
183     CallbackId callbackId(getNextIdLocked(), callbackType);
184     mCallbacks[callbackId].callbackFunction = callbackFunction;
185     auto& callbackSurfaceControls = mCallbacks[callbackId].surfaceControls;
186 
187     for (const auto& surfaceControl : surfaceControls) {
188         callbackSurfaceControls[surfaceControl->getHandle()] = surfaceControl;
189     }
190 
191     return callbackId;
192 }
193 
addJankListener(const sp<JankDataListener> & listener,sp<SurfaceControl> surfaceControl)194 void TransactionCompletedListener::addJankListener(const sp<JankDataListener>& listener,
195                                                    sp<SurfaceControl> surfaceControl) {
196     std::lock_guard<std::mutex> lock(mMutex);
197     mJankListeners.insert({surfaceControl->getLayerId(), listener});
198 }
199 
removeJankListener(const sp<JankDataListener> & listener)200 void TransactionCompletedListener::removeJankListener(const sp<JankDataListener>& listener) {
201     std::lock_guard<std::mutex> lock(mMutex);
202     for (auto it = mJankListeners.begin(); it != mJankListeners.end();) {
203         if (it->second == listener) {
204             it = mJankListeners.erase(it);
205         } else {
206             it++;
207         }
208     }
209 }
210 
setReleaseBufferCallback(const ReleaseCallbackId & callbackId,ReleaseBufferCallback listener)211 void TransactionCompletedListener::setReleaseBufferCallback(const ReleaseCallbackId& callbackId,
212                                                             ReleaseBufferCallback listener) {
213     std::scoped_lock<std::mutex> lock(mMutex);
214     mReleaseBufferCallbacks[callbackId] = listener;
215 }
216 
removeReleaseBufferCallback(const ReleaseCallbackId & callbackId)217 void TransactionCompletedListener::removeReleaseBufferCallback(
218         const ReleaseCallbackId& callbackId) {
219     std::scoped_lock<std::mutex> lock(mMutex);
220     mReleaseBufferCallbacks.erase(callbackId);
221 }
222 
addSurfaceStatsListener(void * context,void * cookie,sp<SurfaceControl> surfaceControl,SurfaceStatsCallback listener)223 void TransactionCompletedListener::addSurfaceStatsListener(void* context, void* cookie,
224         sp<SurfaceControl> surfaceControl, SurfaceStatsCallback listener) {
225     std::scoped_lock<std::recursive_mutex> lock(mSurfaceStatsListenerMutex);
226     mSurfaceStatsListeners.insert(
227             {surfaceControl->getLayerId(), SurfaceStatsCallbackEntry(context, cookie, listener)});
228 }
229 
removeSurfaceStatsListener(void * context,void * cookie)230 void TransactionCompletedListener::removeSurfaceStatsListener(void* context, void* cookie) {
231     std::scoped_lock<std::recursive_mutex> lock(mSurfaceStatsListenerMutex);
232     for (auto it = mSurfaceStatsListeners.begin(); it != mSurfaceStatsListeners.end();) {
233         auto [itContext, itCookie, itListener] = it->second;
234         if (itContext == context && itCookie == cookie) {
235             it = mSurfaceStatsListeners.erase(it);
236         } else {
237             it++;
238         }
239     }
240 }
241 
addSurfaceControlToCallbacks(const sp<SurfaceControl> & surfaceControl,const std::unordered_set<CallbackId,CallbackIdHash> & callbackIds)242 void TransactionCompletedListener::addSurfaceControlToCallbacks(
243         const sp<SurfaceControl>& surfaceControl,
244         const std::unordered_set<CallbackId, CallbackIdHash>& callbackIds) {
245     std::lock_guard<std::mutex> lock(mMutex);
246 
247     for (auto callbackId : callbackIds) {
248         mCallbacks[callbackId].surfaceControls.emplace(std::piecewise_construct,
249                                                        std::forward_as_tuple(
250                                                                surfaceControl->getHandle()),
251                                                        std::forward_as_tuple(surfaceControl));
252     }
253 }
254 
onTransactionCompleted(ListenerStats listenerStats)255 void TransactionCompletedListener::onTransactionCompleted(ListenerStats listenerStats) {
256     std::unordered_map<CallbackId, CallbackTranslation, CallbackIdHash> callbacksMap;
257     std::multimap<int32_t, sp<JankDataListener>> jankListenersMap;
258     {
259         std::lock_guard<std::mutex> lock(mMutex);
260 
261         /* This listener knows all the sp<IBinder> to sp<SurfaceControl> for all its registered
262          * callbackIds, except for when Transactions are merged together. This probably cannot be
263          * solved before this point because the Transactions could be merged together and applied in
264          * a different process.
265          *
266          * Fortunately, we get all the callbacks for this listener for the same frame together at
267          * the same time. This means if any Transactions were merged together, we will get their
268          * callbacks at the same time. We can combine all the sp<IBinder> to sp<SurfaceControl> maps
269          * for all the callbackIds to generate one super map that contains all the sp<IBinder> to
270          * sp<SurfaceControl> that could possibly exist for the callbacks.
271          */
272         callbacksMap = mCallbacks;
273         jankListenersMap = mJankListeners;
274         for (const auto& transactionStats : listenerStats.transactionStats) {
275             for (auto& callbackId : transactionStats.callbackIds) {
276                 mCallbacks.erase(callbackId);
277             }
278         }
279     }
280     for (const auto& transactionStats : listenerStats.transactionStats) {
281         // handle on commit callbacks
282         for (auto callbackId : transactionStats.callbackIds) {
283             if (callbackId.type != CallbackId::Type::ON_COMMIT) {
284                 continue;
285             }
286             auto& [callbackFunction, callbackSurfaceControls] = callbacksMap[callbackId];
287             if (!callbackFunction) {
288                 ALOGE("cannot call null callback function, skipping");
289                 continue;
290             }
291             std::vector<SurfaceControlStats> surfaceControlStats;
292             for (const auto& surfaceStats : transactionStats.surfaceStats) {
293                 surfaceControlStats
294                         .emplace_back(callbacksMap[callbackId]
295                                               .surfaceControls[surfaceStats.surfaceControl],
296                                       transactionStats.latchTime, surfaceStats.acquireTime,
297                                       transactionStats.presentFence,
298                                       surfaceStats.previousReleaseFence, surfaceStats.transformHint,
299                                       surfaceStats.eventStats, surfaceStats.currentMaxAcquiredBufferCount);
300             }
301 
302             callbackFunction(transactionStats.latchTime, transactionStats.presentFence,
303                              surfaceControlStats);
304         }
305 
306         // handle on complete callbacks
307         for (auto callbackId : transactionStats.callbackIds) {
308             if (callbackId.type != CallbackId::Type::ON_COMPLETE) {
309                 continue;
310             }
311             auto& [callbackFunction, callbackSurfaceControls] = callbacksMap[callbackId];
312             if (!callbackFunction) {
313                 ALOGE("cannot call null callback function, skipping");
314                 continue;
315             }
316             std::vector<SurfaceControlStats> surfaceControlStats;
317             for (const auto& surfaceStats : transactionStats.surfaceStats) {
318                 surfaceControlStats
319                         .emplace_back(callbacksMap[callbackId]
320                                               .surfaceControls[surfaceStats.surfaceControl],
321                                       transactionStats.latchTime, surfaceStats.acquireTime,
322                                       transactionStats.presentFence,
323                                       surfaceStats.previousReleaseFence, surfaceStats.transformHint,
324                                       surfaceStats.eventStats, surfaceStats.currentMaxAcquiredBufferCount);
325                 if (callbacksMap[callbackId].surfaceControls[surfaceStats.surfaceControl]) {
326                     callbacksMap[callbackId]
327                             .surfaceControls[surfaceStats.surfaceControl]
328                             ->setTransformHint(surfaceStats.transformHint);
329                 }
330                 // If there is buffer id set, we look up any pending client release buffer callbacks
331                 // and call them. This is a performance optimization when we have a transaction
332                 // callback and a release buffer callback happening at the same time to avoid an
333                 // additional ipc call from the server.
334                 if (surfaceStats.previousReleaseCallbackId != ReleaseCallbackId::INVALID_ID) {
335                     ReleaseBufferCallback callback;
336                     {
337                         std::scoped_lock<std::mutex> lock(mMutex);
338                         callback = popReleaseBufferCallbackLocked(
339                                 surfaceStats.previousReleaseCallbackId);
340                     }
341                     if (callback) {
342                         callback(surfaceStats.previousReleaseCallbackId,
343                                  surfaceStats.previousReleaseFence
344                                          ? surfaceStats.previousReleaseFence
345                                          : Fence::NO_FENCE,
346                                  surfaceStats.transformHint,
347                                  surfaceStats.currentMaxAcquiredBufferCount);
348                     }
349                 }
350             }
351 
352             callbackFunction(transactionStats.latchTime, transactionStats.presentFence,
353                              surfaceControlStats);
354         }
355 
356         for (const auto& surfaceStats : transactionStats.surfaceStats) {
357             // The callbackMap contains the SurfaceControl object, which we need to look up the
358             // layerId. Since we don't know which callback contains the SurfaceControl, iterate
359             // through all until the SC is found.
360             int32_t layerId = -1;
361             for (auto callbackId : transactionStats.callbackIds) {
362                 sp<SurfaceControl> sc =
363                         callbacksMap[callbackId].surfaceControls[surfaceStats.surfaceControl];
364                 if (sc != nullptr) {
365                     layerId = sc->getLayerId();
366                     break;
367                 }
368             }
369 
370             {
371                 // Acquire surface stats listener lock such that we guarantee that after calling
372                 // unregister, there won't be any further callback.
373                 std::scoped_lock<std::recursive_mutex> lock(mSurfaceStatsListenerMutex);
374                 auto listenerRange = mSurfaceStatsListeners.equal_range(layerId);
375                 for (auto it = listenerRange.first; it != listenerRange.second; it++) {
376                     auto entry = it->second;
377                     entry.callback(entry.context, transactionStats.latchTime,
378                         transactionStats.presentFence, surfaceStats);
379                 }
380             }
381 
382             if (surfaceStats.jankData.empty()) continue;
383             auto jankRange = jankListenersMap.equal_range(layerId);
384             for (auto it = jankRange.first; it != jankRange.second; it++) {
385                 it->second->onJankDataAvailable(surfaceStats.jankData);
386             }
387         }
388     }
389 }
390 
onReleaseBuffer(ReleaseCallbackId callbackId,sp<Fence> releaseFence,uint32_t transformHint,uint32_t currentMaxAcquiredBufferCount)391 void TransactionCompletedListener::onReleaseBuffer(ReleaseCallbackId callbackId,
392                                                    sp<Fence> releaseFence, uint32_t transformHint,
393                                                    uint32_t currentMaxAcquiredBufferCount) {
394     ReleaseBufferCallback callback;
395     {
396         std::scoped_lock<std::mutex> lock(mMutex);
397         callback = popReleaseBufferCallbackLocked(callbackId);
398     }
399     if (!callback) {
400         ALOGE("Could not call release buffer callback, buffer not found %s",
401               callbackId.to_string().c_str());
402         return;
403     }
404     callback(callbackId, releaseFence, transformHint, currentMaxAcquiredBufferCount);
405 }
406 
popReleaseBufferCallbackLocked(const ReleaseCallbackId & callbackId)407 ReleaseBufferCallback TransactionCompletedListener::popReleaseBufferCallbackLocked(
408         const ReleaseCallbackId& callbackId) {
409     ReleaseBufferCallback callback;
410     auto itr = mReleaseBufferCallbacks.find(callbackId);
411     if (itr == mReleaseBufferCallbacks.end()) {
412         return nullptr;
413     }
414     callback = itr->second;
415     mReleaseBufferCallbacks.erase(itr);
416     return callback;
417 }
418 
419 // ---------------------------------------------------------------------------
420 
421 void removeDeadBufferCallback(void* /*context*/, uint64_t graphicBufferId);
422 
423 /**
424  * We use the BufferCache to reduce the overhead of exchanging GraphicBuffers with
425  * the server. If we were to simply parcel the GraphicBuffer we would pay two overheads
426  *     1. Cost of sending the FD
427  *     2. Cost of importing the GraphicBuffer with the mapper in the receiving process.
428  * To ease this cost we implement the following scheme of caching buffers to integers,
429  * or said-otherwise, naming them with integers. This is the scheme known as slots in
430  * the legacy BufferQueue system.
431  *     1. When sending Buffers to SurfaceFlinger we look up the Buffer in the cache.
432  *     2. If there is a cache-hit we remove the Buffer from the Transaction and instead
433  *        send the cached integer.
434  *     3. If there is a cache miss, we cache the new buffer and send the integer
435  *        along with the Buffer, SurfaceFlinger on it's side creates a new cache
436  *        entry, and we use the integer for further communication.
437  * A few details about lifetime:
438  *     1. The cache evicts by LRU. The server side cache is keyed by BufferCache::getToken
439  *        which is per process Unique. The server side cache is larger than the client side
440  *        cache so that the server will never evict entries before the client.
441  *     2. When the client evicts an entry it notifies the server via an uncacheBuffer
442  *        transaction.
443  *     3. The client only references the Buffers by ID, and uses buffer->addDeathCallback
444  *        to auto-evict destroyed buffers.
445  */
446 class BufferCache : public Singleton<BufferCache> {
447 public:
BufferCache()448     BufferCache() : token(new BBinder()) {}
449 
getToken()450     sp<IBinder> getToken() {
451         return IInterface::asBinder(TransactionCompletedListener::getIInstance());
452     }
453 
getCacheId(const sp<GraphicBuffer> & buffer,uint64_t * cacheId)454     status_t getCacheId(const sp<GraphicBuffer>& buffer, uint64_t* cacheId) {
455         std::lock_guard<std::mutex> lock(mMutex);
456 
457         auto itr = mBuffers.find(buffer->getId());
458         if (itr == mBuffers.end()) {
459             return BAD_VALUE;
460         }
461         itr->second = getCounter();
462         *cacheId = buffer->getId();
463         return NO_ERROR;
464     }
465 
cache(const sp<GraphicBuffer> & buffer)466     uint64_t cache(const sp<GraphicBuffer>& buffer) {
467         std::lock_guard<std::mutex> lock(mMutex);
468 
469         if (mBuffers.size() >= BUFFER_CACHE_MAX_SIZE) {
470             evictLeastRecentlyUsedBuffer();
471         }
472 
473         buffer->addDeathCallback(removeDeadBufferCallback, nullptr);
474 
475         mBuffers[buffer->getId()] = getCounter();
476         return buffer->getId();
477     }
478 
uncache(uint64_t cacheId)479     void uncache(uint64_t cacheId) {
480         std::lock_guard<std::mutex> lock(mMutex);
481         uncacheLocked(cacheId);
482     }
483 
uncacheLocked(uint64_t cacheId)484     void uncacheLocked(uint64_t cacheId) REQUIRES(mMutex) {
485         mBuffers.erase(cacheId);
486         SurfaceComposerClient::doUncacheBufferTransaction(cacheId);
487     }
488 
489 private:
evictLeastRecentlyUsedBuffer()490     void evictLeastRecentlyUsedBuffer() REQUIRES(mMutex) {
491         auto itr = mBuffers.begin();
492         uint64_t minCounter = itr->second;
493         auto minBuffer = itr;
494         itr++;
495 
496         while (itr != mBuffers.end()) {
497             uint64_t counter = itr->second;
498             if (counter < minCounter) {
499                 minCounter = counter;
500                 minBuffer = itr;
501             }
502             itr++;
503         }
504         uncacheLocked(minBuffer->first);
505     }
506 
getCounter()507     uint64_t getCounter() REQUIRES(mMutex) {
508         static uint64_t counter = 0;
509         return counter++;
510     }
511 
512     std::mutex mMutex;
513     std::map<uint64_t /*Cache id*/, uint64_t /*counter*/> mBuffers GUARDED_BY(mMutex);
514 
515     // Used by ISurfaceComposer to identify which process is sending the cached buffer.
516     sp<IBinder> token;
517 };
518 
519 ANDROID_SINGLETON_STATIC_INSTANCE(BufferCache);
520 
removeDeadBufferCallback(void *,uint64_t graphicBufferId)521 void removeDeadBufferCallback(void* /*context*/, uint64_t graphicBufferId) {
522     // GraphicBuffer id's are used as the cache ids.
523     BufferCache::getInstance().uncache(graphicBufferId);
524 }
525 
526 // ---------------------------------------------------------------------------
527 
528 // Initialize transaction id counter used to generate transaction ids
529 // Transactions will start counting at 1, 0 is used for invalid transactions
530 std::atomic<uint32_t> SurfaceComposerClient::Transaction::idCounter = 1;
531 
Transaction()532 SurfaceComposerClient::Transaction::Transaction() {
533     mId = generateId();
534 }
535 
Transaction(const Transaction & other)536 SurfaceComposerClient::Transaction::Transaction(const Transaction& other)
537       : mId(other.mId),
538         mForceSynchronous(other.mForceSynchronous),
539         mTransactionNestCount(other.mTransactionNestCount),
540         mAnimation(other.mAnimation),
541         mEarlyWakeupStart(other.mEarlyWakeupStart),
542         mEarlyWakeupEnd(other.mEarlyWakeupEnd),
543         mContainsBuffer(other.mContainsBuffer),
544         mDesiredPresentTime(other.mDesiredPresentTime),
545         mIsAutoTimestamp(other.mIsAutoTimestamp),
546         mFrameTimelineInfo(other.mFrameTimelineInfo),
547         mApplyToken(other.mApplyToken) {
548     mDisplayStates = other.mDisplayStates;
549     mComposerStates = other.mComposerStates;
550     mInputWindowCommands = other.mInputWindowCommands;
551     mListenerCallbacks = other.mListenerCallbacks;
552 }
553 
554 std::unique_ptr<SurfaceComposerClient::Transaction>
createFromParcel(const Parcel * parcel)555 SurfaceComposerClient::Transaction::createFromParcel(const Parcel* parcel) {
556     auto transaction = std::make_unique<Transaction>();
557     if (transaction->readFromParcel(parcel) == NO_ERROR) {
558         return transaction;
559     }
560     return nullptr;
561 }
562 
generateId()563 int64_t SurfaceComposerClient::Transaction::generateId() {
564     return (((int64_t)getpid()) << 32) | idCounter++;
565 }
566 
readFromParcel(const Parcel * parcel)567 status_t SurfaceComposerClient::Transaction::readFromParcel(const Parcel* parcel) {
568     const uint32_t forceSynchronous = parcel->readUint32();
569     const uint32_t transactionNestCount = parcel->readUint32();
570     const bool animation = parcel->readBool();
571     const bool earlyWakeupStart = parcel->readBool();
572     const bool earlyWakeupEnd = parcel->readBool();
573     const bool containsBuffer = parcel->readBool();
574     const int64_t desiredPresentTime = parcel->readInt64();
575     const bool isAutoTimestamp = parcel->readBool();
576     FrameTimelineInfo frameTimelineInfo;
577     SAFE_PARCEL(frameTimelineInfo.read, *parcel);
578 
579     sp<IBinder> applyToken;
580     parcel->readNullableStrongBinder(&applyToken);
581     size_t count = static_cast<size_t>(parcel->readUint32());
582     if (count > parcel->dataSize()) {
583         return BAD_VALUE;
584     }
585     SortedVector<DisplayState> displayStates;
586     displayStates.setCapacity(count);
587     for (size_t i = 0; i < count; i++) {
588         DisplayState displayState;
589         if (displayState.read(*parcel) == BAD_VALUE) {
590             return BAD_VALUE;
591         }
592         displayStates.add(displayState);
593     }
594 
595     count = static_cast<size_t>(parcel->readUint32());
596     if (count > parcel->dataSize()) {
597         return BAD_VALUE;
598     }
599     std::unordered_map<sp<ITransactionCompletedListener>, CallbackInfo, TCLHash> listenerCallbacks;
600     listenerCallbacks.reserve(count);
601     for (size_t i = 0; i < count; i++) {
602         sp<ITransactionCompletedListener> listener =
603                 interface_cast<ITransactionCompletedListener>(parcel->readStrongBinder());
604         size_t numCallbackIds = parcel->readUint32();
605         if (numCallbackIds > parcel->dataSize()) {
606             return BAD_VALUE;
607         }
608         for (size_t j = 0; j < numCallbackIds; j++) {
609             CallbackId id;
610             parcel->readParcelable(&id);
611             listenerCallbacks[listener].callbackIds.insert(id);
612         }
613         size_t numSurfaces = parcel->readUint32();
614         if (numSurfaces > parcel->dataSize()) {
615             return BAD_VALUE;
616         }
617         for (size_t j = 0; j < numSurfaces; j++) {
618             sp<SurfaceControl> surface;
619             SAFE_PARCEL(SurfaceControl::readFromParcel, *parcel, &surface);
620             listenerCallbacks[listener].surfaceControls.insert(surface);
621         }
622     }
623 
624     count = static_cast<size_t>(parcel->readUint32());
625     if (count > parcel->dataSize()) {
626         return BAD_VALUE;
627     }
628     std::unordered_map<sp<IBinder>, ComposerState, IBinderHash> composerStates;
629     composerStates.reserve(count);
630     for (size_t i = 0; i < count; i++) {
631         sp<IBinder> surfaceControlHandle;
632         SAFE_PARCEL(parcel->readStrongBinder, &surfaceControlHandle);
633 
634         ComposerState composerState;
635         if (composerState.read(*parcel) == BAD_VALUE) {
636             return BAD_VALUE;
637         }
638 
639         composerStates[surfaceControlHandle] = composerState;
640     }
641 
642     InputWindowCommands inputWindowCommands;
643     inputWindowCommands.read(*parcel);
644 
645     // Parsing was successful. Update the object.
646     mForceSynchronous = forceSynchronous;
647     mTransactionNestCount = transactionNestCount;
648     mAnimation = animation;
649     mEarlyWakeupStart = earlyWakeupStart;
650     mEarlyWakeupEnd = earlyWakeupEnd;
651     mContainsBuffer = containsBuffer;
652     mDesiredPresentTime = desiredPresentTime;
653     mIsAutoTimestamp = isAutoTimestamp;
654     mFrameTimelineInfo = frameTimelineInfo;
655     mDisplayStates = displayStates;
656     mListenerCallbacks = listenerCallbacks;
657     mComposerStates = composerStates;
658     mInputWindowCommands = inputWindowCommands;
659     mApplyToken = applyToken;
660     return NO_ERROR;
661 }
662 
writeToParcel(Parcel * parcel) const663 status_t SurfaceComposerClient::Transaction::writeToParcel(Parcel* parcel) const {
664     // If we write the Transaction to a parcel, we want to ensure the Buffers are cached
665     // before crossing the IPC boundary. Otherwise the receiving party will cache the buffers
666     // but is unlikely to use them again as they are owned by the other process.
667     // You may be asking yourself, is this const cast safe? Const cast is safe up
668     // until the point where you try and write to an object that was originally const at which
669     // point we enter undefined behavior. In this case we are safe though, because there are
670     // two possibilities:
671     //    1. The SurfaceComposerClient::Transaction was originally non-const. Safe.
672     //    2. It was originall const! In this case not only was it useless, but it by definition
673     //       contains no composer states and so cacheBuffers will not perform any writes.
674 
675     const_cast<SurfaceComposerClient::Transaction*>(this)->cacheBuffers();
676 
677     parcel->writeUint32(mForceSynchronous);
678     parcel->writeUint32(mTransactionNestCount);
679     parcel->writeBool(mAnimation);
680     parcel->writeBool(mEarlyWakeupStart);
681     parcel->writeBool(mEarlyWakeupEnd);
682     parcel->writeBool(mContainsBuffer);
683     parcel->writeInt64(mDesiredPresentTime);
684     parcel->writeBool(mIsAutoTimestamp);
685     SAFE_PARCEL(mFrameTimelineInfo.write, *parcel);
686     parcel->writeStrongBinder(mApplyToken);
687     parcel->writeUint32(static_cast<uint32_t>(mDisplayStates.size()));
688     for (auto const& displayState : mDisplayStates) {
689         displayState.write(*parcel);
690     }
691 
692     parcel->writeUint32(static_cast<uint32_t>(mListenerCallbacks.size()));
693     for (auto const& [listener, callbackInfo] : mListenerCallbacks) {
694         parcel->writeStrongBinder(ITransactionCompletedListener::asBinder(listener));
695         parcel->writeUint32(static_cast<uint32_t>(callbackInfo.callbackIds.size()));
696         for (auto callbackId : callbackInfo.callbackIds) {
697             parcel->writeParcelable(callbackId);
698         }
699         parcel->writeUint32(static_cast<uint32_t>(callbackInfo.surfaceControls.size()));
700         for (auto surfaceControl : callbackInfo.surfaceControls) {
701             SAFE_PARCEL(surfaceControl->writeToParcel, *parcel);
702         }
703     }
704 
705     parcel->writeUint32(static_cast<uint32_t>(mComposerStates.size()));
706     for (auto const& [handle, composerState] : mComposerStates) {
707         SAFE_PARCEL(parcel->writeStrongBinder, handle);
708         composerState.write(*parcel);
709     }
710 
711     mInputWindowCommands.write(*parcel);
712     return NO_ERROR;
713 }
714 
merge(Transaction && other)715 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::merge(Transaction&& other) {
716     for (auto const& [handle, composerState] : other.mComposerStates) {
717         if (mComposerStates.count(handle) == 0) {
718             mComposerStates[handle] = composerState;
719         } else {
720             mComposerStates[handle].state.merge(composerState.state);
721         }
722     }
723 
724     for (auto const& state : other.mDisplayStates) {
725         ssize_t index = mDisplayStates.indexOf(state);
726         if (index < 0) {
727             mDisplayStates.add(state);
728         } else {
729             mDisplayStates.editItemAt(static_cast<size_t>(index)).merge(state);
730         }
731     }
732 
733     for (const auto& [listener, callbackInfo] : other.mListenerCallbacks) {
734         auto& [callbackIds, surfaceControls] = callbackInfo;
735         mListenerCallbacks[listener].callbackIds.insert(std::make_move_iterator(
736                                                                 callbackIds.begin()),
737                                                         std::make_move_iterator(callbackIds.end()));
738 
739         mListenerCallbacks[listener].surfaceControls.insert(surfaceControls.begin(),
740                                                             surfaceControls.end());
741 
742         auto& currentProcessCallbackInfo =
743                 mListenerCallbacks[TransactionCompletedListener::getIInstance()];
744         currentProcessCallbackInfo.surfaceControls
745                 .insert(std::make_move_iterator(surfaceControls.begin()),
746                         std::make_move_iterator(surfaceControls.end()));
747 
748         // register all surface controls for all callbackIds for this listener that is merging
749         for (const auto& surfaceControl : currentProcessCallbackInfo.surfaceControls) {
750             TransactionCompletedListener::getInstance()
751                     ->addSurfaceControlToCallbacks(surfaceControl,
752                                                    currentProcessCallbackInfo.callbackIds);
753         }
754     }
755 
756     mInputWindowCommands.merge(other.mInputWindowCommands);
757 
758     mContainsBuffer |= other.mContainsBuffer;
759     mEarlyWakeupStart = mEarlyWakeupStart || other.mEarlyWakeupStart;
760     mEarlyWakeupEnd = mEarlyWakeupEnd || other.mEarlyWakeupEnd;
761     mApplyToken = other.mApplyToken;
762 
763     mFrameTimelineInfo.merge(other.mFrameTimelineInfo);
764 
765     other.clear();
766     return *this;
767 }
768 
clear()769 void SurfaceComposerClient::Transaction::clear() {
770     mComposerStates.clear();
771     mDisplayStates.clear();
772     mListenerCallbacks.clear();
773     mInputWindowCommands.clear();
774     mContainsBuffer = false;
775     mForceSynchronous = 0;
776     mTransactionNestCount = 0;
777     mAnimation = false;
778     mEarlyWakeupStart = false;
779     mEarlyWakeupEnd = false;
780     mDesiredPresentTime = 0;
781     mIsAutoTimestamp = true;
782     mFrameTimelineInfo.clear();
783     mApplyToken = nullptr;
784 }
785 
doUncacheBufferTransaction(uint64_t cacheId)786 void SurfaceComposerClient::doUncacheBufferTransaction(uint64_t cacheId) {
787     sp<ISurfaceComposer> sf(ComposerService::getComposerService());
788 
789     client_cache_t uncacheBuffer;
790     uncacheBuffer.token = BufferCache::getInstance().getToken();
791     uncacheBuffer.id = cacheId;
792 
793     sp<IBinder> applyToken = IInterface::asBinder(TransactionCompletedListener::getIInstance());
794     sf->setTransactionState(FrameTimelineInfo{}, {}, {}, 0, applyToken, {}, systemTime(), true,
795                             uncacheBuffer, false, {}, 0 /* Undefined transactionId */);
796 }
797 
cacheBuffers()798 void SurfaceComposerClient::Transaction::cacheBuffers() {
799     if (!mContainsBuffer) {
800         return;
801     }
802 
803     size_t count = 0;
804     for (auto& [handle, cs] : mComposerStates) {
805         layer_state_t* s = &(mComposerStates[handle].state);
806         if (!(s->what & layer_state_t::eBufferChanged)) {
807             continue;
808         } else if (s->what & layer_state_t::eCachedBufferChanged) {
809             // If eBufferChanged and eCachedBufferChanged are both trued then that means
810             // we already cached the buffer in a previous call to cacheBuffers, perhaps
811             // from writeToParcel on a Transaction that was merged in to this one.
812             continue;
813         }
814 
815         // Don't try to cache a null buffer. Sending null buffers is cheap so we shouldn't waste
816         // time trying to cache them.
817         if (!s->buffer) {
818             continue;
819         }
820 
821         uint64_t cacheId = 0;
822         status_t ret = BufferCache::getInstance().getCacheId(s->buffer, &cacheId);
823         if (ret == NO_ERROR) {
824             // Cache-hit. Strip the buffer and send only the id.
825             s->what &= ~static_cast<uint64_t>(layer_state_t::eBufferChanged);
826             s->buffer = nullptr;
827         } else {
828             // Cache-miss. Include the buffer and send the new cacheId.
829             cacheId = BufferCache::getInstance().cache(s->buffer);
830         }
831         s->what |= layer_state_t::eCachedBufferChanged;
832         s->cachedBuffer.token = BufferCache::getInstance().getToken();
833         s->cachedBuffer.id = cacheId;
834 
835         // If we have more buffers than the size of the cache, we should stop caching so we don't
836         // evict other buffers in this transaction
837         count++;
838         if (count >= BUFFER_CACHE_MAX_SIZE) {
839             break;
840         }
841     }
842 }
843 
apply(bool synchronous)844 status_t SurfaceComposerClient::Transaction::apply(bool synchronous) {
845     if (mStatus != NO_ERROR) {
846         return mStatus;
847     }
848 
849     sp<ISurfaceComposer> sf(ComposerService::getComposerService());
850 
851     bool hasListenerCallbacks = !mListenerCallbacks.empty();
852     std::vector<ListenerCallbacks> listenerCallbacks;
853     // For every listener with registered callbacks
854     for (const auto& [listener, callbackInfo] : mListenerCallbacks) {
855         auto& [callbackIds, surfaceControls] = callbackInfo;
856         if (callbackIds.empty()) {
857             continue;
858         }
859 
860         if (surfaceControls.empty()) {
861             listenerCallbacks.emplace_back(IInterface::asBinder(listener), std::move(callbackIds));
862         } else {
863             // If the listener has any SurfaceControls set on this Transaction update the surface
864             // state
865             for (const auto& surfaceControl : surfaceControls) {
866                 layer_state_t* s = getLayerState(surfaceControl);
867                 if (!s) {
868                     ALOGE("failed to get layer state");
869                     continue;
870                 }
871                 std::vector<CallbackId> callbacks(callbackIds.begin(), callbackIds.end());
872                 s->what |= layer_state_t::eHasListenerCallbacksChanged;
873                 s->listeners.emplace_back(IInterface::asBinder(listener), callbacks);
874             }
875         }
876     }
877 
878     cacheBuffers();
879 
880     Vector<ComposerState> composerStates;
881     Vector<DisplayState> displayStates;
882     uint32_t flags = 0;
883 
884     mForceSynchronous |= synchronous;
885 
886     for (auto const& kv : mComposerStates){
887         composerStates.add(kv.second);
888     }
889 
890     displayStates = std::move(mDisplayStates);
891 
892     if (mForceSynchronous) {
893         flags |= ISurfaceComposer::eSynchronous;
894     }
895     if (mAnimation) {
896         flags |= ISurfaceComposer::eAnimation;
897     }
898 
899     // If both mEarlyWakeupStart and mEarlyWakeupEnd are set
900     // it is equivalent for none
901     if (mEarlyWakeupStart && !mEarlyWakeupEnd) {
902         flags |= ISurfaceComposer::eEarlyWakeupStart;
903     }
904     if (mEarlyWakeupEnd && !mEarlyWakeupStart) {
905         flags |= ISurfaceComposer::eEarlyWakeupEnd;
906     }
907 
908     sp<IBinder> applyToken = mApplyToken
909             ? mApplyToken
910             : IInterface::asBinder(TransactionCompletedListener::getIInstance());
911 
912     sf->setTransactionState(mFrameTimelineInfo, composerStates, displayStates, flags, applyToken,
913                             mInputWindowCommands, mDesiredPresentTime, mIsAutoTimestamp,
914                             {} /*uncacheBuffer - only set in doUncacheBufferTransaction*/,
915                             hasListenerCallbacks, listenerCallbacks, mId);
916     mId = generateId();
917 
918     // Clear the current states and flags
919     clear();
920 
921     mStatus = NO_ERROR;
922     return NO_ERROR;
923 }
924 
925 // ---------------------------------------------------------------------------
926 
createDisplay(const String8 & displayName,bool secure)927 sp<IBinder> SurfaceComposerClient::createDisplay(const String8& displayName, bool secure) {
928     return ComposerService::getComposerService()->createDisplay(displayName,
929             secure);
930 }
931 
destroyDisplay(const sp<IBinder> & display)932 void SurfaceComposerClient::destroyDisplay(const sp<IBinder>& display) {
933     return ComposerService::getComposerService()->destroyDisplay(display);
934 }
935 
getPhysicalDisplayIds()936 std::vector<PhysicalDisplayId> SurfaceComposerClient::getPhysicalDisplayIds() {
937     return ComposerService::getComposerService()->getPhysicalDisplayIds();
938 }
939 
getPrimaryPhysicalDisplayId(PhysicalDisplayId * id)940 status_t SurfaceComposerClient::getPrimaryPhysicalDisplayId(PhysicalDisplayId* id) {
941     return ComposerService::getComposerService()->getPrimaryPhysicalDisplayId(id);
942 }
943 
getInternalDisplayId()944 std::optional<PhysicalDisplayId> SurfaceComposerClient::getInternalDisplayId() {
945     return ComposerService::getComposerService()->getInternalDisplayId();
946 }
947 
getPhysicalDisplayToken(PhysicalDisplayId displayId)948 sp<IBinder> SurfaceComposerClient::getPhysicalDisplayToken(PhysicalDisplayId displayId) {
949     return ComposerService::getComposerService()->getPhysicalDisplayToken(displayId);
950 }
951 
getInternalDisplayToken()952 sp<IBinder> SurfaceComposerClient::getInternalDisplayToken() {
953     return ComposerService::getComposerService()->getInternalDisplayToken();
954 }
955 
setAnimationTransaction()956 void SurfaceComposerClient::Transaction::setAnimationTransaction() {
957     mAnimation = true;
958 }
959 
setEarlyWakeupStart()960 void SurfaceComposerClient::Transaction::setEarlyWakeupStart() {
961     mEarlyWakeupStart = true;
962 }
963 
setEarlyWakeupEnd()964 void SurfaceComposerClient::Transaction::setEarlyWakeupEnd() {
965     mEarlyWakeupEnd = true;
966 }
967 
getLayerState(const sp<SurfaceControl> & sc)968 layer_state_t* SurfaceComposerClient::Transaction::getLayerState(const sp<SurfaceControl>& sc) {
969     auto handle = sc->getLayerStateHandle();
970 
971     if (mComposerStates.count(handle) == 0) {
972         // we don't have it, add an initialized layer_state to our list
973         ComposerState s;
974 
975         s.state.surface = handle;
976         s.state.layerId = sc->getLayerId();
977 
978         mComposerStates[handle] = s;
979     }
980 
981     return &(mComposerStates[handle].state);
982 }
983 
registerSurfaceControlForCallback(const sp<SurfaceControl> & sc)984 void SurfaceComposerClient::Transaction::registerSurfaceControlForCallback(
985         const sp<SurfaceControl>& sc) {
986     auto& callbackInfo = mListenerCallbacks[TransactionCompletedListener::getIInstance()];
987     callbackInfo.surfaceControls.insert(sc);
988 
989     TransactionCompletedListener::getInstance()
990             ->addSurfaceControlToCallbacks(sc, callbackInfo.callbackIds);
991 }
992 
setPosition(const sp<SurfaceControl> & sc,float x,float y)993 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setPosition(
994         const sp<SurfaceControl>& sc, float x, float y) {
995     layer_state_t* s = getLayerState(sc);
996     if (!s) {
997         mStatus = BAD_INDEX;
998         return *this;
999     }
1000     s->what |= layer_state_t::ePositionChanged;
1001     s->x = x;
1002     s->y = y;
1003 
1004     registerSurfaceControlForCallback(sc);
1005     return *this;
1006 }
1007 
show(const sp<SurfaceControl> & sc)1008 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::show(
1009         const sp<SurfaceControl>& sc) {
1010     return setFlags(sc, 0, layer_state_t::eLayerHidden);
1011 }
1012 
hide(const sp<SurfaceControl> & sc)1013 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::hide(
1014         const sp<SurfaceControl>& sc) {
1015     return setFlags(sc, layer_state_t::eLayerHidden, layer_state_t::eLayerHidden);
1016 }
1017 
setSize(const sp<SurfaceControl> & sc,uint32_t w,uint32_t h)1018 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setSize(
1019         const sp<SurfaceControl>& sc, uint32_t w, uint32_t h) {
1020     layer_state_t* s = getLayerState(sc);
1021     if (!s) {
1022         mStatus = BAD_INDEX;
1023         return *this;
1024     }
1025     s->what |= layer_state_t::eSizeChanged;
1026     s->w = w;
1027     s->h = h;
1028 
1029     registerSurfaceControlForCallback(sc);
1030     return *this;
1031 }
1032 
setLayer(const sp<SurfaceControl> & sc,int32_t z)1033 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setLayer(
1034         const sp<SurfaceControl>& sc, int32_t z) {
1035     layer_state_t* s = getLayerState(sc);
1036     if (!s) {
1037         mStatus = BAD_INDEX;
1038         return *this;
1039     }
1040     s->what |= layer_state_t::eLayerChanged;
1041     s->what &= ~layer_state_t::eRelativeLayerChanged;
1042     s->z = z;
1043 
1044     registerSurfaceControlForCallback(sc);
1045     return *this;
1046 }
1047 
setRelativeLayer(const sp<SurfaceControl> & sc,const sp<SurfaceControl> & relativeTo,int32_t z)1048 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setRelativeLayer(
1049         const sp<SurfaceControl>& sc, const sp<SurfaceControl>& relativeTo, int32_t z) {
1050     layer_state_t* s = getLayerState(sc);
1051     if (!s) {
1052         mStatus = BAD_INDEX;
1053         return *this;
1054     }
1055     s->what |= layer_state_t::eRelativeLayerChanged;
1056     s->what &= ~layer_state_t::eLayerChanged;
1057     s->relativeLayerSurfaceControl = relativeTo;
1058     s->z = z;
1059 
1060     registerSurfaceControlForCallback(sc);
1061     return *this;
1062 }
1063 
setFlags(const sp<SurfaceControl> & sc,uint32_t flags,uint32_t mask)1064 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setFlags(
1065         const sp<SurfaceControl>& sc, uint32_t flags,
1066         uint32_t mask) {
1067     layer_state_t* s = getLayerState(sc);
1068     if (!s) {
1069         mStatus = BAD_INDEX;
1070         return *this;
1071     }
1072     if ((mask & layer_state_t::eLayerOpaque) || (mask & layer_state_t::eLayerHidden) ||
1073         (mask & layer_state_t::eLayerSecure) || (mask & layer_state_t::eLayerSkipScreenshot) ||
1074         (mask & layer_state_t::eEnableBackpressure)) {
1075         s->what |= layer_state_t::eFlagsChanged;
1076     }
1077     s->flags &= ~mask;
1078     s->flags |= (flags & mask);
1079     s->mask |= mask;
1080 
1081     registerSurfaceControlForCallback(sc);
1082     return *this;
1083 }
1084 
setTransparentRegionHint(const sp<SurfaceControl> & sc,const Region & transparentRegion)1085 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setTransparentRegionHint(
1086         const sp<SurfaceControl>& sc,
1087         const Region& transparentRegion) {
1088     layer_state_t* s = getLayerState(sc);
1089     if (!s) {
1090         mStatus = BAD_INDEX;
1091         return *this;
1092     }
1093     s->what |= layer_state_t::eTransparentRegionChanged;
1094     s->transparentRegion = transparentRegion;
1095 
1096     registerSurfaceControlForCallback(sc);
1097     return *this;
1098 }
1099 
setAlpha(const sp<SurfaceControl> & sc,float alpha)1100 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setAlpha(
1101         const sp<SurfaceControl>& sc, float alpha) {
1102     layer_state_t* s = getLayerState(sc);
1103     if (!s) {
1104         mStatus = BAD_INDEX;
1105         return *this;
1106     }
1107     s->what |= layer_state_t::eAlphaChanged;
1108     s->alpha = alpha;
1109 
1110     registerSurfaceControlForCallback(sc);
1111     return *this;
1112 }
1113 
setLayerStack(const sp<SurfaceControl> & sc,uint32_t layerStack)1114 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setLayerStack(
1115         const sp<SurfaceControl>& sc, uint32_t layerStack) {
1116     layer_state_t* s = getLayerState(sc);
1117     if (!s) {
1118         mStatus = BAD_INDEX;
1119         return *this;
1120     }
1121     s->what |= layer_state_t::eLayerStackChanged;
1122     s->layerStack = layerStack;
1123 
1124     registerSurfaceControlForCallback(sc);
1125     return *this;
1126 }
1127 
setMetadata(const sp<SurfaceControl> & sc,uint32_t key,const Parcel & p)1128 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setMetadata(
1129         const sp<SurfaceControl>& sc, uint32_t key, const Parcel& p) {
1130     layer_state_t* s = getLayerState(sc);
1131     if (!s) {
1132         mStatus = BAD_INDEX;
1133         return *this;
1134     }
1135     s->what |= layer_state_t::eMetadataChanged;
1136 
1137     s->metadata.mMap[key] = {p.data(), p.data() + p.dataSize()};
1138 
1139     registerSurfaceControlForCallback(sc);
1140     return *this;
1141 }
1142 
setMatrix(const sp<SurfaceControl> & sc,float dsdx,float dtdx,float dtdy,float dsdy)1143 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setMatrix(
1144         const sp<SurfaceControl>& sc, float dsdx, float dtdx,
1145         float dtdy, float dsdy) {
1146     layer_state_t* s = getLayerState(sc);
1147     if (!s) {
1148         mStatus = BAD_INDEX;
1149         return *this;
1150     }
1151     s->what |= layer_state_t::eMatrixChanged;
1152     layer_state_t::matrix22_t matrix;
1153     matrix.dsdx = dsdx;
1154     matrix.dtdx = dtdx;
1155     matrix.dsdy = dsdy;
1156     matrix.dtdy = dtdy;
1157     s->matrix = matrix;
1158 
1159     registerSurfaceControlForCallback(sc);
1160     return *this;
1161 }
1162 
setCrop(const sp<SurfaceControl> & sc,const Rect & crop)1163 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setCrop(
1164         const sp<SurfaceControl>& sc, const Rect& crop) {
1165     layer_state_t* s = getLayerState(sc);
1166     if (!s) {
1167         mStatus = BAD_INDEX;
1168         return *this;
1169     }
1170     s->what |= layer_state_t::eCropChanged;
1171     s->crop = crop;
1172 
1173     registerSurfaceControlForCallback(sc);
1174     return *this;
1175 }
1176 
setCornerRadius(const sp<SurfaceControl> & sc,float cornerRadius)1177 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setCornerRadius(
1178         const sp<SurfaceControl>& sc, float cornerRadius) {
1179     layer_state_t* s = getLayerState(sc);
1180     if (!s) {
1181         mStatus = BAD_INDEX;
1182         return *this;
1183     }
1184     s->what |= layer_state_t::eCornerRadiusChanged;
1185     s->cornerRadius = cornerRadius;
1186     return *this;
1187 }
1188 
setBackgroundBlurRadius(const sp<SurfaceControl> & sc,int backgroundBlurRadius)1189 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setBackgroundBlurRadius(
1190         const sp<SurfaceControl>& sc, int backgroundBlurRadius) {
1191     layer_state_t* s = getLayerState(sc);
1192     if (!s) {
1193         mStatus = BAD_INDEX;
1194         return *this;
1195     }
1196     s->what |= layer_state_t::eBackgroundBlurRadiusChanged;
1197     s->backgroundBlurRadius = backgroundBlurRadius;
1198     return *this;
1199 }
1200 
setBlurRegions(const sp<SurfaceControl> & sc,const std::vector<BlurRegion> & blurRegions)1201 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setBlurRegions(
1202         const sp<SurfaceControl>& sc, const std::vector<BlurRegion>& blurRegions) {
1203     layer_state_t* s = getLayerState(sc);
1204     if (!s) {
1205         mStatus = BAD_INDEX;
1206         return *this;
1207     }
1208     s->what |= layer_state_t::eBlurRegionsChanged;
1209     s->blurRegions = blurRegions;
1210     return *this;
1211 }
1212 
reparent(const sp<SurfaceControl> & sc,const sp<SurfaceControl> & newParent)1213 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::reparent(
1214         const sp<SurfaceControl>& sc, const sp<SurfaceControl>& newParent) {
1215     layer_state_t* s = getLayerState(sc);
1216     if (!s) {
1217         mStatus = BAD_INDEX;
1218         return *this;
1219     }
1220     if (SurfaceControl::isSameSurface(sc, newParent)) {
1221         return *this;
1222     }
1223     s->what |= layer_state_t::eReparent;
1224     s->parentSurfaceControlForChild = newParent ? newParent->getParentingLayer() : nullptr;
1225 
1226     registerSurfaceControlForCallback(sc);
1227     return *this;
1228 }
1229 
setColor(const sp<SurfaceControl> & sc,const half3 & color)1230 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setColor(
1231         const sp<SurfaceControl>& sc,
1232         const half3& color) {
1233     layer_state_t* s = getLayerState(sc);
1234     if (!s) {
1235         mStatus = BAD_INDEX;
1236         return *this;
1237     }
1238     s->what |= layer_state_t::eColorChanged;
1239     s->color = color;
1240 
1241     registerSurfaceControlForCallback(sc);
1242     return *this;
1243 }
1244 
setBackgroundColor(const sp<SurfaceControl> & sc,const half3 & color,float alpha,ui::Dataspace dataspace)1245 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setBackgroundColor(
1246         const sp<SurfaceControl>& sc, const half3& color, float alpha, ui::Dataspace dataspace) {
1247     layer_state_t* s = getLayerState(sc);
1248     if (!s) {
1249         mStatus = BAD_INDEX;
1250         return *this;
1251     }
1252 
1253     s->what |= layer_state_t::eBackgroundColorChanged;
1254     s->color = color;
1255     s->bgColorAlpha = alpha;
1256     s->bgColorDataspace = dataspace;
1257 
1258     registerSurfaceControlForCallback(sc);
1259     return *this;
1260 }
1261 
setTransform(const sp<SurfaceControl> & sc,uint32_t transform)1262 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setTransform(
1263         const sp<SurfaceControl>& sc, uint32_t transform) {
1264     layer_state_t* s = getLayerState(sc);
1265     if (!s) {
1266         mStatus = BAD_INDEX;
1267         return *this;
1268     }
1269     s->what |= layer_state_t::eTransformChanged;
1270     s->transform = transform;
1271 
1272     registerSurfaceControlForCallback(sc);
1273     return *this;
1274 }
1275 
1276 SurfaceComposerClient::Transaction&
setTransformToDisplayInverse(const sp<SurfaceControl> & sc,bool transformToDisplayInverse)1277 SurfaceComposerClient::Transaction::setTransformToDisplayInverse(const sp<SurfaceControl>& sc,
1278                                                                  bool transformToDisplayInverse) {
1279     layer_state_t* s = getLayerState(sc);
1280     if (!s) {
1281         mStatus = BAD_INDEX;
1282         return *this;
1283     }
1284     s->what |= layer_state_t::eTransformToDisplayInverseChanged;
1285     s->transformToDisplayInverse = transformToDisplayInverse;
1286 
1287     registerSurfaceControlForCallback(sc);
1288     return *this;
1289 }
1290 
setBuffer(const sp<SurfaceControl> & sc,const sp<GraphicBuffer> & buffer,const ReleaseCallbackId & id,ReleaseBufferCallback callback)1291 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setBuffer(
1292         const sp<SurfaceControl>& sc, const sp<GraphicBuffer>& buffer, const ReleaseCallbackId& id,
1293         ReleaseBufferCallback callback) {
1294     layer_state_t* s = getLayerState(sc);
1295     if (!s) {
1296         mStatus = BAD_INDEX;
1297         return *this;
1298     }
1299     removeReleaseBufferCallback(s);
1300     s->what |= layer_state_t::eBufferChanged;
1301     s->buffer = buffer;
1302     s->releaseBufferEndpoint = IInterface::asBinder(TransactionCompletedListener::getIInstance());
1303     if (mIsAutoTimestamp) {
1304         mDesiredPresentTime = systemTime();
1305     }
1306     setReleaseBufferCallback(s, id, callback);
1307 
1308     registerSurfaceControlForCallback(sc);
1309 
1310     mContainsBuffer = true;
1311     return *this;
1312 }
1313 
removeReleaseBufferCallback(layer_state_t * s)1314 void SurfaceComposerClient::Transaction::removeReleaseBufferCallback(layer_state_t* s) {
1315     if (!s->releaseBufferListener) {
1316         return;
1317     }
1318 
1319     s->what &= ~static_cast<uint64_t>(layer_state_t::eReleaseBufferListenerChanged);
1320     s->releaseBufferListener = nullptr;
1321     auto listener = TransactionCompletedListener::getInstance();
1322     listener->removeReleaseBufferCallback(s->releaseCallbackId);
1323     s->releaseCallbackId = ReleaseCallbackId::INVALID_ID;
1324 }
1325 
setReleaseBufferCallback(layer_state_t * s,const ReleaseCallbackId & id,ReleaseBufferCallback callback)1326 void SurfaceComposerClient::Transaction::setReleaseBufferCallback(layer_state_t* s,
1327                                                                   const ReleaseCallbackId& id,
1328                                                                   ReleaseBufferCallback callback) {
1329     if (!callback) {
1330         return;
1331     }
1332 
1333     if (!s->buffer) {
1334         ALOGW("Transaction::setReleaseBufferCallback"
1335               "ignored trying to set a callback on a null buffer.");
1336         return;
1337     }
1338 
1339     s->what |= layer_state_t::eReleaseBufferListenerChanged;
1340     s->releaseBufferListener = TransactionCompletedListener::getIInstance();
1341     s->releaseCallbackId = id;
1342     auto listener = TransactionCompletedListener::getInstance();
1343     listener->setReleaseBufferCallback(id, callback);
1344 }
1345 
setAcquireFence(const sp<SurfaceControl> & sc,const sp<Fence> & fence)1346 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setAcquireFence(
1347         const sp<SurfaceControl>& sc, const sp<Fence>& fence) {
1348     layer_state_t* s = getLayerState(sc);
1349     if (!s) {
1350         mStatus = BAD_INDEX;
1351         return *this;
1352     }
1353     s->what |= layer_state_t::eAcquireFenceChanged;
1354     s->acquireFence = fence;
1355 
1356     registerSurfaceControlForCallback(sc);
1357     return *this;
1358 }
1359 
setDataspace(const sp<SurfaceControl> & sc,ui::Dataspace dataspace)1360 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setDataspace(
1361         const sp<SurfaceControl>& sc, ui::Dataspace dataspace) {
1362     layer_state_t* s = getLayerState(sc);
1363     if (!s) {
1364         mStatus = BAD_INDEX;
1365         return *this;
1366     }
1367     s->what |= layer_state_t::eDataspaceChanged;
1368     s->dataspace = dataspace;
1369 
1370     registerSurfaceControlForCallback(sc);
1371     return *this;
1372 }
1373 
setHdrMetadata(const sp<SurfaceControl> & sc,const HdrMetadata & hdrMetadata)1374 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setHdrMetadata(
1375         const sp<SurfaceControl>& sc, const HdrMetadata& hdrMetadata) {
1376     layer_state_t* s = getLayerState(sc);
1377     if (!s) {
1378         mStatus = BAD_INDEX;
1379         return *this;
1380     }
1381     s->what |= layer_state_t::eHdrMetadataChanged;
1382     s->hdrMetadata = hdrMetadata;
1383 
1384     registerSurfaceControlForCallback(sc);
1385     return *this;
1386 }
1387 
setSurfaceDamageRegion(const sp<SurfaceControl> & sc,const Region & surfaceDamageRegion)1388 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setSurfaceDamageRegion(
1389         const sp<SurfaceControl>& sc, const Region& surfaceDamageRegion) {
1390     layer_state_t* s = getLayerState(sc);
1391     if (!s) {
1392         mStatus = BAD_INDEX;
1393         return *this;
1394     }
1395     s->what |= layer_state_t::eSurfaceDamageRegionChanged;
1396     s->surfaceDamageRegion = surfaceDamageRegion;
1397 
1398     registerSurfaceControlForCallback(sc);
1399     return *this;
1400 }
1401 
setApi(const sp<SurfaceControl> & sc,int32_t api)1402 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setApi(
1403         const sp<SurfaceControl>& sc, int32_t api) {
1404     layer_state_t* s = getLayerState(sc);
1405     if (!s) {
1406         mStatus = BAD_INDEX;
1407         return *this;
1408     }
1409     s->what |= layer_state_t::eApiChanged;
1410     s->api = api;
1411 
1412     registerSurfaceControlForCallback(sc);
1413     return *this;
1414 }
1415 
setSidebandStream(const sp<SurfaceControl> & sc,const sp<NativeHandle> & sidebandStream)1416 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setSidebandStream(
1417         const sp<SurfaceControl>& sc, const sp<NativeHandle>& sidebandStream) {
1418     layer_state_t* s = getLayerState(sc);
1419     if (!s) {
1420         mStatus = BAD_INDEX;
1421         return *this;
1422     }
1423     s->what |= layer_state_t::eSidebandStreamChanged;
1424     s->sidebandStream = sidebandStream;
1425 
1426     registerSurfaceControlForCallback(sc);
1427     return *this;
1428 }
1429 
setDesiredPresentTime(nsecs_t desiredPresentTime)1430 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setDesiredPresentTime(
1431         nsecs_t desiredPresentTime) {
1432     mDesiredPresentTime = desiredPresentTime;
1433     mIsAutoTimestamp = false;
1434     return *this;
1435 }
1436 
setColorSpaceAgnostic(const sp<SurfaceControl> & sc,const bool agnostic)1437 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setColorSpaceAgnostic(
1438         const sp<SurfaceControl>& sc, const bool agnostic) {
1439     layer_state_t* s = getLayerState(sc);
1440     if (!s) {
1441         mStatus = BAD_INDEX;
1442         return *this;
1443     }
1444     s->what |= layer_state_t::eColorSpaceAgnosticChanged;
1445     s->colorSpaceAgnostic = agnostic;
1446 
1447     registerSurfaceControlForCallback(sc);
1448     return *this;
1449 }
1450 
1451 SurfaceComposerClient::Transaction&
setFrameRateSelectionPriority(const sp<SurfaceControl> & sc,int32_t priority)1452 SurfaceComposerClient::Transaction::setFrameRateSelectionPriority(const sp<SurfaceControl>& sc,
1453                                                                   int32_t priority) {
1454     layer_state_t* s = getLayerState(sc);
1455     if (!s) {
1456         mStatus = BAD_INDEX;
1457         return *this;
1458     }
1459 
1460     s->what |= layer_state_t::eFrameRateSelectionPriority;
1461     s->frameRateSelectionPriority = priority;
1462 
1463     registerSurfaceControlForCallback(sc);
1464     return *this;
1465 }
1466 
addTransactionCallback(TransactionCompletedCallbackTakesContext callback,void * callbackContext,CallbackId::Type callbackType)1467 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::addTransactionCallback(
1468         TransactionCompletedCallbackTakesContext callback, void* callbackContext,
1469         CallbackId::Type callbackType) {
1470     auto listener = TransactionCompletedListener::getInstance();
1471 
1472     auto callbackWithContext = std::bind(callback, callbackContext, std::placeholders::_1,
1473                                          std::placeholders::_2, std::placeholders::_3);
1474     const auto& surfaceControls =
1475             mListenerCallbacks[TransactionCompletedListener::getIInstance()].surfaceControls;
1476 
1477     CallbackId callbackId =
1478             listener->addCallbackFunction(callbackWithContext, surfaceControls, callbackType);
1479 
1480     mListenerCallbacks[TransactionCompletedListener::getIInstance()].callbackIds.emplace(
1481             callbackId);
1482     return *this;
1483 }
1484 
1485 SurfaceComposerClient::Transaction&
addTransactionCompletedCallback(TransactionCompletedCallbackTakesContext callback,void * callbackContext)1486 SurfaceComposerClient::Transaction::addTransactionCompletedCallback(
1487         TransactionCompletedCallbackTakesContext callback, void* callbackContext) {
1488     return addTransactionCallback(callback, callbackContext, CallbackId::Type::ON_COMPLETE);
1489 }
1490 
1491 SurfaceComposerClient::Transaction&
addTransactionCommittedCallback(TransactionCompletedCallbackTakesContext callback,void * callbackContext)1492 SurfaceComposerClient::Transaction::addTransactionCommittedCallback(
1493         TransactionCompletedCallbackTakesContext callback, void* callbackContext) {
1494     return addTransactionCallback(callback, callbackContext, CallbackId::Type::ON_COMMIT);
1495 }
1496 
notifyProducerDisconnect(const sp<SurfaceControl> & sc)1497 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::notifyProducerDisconnect(
1498         const sp<SurfaceControl>& sc) {
1499     layer_state_t* s = getLayerState(sc);
1500     if (!s) {
1501         mStatus = BAD_INDEX;
1502         return *this;
1503     }
1504 
1505     s->what |= layer_state_t::eProducerDisconnect;
1506     return *this;
1507 }
1508 
setFrameNumber(const sp<SurfaceControl> & sc,uint64_t frameNumber)1509 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setFrameNumber(
1510         const sp<SurfaceControl>& sc, uint64_t frameNumber) {
1511     layer_state_t* s = getLayerState(sc);
1512     if (!s) {
1513         mStatus = BAD_INDEX;
1514         return *this;
1515     }
1516 
1517     s->what |= layer_state_t::eFrameNumberChanged;
1518     s->frameNumber = frameNumber;
1519 
1520     return *this;
1521 }
1522 
setInputWindowInfo(const sp<SurfaceControl> & sc,const WindowInfo & info)1523 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setInputWindowInfo(
1524         const sp<SurfaceControl>& sc, const WindowInfo& info) {
1525     layer_state_t* s = getLayerState(sc);
1526     if (!s) {
1527         mStatus = BAD_INDEX;
1528         return *this;
1529     }
1530     s->windowInfoHandle = new WindowInfoHandle(info);
1531     s->what |= layer_state_t::eInputInfoChanged;
1532     return *this;
1533 }
1534 
setFocusedWindow(const FocusRequest & request)1535 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setFocusedWindow(
1536         const FocusRequest& request) {
1537     mInputWindowCommands.focusRequests.push_back(request);
1538     return *this;
1539 }
1540 
syncInputWindows()1541 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::syncInputWindows() {
1542     mInputWindowCommands.syncInputWindows = true;
1543     return *this;
1544 }
1545 
setColorTransform(const sp<SurfaceControl> & sc,const mat3 & matrix,const vec3 & translation)1546 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setColorTransform(
1547     const sp<SurfaceControl>& sc, const mat3& matrix, const vec3& translation) {
1548     layer_state_t* s = getLayerState(sc);
1549     if (!s) {
1550         mStatus = BAD_INDEX;
1551         return *this;
1552     }
1553     s->what |= layer_state_t::eColorTransformChanged;
1554     s->colorTransform = mat4(matrix, translation);
1555 
1556     registerSurfaceControlForCallback(sc);
1557     return *this;
1558 }
1559 
setGeometry(const sp<SurfaceControl> & sc,const Rect & source,const Rect & dst,int transform)1560 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setGeometry(
1561         const sp<SurfaceControl>& sc, const Rect& source, const Rect& dst, int transform) {
1562     setCrop(sc, source);
1563 
1564     int x = dst.left;
1565     int y = dst.top;
1566 
1567     float sourceWidth = source.getWidth();
1568     float sourceHeight = source.getHeight();
1569 
1570     float xScale = sourceWidth < 0 ? 1.0f : dst.getWidth() / sourceWidth;
1571     float yScale = sourceHeight < 0 ? 1.0f : dst.getHeight() / sourceHeight;
1572     float matrix[4] = {1, 0, 0, 1};
1573 
1574     switch (transform) {
1575         case NATIVE_WINDOW_TRANSFORM_FLIP_H:
1576             matrix[0] = -xScale; matrix[1] = 0;
1577             matrix[2] = 0; matrix[3] = yScale;
1578             x += source.getWidth();
1579             break;
1580         case NATIVE_WINDOW_TRANSFORM_FLIP_V:
1581             matrix[0] = xScale; matrix[1] = 0;
1582             matrix[2] = 0; matrix[3] = -yScale;
1583             y += source.getHeight();
1584             break;
1585         case NATIVE_WINDOW_TRANSFORM_ROT_90:
1586             matrix[0] = 0; matrix[1] = -yScale;
1587             matrix[2] = xScale; matrix[3] = 0;
1588             x += source.getHeight();
1589             break;
1590         case NATIVE_WINDOW_TRANSFORM_ROT_180:
1591             matrix[0] = -xScale; matrix[1] = 0;
1592             matrix[2] = 0; matrix[3] = -yScale;
1593             x += source.getWidth();
1594             y += source.getHeight();
1595             break;
1596         case NATIVE_WINDOW_TRANSFORM_ROT_270:
1597             matrix[0] = 0; matrix[1] = yScale;
1598             matrix[2] = -xScale; matrix[3] = 0;
1599             y += source.getWidth();
1600             break;
1601         default:
1602             matrix[0] = xScale; matrix[1] = 0;
1603             matrix[2] = 0; matrix[3] = yScale;
1604             break;
1605     }
1606     setMatrix(sc, matrix[0], matrix[1], matrix[2], matrix[3]);
1607     float offsetX = xScale * source.left;
1608     float offsetY = yScale * source.top;
1609     setPosition(sc, x - offsetX, y - offsetY);
1610 
1611     return *this;
1612 }
1613 
setShadowRadius(const sp<SurfaceControl> & sc,float shadowRadius)1614 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setShadowRadius(
1615         const sp<SurfaceControl>& sc, float shadowRadius) {
1616     layer_state_t* s = getLayerState(sc);
1617     if (!s) {
1618         mStatus = BAD_INDEX;
1619         return *this;
1620     }
1621     s->what |= layer_state_t::eShadowRadiusChanged;
1622     s->shadowRadius = shadowRadius;
1623     return *this;
1624 }
1625 
setFrameRate(const sp<SurfaceControl> & sc,float frameRate,int8_t compatibility,int8_t changeFrameRateStrategy)1626 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setFrameRate(
1627         const sp<SurfaceControl>& sc, float frameRate, int8_t compatibility,
1628         int8_t changeFrameRateStrategy) {
1629     layer_state_t* s = getLayerState(sc);
1630     if (!s) {
1631         mStatus = BAD_INDEX;
1632         return *this;
1633     }
1634     // Allow privileged values as well here, those will be ignored by SF if
1635     // the caller is not privileged
1636     if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
1637                            "Transaction::setFrameRate",
1638                            /*privileged=*/true)) {
1639         mStatus = BAD_VALUE;
1640         return *this;
1641     }
1642     s->what |= layer_state_t::eFrameRateChanged;
1643     s->frameRate = frameRate;
1644     s->frameRateCompatibility = compatibility;
1645     s->changeFrameRateStrategy = changeFrameRateStrategy;
1646     return *this;
1647 }
1648 
setFixedTransformHint(const sp<SurfaceControl> & sc,int32_t fixedTransformHint)1649 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setFixedTransformHint(
1650         const sp<SurfaceControl>& sc, int32_t fixedTransformHint) {
1651     layer_state_t* s = getLayerState(sc);
1652     if (!s) {
1653         mStatus = BAD_INDEX;
1654         return *this;
1655     }
1656 
1657     const ui::Transform::RotationFlags transform = fixedTransformHint == -1
1658             ? ui::Transform::ROT_INVALID
1659             : ui::Transform::toRotationFlags(static_cast<ui::Rotation>(fixedTransformHint));
1660     s->what |= layer_state_t::eFixedTransformHintChanged;
1661     s->fixedTransformHint = transform;
1662     return *this;
1663 }
1664 
setFrameTimelineInfo(const FrameTimelineInfo & frameTimelineInfo)1665 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setFrameTimelineInfo(
1666         const FrameTimelineInfo& frameTimelineInfo) {
1667     mFrameTimelineInfo.merge(frameTimelineInfo);
1668     return *this;
1669 }
1670 
setAutoRefresh(const sp<SurfaceControl> & sc,bool autoRefresh)1671 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setAutoRefresh(
1672         const sp<SurfaceControl>& sc, bool autoRefresh) {
1673     layer_state_t* s = getLayerState(sc);
1674     if (!s) {
1675         mStatus = BAD_INDEX;
1676         return *this;
1677     }
1678 
1679     s->what |= layer_state_t::eAutoRefreshChanged;
1680     s->autoRefresh = autoRefresh;
1681     return *this;
1682 }
1683 
setTrustedOverlay(const sp<SurfaceControl> & sc,bool isTrustedOverlay)1684 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setTrustedOverlay(
1685         const sp<SurfaceControl>& sc, bool isTrustedOverlay) {
1686     layer_state_t* s = getLayerState(sc);
1687     if (!s) {
1688         mStatus = BAD_INDEX;
1689         return *this;
1690     }
1691 
1692     s->what |= layer_state_t::eTrustedOverlayChanged;
1693     s->isTrustedOverlay = isTrustedOverlay;
1694     return *this;
1695 }
1696 
setApplyToken(const sp<IBinder> & applyToken)1697 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setApplyToken(
1698         const sp<IBinder>& applyToken) {
1699     mApplyToken = applyToken;
1700     return *this;
1701 }
1702 
setStretchEffect(const sp<SurfaceControl> & sc,const StretchEffect & stretchEffect)1703 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setStretchEffect(
1704     const sp<SurfaceControl>& sc, const StretchEffect& stretchEffect) {
1705     layer_state_t* s = getLayerState(sc);
1706     if (!s) {
1707         mStatus = BAD_INDEX;
1708         return *this;
1709     }
1710 
1711     s->what |= layer_state_t::eStretchChanged;
1712     s->stretchEffect = stretchEffect;
1713     return *this;
1714 }
1715 
setBufferCrop(const sp<SurfaceControl> & sc,const Rect & bufferCrop)1716 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setBufferCrop(
1717         const sp<SurfaceControl>& sc, const Rect& bufferCrop) {
1718     layer_state_t* s = getLayerState(sc);
1719     if (!s) {
1720         mStatus = BAD_INDEX;
1721         return *this;
1722     }
1723 
1724     s->what |= layer_state_t::eBufferCropChanged;
1725     s->bufferCrop = bufferCrop;
1726 
1727     registerSurfaceControlForCallback(sc);
1728     return *this;
1729 }
1730 
setDestinationFrame(const sp<SurfaceControl> & sc,const Rect & destinationFrame)1731 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setDestinationFrame(
1732         const sp<SurfaceControl>& sc, const Rect& destinationFrame) {
1733     layer_state_t* s = getLayerState(sc);
1734     if (!s) {
1735         mStatus = BAD_INDEX;
1736         return *this;
1737     }
1738 
1739     s->what |= layer_state_t::eDestinationFrameChanged;
1740     s->destinationFrame = destinationFrame;
1741 
1742     registerSurfaceControlForCallback(sc);
1743     return *this;
1744 }
1745 
setDropInputMode(const sp<SurfaceControl> & sc,gui::DropInputMode mode)1746 SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setDropInputMode(
1747         const sp<SurfaceControl>& sc, gui::DropInputMode mode) {
1748     layer_state_t* s = getLayerState(sc);
1749     if (!s) {
1750         mStatus = BAD_INDEX;
1751         return *this;
1752     }
1753 
1754     s->what |= layer_state_t::eDropInputModeChanged;
1755     s->dropInputMode = mode;
1756 
1757     registerSurfaceControlForCallback(sc);
1758     return *this;
1759 }
1760 
1761 // ---------------------------------------------------------------------------
1762 
getDisplayState(const sp<IBinder> & token)1763 DisplayState& SurfaceComposerClient::Transaction::getDisplayState(const sp<IBinder>& token) {
1764     DisplayState s;
1765     s.token = token;
1766     ssize_t index = mDisplayStates.indexOf(s);
1767     if (index < 0) {
1768         // we don't have it, add an initialized layer_state to our list
1769         s.what = 0;
1770         index = mDisplayStates.add(s);
1771     }
1772     return mDisplayStates.editItemAt(static_cast<size_t>(index));
1773 }
1774 
setDisplaySurface(const sp<IBinder> & token,const sp<IGraphicBufferProducer> & bufferProducer)1775 status_t SurfaceComposerClient::Transaction::setDisplaySurface(const sp<IBinder>& token,
1776         const sp<IGraphicBufferProducer>& bufferProducer) {
1777     if (bufferProducer.get() != nullptr) {
1778         // Make sure that composition can never be stalled by a virtual display
1779         // consumer that isn't processing buffers fast enough.
1780         status_t err = bufferProducer->setAsyncMode(true);
1781         if (err != NO_ERROR) {
1782             ALOGE("Composer::setDisplaySurface Failed to enable async mode on the "
1783                     "BufferQueue. This BufferQueue cannot be used for virtual "
1784                     "display. (%d)", err);
1785             return err;
1786         }
1787     }
1788     DisplayState& s(getDisplayState(token));
1789     s.surface = bufferProducer;
1790     s.what |= DisplayState::eSurfaceChanged;
1791     return NO_ERROR;
1792 }
1793 
setDisplayLayerStack(const sp<IBinder> & token,uint32_t layerStack)1794 void SurfaceComposerClient::Transaction::setDisplayLayerStack(const sp<IBinder>& token,
1795         uint32_t layerStack) {
1796     DisplayState& s(getDisplayState(token));
1797     s.layerStack = layerStack;
1798     s.what |= DisplayState::eLayerStackChanged;
1799 }
1800 
setDisplayFlags(const sp<IBinder> & token,uint32_t flags)1801 void SurfaceComposerClient::Transaction::setDisplayFlags(const sp<IBinder>& token, uint32_t flags) {
1802     DisplayState& s(getDisplayState(token));
1803     s.flags = flags;
1804     s.what |= DisplayState::eFlagsChanged;
1805 }
1806 
setDisplayProjection(const sp<IBinder> & token,ui::Rotation orientation,const Rect & layerStackRect,const Rect & displayRect)1807 void SurfaceComposerClient::Transaction::setDisplayProjection(const sp<IBinder>& token,
1808                                                               ui::Rotation orientation,
1809                                                               const Rect& layerStackRect,
1810                                                               const Rect& displayRect) {
1811     DisplayState& s(getDisplayState(token));
1812     s.orientation = orientation;
1813     s.layerStackSpaceRect = layerStackRect;
1814     s.orientedDisplaySpaceRect = displayRect;
1815     s.what |= DisplayState::eDisplayProjectionChanged;
1816     mForceSynchronous = true; // TODO: do we actually still need this?
1817 }
1818 
setDisplaySize(const sp<IBinder> & token,uint32_t width,uint32_t height)1819 void SurfaceComposerClient::Transaction::setDisplaySize(const sp<IBinder>& token, uint32_t width, uint32_t height) {
1820     DisplayState& s(getDisplayState(token));
1821     s.width = width;
1822     s.height = height;
1823     s.what |= DisplayState::eDisplaySizeChanged;
1824 }
1825 
1826 // ---------------------------------------------------------------------------
1827 
SurfaceComposerClient()1828 SurfaceComposerClient::SurfaceComposerClient() : mStatus(NO_INIT) {}
1829 
SurfaceComposerClient(const sp<ISurfaceComposerClient> & client)1830 SurfaceComposerClient::SurfaceComposerClient(const sp<ISurfaceComposerClient>& client)
1831       : mStatus(NO_ERROR), mClient(client) {}
1832 
onFirstRef()1833 void SurfaceComposerClient::onFirstRef() {
1834     sp<ISurfaceComposer> sf(ComposerService::getComposerService());
1835     if (sf != nullptr && mStatus == NO_INIT) {
1836         sp<ISurfaceComposerClient> conn;
1837         conn = sf->createConnection();
1838         if (conn != nullptr) {
1839             mClient = conn;
1840             mStatus = NO_ERROR;
1841         }
1842     }
1843 }
1844 
~SurfaceComposerClient()1845 SurfaceComposerClient::~SurfaceComposerClient() {
1846     dispose();
1847 }
1848 
initCheck() const1849 status_t SurfaceComposerClient::initCheck() const {
1850     return mStatus;
1851 }
1852 
connection() const1853 sp<IBinder> SurfaceComposerClient::connection() const {
1854     return IInterface::asBinder(mClient);
1855 }
1856 
linkToComposerDeath(const sp<IBinder::DeathRecipient> & recipient,void * cookie,uint32_t flags)1857 status_t SurfaceComposerClient::linkToComposerDeath(
1858         const sp<IBinder::DeathRecipient>& recipient,
1859         void* cookie, uint32_t flags) {
1860     sp<ISurfaceComposer> sf(ComposerService::getComposerService());
1861     return IInterface::asBinder(sf)->linkToDeath(recipient, cookie, flags);
1862 }
1863 
dispose()1864 void SurfaceComposerClient::dispose() {
1865     // this can be called more than once.
1866     sp<ISurfaceComposerClient> client;
1867     Mutex::Autolock _lm(mLock);
1868     if (mClient != nullptr) {
1869         client = mClient; // hold ref while lock is held
1870         mClient.clear();
1871     }
1872     mStatus = NO_INIT;
1873 }
1874 
createSurface(const String8 & name,uint32_t w,uint32_t h,PixelFormat format,uint32_t flags,const sp<IBinder> & parentHandle,LayerMetadata metadata,uint32_t * outTransformHint)1875 sp<SurfaceControl> SurfaceComposerClient::createSurface(const String8& name, uint32_t w, uint32_t h,
1876                                                         PixelFormat format, uint32_t flags,
1877                                                         const sp<IBinder>& parentHandle,
1878                                                         LayerMetadata metadata,
1879                                                         uint32_t* outTransformHint) {
1880     sp<SurfaceControl> s;
1881     createSurfaceChecked(name, w, h, format, &s, flags, parentHandle, std::move(metadata),
1882                          outTransformHint);
1883     return s;
1884 }
1885 
createWithSurfaceParent(const String8 & name,uint32_t w,uint32_t h,PixelFormat format,uint32_t flags,Surface * parent,LayerMetadata metadata,uint32_t * outTransformHint)1886 sp<SurfaceControl> SurfaceComposerClient::createWithSurfaceParent(const String8& name, uint32_t w,
1887                                                                   uint32_t h, PixelFormat format,
1888                                                                   uint32_t flags, Surface* parent,
1889                                                                   LayerMetadata metadata,
1890                                                                   uint32_t* outTransformHint) {
1891     sp<SurfaceControl> sur;
1892     status_t err = mStatus;
1893 
1894     if (mStatus == NO_ERROR) {
1895         sp<IBinder> handle;
1896         sp<IGraphicBufferProducer> parentGbp = parent->getIGraphicBufferProducer();
1897         sp<IGraphicBufferProducer> gbp;
1898 
1899         uint32_t transformHint = 0;
1900         int32_t id = -1;
1901         err = mClient->createWithSurfaceParent(name, w, h, format, flags, parentGbp,
1902                                                std::move(metadata), &handle, &gbp, &id,
1903                                                &transformHint);
1904         if (outTransformHint) {
1905             *outTransformHint = transformHint;
1906         }
1907         ALOGE_IF(err, "SurfaceComposerClient::createWithSurfaceParent error %s", strerror(-err));
1908         if (err == NO_ERROR) {
1909             return new SurfaceControl(this, handle, gbp, id, transformHint);
1910         }
1911     }
1912     return nullptr;
1913 }
1914 
createSurfaceChecked(const String8 & name,uint32_t w,uint32_t h,PixelFormat format,sp<SurfaceControl> * outSurface,uint32_t flags,const sp<IBinder> & parentHandle,LayerMetadata metadata,uint32_t * outTransformHint)1915 status_t SurfaceComposerClient::createSurfaceChecked(const String8& name, uint32_t w, uint32_t h,
1916                                                      PixelFormat format,
1917                                                      sp<SurfaceControl>* outSurface, uint32_t flags,
1918                                                      const sp<IBinder>& parentHandle,
1919                                                      LayerMetadata metadata,
1920                                                      uint32_t* outTransformHint) {
1921     sp<SurfaceControl> sur;
1922     status_t err = mStatus;
1923 
1924     if (mStatus == NO_ERROR) {
1925         sp<IBinder> handle;
1926         sp<IGraphicBufferProducer> gbp;
1927 
1928         uint32_t transformHint = 0;
1929         int32_t id = -1;
1930         err = mClient->createSurface(name, w, h, format, flags, parentHandle, std::move(metadata),
1931                                      &handle, &gbp, &id, &transformHint);
1932 
1933         if (outTransformHint) {
1934             *outTransformHint = transformHint;
1935         }
1936         ALOGE_IF(err, "SurfaceComposerClient::createSurface error %s", strerror(-err));
1937         if (err == NO_ERROR) {
1938             *outSurface =
1939                     new SurfaceControl(this, handle, gbp, id, w, h, format, transformHint, flags);
1940         }
1941     }
1942     return err;
1943 }
1944 
mirrorSurface(SurfaceControl * mirrorFromSurface)1945 sp<SurfaceControl> SurfaceComposerClient::mirrorSurface(SurfaceControl* mirrorFromSurface) {
1946     if (mirrorFromSurface == nullptr) {
1947         return nullptr;
1948     }
1949 
1950     sp<IBinder> handle;
1951     sp<IBinder> mirrorFromHandle = mirrorFromSurface->getHandle();
1952     int32_t layer_id = -1;
1953     status_t err = mClient->mirrorSurface(mirrorFromHandle, &handle, &layer_id);
1954     if (err == NO_ERROR) {
1955         return new SurfaceControl(this, handle, nullptr, layer_id, true /* owned */);
1956     }
1957     return nullptr;
1958 }
1959 
clearLayerFrameStats(const sp<IBinder> & token) const1960 status_t SurfaceComposerClient::clearLayerFrameStats(const sp<IBinder>& token) const {
1961     if (mStatus != NO_ERROR) {
1962         return mStatus;
1963     }
1964     return mClient->clearLayerFrameStats(token);
1965 }
1966 
getLayerFrameStats(const sp<IBinder> & token,FrameStats * outStats) const1967 status_t SurfaceComposerClient::getLayerFrameStats(const sp<IBinder>& token,
1968         FrameStats* outStats) const {
1969     if (mStatus != NO_ERROR) {
1970         return mStatus;
1971     }
1972     return mClient->getLayerFrameStats(token, outStats);
1973 }
1974 
1975 // ----------------------------------------------------------------------------
1976 
enableVSyncInjections(bool enable)1977 status_t SurfaceComposerClient::enableVSyncInjections(bool enable) {
1978     sp<ISurfaceComposer> sf(ComposerService::getComposerService());
1979     return sf->enableVSyncInjections(enable);
1980 }
1981 
injectVSync(nsecs_t when)1982 status_t SurfaceComposerClient::injectVSync(nsecs_t when) {
1983     sp<ISurfaceComposer> sf(ComposerService::getComposerService());
1984     return sf->injectVSync(when);
1985 }
1986 
getDisplayState(const sp<IBinder> & display,ui::DisplayState * state)1987 status_t SurfaceComposerClient::getDisplayState(const sp<IBinder>& display,
1988                                                 ui::DisplayState* state) {
1989     return ComposerService::getComposerService()->getDisplayState(display, state);
1990 }
1991 
getStaticDisplayInfo(const sp<IBinder> & display,ui::StaticDisplayInfo * info)1992 status_t SurfaceComposerClient::getStaticDisplayInfo(const sp<IBinder>& display,
1993                                                      ui::StaticDisplayInfo* info) {
1994     return ComposerService::getComposerService()->getStaticDisplayInfo(display, info);
1995 }
1996 
getDynamicDisplayInfo(const sp<IBinder> & display,ui::DynamicDisplayInfo * info)1997 status_t SurfaceComposerClient::getDynamicDisplayInfo(const sp<IBinder>& display,
1998                                                       ui::DynamicDisplayInfo* info) {
1999     return ComposerService::getComposerService()->getDynamicDisplayInfo(display, info);
2000 }
2001 
getActiveDisplayMode(const sp<IBinder> & display,ui::DisplayMode * mode)2002 status_t SurfaceComposerClient::getActiveDisplayMode(const sp<IBinder>& display,
2003                                                      ui::DisplayMode* mode) {
2004     ui::DynamicDisplayInfo info;
2005     status_t result = getDynamicDisplayInfo(display, &info);
2006     if (result != NO_ERROR) {
2007         return result;
2008     }
2009 
2010     if (const auto activeMode = info.getActiveDisplayMode()) {
2011         *mode = *activeMode;
2012         return NO_ERROR;
2013     }
2014 
2015     ALOGE("Active display mode not found.");
2016     return NAME_NOT_FOUND;
2017 }
2018 
setDesiredDisplayModeSpecs(const sp<IBinder> & displayToken,ui::DisplayModeId defaultMode,bool allowGroupSwitching,float primaryRefreshRateMin,float primaryRefreshRateMax,float appRequestRefreshRateMin,float appRequestRefreshRateMax)2019 status_t SurfaceComposerClient::setDesiredDisplayModeSpecs(
2020         const sp<IBinder>& displayToken, ui::DisplayModeId defaultMode, bool allowGroupSwitching,
2021         float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin,
2022         float appRequestRefreshRateMax) {
2023     return ComposerService::getComposerService()
2024             ->setDesiredDisplayModeSpecs(displayToken, defaultMode, allowGroupSwitching,
2025                                          primaryRefreshRateMin, primaryRefreshRateMax,
2026                                          appRequestRefreshRateMin, appRequestRefreshRateMax);
2027 }
2028 
getDesiredDisplayModeSpecs(const sp<IBinder> & displayToken,ui::DisplayModeId * outDefaultMode,bool * outAllowGroupSwitching,float * outPrimaryRefreshRateMin,float * outPrimaryRefreshRateMax,float * outAppRequestRefreshRateMin,float * outAppRequestRefreshRateMax)2029 status_t SurfaceComposerClient::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
2030                                                            ui::DisplayModeId* outDefaultMode,
2031                                                            bool* outAllowGroupSwitching,
2032                                                            float* outPrimaryRefreshRateMin,
2033                                                            float* outPrimaryRefreshRateMax,
2034                                                            float* outAppRequestRefreshRateMin,
2035                                                            float* outAppRequestRefreshRateMax) {
2036     return ComposerService::getComposerService()
2037             ->getDesiredDisplayModeSpecs(displayToken, outDefaultMode, outAllowGroupSwitching,
2038                                          outPrimaryRefreshRateMin, outPrimaryRefreshRateMax,
2039                                          outAppRequestRefreshRateMin, outAppRequestRefreshRateMax);
2040 }
2041 
getDisplayNativePrimaries(const sp<IBinder> & display,ui::DisplayPrimaries & outPrimaries)2042 status_t SurfaceComposerClient::getDisplayNativePrimaries(const sp<IBinder>& display,
2043         ui::DisplayPrimaries& outPrimaries) {
2044     return ComposerService::getComposerService()->getDisplayNativePrimaries(display, outPrimaries);
2045 }
2046 
setActiveColorMode(const sp<IBinder> & display,ColorMode colorMode)2047 status_t SurfaceComposerClient::setActiveColorMode(const sp<IBinder>& display,
2048         ColorMode colorMode) {
2049     return ComposerService::getComposerService()->setActiveColorMode(display, colorMode);
2050 }
2051 
setAutoLowLatencyMode(const sp<IBinder> & display,bool on)2052 void SurfaceComposerClient::setAutoLowLatencyMode(const sp<IBinder>& display, bool on) {
2053     ComposerService::getComposerService()->setAutoLowLatencyMode(display, on);
2054 }
2055 
setGameContentType(const sp<IBinder> & display,bool on)2056 void SurfaceComposerClient::setGameContentType(const sp<IBinder>& display, bool on) {
2057     ComposerService::getComposerService()->setGameContentType(display, on);
2058 }
2059 
setDisplayPowerMode(const sp<IBinder> & token,int mode)2060 void SurfaceComposerClient::setDisplayPowerMode(const sp<IBinder>& token,
2061         int mode) {
2062     ComposerService::getComposerService()->setPowerMode(token, mode);
2063 }
2064 
getCompositionPreference(ui::Dataspace * defaultDataspace,ui::PixelFormat * defaultPixelFormat,ui::Dataspace * wideColorGamutDataspace,ui::PixelFormat * wideColorGamutPixelFormat)2065 status_t SurfaceComposerClient::getCompositionPreference(
2066         ui::Dataspace* defaultDataspace, ui::PixelFormat* defaultPixelFormat,
2067         ui::Dataspace* wideColorGamutDataspace, ui::PixelFormat* wideColorGamutPixelFormat) {
2068     return ComposerService::getComposerService()
2069             ->getCompositionPreference(defaultDataspace, defaultPixelFormat,
2070                                        wideColorGamutDataspace, wideColorGamutPixelFormat);
2071 }
2072 
getProtectedContentSupport()2073 bool SurfaceComposerClient::getProtectedContentSupport() {
2074     bool supported = false;
2075     ComposerService::getComposerService()->getProtectedContentSupport(&supported);
2076     return supported;
2077 }
2078 
clearAnimationFrameStats()2079 status_t SurfaceComposerClient::clearAnimationFrameStats() {
2080     return ComposerService::getComposerService()->clearAnimationFrameStats();
2081 }
2082 
getAnimationFrameStats(FrameStats * outStats)2083 status_t SurfaceComposerClient::getAnimationFrameStats(FrameStats* outStats) {
2084     return ComposerService::getComposerService()->getAnimationFrameStats(outStats);
2085 }
2086 
overrideHdrTypes(const sp<IBinder> & display,const std::vector<ui::Hdr> & hdrTypes)2087 status_t SurfaceComposerClient::overrideHdrTypes(const sp<IBinder>& display,
2088                                                  const std::vector<ui::Hdr>& hdrTypes) {
2089     return ComposerService::getComposerService()->overrideHdrTypes(display, hdrTypes);
2090 }
2091 
onPullAtom(const int32_t atomId,std::string * outData,bool * success)2092 status_t SurfaceComposerClient::onPullAtom(const int32_t atomId, std::string* outData,
2093                                            bool* success) {
2094     return ComposerService::getComposerService()->onPullAtom(atomId, outData, success);
2095 }
2096 
getDisplayedContentSamplingAttributes(const sp<IBinder> & display,ui::PixelFormat * outFormat,ui::Dataspace * outDataspace,uint8_t * outComponentMask)2097 status_t SurfaceComposerClient::getDisplayedContentSamplingAttributes(const sp<IBinder>& display,
2098                                                                       ui::PixelFormat* outFormat,
2099                                                                       ui::Dataspace* outDataspace,
2100                                                                       uint8_t* outComponentMask) {
2101     return ComposerService::getComposerService()
2102             ->getDisplayedContentSamplingAttributes(display, outFormat, outDataspace,
2103                                                     outComponentMask);
2104 }
2105 
setDisplayContentSamplingEnabled(const sp<IBinder> & display,bool enable,uint8_t componentMask,uint64_t maxFrames)2106 status_t SurfaceComposerClient::setDisplayContentSamplingEnabled(const sp<IBinder>& display,
2107                                                                  bool enable, uint8_t componentMask,
2108                                                                  uint64_t maxFrames) {
2109     return ComposerService::getComposerService()->setDisplayContentSamplingEnabled(display, enable,
2110                                                                                    componentMask,
2111                                                                                    maxFrames);
2112 }
2113 
getDisplayedContentSample(const sp<IBinder> & display,uint64_t maxFrames,uint64_t timestamp,DisplayedFrameStats * outStats)2114 status_t SurfaceComposerClient::getDisplayedContentSample(const sp<IBinder>& display,
2115                                                           uint64_t maxFrames, uint64_t timestamp,
2116                                                           DisplayedFrameStats* outStats) {
2117     return ComposerService::getComposerService()->getDisplayedContentSample(display, maxFrames,
2118                                                                             timestamp, outStats);
2119 }
2120 
isWideColorDisplay(const sp<IBinder> & display,bool * outIsWideColorDisplay)2121 status_t SurfaceComposerClient::isWideColorDisplay(const sp<IBinder>& display,
2122                                                    bool* outIsWideColorDisplay) {
2123     return ComposerService::getComposerService()->isWideColorDisplay(display,
2124                                                                      outIsWideColorDisplay);
2125 }
2126 
addRegionSamplingListener(const Rect & samplingArea,const sp<IBinder> & stopLayerHandle,const sp<IRegionSamplingListener> & listener)2127 status_t SurfaceComposerClient::addRegionSamplingListener(
2128         const Rect& samplingArea, const sp<IBinder>& stopLayerHandle,
2129         const sp<IRegionSamplingListener>& listener) {
2130     return ComposerService::getComposerService()->addRegionSamplingListener(samplingArea,
2131                                                                             stopLayerHandle,
2132                                                                             listener);
2133 }
2134 
removeRegionSamplingListener(const sp<IRegionSamplingListener> & listener)2135 status_t SurfaceComposerClient::removeRegionSamplingListener(
2136         const sp<IRegionSamplingListener>& listener) {
2137     return ComposerService::getComposerService()->removeRegionSamplingListener(listener);
2138 }
2139 
addFpsListener(int32_t taskId,const sp<gui::IFpsListener> & listener)2140 status_t SurfaceComposerClient::addFpsListener(int32_t taskId,
2141                                                const sp<gui::IFpsListener>& listener) {
2142     return ComposerService::getComposerService()->addFpsListener(taskId, listener);
2143 }
2144 
removeFpsListener(const sp<gui::IFpsListener> & listener)2145 status_t SurfaceComposerClient::removeFpsListener(const sp<gui::IFpsListener>& listener) {
2146     return ComposerService::getComposerService()->removeFpsListener(listener);
2147 }
2148 
addTunnelModeEnabledListener(const sp<gui::ITunnelModeEnabledListener> & listener)2149 status_t SurfaceComposerClient::addTunnelModeEnabledListener(
2150         const sp<gui::ITunnelModeEnabledListener>& listener) {
2151     return ComposerService::getComposerService()->addTunnelModeEnabledListener(listener);
2152 }
2153 
removeTunnelModeEnabledListener(const sp<gui::ITunnelModeEnabledListener> & listener)2154 status_t SurfaceComposerClient::removeTunnelModeEnabledListener(
2155         const sp<gui::ITunnelModeEnabledListener>& listener) {
2156     return ComposerService::getComposerService()->removeTunnelModeEnabledListener(listener);
2157 }
2158 
getDisplayBrightnessSupport(const sp<IBinder> & displayToken)2159 bool SurfaceComposerClient::getDisplayBrightnessSupport(const sp<IBinder>& displayToken) {
2160     bool support = false;
2161     ComposerService::getComposerService()->getDisplayBrightnessSupport(displayToken, &support);
2162     return support;
2163 }
2164 
setDisplayBrightness(const sp<IBinder> & displayToken,const gui::DisplayBrightness & brightness)2165 status_t SurfaceComposerClient::setDisplayBrightness(const sp<IBinder>& displayToken,
2166                                                      const gui::DisplayBrightness& brightness) {
2167     return ComposerService::getComposerService()->setDisplayBrightness(displayToken, brightness);
2168 }
2169 
addHdrLayerInfoListener(const sp<IBinder> & displayToken,const sp<gui::IHdrLayerInfoListener> & listener)2170 status_t SurfaceComposerClient::addHdrLayerInfoListener(
2171         const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
2172     return ComposerService::getComposerService()->addHdrLayerInfoListener(displayToken, listener);
2173 }
2174 
removeHdrLayerInfoListener(const sp<IBinder> & displayToken,const sp<gui::IHdrLayerInfoListener> & listener)2175 status_t SurfaceComposerClient::removeHdrLayerInfoListener(
2176         const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
2177     return ComposerService::getComposerService()->removeHdrLayerInfoListener(displayToken,
2178                                                                              listener);
2179 }
2180 
notifyPowerBoost(int32_t boostId)2181 status_t SurfaceComposerClient::notifyPowerBoost(int32_t boostId) {
2182     return ComposerService::getComposerService()->notifyPowerBoost(boostId);
2183 }
2184 
setGlobalShadowSettings(const half4 & ambientColor,const half4 & spotColor,float lightPosY,float lightPosZ,float lightRadius)2185 status_t SurfaceComposerClient::setGlobalShadowSettings(const half4& ambientColor,
2186                                                         const half4& spotColor, float lightPosY,
2187                                                         float lightPosZ, float lightRadius) {
2188     return ComposerService::getComposerService()->setGlobalShadowSettings(ambientColor, spotColor,
2189                                                                           lightPosY, lightPosZ,
2190                                                                           lightRadius);
2191 }
2192 
getGPUContextPriority()2193 int SurfaceComposerClient::getGPUContextPriority() {
2194     return ComposerService::getComposerService()->getGPUContextPriority();
2195 }
2196 
addWindowInfosListener(const sp<WindowInfosListener> & windowInfosListener)2197 status_t SurfaceComposerClient::addWindowInfosListener(
2198         const sp<WindowInfosListener>& windowInfosListener) {
2199     return WindowInfosListenerReporter::getInstance()
2200             ->addWindowInfosListener(windowInfosListener, ComposerService::getComposerService());
2201 }
2202 
removeWindowInfosListener(const sp<WindowInfosListener> & windowInfosListener)2203 status_t SurfaceComposerClient::removeWindowInfosListener(
2204         const sp<WindowInfosListener>& windowInfosListener) {
2205     return WindowInfosListenerReporter::getInstance()
2206             ->removeWindowInfosListener(windowInfosListener, ComposerService::getComposerService());
2207 }
2208 
2209 // ----------------------------------------------------------------------------
2210 
captureDisplay(const DisplayCaptureArgs & captureArgs,const sp<IScreenCaptureListener> & captureListener)2211 status_t ScreenshotClient::captureDisplay(const DisplayCaptureArgs& captureArgs,
2212                                           const sp<IScreenCaptureListener>& captureListener) {
2213     sp<ISurfaceComposer> s(ComposerService::getComposerService());
2214     if (s == nullptr) return NO_INIT;
2215 
2216     return s->captureDisplay(captureArgs, captureListener);
2217 }
2218 
captureDisplay(uint64_t displayOrLayerStack,const sp<IScreenCaptureListener> & captureListener)2219 status_t ScreenshotClient::captureDisplay(uint64_t displayOrLayerStack,
2220                                           const sp<IScreenCaptureListener>& captureListener) {
2221     sp<ISurfaceComposer> s(ComposerService::getComposerService());
2222     if (s == nullptr) return NO_INIT;
2223 
2224     return s->captureDisplay(displayOrLayerStack, captureListener);
2225 }
2226 
captureLayers(const LayerCaptureArgs & captureArgs,const sp<IScreenCaptureListener> & captureListener)2227 status_t ScreenshotClient::captureLayers(const LayerCaptureArgs& captureArgs,
2228                                          const sp<IScreenCaptureListener>& captureListener) {
2229     sp<ISurfaceComposer> s(ComposerService::getComposerService());
2230     if (s == nullptr) return NO_INIT;
2231 
2232     return s->captureLayers(captureArgs, captureListener);
2233 }
2234 
2235 } // namespace android
2236