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