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