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