blob: 7fd8a07ba3046aab63a2497dbf11a4c7e64e08cb [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
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
Alec Mourie7d1d4a2019-02-05 01:13:46 +000017//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070022#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080023
24#include <algorithm>
25#include <cinttypes>
26#include <cmath>
27#include <cstdint>
28#include <functional>
29#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070030#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080031#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Lloyd Pique70d91362018-10-18 16:02:55 -070040#include <compositionengine/CompositionEngine.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070041#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070042#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080043#include <compositionengine/Layer.h>
44#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070045#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070046#include <compositionengine/impl/OutputCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080047#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070049#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080051#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080052#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080053#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070054#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070055#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070056#include <ui/ColorSpace.h>
57#include <ui/DebugUtils.h>
58#include <ui/DisplayInfo.h>
59#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070060#include <ui/GraphicBufferAllocator.h>
61#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070062#include <ui/UiConfig.h>
Ady Abraham8164d482019-01-11 14:47:59 -080063#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070065#include <utils/String16.h>
66#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070067#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080068#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070069#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080070
Mathias Agopian921e6ac2012-07-23 23:11:29 -070071#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070072#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073
Robert Carr578038f2018-03-09 12:25:24 -080074#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070075#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070076#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020077#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020079#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080080#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080081#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070083#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080084#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070085#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070086#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080087#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070088#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089
Steven Thomasb02664d2017-07-26 18:48:28 -070090#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070091#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070092#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070093#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070094#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070095#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070096#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070097#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070098#include "Scheduler/EventControlThread.h"
99#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700100#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700101#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700102#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800103#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700104
Mathias Agopianff2ed702013-09-01 21:36:12 -0700105#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700106
David Sodman7e4ae112018-02-09 15:02:28 -0800107#include "android-base/stringprintf.h"
108
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900109#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800110#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700111#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800112#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900113#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900114
chaviw1d044282017-09-27 12:19:28 -0700115#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900116#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700117
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800118namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700119
Jaesoo Lee43518572017-01-23 19:03:16 +0900120using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900121using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900122using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800123
Yiwei Zhang5434a782018-12-05 18:06:32 -0800124using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700125using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700126using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800127using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700128using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700129using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900130
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800131using RefreshRateType = scheduler::RefreshRateConfigs::RefreshRateType;
132
Steven Thomasb02664d2017-07-26 18:48:28 -0700133namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700134
135#pragma clang diagnostic push
136#pragma clang diagnostic error "-Wswitch-enum"
137
138bool isWideColorMode(const ColorMode colorMode) {
139 switch (colorMode) {
140 case ColorMode::DISPLAY_P3:
141 case ColorMode::ADOBE_RGB:
142 case ColorMode::DCI_P3:
143 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700144 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700145 case ColorMode::BT2100_PQ:
146 case ColorMode::BT2100_HLG:
147 return true;
148 case ColorMode::NATIVE:
149 case ColorMode::STANDARD_BT601_625:
150 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
151 case ColorMode::STANDARD_BT601_525:
152 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
153 case ColorMode::STANDARD_BT709:
154 case ColorMode::SRGB:
155 return false;
156 }
157 return false;
158}
159
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700160ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
161 switch (rotation) {
162 case ISurfaceComposer::eRotateNone:
163 return ui::Transform::ROT_0;
164 case ISurfaceComposer::eRotate90:
165 return ui::Transform::ROT_90;
166 case ISurfaceComposer::eRotate180:
167 return ui::Transform::ROT_180;
168 case ISurfaceComposer::eRotate270:
169 return ui::Transform::ROT_270;
170 }
171 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
172 return ui::Transform::ROT_0;
173}
174
Peiyong Linfca547f2018-07-09 13:03:33 -0700175#pragma clang diagnostic pop
176
Steven Thomasb02664d2017-07-26 18:48:28 -0700177class ConditionalLock {
178public:
179 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
180 if (lock) {
181 mMutex.lock();
182 }
183 }
184 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
185private:
186 Mutex& mMutex;
187 bool mLocked;
188};
Peiyong Linfca547f2018-07-09 13:03:33 -0700189
Peiyong Lin9d846a52018-11-05 13:18:20 -0800190// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
191bool validateCompositionDataspace(Dataspace dataspace) {
192 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
193}
194
Steven Thomasb02664d2017-07-26 18:48:28 -0700195} // namespace anonymous
196
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800197// ---------------------------------------------------------------------------
198
Mathias Agopian99b49842011-06-27 16:05:52 -0700199const String16 sHardwareTest("android.permission.HARDWARE_TEST");
200const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
201const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
202const String16 sDump("android.permission.DUMP");
203
Daniel Solomon42d04562019-01-20 21:03:19 -0800204constexpr float kSrgbRedX = 0.4123f;
205constexpr float kSrgbRedY = 0.2126f;
206constexpr float kSrgbRedZ = 0.0193f;
207constexpr float kSrgbGreenX = 0.3576f;
208constexpr float kSrgbGreenY = 0.7152f;
209constexpr float kSrgbGreenZ = 0.1192f;
210constexpr float kSrgbBlueX = 0.1805f;
211constexpr float kSrgbBlueY = 0.0722f;
212constexpr float kSrgbBlueZ = 0.9506f;
213constexpr float kSrgbWhiteX = 0.9505f;
214constexpr float kSrgbWhiteY = 1.0000f;
215constexpr float kSrgbWhiteZ = 1.0891f;
216
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800217constexpr float kDefaultRefreshRate = 60.f;
218constexpr float kPerformanceRefreshRate = 90.f;
219
Mathias Agopian99b49842011-06-27 16:05:52 -0700220// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700221int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700222bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800223uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800224bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800225bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800226int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600227bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700228int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700229bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700230bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700231Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
232ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
233Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
234ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700235
Kalle Raitaa099a242017-01-11 11:17:29 -0800236std::string getHwcServiceName() {
237 char value[PROPERTY_VALUE_MAX] = {};
238 property_get("debug.sf.hwc_service_name", value, "default");
239 ALOGI("Using HWComposer service: '%s'", value);
240 return std::string(value);
241}
242
243bool useTrebleTestingOverride() {
244 char value[PROPERTY_VALUE_MAX] = {};
245 property_get("debug.sf.treble_testing_override", value, "false");
246 ALOGI("Treble testing override: '%s'", value);
247 return std::string(value) == "true";
248}
249
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800250std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
251 switch(displayColorSetting) {
252 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700253 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800254 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700255 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800256 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700257 return std::string("Enhanced");
258 default:
259 return std::string("Unknown ") +
260 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800261 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800262}
263
David Sodmanbc815282017-11-05 18:57:52 -0800264SurfaceFlingerBE::SurfaceFlingerBE()
265 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800266 mFrameBuckets(),
267 mTotalTime(0),
268 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800269 mComposerSequenceId(0) {
270}
271
Lloyd Pique90c115d2018-09-18 21:39:42 -0700272SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
273 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800274 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700275 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700276 mTransactionPending(false),
277 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700278 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700279 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800280 mBootTime(systemTime()),
Ana Krulec757f63a2019-01-25 10:46:18 -0800281 mPhaseOffsets{getFactory().createPhaseOffsets()},
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800282 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800283 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800284 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800285 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800286 mDebugRegion(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700287 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700288 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700289 mDebugInTransaction(0),
290 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700291 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800292 mTimeStats(factory.createTimeStats()),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700293 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700294 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800295 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800296 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800297 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700298 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700299 mMainThreadId(std::this_thread::get_id()),
300 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800301
Lloyd Pique90c115d2018-09-18 21:39:42 -0700302SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
303 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800304 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800305
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900306 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800307
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900308 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700309
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900310 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700311
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900312 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800313
Steven Thomas050b2c82017-03-06 11:45:16 -0800314 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900315 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800316
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900317 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800318
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900319 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700320
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900321 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600322
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900323 mDefaultCompositionDataspace =
324 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
325 mWideColorGamutCompositionDataspace =
326 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
327 defaultCompositionDataspace = mDefaultCompositionDataspace;
328 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
329 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
330 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
331 wideColorGamutCompositionPixelFormat =
332 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700333
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900334 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800335
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900336 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
337 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
338 switch (tmpPrimaryDisplayOrientation) {
339 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700340 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800341 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900342 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700343 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800344 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900345 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700346 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800347 break;
348 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700349 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800350 break;
351 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700352 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800353
Daniel Solomon42d04562019-01-20 21:03:19 -0800354 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
355 if (surfaceFlingerConfigsServiceV1_2) {
356 surfaceFlingerConfigsServiceV1_2->getDisplayNativePrimaries(
357 [&](auto tmpPrimaries) {
358 memcpy(&mInternalDisplayPrimaries, &tmpPrimaries, sizeof(ui::DisplayPrimaries));
359 });
360 } else {
361 initDefaultDisplayNativePrimaries();
362 }
363
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800364 // debugging stuff...
365 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700366
Mathias Agopianb4b17302013-03-20 18:36:41 -0700367 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700368 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700369
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800370 property_get("debug.sf.showupdates", value, "0");
371 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700372
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700373 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000374
375 // DDMS debugging deprecated (b/120782499)
376 property_get("debug.sf.ddms", value, "0");
377 int debugDdms = atoi(value);
378 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700379
380 property_get("debug.sf.disable_backpressure", value, "0");
381 mPropagateBackpressure = !atoi(value);
382 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700383
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800384 property_get("debug.sf.enable_hwc_vds", value, "0");
385 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800386 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800387
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800388 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800389 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800390 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700391
Yiwei Zhang243b3782018-05-15 17:40:04 -0700392 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700393 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
394 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
395
Ana Krulec98b5b242018-08-10 15:03:23 -0700396 property_get("debug.sf.use_scheduler", value, "0");
397 mUseScheduler = atoi(value);
398
Ady Abrahamc3e21312019-02-07 14:30:23 -0800399 if (!mUseScheduler) {
400 mPrimaryDispSync =
401 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
402 SurfaceFlinger::dispSyncPresentTimeOffset);
403 }
404
Ana Krulec757f63a2019-01-25 10:46:18 -0800405 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
406 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700407
Romain Guy11d63f42017-07-20 12:47:14 -0700408 // We should be reading 'persist.sys.sf.color_saturation' here
409 // but since /data may be encrypted, we need to wait until after vold
410 // comes online to attempt to read the property. The property is
411 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800412
413 if (useTrebleTestingOverride()) {
414 // Without the override SurfaceFlinger cannot connect to HIDL
415 // services that are not listed in the manifests. Considered
416 // deriving the setting from the set service name, but it
417 // would be brittle if the name that's not 'default' is used
418 // for production purposes later on.
419 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
420 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800421}
422
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800423void SurfaceFlinger::onFirstRef()
424{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800425 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800426}
427
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800428SurfaceFlinger::~SurfaceFlinger()
429{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800430}
431
Dan Stozac7014012014-02-14 15:03:43 -0800432void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800433{
434 // the window manager died on us. prepare its eulogy.
435
Andy McFadden13a082e2012-08-24 10:16:42 -0700436 // restore initial conditions (default device unblank, etc)
437 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800438
439 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700440 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800441}
442
Robert Carr1db73f62016-12-21 12:58:51 -0800443static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700444 status_t err = client->initCheck();
445 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800446 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800447 }
Robert Carr1db73f62016-12-21 12:58:51 -0800448 return nullptr;
449}
450
451sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
452 return initClient(new Client(this));
453}
454
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700455sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
456 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700457{
458 class DisplayToken : public BBinder {
459 sp<SurfaceFlinger> flinger;
460 virtual ~DisplayToken() {
461 // no more references, this display must be terminated
462 Mutex::Autolock _l(flinger->mStateLock);
463 flinger->mCurrentState.displays.removeItem(this);
464 flinger->setTransactionFlags(eDisplayTransactionNeeded);
465 }
466 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700467 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700468 : flinger(flinger) {
469 }
470 };
471
472 sp<BBinder> token = new DisplayToken(this);
473
474 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700475 // Display ID is assigned when virtual display is allocated by HWC.
476 DisplayDeviceState state;
477 state.isSecure = secure;
478 state.displayName = displayName;
479 mCurrentState.displays.add(token, state);
480 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700481 return token;
482}
483
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700484void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700485 Mutex::Autolock _l(mStateLock);
486
Dominik Laskowski075d3172018-05-24 15:50:06 -0700487 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
488 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700489 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700490 return;
491 }
492
Dominik Laskowski075d3172018-05-24 15:50:06 -0700493 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
494 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700495 ALOGE("destroyDisplay called for non-virtual display");
496 return;
497 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700498 mInterceptor->saveDisplayDeletion(state.sequenceId);
499 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700500 setTransactionFlags(eDisplayTransactionNeeded);
501}
502
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800503std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
504 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700505
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800506 const auto internalDisplayId = getInternalDisplayIdLocked();
507 if (!internalDisplayId) {
508 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700509 }
510
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800511 std::vector<PhysicalDisplayId> displayIds;
512 displayIds.reserve(mPhysicalDisplayTokens.size());
513 displayIds.push_back(internalDisplayId->value);
514
515 for (const auto& [id, token] : mPhysicalDisplayTokens) {
516 if (id != *internalDisplayId) {
517 displayIds.push_back(id.value);
518 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700519 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700520
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800521 return displayIds;
522}
523
524sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
525 Mutex::Autolock lock(mStateLock);
526 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700527}
528
Ady Abraham37965d42018-11-01 13:43:32 -0700529status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
530 if (!outGetColorManagement) {
531 return BAD_VALUE;
532 }
533 *outGetColorManagement = useColorManagement;
534 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700535}
536
Lloyd Pique441d5042018-10-18 16:49:51 -0700537HWComposer& SurfaceFlinger::getHwComposer() const {
538 return mCompositionEngine->getHwComposer();
539}
540
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700541renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
542 return mCompositionEngine->getRenderEngine();
543}
544
Lloyd Pique70d91362018-10-18 16:02:55 -0700545compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
546 return *mCompositionEngine.get();
547}
548
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800549void SurfaceFlinger::bootFinished()
550{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700551 if (mStartPropertySetThread->join() != NO_ERROR) {
552 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800553 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800554 const nsecs_t now = systemTime();
555 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000556 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700557
558 // wait patiently for the window manager death
559 const String16 name("window");
560 sp<IBinder> window(defaultServiceManager()->getService(name));
561 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700562 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700563 }
Robert Carr720e5062018-07-30 17:45:14 -0700564 sp<IBinder> input(defaultServiceManager()->getService(
565 String16("inputflinger")));
566 if (input == nullptr) {
567 ALOGE("Failed to link to input service");
568 } else {
569 mInputFlinger = interface_cast<IInputFlinger>(input);
570 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700571
Steven Thomas050b2c82017-03-06 11:45:16 -0800572 if (mVrFlinger) {
573 mVrFlinger->OnBootFinished();
574 }
575
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700576 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700577 // formerly we would just kill the process, but we now ask it to exit so it
578 // can choose where to stop the animation.
579 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700580
581 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
582 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
583 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700584
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800585 postMessageAsync(new LambdaMessage([this] {
586 readPersistentProperties();
587 mBootStage = BootStage::FINISHED;
588 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800589}
590
Dan Stoza436ccf32018-06-21 12:10:12 -0700591uint32_t SurfaceFlinger::getNewTexture() {
592 {
593 std::lock_guard lock(mTexturePoolMutex);
594 if (!mTexturePool.empty()) {
595 uint32_t name = mTexturePool.back();
596 mTexturePool.pop_back();
597 ATRACE_INT("TexturePoolSize", mTexturePool.size());
598 return name;
599 }
600
601 // The pool was too small, so increase it for the future
602 ++mTexturePoolSize;
603 }
604
605 // The pool was empty, so we need to get a new texture name directly using a
606 // blocking call to the main thread
607 uint32_t name = 0;
608 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
609 return name;
610}
611
Mathias Agopian3f844832013-08-07 21:24:32 -0700612void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700613 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700614}
615
Wei Wangf9b05ee2017-07-19 20:59:39 -0700616// Do not call property_set on main thread which will be blocked by init
617// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700618void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700619 ALOGI( "SurfaceFlinger's main thread ready to run. "
620 "Initializing graphics H/W...");
621
Ana Krulec757f63a2019-01-25 10:46:18 -0800622 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900623
Steven Thomasb02664d2017-07-26 18:48:28 -0700624 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800625
Dominik Laskowski83b88212018-12-11 13:34:06 -0800626 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -0800627
Steven Thomasb02664d2017-07-26 18:48:28 -0700628 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700629 if (mUseScheduler) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800630 mScheduler = getFactory().createScheduler(
631 [this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
632
Ana Krulec757f63a2019-01-25 10:46:18 -0800633 // TODO(b/113612090): Currently we assume that if scheduler is turned on, then the refresh
634 // rate is 90. Once b/122905403 is completed, this should be updated accordingly.
635 mPhaseOffsets->setRefreshRateType(
636 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700637
Ana Krulec98b5b242018-08-10 15:03:23 -0700638 mAppConnectionHandle =
Ana Krulec757f63a2019-01-25 10:46:18 -0800639 mScheduler->createConnection("appConnection", mPhaseOffsets->getCurrentAppOffset(),
Ady Abrahama1a49af2019-02-07 14:36:55 -0800640 resyncCallback,
Ana Krulec98b5b242018-08-10 15:03:23 -0700641 impl::EventThread::InterceptVSyncsCallback());
642 mSfConnectionHandle =
Ana Krulec757f63a2019-01-25 10:46:18 -0800643 mScheduler->createConnection("sfConnection", mPhaseOffsets->getCurrentSfOffset(),
Ady Abrahama1a49af2019-02-07 14:36:55 -0800644 resyncCallback, [this](nsecs_t timestamp) {
Ana Krulec98b5b242018-08-10 15:03:23 -0700645 mInterceptor->saveVSyncEvent(timestamp);
646 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800647
Ana Krulec98b5b242018-08-10 15:03:23 -0700648 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700649 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
650 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700651 } else {
652 mEventThreadSource =
653 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800654 mPhaseOffsets->getCurrentAppOffset(), true, "app");
Ana Krulec98b5b242018-08-10 15:03:23 -0700655 mEventThread =
656 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700657 impl::EventThread::InterceptVSyncsCallback(),
658 "appEventThread");
659 mSfEventThreadSource =
660 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800661 mPhaseOffsets->getCurrentSfOffset(), true, "sf");
Ana Krulec98b5b242018-08-10 15:03:23 -0700662
663 mSFEventThread =
664 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700665 [this](nsecs_t timestamp) {
666 mInterceptor->saveVSyncEvent(timestamp);
667 },
668 "sfEventThread");
Dominik Laskowskif654d572018-12-20 11:03:06 -0800669 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Ana Krulec98b5b242018-08-10 15:03:23 -0700670 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
671 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800672
Steven Thomasb02664d2017-07-26 18:48:28 -0700673 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700674 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700675 renderEngineFeature |= (useColorManagement ?
676 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700677 renderEngineFeature |= (useContextPriority ?
678 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700679
680 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700681 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700682 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700683 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700684
685 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
686 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700687 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
688 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800689 // Process any initial hotplug and resulting display changes.
690 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700691 const auto display = getDefaultDisplayDeviceLocked();
692 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700693 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700694 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800695
Steven Thomas050b2c82017-03-06 11:45:16 -0800696 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700697 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700698 // This callback is called from the vr flinger dispatch thread. We
699 // need to call signalTransaction(), which requires holding
700 // mStateLock when we're not on the main thread. Acquiring
701 // mStateLock from the vr flinger dispatch thread might trigger a
702 // deadlock in surface flinger (see b/66916578), so post a message
703 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700704 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700705 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
706 mVrFlingerRequestsDisplay = requestDisplay;
707 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700708 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800709 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700710 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
711 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700712 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700713 .value_or(0),
714 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800715 if (!mVrFlinger) {
716 ALOGE("Failed to start vrflinger");
717 }
718 }
719
Ady Abrahamc3e21312019-02-07 14:30:23 -0800720 if (!mUseScheduler) {
721 mEventControlThread = getFactory().createEventControlThread(
722 [this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
723 }
Jamie Gennisd1700752013-10-14 12:22:52 -0700724
Mathias Agopian92a979a2012-08-02 18:32:23 -0700725 // initialize our drawing state
726 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700727
Andy McFadden13a082e2012-08-24 10:16:42 -0700728 // set initial conditions (e.g. unblank default device)
729 initializeDisplays();
730
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700731 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700732
Wei Wangf9b05ee2017-07-19 20:59:39 -0700733 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700734
735 const bool presentFenceReliable =
736 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
737 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700738
739 if (mStartPropertySetThread->Start() != NO_ERROR) {
740 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800741 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800742
Ana Krulec7d1d6832018-12-27 11:10:09 -0800743 if (mUseScheduler) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800744 mScheduler->setExpiredIdleTimerCallback([this] {
745 Mutex::Autolock lock(mStateLock);
746 setRefreshRateTo(RefreshRateType::DEFAULT);
Ana Krulec757f63a2019-01-25 10:46:18 -0800747 });
Ady Abrahama1a49af2019-02-07 14:36:55 -0800748 mScheduler->setResetIdleTimerCallback([this] {
749 Mutex::Autolock lock(mStateLock);
750 setRefreshRateTo(RefreshRateType::PERFORMANCE);
751 });
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800752
Alec Mourifb571ea2019-01-24 18:42:10 -0800753 mRefreshRateStats =
754 std::make_unique<scheduler::RefreshRateStats>(getHwComposer().getConfigs(
755 *display->getId()),
756 mTimeStats);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800757 }
758
Dan Stoza9e56aa02015-11-02 13:00:03 -0800759 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700760}
761
Romain Guy11d63f42017-07-20 12:47:14 -0700762void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700763 Mutex::Autolock _l(mStateLock);
764
Romain Guy11d63f42017-07-20 12:47:14 -0700765 char value[PROPERTY_VALUE_MAX];
766
767 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800768 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700769 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800770 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100771
772 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700773 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700774}
775
Mathias Agopiana67e4182012-06-19 17:26:12 -0700776void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800777 // Start boot animation service by setting a property mailbox
778 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700779 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800780 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700781 if (mStartPropertySetThread->join() != NO_ERROR) {
782 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800783 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700784}
785
Mathias Agopian875d8e12013-06-07 15:35:48 -0700786size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700787 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700788}
789
Mathias Agopian875d8e12013-06-07 15:35:48 -0700790size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700791 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700792}
793
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800794// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800795
Jamie Gennis582270d2011-08-17 18:19:00 -0700796bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800797 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800798 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800799 return authenticateSurfaceTextureLocked(bufferProducer);
800}
801
802bool SurfaceFlinger::authenticateSurfaceTextureLocked(
803 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800804 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800805 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800806}
807
Brian Anderson6b376712017-04-04 10:51:39 -0700808status_t SurfaceFlinger::getSupportedFrameTimestamps(
809 std::vector<FrameEvent>* outSupported) const {
810 *outSupported = {
811 FrameEvent::REQUESTED_PRESENT,
812 FrameEvent::ACQUIRE,
813 FrameEvent::LATCH,
814 FrameEvent::FIRST_REFRESH_START,
815 FrameEvent::LAST_REFRESH_START,
816 FrameEvent::GPU_COMPOSITION_DONE,
817 FrameEvent::DEQUEUE_READY,
818 FrameEvent::RELEASE,
819 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700820 ConditionalLock _l(mStateLock,
821 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700822 if (!getHwComposer().hasCapability(
823 HWC2::Capability::PresentFenceIsNotReliable)) {
824 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
825 }
826 return NO_ERROR;
827}
828
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800829status_t SurfaceFlinger::getDisplayConfigsLocked(const sp<IBinder>& displayToken,
830 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700831 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700832 return BAD_VALUE;
833 }
834
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800835 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700836 if (!displayId) {
837 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700838 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700839
Mathias Agopian8b736f12012-08-13 17:54:26 -0700840 // TODO: Not sure if display density should handled by SF any longer
841 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700842 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700843 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700844 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800845 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700846 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700847 }
848 return density;
849 }
850 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700851 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700852 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700853 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700854 return getDensityFromProperty("ro.sf.lcd_density"); }
855 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700856
Dan Stoza7f7da322014-05-02 15:26:25 -0700857 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700858
Dominik Laskowski075d3172018-05-24 15:50:06 -0700859 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700860 DisplayInfo info = DisplayInfo();
861
Dan Stoza9e56aa02015-11-02 13:00:03 -0800862 float xdpi = hwConfig->getDpiX();
863 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700864
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700865 info.w = hwConfig->getWidth();
866 info.h = hwConfig->getHeight();
867 // Default display viewport to display width and height
868 info.viewportW = info.w;
869 info.viewportH = info.h;
870
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800871 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700872 // The density of the device is provided by a build property
873 float density = Density::getBuildDensity() / 160.0f;
874 if (density == 0) {
875 // the build doesn't provide a density -- this is wrong!
876 // use xdpi instead
877 ALOGE("ro.sf.lcd_density must be defined as a build property");
878 density = xdpi / 160.0f;
879 }
880 if (Density::getEmuDensity()) {
881 // if "qemu.sf.lcd_density" is specified, it overrides everything
882 xdpi = ydpi = density = Density::getEmuDensity();
883 density /= 160.0f;
884 }
885 info.density = density;
886
887 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700888 const auto display = getDefaultDisplayDeviceLocked();
889 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700890
891 // This is for screenrecord
892 const Rect viewport = display->getViewport();
893 if (viewport.isValid()) {
894 info.viewportW = uint32_t(viewport.getWidth());
895 info.viewportH = uint32_t(viewport.getHeight());
896 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700897 } else {
898 // TODO: where should this value come from?
899 static const int TV_DENSITY = 213;
900 info.density = TV_DENSITY / 160.0f;
901 info.orientation = 0;
902 }
903
Dan Stoza7f7da322014-05-02 15:26:25 -0700904 info.xdpi = xdpi;
905 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800906 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800907 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800908
Andy McFadden91b2ca82014-06-13 14:04:23 -0700909 // This is how far in advance a buffer must be queued for
910 // presentation at a given time. If you want a buffer to appear
911 // on the screen at time N, you must submit the buffer before
912 // (N - presentationDeadline).
913 //
914 // Normally it's one full refresh period (to give SF a chance to
915 // latch the buffer), but this can be reduced by configuring a
916 // DispSync offset. Any additional delays introduced by the hardware
917 // composer or panel must be accounted for here.
918 //
919 // We add an additional 1ms to allow for processing time and
920 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800921 info.presentationDeadline =
922 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700923
924 // All non-virtual displays are currently considered secure.
925 info.secure = true;
926
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800927 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700928 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800929 std::swap(info.w, info.h);
930 }
931
Michael Wright28f24d02016-07-12 13:30:53 -0700932 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700933 }
934
Dan Stoza7f7da322014-05-02 15:26:25 -0700935 return NO_ERROR;
936}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700937
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700938status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
939 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700940 return BAD_VALUE;
941 }
942
Ana Krulece588e312018-09-18 12:32:24 -0700943 if (mUseScheduler) {
944 mScheduler->getDisplayStatInfo(stats);
945 } else {
946 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
947 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
948 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700949 return NO_ERROR;
950}
951
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700952int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
953 const auto display = getDisplayDevice(displayToken);
954 if (!display) {
955 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800956 return BAD_VALUE;
957 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700958
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700959 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700960}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700961
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800962void SurfaceFlinger::setDesiredActiveConfig(const sp<IBinder>& displayToken, int mode) {
963 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800964
Ana Krulec7d1d6832018-12-27 11:10:09 -0800965 Vector<DisplayInfo> configs;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800966 // Lock is acquired by setRefreshRateTo.
967 getDisplayConfigsLocked(displayToken, &configs);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800968 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
969 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
970 return;
971 }
972
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800973 // Lock is acquired by setRefreshRateTo.
974 const auto display = getDisplayDeviceLocked(displayToken);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800975 if (!display) {
976 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
977 displayToken.get());
978 return;
979 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700980 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800981 ALOGW("Attempt to set active config %d for virtual display", mode);
982 return;
983 }
984 int currentDisplayPowerMode = display->getPowerMode();
985 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
986 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700987 return;
988 }
989
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800990 // Don't check against the current mode yet. Worst case we set the desired
991 // config twice.
992 {
993 std::lock_guard<std::mutex> lock(mActiveConfigLock);
994 mDesiredActiveConfig = ActiveConfigInfo{mode, displayToken};
995 }
996 // This will trigger HWC refresh without resetting the idle timer.
997 repaintEverythingForHWC();
998}
999
1000status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
1001 ATRACE_CALL();
1002 postMessageSync(new LambdaMessage(
1003 [&]() NO_THREAD_SAFETY_ANALYSIS { setDesiredActiveConfig(displayToken, mode); }));
1004 return NO_ERROR;
1005}
1006
1007void SurfaceFlinger::setActiveConfigInHWC() {
1008 ATRACE_CALL();
1009
1010 const auto display = getDisplayDevice(mUpcomingActiveConfig.displayToken);
1011 if (!display) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001012 return;
1013 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001014 const auto displayId = display->getId();
1015 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001016
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001017 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1018 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1019 mSetActiveConfigState = SetActiveConfigState::NOTIFIED_HWC;
1020 ATRACE_INT("SetActiveConfigState", mSetActiveConfigState);
1021}
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001022
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001023void SurfaceFlinger::setActiveConfigInternal() {
1024 ATRACE_CALL();
1025
1026 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1027 if (mUseScheduler) {
1028 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
1029 }
1030
1031 const auto display = getDisplayDeviceLocked(mUpcomingActiveConfig.displayToken);
1032 display->setActiveConfig(mUpcomingActiveConfig.configId);
1033
1034 mSetActiveConfigState = SetActiveConfigState::NONE;
1035 ATRACE_INT("SetActiveConfigState", mSetActiveConfigState);
1036
Dominik Laskowski83b88212018-12-11 13:34:06 -08001037 resyncToHardwareVsync(true, getVsyncPeriod());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001038 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
1039}
1040
1041bool SurfaceFlinger::updateSetActiveConfigStateMachine() NO_THREAD_SAFETY_ANALYSIS {
1042 // Store the local variable to release the lock.
1043 ActiveConfigInfo desiredActiveConfig;
1044 {
1045 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1046 desiredActiveConfig = mDesiredActiveConfig;
1047 }
1048
1049 const auto display = getDisplayDevice(desiredActiveConfig.displayToken);
1050 if (display) {
1051 if (mSetActiveConfigState == SetActiveConfigState::NONE &&
1052 display->getActiveConfig() != desiredActiveConfig.configId) {
1053 // Step 1) Desired active config was set, it is different than the
1054 // config currently in use. Notify HWC.
1055 mUpcomingActiveConfig = desiredActiveConfig;
1056 setActiveConfigInHWC();
1057 } else if (mSetActiveConfigState == SetActiveConfigState::NOTIFIED_HWC) {
1058 // Step 2) HWC was notified and we received refresh from it.
1059 mSetActiveConfigState = SetActiveConfigState::REFRESH_RECEIVED;
1060 ATRACE_INT("SetActiveConfigState", mSetActiveConfigState);
1061 repaintEverythingForHWC();
1062 // We do not want to give another frame to HWC while we are transitioning.
1063 return false;
1064 } else if (mSetActiveConfigState == SetActiveConfigState::REFRESH_RECEIVED &&
1065 !(mPreviousPresentFence != Fence::NO_FENCE &&
1066 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled))) {
1067 // Step 3) We received the present fence from the HWC, so we assume it
1068 // successfully updated the config, hence we update SF.
1069 setActiveConfigInternal();
1070 // If the config changed again while we were transitioning, restart the
1071 // process.
1072 if (desiredActiveConfig != mUpcomingActiveConfig) {
1073 mUpcomingActiveConfig = desiredActiveConfig;
1074 setActiveConfigInHWC(); // sets the state to NOTIFY_HWC
1075 }
1076 }
1077 }
1078 return true;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001079}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001080
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001081status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1082 Vector<ColorMode>* outColorModes) {
1083 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001084 return BAD_VALUE;
1085 }
1086
Peiyong Lina52f0292018-03-14 17:26:31 -07001087 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001088 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001089 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1090
1091 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1092 if (!displayId) {
1093 return NAME_NOT_FOUND;
1094 }
1095
Dominik Laskowski075d3172018-05-24 15:50:06 -07001096 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001097 }
Michael Wright28f24d02016-07-12 13:30:53 -07001098 outColorModes->clear();
1099 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1100
1101 return NO_ERROR;
1102}
1103
Daniel Solomon42d04562019-01-20 21:03:19 -08001104status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1105 ui::DisplayPrimaries &primaries) {
1106 if (!displayToken) {
1107 return BAD_VALUE;
1108 }
1109
1110 // Currently we only support this API for a single internal display.
1111 if (getInternalDisplayToken() != displayToken) {
1112 return BAD_VALUE;
1113 }
1114
1115 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1116 return NO_ERROR;
1117}
1118
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001119ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1120 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001121 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001122 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001123 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001124}
1125
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001126status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001127 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001128 Vector<ColorMode> modes;
1129 getDisplayColorModes(displayToken, &modes);
1130 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1131 if (mode < ColorMode::NATIVE || !exists) {
1132 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1133 decodeColorMode(mode).c_str(), mode, displayToken.get());
1134 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001135 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001136 const auto display = getDisplayDevice(displayToken);
1137 if (!display) {
1138 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1139 decodeColorMode(mode).c_str(), mode, displayToken.get());
1140 } else if (display->isVirtual()) {
1141 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1142 decodeColorMode(mode).c_str(), mode);
1143 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001144 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1145 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001146 }
1147 }));
1148
Michael Wright28f24d02016-07-12 13:30:53 -07001149 return NO_ERROR;
1150}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001151
Svetoslavd85084b2014-03-20 10:28:31 -07001152status_t SurfaceFlinger::clearAnimationFrameStats() {
1153 Mutex::Autolock _l(mStateLock);
1154 mAnimFrameTracker.clearStats();
1155 return NO_ERROR;
1156}
1157
1158status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1159 Mutex::Autolock _l(mStateLock);
1160 mAnimFrameTracker.getStats(outStats);
1161 return NO_ERROR;
1162}
1163
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001164status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1165 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001166 Mutex::Autolock _l(mStateLock);
1167
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001168 const auto display = getDisplayDeviceLocked(displayToken);
1169 if (!display) {
1170 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001171 return BAD_VALUE;
1172 }
1173
Peiyong Linfb069302018-04-25 14:34:31 -07001174 // At this point the DisplayDeivce should already be set up,
1175 // meaning the luminance information is already queried from
1176 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001177 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001178 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1179 capabilities.getDesiredMaxLuminance(),
1180 capabilities.getDesiredMaxAverageLuminance(),
1181 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001182
1183 return NO_ERROR;
1184}
1185
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001186status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1187 ui::PixelFormat* outFormat,
1188 ui::Dataspace* outDataspace,
1189 uint8_t* outComponentMask) const {
1190 if (!outFormat || !outDataspace || !outComponentMask) {
1191 return BAD_VALUE;
1192 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001193 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001194 if (!display || !display->getId()) {
1195 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1196 return BAD_VALUE;
1197 }
1198 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1199 outDataspace, outComponentMask);
1200}
1201
Kevin DuBois74e53772018-11-19 10:52:38 -08001202status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1203 bool enable, uint8_t componentMask,
1204 uint64_t maxFrames) const {
1205 const auto display = getDisplayDevice(displayToken);
1206 if (!display || !display->getId()) {
1207 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1208 return BAD_VALUE;
1209 }
1210
1211 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1212 componentMask, maxFrames);
1213}
1214
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001215status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1216 uint64_t maxFrames, uint64_t timestamp,
1217 DisplayedFrameStats* outStats) const {
1218 const auto display = getDisplayDevice(displayToken);
1219 if (!display || !display->getId()) {
1220 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1221 return BAD_VALUE;
1222 }
1223
1224 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1225 outStats);
1226}
1227
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001228status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1229 if (!outSupported) {
1230 return BAD_VALUE;
1231 }
1232 *outSupported = getRenderEngine().supportsProtectedContent();
1233 return NO_ERROR;
1234}
1235
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001236status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1237 bool* outIsWideColorDisplay) const {
1238 if (!displayToken || !outIsWideColorDisplay) {
1239 return BAD_VALUE;
1240 }
1241 Mutex::Autolock _l(mStateLock);
1242 const auto display = getDisplayDeviceLocked(displayToken);
1243 if (!display) {
1244 return BAD_VALUE;
1245 }
1246 *outIsWideColorDisplay = display->hasWideColorGamut();
1247 return NO_ERROR;
1248}
1249
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001250status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001251 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001252 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001253
Chia-I Wu90f669f2017-10-05 14:24:41 -07001254 if (mInjectVSyncs == enable) {
1255 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001256 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001257
Dominik Laskowski83b88212018-12-11 13:34:06 -08001258 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001259
Ana Krulec98b5b242018-08-10 15:03:23 -07001260 // TODO(akrulec): Part of the Injector should be refactored, so that it
1261 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001262 if (enable) {
1263 ALOGV("VSync Injections enabled");
1264 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001265 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001266 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001267 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001268 impl::EventThread::InterceptVSyncsCallback(),
1269 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001270 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001271 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001272 } else {
1273 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001274 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001275 }
1276
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001277 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001278 }));
1279
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001280 return NO_ERROR;
1281}
1282
1283status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001284 Mutex::Autolock _l(mStateLock);
1285
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001286 if (!mInjectVSyncs) {
1287 ALOGE("VSync Injections not enabled");
1288 return BAD_VALUE;
1289 }
1290 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1291 ALOGV("Injecting VSync inside SurfaceFlinger");
1292 mVSyncInjector->onInjectSyncEvent(when);
1293 }
1294 return NO_ERROR;
1295}
1296
Lloyd Pique755e3192018-01-31 16:46:15 -08001297status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1298 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001299 // Try to acquire a lock for 1s, fail gracefully
1300 const status_t err = mStateLock.timedLock(s2ns(1));
1301 const bool locked = (err == NO_ERROR);
1302 if (!locked) {
1303 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1304 return TIMED_OUT;
1305 }
1306
1307 outLayers->clear();
1308 mCurrentState.traverseInZOrder([&](Layer* layer) {
1309 outLayers->push_back(layer->getLayerDebugInfo());
1310 });
1311
1312 mStateLock.unlock();
1313 return NO_ERROR;
1314}
1315
Peiyong Linc6780972018-10-28 15:24:08 -07001316status_t SurfaceFlinger::getCompositionPreference(
1317 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1318 Dataspace* outWideColorGamutDataspace,
1319 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001320 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001321 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001322 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001323 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001324 return NO_ERROR;
1325}
1326
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001327// ----------------------------------------------------------------------------
1328
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001329sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1330 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001331 auto resyncCallback = makeResyncCallback([this] {
1332 Mutex::Autolock lock(mStateLock);
1333 return getVsyncPeriod();
1334 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001335
Ana Krulec98b5b242018-08-10 15:03:23 -07001336 if (mUseScheduler) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001337 const auto& handle = vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle
1338 : mAppConnectionHandle;
1339
Ady Abrahama1a49af2019-02-07 14:36:55 -08001340 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001341 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001342 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001343 return mSFEventThread->createEventConnection(resyncCallback, ResetIdleTimerCallback());
Ana Krulec98b5b242018-08-10 15:03:23 -07001344 } else {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001345 return mEventThread->createEventConnection(resyncCallback, ResetIdleTimerCallback());
Ana Krulec98b5b242018-08-10 15:03:23 -07001346 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001347 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001348}
1349
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001350// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001351
1352void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001353 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001354}
1355
1356void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001357 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001358}
1359
1360void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001361 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001362}
1363
1364void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001365 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001366 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001367}
1368
1369status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001370 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001371 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001372}
1373
1374status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001375 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001376 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001377 if (res == NO_ERROR) {
1378 msg->wait();
1379 }
1380 return res;
1381}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001382
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001383void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001384 do {
1385 waitForEvent();
1386 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001387}
1388
Dominik Laskowski83b88212018-12-11 13:34:06 -08001389nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001390 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001391 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1392 return 0;
1393 }
1394
1395 const auto config = getHwComposer().getActiveConfig(*displayId);
1396 return config ? config->getVsyncPeriod() : 0;
1397}
1398
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001399void SurfaceFlinger::enableHardwareVsync() {
Ady Abrahamc3e21312019-02-07 14:30:23 -08001400 assert(!mUseScheduler);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001401 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001402 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001403 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001404 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001405 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001406 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001407}
1408
Dominik Laskowski83b88212018-12-11 13:34:06 -08001409void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001410 Mutex::Autolock _l(mHWVsyncLock);
1411
Jesse Hall948fe0c2013-10-14 12:56:09 -07001412 if (makeAvailable) {
1413 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001414 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1415 if (mUseScheduler) {
1416 mScheduler->makeHWSyncAvailable(true);
1417 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001418 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001419 // Hardware vsync is not currently available, so abort the resync
1420 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001421 return;
1422 }
1423
Dominik Laskowski83b88212018-12-11 13:34:06 -08001424 if (period <= 0) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001425 return;
1426 }
1427
Ana Krulece588e312018-09-18 12:32:24 -07001428 if (mUseScheduler) {
1429 mScheduler->setVsyncPeriod(period);
1430 } else {
1431 mPrimaryDispSync->reset();
1432 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001433
Ana Krulece588e312018-09-18 12:32:24 -07001434 if (!mPrimaryHWVsyncEnabled) {
1435 mPrimaryDispSync->beginResync();
1436 mEventControlThread->setVsyncEnabled(true);
1437 mPrimaryHWVsyncEnabled = true;
1438 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001439 }
1440}
1441
Jesse Hall948fe0c2013-10-14 12:56:09 -07001442void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Ady Abrahamc3e21312019-02-07 14:30:23 -08001443 assert(!mUseScheduler);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001444 Mutex::Autolock _l(mHWVsyncLock);
1445 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001446 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001447 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001448 mPrimaryHWVsyncEnabled = false;
1449 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001450 if (makeUnavailable) {
1451 mHWVsyncAvailable = false;
1452 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001453}
1454
Dominik Laskowski83b88212018-12-11 13:34:06 -08001455void SurfaceFlinger::VsyncState::resync(const GetVsyncPeriod& getVsyncPeriod) {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001456 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001457
Dan Stoza57164302017-05-08 14:03:54 -07001458 const nsecs_t now = systemTime();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001459 const nsecs_t last = lastResyncTime.exchange(now);
1460
1461 if (now - last > kIgnoreDelay) {
1462 flinger.resyncToHardwareVsync(false, getVsyncPeriod());
Tim Murray4a4e4a22016-04-19 16:29:23 +00001463 }
1464}
1465
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001466void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1467 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001468 ATRACE_NAME("SF onVsync");
1469
Steven Thomas3cfac282017-02-06 12:29:30 -08001470 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001471 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001472 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001473 return;
1474 }
1475
Dominik Laskowski075d3172018-05-24 15:50:06 -07001476 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001477 return;
1478 }
1479
Dominik Laskowski075d3172018-05-24 15:50:06 -07001480 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001481 // For now, we don't do anything with external display vsyncs.
1482 return;
1483 }
1484
Ana Krulece588e312018-09-18 12:32:24 -07001485 if (mUseScheduler) {
1486 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001487 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001488 bool needsHwVsync = false;
1489 { // Scope for the lock
1490 Mutex::Autolock _l(mHWVsyncLock);
1491 if (mPrimaryHWVsyncEnabled) {
1492 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1493 }
1494 }
1495
1496 if (needsHwVsync) {
1497 enableHardwareVsync();
1498 } else {
1499 disableHardwareVsync(false);
1500 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001501 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001502}
1503
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001504void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001505 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1506 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001507}
1508
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001509void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate) {
1510 mPhaseOffsets->setRefreshRateType(refreshRate);
1511
1512 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1513 mVsyncModulator.setPhaseOffsets(early, gl, late);
1514
1515 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001516 return;
1517 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001518
Ana Krulec7d1d6832018-12-27 11:10:09 -08001519 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1520 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1521 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1522 // refresh cycle.
1523
1524 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001525 const nsecs_t currentVsyncPeriod = getVsyncPeriod();
Ana Krulec7d1d6832018-12-27 11:10:09 -08001526 if (currentVsyncPeriod == 0) {
1527 return;
1528 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001529
Ana Krulec7d1d6832018-12-27 11:10:09 -08001530 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1531 // floating numbers.
1532 const float currentFps = 1e9 / currentVsyncPeriod;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001533 const float newFps = refreshRate == RefreshRateType::PERFORMANCE ? kPerformanceRefreshRate
1534 : kDefaultRefreshRate;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001535 if (std::abs(currentFps - newFps) <= 1) {
1536 return;
1537 }
1538
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001539 const auto displayId = getInternalDisplayIdLocked();
1540 LOG_ALWAYS_FATAL_IF(!displayId);
1541
1542 auto configs = getHwComposer().getConfigs(*displayId);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001543 for (int i = 0; i < configs.size(); i++) {
1544 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1545 if (vsyncPeriod == 0) {
1546 continue;
1547 }
1548 const float fps = 1e9 / vsyncPeriod;
1549 // TODO(b/113612090): There should be a better way at determining which config
1550 // has the right refresh rate.
1551 if (std::abs(fps - newFps) <= 1) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001552 setDesiredActiveConfig(getInternalDisplayTokenLocked(), i);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001553 }
1554 }
1555}
1556
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001557void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001558 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001559 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001560 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001561
Lloyd Piqueba04e622017-12-14 17:11:26 -08001562 // Ignore events that do not have the right sequenceId.
1563 if (sequenceId != getBE().mComposerSequenceId) {
1564 return;
1565 }
1566
Steven Thomasb02664d2017-07-26 18:48:28 -07001567 // Only lock if we're not on the main thread. This function is normally
1568 // called on a hwbinder thread, but for the primary display it's called on
1569 // the main thread with the state lock already held, so don't attempt to
1570 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001571 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001572
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001573 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001574
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001575 if (std::this_thread::get_id() == mMainThreadId) {
1576 // Process all pending hot plug events immediately if we are on the main thread.
1577 processDisplayHotplugEventsLocked();
1578 }
1579
Lloyd Piqueba04e622017-12-14 17:11:26 -08001580 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001581}
1582
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001583void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001584 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001585 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001586 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001587 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001588 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001589}
1590
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001591void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001592 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001593 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001594 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001595 getHwComposer().setVsyncEnabled(*displayId,
1596 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1597 }
Mathias Agopian86303202012-07-24 22:46:10 -07001598}
1599
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001600// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001601void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001602 if (mUseScheduler) {
1603 mScheduler->disableHardwareVsync(true);
1604 } else {
1605 disableHardwareVsync(true);
1606 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001607 // Clear the drawing state so that the logic inside of
1608 // handleTransactionLocked will fire. It will determine the delta between
1609 // mCurrentState and mDrawingState and re-apply all changes when we make the
1610 // transition.
1611 mDrawingState.displays.clear();
1612 mDisplays.clear();
1613}
1614
Steven Thomas050b2c82017-03-06 11:45:16 -08001615void SurfaceFlinger::updateVrFlinger() {
1616 if (!mVrFlinger)
1617 return;
1618 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001619 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001620 return;
1621 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001622
Lloyd Pique441d5042018-10-18 16:49:51 -07001623 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001624 ALOGE("Vr flinger is only supported for remote hardware composer"
1625 " service connections. Ignoring request to transition to vr"
1626 " flinger.");
1627 mVrFlingerRequestsDisplay = false;
1628 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001629 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001630
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001631 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001632
Steven Thomas0123ac62018-07-12 11:32:34 -07001633 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001634 LOG_ALWAYS_FATAL_IF(!display);
1635 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001636 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1637 // called below. Clear the reference now so we don't accidentally use it
1638 // later.
1639 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001640
Steven Thomasb02664d2017-07-26 18:48:28 -07001641 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001642 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001643 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001644
Steven Thomasb02664d2017-07-26 18:48:28 -07001645 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001646 // Delete the current instance before creating the new one
1647 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1648 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1649 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1650 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001651
Lloyd Pique441d5042018-10-18 16:49:51 -07001652 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001653 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001654
1655 if (vrFlingerRequestsDisplay) {
1656 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001657 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001658
1659 mVisibleRegionsDirty = true;
1660 invalidateHwcGeometry();
1661
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001662 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001663 display = getDefaultDisplayDeviceLocked();
1664 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001665 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001666
Steven Thomasb02664d2017-07-26 18:48:28 -07001667 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001668 const nsecs_t vsyncPeriod = getVsyncPeriod();
1669 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001670
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001671 // The present fences returned from vr_hwc are not an accurate
1672 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001673 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001674 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1675 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001676 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001677 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001678 !hasSyncFramework);
1679 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001680
Steven Thomasb02664d2017-07-26 18:48:28 -07001681 // Use phase of 0 since phase is not known.
1682 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001683 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001684 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001685
Dominik Laskowski83b88212018-12-11 13:34:06 -08001686 resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001687
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001688 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001689 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001690}
1691
Mathias Agopian4fec8732012-06-29 14:12:52 -07001692void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001693 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001694 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001695 case MessageQueue::INVALIDATE: {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001696 if (!updateSetActiveConfigStateMachine()) {
1697 break;
1698 }
1699
Ana Krulec3084c052018-11-21 20:27:17 +01001700 if (mUseScheduler) {
1701 // This call is made each time SF wakes up and creates a new frame.
1702 mScheduler->incrementFrameCounter();
1703 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001704 bool frameMissed = !mHadClientComposition && mPreviousPresentFence != Fence::NO_FENCE &&
1705 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001706 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001707 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001708 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001709 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001710 if (mPropagateBackpressure) {
1711 signalLayerUpdate();
1712 break;
1713 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001714 }
Dan Stoza50182882016-07-08 12:02:20 -07001715
Steven Thomas050b2c82017-03-06 11:45:16 -08001716 // Now that we're going to make it to the handleMessageTransaction()
1717 // call below it's safe to call updateVrFlinger(), which will
1718 // potentially trigger a display handoff.
1719 updateVrFlinger();
1720
Dan Stoza6b9454d2014-11-07 16:00:59 -08001721 bool refreshNeeded = handleMessageTransaction();
1722 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001723
1724 updateCursorAsync();
1725 updateInputFlinger();
1726
Dan Stoza58784442014-12-02 16:58:17 -08001727 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001728 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001729 // Signal a refresh if a transaction modified the window state,
1730 // a new buffer was latched, or if HWC has requested a full
1731 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001732 signalRefresh();
1733 }
1734 break;
1735 }
1736 case MessageQueue::REFRESH: {
1737 handleMessageRefresh();
1738 break;
1739 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001740 }
1741}
1742
Dan Stoza6b9454d2014-11-07 16:00:59 -08001743bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001744 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001745
1746 // Apply any ready transactions in the queues if there are still transactions that have not been
1747 // applied, wake up during the next vsync period and check again
1748 bool transactionNeeded = false;
1749 if (!flushTransactionQueues()) {
1750 transactionNeeded = true;
1751 }
1752
Mathias Agopian4fec8732012-06-29 14:12:52 -07001753 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001754 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001755 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001756
1757 if (transactionNeeded) {
1758 setTransactionFlags(eTransactionNeeded);
1759 }
1760
1761 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001762}
1763
Mathias Agopian4fec8732012-06-29 14:12:52 -07001764void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001765 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001766
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001767 mRefreshPending = false;
1768
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001769 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001770 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001771 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001772 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001773 for (const auto& [token, display] : mDisplays) {
1774 beginFrame(display);
1775 prepareFrame(display);
1776 doDebugFlashRegions(display, repaintEverything);
1777 doComposition(display, repaintEverything);
1778 }
1779
Adrian Roos1e1a1282017-11-01 19:05:31 +01001780 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001781 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001782
1783 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001784 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001785
Dan Stozabfbffeb2016-07-21 14:49:33 -07001786 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001787 for (const auto& [token, displayDevice] : mDisplays) {
1788 auto display = displayDevice->getCompositionDisplay();
1789 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001790 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001791 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001792 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001793
Alec Mouri86770e52018-09-24 22:40:58 +00001794 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001795 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001796 if (mHadClientComposition) {
1797 base::unique_fd flushFence(getRenderEngine().flush());
1798 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1799 getBE().flushFence = new Fence(std::move(flushFence));
1800 } else {
1801 // Cleanup for hygiene.
1802 getBE().flushFence = Fence::NO_FENCE;
1803 }
1804 }
1805
Jorim Jaggi90535212018-05-23 23:44:06 +02001806 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001807
David Sodman7e4ae112018-02-09 15:02:28 -08001808 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001809 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001810 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001811 compositionInfo.hwc.hwcLayer = nullptr;
1812 }
David Sodmanba340492018-08-05 21:51:33 -07001813 }
David Sodman7e4ae112018-02-09 15:02:28 -08001814
1815 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001816}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001817
David Sodmanfa9b2af2017-12-24 13:28:59 -08001818
1819bool SurfaceFlinger::handleMessageInvalidate() {
1820 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001821 bool refreshNeeded = handlePageFlip();
1822
1823 for (auto& layer : mLayersPendingRefresh) {
1824 Region visibleReg;
1825 visibleReg.set(layer->computeScreenBounds());
1826 invalidateLayerStack(layer, visibleReg);
1827 }
1828 mLayersPendingRefresh.clear();
1829 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001830}
1831
David Sodman79bba0e2018-08-05 18:07:49 -07001832void SurfaceFlinger::calculateWorkingSet() {
1833 ATRACE_CALL();
1834 ALOGV(__FUNCTION__);
1835
David Sodman79bba0e2018-08-05 18:07:49 -07001836 // build the h/w work list
1837 if (CC_UNLIKELY(mGeometryInvalid)) {
1838 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001839 for (const auto& [token, displayDevice] : mDisplays) {
1840 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001841 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001842 if (!displayId) {
1843 continue;
1844 }
David Sodman79bba0e2018-08-05 18:07:49 -07001845
Lloyd Pique32cbe282018-10-19 13:09:22 -07001846 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001847 for (size_t i = 0; i < currentLayers.size(); i++) {
1848 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001849
Dominik Laskowski075d3172018-05-24 15:50:06 -07001850 if (!layer->hasHwcLayer(*displayId)) {
1851 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1852 layer->forceClientComposition(*displayId);
1853 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001854 }
1855 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001856
Lloyd Pique32cbe282018-10-19 13:09:22 -07001857 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001858 if (mDebugDisableHWC || mDebugRegion) {
1859 layer->forceClientComposition(*displayId);
1860 }
David Sodman79bba0e2018-08-05 18:07:49 -07001861 }
1862 }
1863 }
1864
1865 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001866 for (const auto& [token, displayDevice] : mDisplays) {
1867 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001868 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001869 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001870 continue;
1871 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001872 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001873
1874 if (mDrawingState.colorMatrixChanged) {
1875 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001876 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001877 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001878 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001879 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001880 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1881 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001882 !profile->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001883 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001884 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1885 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001886 !profile->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001887 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001888 }
1889
Peiyong Lind3788632018-09-18 16:01:31 -07001890 // TODO(b/111562338) remove when composer 2.3 is shipped.
1891 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001892 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001893 }
1894
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001895 if (layer->getRoundedCornerState().radius > 0.0f) {
1896 layer->forceClientComposition(*displayId);
1897 }
1898
Dominik Laskowski075d3172018-05-24 15:50:06 -07001899 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001900 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001901 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001902 continue;
1903 }
1904
Lloyd Pique32cbe282018-10-19 13:09:22 -07001905 const auto& displayState = display->getState();
1906 layer->setPerFrameData(*displayId, displayState.transform, displayState.viewport,
1907 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001908 }
1909
Peiyong Lin13effd12018-07-24 17:01:47 -07001910 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001911 ColorMode colorMode;
1912 Dataspace dataSpace;
1913 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001914 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001915 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001916 }
1917 }
1918
1919 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001920
1921 for (const auto& [token, display] : mDisplays) {
1922 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001923 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001924 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001925
1926 if (displayId) {
1927 if (!layer->setHwcLayer(*displayId)) {
1928 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1929 }
1930 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001931 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001932
Dominik Laskowski05275f12018-11-01 15:03:24 -07001933 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001934 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1935 }
1936 }
David Sodman79bba0e2018-08-05 18:07:49 -07001937}
1938
Lloyd Pique32cbe282018-10-19 13:09:22 -07001939void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1940 bool repaintEverything) {
1941 auto display = displayDevice->getCompositionDisplay();
1942 const auto& displayState = display->getState();
1943
Mathias Agopiancd60f992012-08-16 16:28:27 -07001944 // is debugging enabled
1945 if (CC_LIKELY(!mDebugRegion))
1946 return;
1947
Lloyd Pique32cbe282018-10-19 13:09:22 -07001948 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001949 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001950 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001951 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001952 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001953 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001954 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001955
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001956 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001957 }
1958 }
1959
Lloyd Pique32cbe282018-10-19 13:09:22 -07001960 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001961
1962 if (mDebugRegion > 1) {
1963 usleep(mDebugRegion * 1000);
1964 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001965
Lloyd Pique32cbe282018-10-19 13:09:22 -07001966 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001967}
1968
Adrian Roos1e1a1282017-11-01 19:05:31 +01001969void SurfaceFlinger::doTracing(const char* where) {
1970 ATRACE_CALL();
1971 ATRACE_NAME(where);
1972 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001973 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001974 }
1975}
1976
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001977void SurfaceFlinger::logLayerStats() {
1978 ATRACE_CALL();
1979 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001980 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001981 if (display->isPrimary()) {
1982 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001983 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001984 }
1985 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001986
1987 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001988 }
1989}
1990
David Sodman2b406362017-12-15 13:33:47 -08001991void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001992{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001993 ATRACE_CALL();
1994 ALOGV("preComposition");
1995
David Sodman2b406362017-12-15 13:33:47 -08001996 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1997
Mathias Agopiancd60f992012-08-16 16:28:27 -07001998 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001999 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08002000 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002001 needExtraInvalidate = true;
2002 }
Robert Carr2047fae2016-11-28 14:09:09 -08002003 });
2004
Mathias Agopiancd60f992012-08-16 16:28:27 -07002005 if (needExtraInvalidate) {
2006 signalLayerUpdate();
2007 }
2008}
2009
Ana Krulece588e312018-09-18 12:32:24 -07002010void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2011 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002012 // Update queue of past composite+present times and determine the
2013 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002014 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002015 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002016 while (!getBE().mCompositePresentTimes.empty()) {
2017 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002018 // Cached values should have been updated before calling this method,
2019 // which helps avoid duplicate syscalls.
2020 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2021 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2022 break;
2023 }
2024 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002025 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002026 }
2027
2028 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002029 while (getBE().mCompositePresentTimes.size() > 16) {
2030 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002031 }
2032
Ana Krulece588e312018-09-18 12:32:24 -07002033 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002034}
2035
Ana Krulece588e312018-09-18 12:32:24 -07002036void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2037 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002038 // Integer division and modulo round toward 0 not -inf, so we need to
2039 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08002040 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
2041 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
2042 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002043
Ana Krulec757f63a2019-01-25 10:46:18 -08002044 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002045 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002046 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002047 }
2048
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002049 // Snap the latency to a value that removes scheduling jitter from the
2050 // composition and present times, which often have >1ms of jitter.
2051 // Reducing jitter is important if an app attempts to extrapolate
2052 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08002053 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002054 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002055 nsecs_t bias = stats.vsyncPeriod / 2;
2056 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2057 nsecs_t snappedCompositeToPresentLatency =
2058 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002059
David Sodman99974d22017-11-28 12:04:33 -08002060 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002061 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2062 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002063 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002064}
2065
Ady Abraham8164d482019-01-11 14:47:59 -08002066// debug patch for b/119477596 - add stack guards to catch stack
2067// corruptions and disable clang optimizations.
2068// The code below is temporary and planned to be removed once stack
2069// corruptions are found.
2070#pragma clang optimize off
2071class StackGuard {
2072public:
2073 StackGuard(const char* name, const char* func, int line) {
2074 guarders.reserve(MIN_CAPACITY);
2075 guarders.push_back({this, name, func, line});
2076 validate();
2077 }
2078 ~StackGuard() {
2079 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
2080 if (i->guard == this) {
2081 guarders.erase(i);
2082 break;
2083 }
2084 }
2085 }
2086
2087 static void validate() {
2088 for (const auto& guard : guarders) {
2089 if (guard.guard->cookie != COOKIE_VALUE) {
2090 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
2091 CallStack stack(LOG_TAG);
2092 abort();
2093 }
2094 }
2095 }
2096
2097private:
2098 uint64_t cookie = COOKIE_VALUE;
2099 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
2100 static constexpr size_t MIN_CAPACITY = 16;
2101
2102 struct GuarderElement {
2103 StackGuard* guard;
2104 const char* name;
2105 const char* func;
2106 int line;
2107 };
2108
2109 static std::vector<GuarderElement> guarders;
2110};
2111std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2112
2113#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2114
2115#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002116void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002117{
Ady Abraham8164d482019-01-11 14:47:59 -08002118 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002119 ATRACE_CALL();
2120 ALOGV("postComposition");
2121
Brian Anderson3546a3f2016-07-14 11:51:14 -07002122 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002123 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002124 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002125 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002126 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002127 }
Ady Abraham8164d482019-01-11 14:47:59 -08002128 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002129
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002130 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002131 const auto displayDevice = getDefaultDisplayDeviceLocked();
2132 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002133
David Sodman73beded2017-11-15 11:56:06 -08002134 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002135 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002136 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2137
Lloyd Pique32cbe282018-10-19 13:09:22 -07002138 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002139 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002140 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2141 ->getRenderSurface()
2142 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002143 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002144 } else {
2145 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2146 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002147
Ady Abraham8164d482019-01-11 14:47:59 -08002148 ASSERT_ON_STACK_GUARD();
2149
David Sodman73beded2017-11-15 11:56:06 -08002150 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002151 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2152 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002153 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002154 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002155 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002156
Ana Krulece588e312018-09-18 12:32:24 -07002157 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002158 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002159 if (mUseScheduler) {
2160 mScheduler->getDisplayStatInfo(&stats);
2161 } else {
2162 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2163 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2164 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002165
Ady Abraham8164d482019-01-11 14:47:59 -08002166 ASSERT_ON_STACK_GUARD();
2167
David Sodman2b406362017-12-15 13:33:47 -08002168 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002169 // when we started doing work for this frame, but that should be okay
2170 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002171 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002172 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002173 DEFINE_STACK_GUARD(compositorTiming);
2174
Brian Andersond0010582017-03-07 13:20:31 -08002175 {
David Sodman99974d22017-11-28 12:04:33 -08002176 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002177 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002178 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002179
2180 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002181 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002182
Robert Carr2047fae2016-11-28 14:09:09 -08002183 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002184 bool frameLatched =
2185 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2186 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002187 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002188 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002189 recordBufferingStats(layer->getName().string(),
2190 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002191 }
Ady Abraham8164d482019-01-11 14:47:59 -08002192 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002193 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002194
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002195 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002196 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002197 if (mUseScheduler) {
2198 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002199 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002200 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002201 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2202 enableHardwareVsync();
2203 } else {
2204 disableHardwareVsync(false);
2205 }
Ady Abraham8164d482019-01-11 14:47:59 -08002206 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002207 }
2208 }
2209
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002210 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002211 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2212 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002213 if (mUseScheduler) {
2214 mScheduler->enableHardwareVsync();
2215 } else {
2216 enableHardwareVsync();
2217 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002218 }
2219 }
2220
Ady Abraham8164d482019-01-11 14:47:59 -08002221 ASSERT_ON_STACK_GUARD();
2222
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002223 if (mAnimCompositionPending) {
2224 mAnimCompositionPending = false;
2225
Brian Anderson4e606e32017-03-16 15:34:57 -07002226 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002227 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002228 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002229
2230 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002231 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002232 // The HWC doesn't support present fences, so use the refresh
2233 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002234 const nsecs_t presentTime =
2235 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002236 DEFINE_STACK_GUARD(presentTime);
2237
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002238 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002239 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002240 }
2241 mAnimFrameTracker.advanceFrame();
2242 }
Dan Stozab90cf072015-03-05 11:05:59 -08002243
Ady Abraham8164d482019-01-11 14:47:59 -08002244 ASSERT_ON_STACK_GUARD();
2245
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002246 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002247 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002248 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002249 }
2250
Ady Abraham8164d482019-01-11 14:47:59 -08002251 ASSERT_ON_STACK_GUARD();
2252
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002253 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002254
Ady Abraham8164d482019-01-11 14:47:59 -08002255 ASSERT_ON_STACK_GUARD();
2256
Lloyd Pique32cbe282018-10-19 13:09:22 -07002257 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2258 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002259 return;
2260 }
2261
2262 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002263 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002264 if (mHasPoweredOff) {
2265 mHasPoweredOff = false;
2266 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002267 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002268 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002269 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002270 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002271 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2272 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002273 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002274 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002275 }
David Sodman4a36e932017-11-07 14:29:47 -08002276 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002277
2278 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002279 }
David Sodman4a36e932017-11-07 14:29:47 -08002280 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002281 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002282
2283 {
2284 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002285 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002286 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002287 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002288 if (refillCount > 0) {
2289 const size_t offset = mTexturePool.size();
2290 mTexturePool.resize(mTexturePoolSize);
2291 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2292 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2293 }
Ady Abraham8164d482019-01-11 14:47:59 -08002294 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002295 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002296
Marissa Wallfda30bb2018-10-12 11:34:28 -07002297 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002298 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002299
2300 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002301}
Ady Abraham8164d482019-01-11 14:47:59 -08002302#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002303
2304void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002305 ATRACE_CALL();
2306 ALOGV("rebuildLayerStacks");
2307
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002308 // We need to clear these out now as these may be holding on to a
2309 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2310 // also holds a reference. When the set of visible layers is recomputed,
2311 // some layers may be destroyed if the only thing keeping them alive was
2312 // that list of visible layers associated with each display. The layer
2313 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2314 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2315 for (const auto& [token, display] : mDisplays) {
2316 getBE().mCompositionInfo[token].clear();
2317 }
2318
Mathias Agopiancd60f992012-08-16 16:28:27 -07002319 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002320 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002321 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002322 mVisibleRegionsDirty = false;
2323 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002324
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002325 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002326 const auto& displayDevice = pair.second;
2327 auto display = displayDevice->getCompositionDisplay();
2328 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002329 Region opaqueRegion;
2330 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002331 compositionengine::Output::OutputLayers layersSortedByZ;
2332 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002333 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002334 const ui::Transform& tr = displayState.transform;
2335 const Rect bounds = displayState.bounds;
2336 if (displayState.isEnabled) {
2337 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002338
Jeff Sharkey76488112017-02-27 14:15:18 -07002339 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002340 auto compositionLayer = layer->getCompositionLayer();
2341 if (compositionLayer == nullptr) {
2342 return;
2343 }
2344
Chia-I Wu83806892017-11-16 10:50:20 -08002345 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002346 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002347 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2348 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2349
Lloyd Piqueef36b002019-01-23 17:52:04 -08002350 if (display->belongsInOutput(layer->getLayerStack(),
2351 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002352 Region drawRegion(tr.transform(
2353 layer->visibleNonTransparentRegion));
2354 drawRegion.andSelf(bounds);
2355 if (!drawRegion.isEmpty()) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002356 layersSortedByZ.emplace_back(
2357 display->getOrCreateOutputLayer(layer->getCompositionLayer(),
2358 layerFE));
2359
2360 deprecated_layersSortedByZ.add(layer);
Jeff Sharkey76488112017-02-27 14:15:18 -07002361 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002362 // Clear out the HWC layer if this layer was
2363 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002364 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002365 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002366 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002367 // WM changes display->layerStack upon sleep/awake.
2368 // Here we make sure we delete the HWC layers even if
2369 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002370 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002371 }
2372
2373 // If a layer is not going to get a release fence because
2374 // it is invisible, but it is also going to release its
2375 // old buffer, add it to the list of layers needing
2376 // fences.
2377 if (hwcLayerDestroyed) {
2378 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2379 mLayersWithQueuedFrames.cend(), layer);
2380 if (found != mLayersWithQueuedFrames.cend()) {
2381 layersNeedingFences.add(layer);
2382 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002383 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002384 });
2385 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002386
2387 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2388
2389 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002390 displayDevice->setLayersNeedingFences(layersNeedingFences);
2391
2392 Region undefinedRegion{bounds};
2393 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2394
2395 display->editState().undefinedRegion = undefinedRegion;
2396 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002397 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002398 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002399}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002400
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002401// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002402// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002403// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002404// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002405// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002406// The returned HDR data space is one of
2407// - Dataspace::UNKNOWN
2408// - Dataspace::BT2020_HLG
2409// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002410Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2411 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002412 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002413 *outHdrDataSpace = Dataspace::UNKNOWN;
2414
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002415 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002416 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002417 case Dataspace::V0_SCRGB:
2418 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002419 case Dataspace::BT2020:
2420 case Dataspace::BT2020_ITU:
2421 case Dataspace::BT2020_LINEAR:
2422 case Dataspace::DISPLAY_BT2020:
2423 bestDataSpace = Dataspace::DISPLAY_BT2020;
2424 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002425 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002426 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002427 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002428 case Dataspace::BT2020_PQ:
2429 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002430 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002431 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002432 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002433 case Dataspace::BT2020_HLG:
2434 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002435 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002436 // When there's mixed PQ content and HLG content, we set the HDR
2437 // data space to be BT2020_PQ and convert HLG to PQ.
2438 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2439 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002440 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002441 break;
2442 default:
2443 break;
2444 }
Romain Guy54f154a2017-10-24 21:40:32 +01002445 }
2446
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002447 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002448}
2449
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002450// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002451void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2452 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002453 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2454 *outMode = ColorMode::NATIVE;
2455 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002456 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002457 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002458 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002459
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002460 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002461 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002462
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002463 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2464
Peiyong Lindfde5112018-06-05 10:58:41 -07002465 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002466 const bool isHdr =
2467 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002468 if (isHdr) {
2469 bestDataSpace = hdrDataSpace;
2470 }
2471
Chia-I Wu0d711262018-05-21 15:19:35 -07002472 RenderIntent intent;
2473 switch (mDisplayColorSetting) {
2474 case DisplayColorSetting::MANAGED:
2475 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002476 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002477 break;
2478 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002479 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002480 break;
2481 default: // vendor display color setting
2482 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2483 break;
2484 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002485
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002486 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002487}
2488
Lloyd Pique32cbe282018-10-19 13:09:22 -07002489void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2490 auto display = displayDevice->getCompositionDisplay();
2491 const auto& displayState = display->getState();
2492
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002493 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002494 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2495 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002496
David Sodmanfa9b2af2017-12-24 13:28:59 -08002497 // If nothing has changed (!dirty), don't recompose.
2498 // If something changed, but we don't currently have any visible layers,
2499 // and didn't when we last did a composition, then skip it this time.
2500 // The second rule does two things:
2501 // - When all layers are removed from a display, we'll emit one black
2502 // frame, then nothing more until we get new layers.
2503 // - When a display is created with a private layer stack, we won't
2504 // emit any black frames until a layer is added to the layer stack.
2505 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002506
Dominik Laskowski075d3172018-05-24 15:50:06 -07002507 const char flagPrefix[] = {'-', '+'};
2508 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002509 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2510 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2511 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2512 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002513
Lloyd Pique31cb2942018-10-19 17:23:03 -07002514 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002515
David Sodmanfa9b2af2017-12-24 13:28:59 -08002516 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002517 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002518 }
2519}
2520
Lloyd Pique32cbe282018-10-19 13:09:22 -07002521void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2522 auto display = displayDevice->getCompositionDisplay();
2523 const auto& displayState = display->getState();
2524
2525 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002526 return;
David Sodman2b406362017-12-15 13:33:47 -08002527 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002528
Lloyd Pique31cb2942018-10-19 17:23:03 -07002529 status_t result = display->getRenderSurface()->prepareFrame(
2530 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002531 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002532 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002533}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002534
Lloyd Pique32cbe282018-10-19 13:09:22 -07002535void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002536 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002537 ALOGV("doComposition");
2538
Lloyd Pique32cbe282018-10-19 13:09:22 -07002539 auto display = displayDevice->getCompositionDisplay();
2540 const auto& displayState = display->getState();
2541
2542 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002543 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002544 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002545
David Sodmanfa9b2af2017-12-24 13:28:59 -08002546 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002547 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002548
Lloyd Pique32cbe282018-10-19 13:09:22 -07002549 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002550 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002551 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002552 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002553}
2554
David Sodmanfa9b2af2017-12-24 13:28:59 -08002555void SurfaceFlinger::postFrame()
2556{
2557 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002558 const auto display = getDefaultDisplayDeviceLocked();
2559 if (display && getHwComposer().isConnected(*display->getId())) {
2560 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002561 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2562 logFrameStats();
2563 }
2564 }
2565}
2566
Lloyd Pique32cbe282018-10-19 13:09:22 -07002567void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002568 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002569 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002570
Lloyd Pique32cbe282018-10-19 13:09:22 -07002571 auto display = displayDevice->getCompositionDisplay();
2572 const auto& displayState = display->getState();
2573 const auto displayId = display->getId();
2574
David Sodmanfa9b2af2017-12-24 13:28:59 -08002575 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002576
Lloyd Pique32cbe282018-10-19 13:09:22 -07002577 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002578 if (displayId) {
2579 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002580 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002581 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002582 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002583 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002584
Chia-I Wu7b549592017-11-15 09:14:57 -08002585 // The layer buffer from the previous frame (if any) is released
2586 // by HWC only when the release fence from this frame (if any) is
2587 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002588 if (displayId && layer->hasHwcLayer(*displayId)) {
2589 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2590 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002591 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002592
2593 // If the layer was client composited in the previous frame, we
2594 // need to merge with the previous client target acquire fence.
2595 // Since we do not track that, always merge with the current
2596 // client target acquire fence when it is available, even though
2597 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002598 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002599 releaseFence =
2600 Fence::merge("LayerRelease", releaseFence,
2601 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002602 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002603
David Sodman15094112018-10-11 09:39:37 -07002604 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002605 }
Chia-I Wu83806892017-11-16 10:50:20 -08002606
2607 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002608 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002609 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002610 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002611 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002612 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002613 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002614 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002615 }
2616 }
2617
Dominik Laskowski075d3172018-05-24 15:50:06 -07002618 if (displayId) {
2619 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002620 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002621 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002622}
2623
Mathias Agopian87baae12012-07-31 12:38:26 -07002624void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002625{
Mathias Agopian841cde52012-03-01 15:44:37 -08002626 ATRACE_CALL();
2627
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002628 // here we keep a copy of the drawing state (that is the state that's
2629 // going to be overwritten by handleTransactionLocked()) outside of
2630 // mStateLock so that the side-effects of the State assignment
2631 // don't happen with mStateLock held (which can cause deadlocks).
2632 State drawingState(mDrawingState);
2633
Mathias Agopianca4d3602011-05-19 15:38:14 -07002634 Mutex::Autolock _l(mStateLock);
2635 const nsecs_t now = systemTime();
2636 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002637
Mathias Agopianca4d3602011-05-19 15:38:14 -07002638 // Here we're guaranteed that some transaction flags are set
2639 // so we can call handleTransactionLocked() unconditionally.
2640 // We call getTransactionFlags(), which will also clear the flags,
2641 // with mStateLock held to guarantee that mCurrentState won't change
2642 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002643
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002644 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002645 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002646 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002647
Mathias Agopianca4d3602011-05-19 15:38:14 -07002648 mLastTransactionTime = systemTime() - now;
2649 mDebugInTransaction = 0;
2650 invalidateHwcGeometry();
2651 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002652}
2653
Lloyd Piqueba04e622017-12-14 17:11:26 -08002654void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2655 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002656 const std::optional<DisplayIdentificationInfo> info =
2657 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002658
Dominik Laskowski075d3172018-05-24 15:50:06 -07002659 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002660 continue;
2661 }
2662
Lloyd Piqueba04e622017-12-14 17:11:26 -08002663 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002664 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002665 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002666 mPhysicalDisplayTokens[info->id] = new BBinder();
2667 DisplayDeviceState state;
2668 state.displayId = info->id;
2669 state.isSecure = true; // All physical displays are currently considered secure.
2670 state.displayName = info->name;
2671 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2672 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002673 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002674 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002675 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002676
Dominik Laskowski075d3172018-05-24 15:50:06 -07002677 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2678 if (index >= 0) {
2679 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2680 mInterceptor->saveDisplayDeletion(state.sequenceId);
2681 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002682 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002683 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002684 }
2685
2686 processDisplayChangesLocked();
2687 }
2688
2689 mPendingHotplugEvents.clear();
2690}
2691
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002692void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002693 if (mUseScheduler) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002694 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2695 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002696 } else {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002697 mEventThread->onHotplugReceived(displayId, connected);
2698 mSFEventThread->onHotplugReceived(displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002699 }
2700}
2701
Lloyd Pique99d3da52018-01-22 17:48:03 -08002702sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002703 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002704 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002705 const sp<IGraphicBufferProducer>& producer) {
2706 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002707 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002708 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002709 creationArgs.isSecure = state.isSecure;
2710 creationArgs.displaySurface = dispSurface;
2711 creationArgs.hasWideColorGamut = false;
2712 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002713
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002714 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002715 creationArgs.isPrimary = isInternalDisplay;
2716
2717 if (useColorManagement && displayId) {
2718 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002719 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002720 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002721 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002722 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002723
Dominik Laskowski7e045462018-05-30 13:02:02 -07002724 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002725 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002726 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002727 }
tangrobin6753a022018-08-10 10:58:54 +08002728 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002729
Dominik Laskowski075d3172018-05-24 15:50:06 -07002730 if (displayId) {
2731 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002732 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002733 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002734 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002735
Lloyd Pique90c115d2018-09-18 21:39:42 -07002736 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002737 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002738 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002739
Lloyd Pique99d3da52018-01-22 17:48:03 -08002740 // Make sure that composition can never be stalled by a virtual display
2741 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002742 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002743 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002744 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2745 }
2746
Dominik Laskowski075d3172018-05-24 15:50:06 -07002747 creationArgs.displayInstallOrientation =
2748 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002749
Lloyd Pique99d3da52018-01-22 17:48:03 -08002750 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002751 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002752
Lloyd Pique90c115d2018-09-18 21:39:42 -07002753 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002754
2755 if (maxFrameBufferAcquiredBuffers >= 3) {
2756 nativeWindowSurface->preallocateBuffers();
2757 }
2758
2759 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002760 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002761 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002762 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002763 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002764 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002765 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2766 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002767 if (!state.isVirtual()) {
2768 LOG_ALWAYS_FATAL_IF(!displayId);
2769 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002770 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002771
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002772 display->setLayerStack(state.layerStack);
2773 display->setProjection(state.orientation, state.viewport, state.frame);
2774 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002775
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002776 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002777}
2778
Lloyd Pique347200f2017-12-14 17:00:15 -08002779void SurfaceFlinger::processDisplayChangesLocked() {
2780 // here we take advantage of Vector's copy-on-write semantics to
2781 // improve performance by skipping the transaction entirely when
2782 // know that the lists are identical
2783 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2784 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2785 if (!curr.isIdenticalTo(draw)) {
2786 mVisibleRegionsDirty = true;
2787 const size_t cc = curr.size();
2788 size_t dc = draw.size();
2789
2790 // find the displays that were removed
2791 // (ie: in drawing state but not in current state)
2792 // also handle displays that changed
2793 // (ie: displays that are in both lists)
2794 for (size_t i = 0; i < dc;) {
2795 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2796 if (j < 0) {
2797 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002798 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002799 // Save display ID before disconnecting.
2800 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002801 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002802
2803 if (!display->isVirtual()) {
2804 LOG_ALWAYS_FATAL_IF(!displayId);
2805 dispatchDisplayHotplugEvent(displayId->value, false);
2806 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002807 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002808
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002809 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002810 } else {
2811 // this display is in both lists. see if something changed.
2812 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002813 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002814 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2815 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2816 if (state_binder != draw_binder) {
2817 // changing the surface is like destroying and
2818 // recreating the DisplayDevice, so we just remove it
2819 // from the drawing state, so that it get re-added
2820 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002821 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002822 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002823 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002824 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002825 mDrawingState.displays.removeItemsAt(i);
2826 dc--;
2827 // at this point we must loop to the next item
2828 continue;
2829 }
2830
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002831 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002832 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002833 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002834 }
2835 if ((state.orientation != draw[i].orientation) ||
2836 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002837 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002838 }
2839 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002840 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002841 }
2842 }
2843 }
2844 ++i;
2845 }
2846
2847 // find displays that were added
2848 // (ie: in current state but not in drawing state)
2849 for (size_t i = 0; i < cc; i++) {
2850 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2851 const DisplayDeviceState& state(curr[i]);
2852
Lloyd Pique542307f2018-10-19 13:24:08 -07002853 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002854 sp<IGraphicBufferProducer> producer;
2855 sp<IGraphicBufferProducer> bqProducer;
2856 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002857 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002858
Dominik Laskowski075d3172018-05-24 15:50:06 -07002859 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002860 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002861 // Virtual displays without a surface are dormant:
2862 // they have external state (layer stack, projection,
2863 // etc.) but no internal state (i.e. a DisplayDevice).
2864 if (state.surface != nullptr) {
2865 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002866 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002867 int width = 0;
2868 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2869 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2870 int height = 0;
2871 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2872 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2873 int intFormat = 0;
2874 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2875 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002876 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002877
Dominik Laskowski075d3172018-05-24 15:50:06 -07002878 displayId =
2879 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002880 }
2881
2882 // TODO: Plumb requested format back up to consumer
2883
2884 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002885 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002886 bqProducer, bqConsumer,
2887 state.displayName);
2888
2889 dispSurface = vds;
2890 producer = vds;
2891 }
2892 } else {
2893 ALOGE_IF(state.surface != nullptr,
2894 "adding a supported display, but rendering "
2895 "surface is provided (%p), ignoring it",
2896 state.surface.get());
2897
Dominik Laskowski075d3172018-05-24 15:50:06 -07002898 displayId = state.displayId;
2899 LOG_ALWAYS_FATAL_IF(!displayId);
2900 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002901 producer = bqProducer;
2902 }
2903
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002904 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002905 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002906 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002907 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002908 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002909 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002910 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002911 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002912 }
2913 }
2914 }
2915 }
2916 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002917
2918 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002919}
2920
Mathias Agopian87baae12012-07-31 12:38:26 -07002921void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002922{
Dan Stoza7dde5992015-05-22 09:51:44 -07002923 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002924 mCurrentState.traverseInZOrder([](Layer* layer) {
2925 layer->notifyAvailableFrames();
2926 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002927
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002928 /*
2929 * Traversal of the children
2930 * (perform the transaction for each of them if needed)
2931 */
2932
Mathias Agopian3559b072012-08-15 13:46:03 -07002933 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002934 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002935 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002936 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002937
2938 const uint32_t flags = layer->doTransaction(0);
2939 if (flags & Layer::eVisibleRegion)
2940 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002941
2942 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002943 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002944 }
Robert Carr2047fae2016-11-28 14:09:09 -08002945 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002946 }
2947
2948 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002949 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002950 */
2951
Mathias Agopiane57f2922012-08-09 16:29:12 -07002952 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002953 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002954 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002955 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002956
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002957 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002958 // The transform hint might have changed for some layers
2959 // (either because a display has changed, or because a layer
2960 // as changed).
2961 //
2962 // Walk through all the layers in currentLayers,
2963 // and update their transform hint.
2964 //
2965 // If a layer is visible only on a single display, then that
2966 // display is used to calculate the hint, otherwise we use the
2967 // default display.
2968 //
2969 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2970 // the hint is set before we acquire a buffer from the surface texture.
2971 //
2972 // NOTE: layer transactions have taken place already, so we use their
2973 // drawing state. However, SurfaceFlinger's own transaction has not
2974 // happened yet, so we must use the current state layer list
2975 // (soon to become the drawing state list).
2976 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002977 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002978 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002979 bool first = true;
2980 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002981 // NOTE: we rely on the fact that layers are sorted by
2982 // layerStack first (so we don't have to traverse the list
2983 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002984 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002985 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002986 currentlayerStack = layerStack;
2987 // figure out if this layerstack is mirrored
2988 // (more than one display) if so, pick the default display,
2989 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002990 hintDisplay = nullptr;
2991 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002992 if (display->getCompositionDisplay()
2993 ->belongsInOutput(layer->getLayerStack(),
2994 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002995 if (hintDisplay) {
2996 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002997 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002998 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002999 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08003000 }
3001 }
3002 }
3003 }
Chet Haase91d25932013-04-11 15:24:55 -07003004
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003005 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003006 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
3007 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08003008
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003009 // could be null when this layer is using a layerStack
3010 // that is not visible on any display. Also can occur at
3011 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003012 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08003013 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003014
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003015 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003016 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003017 if (hintDisplay) {
3018 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08003019 }
Robert Carr2047fae2016-11-28 14:09:09 -08003020
3021 first = false;
3022 });
Mathias Agopian84300952012-11-21 16:02:13 -08003023 }
3024
3025
Mathias Agopian3559b072012-08-15 13:46:03 -07003026 /*
3027 * Perform our own transaction if needed
3028 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07003029
3030 if (mLayersAdded) {
3031 mLayersAdded = false;
3032 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07003033 mVisibleRegionsDirty = true;
3034 }
3035
3036 // some layers might have been removed, so
3037 // we need to update the regions they're exposing.
3038 if (mLayersRemoved) {
3039 mLayersRemoved = false;
3040 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08003041 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003042 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07003043 // this layer is not visible anymore
3044 // TODO: we could traverse the tree from front to back and
3045 // compute the actual visible region
3046 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003047 Region visibleReg;
3048 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07003049 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07003050 }
Robert Carr2047fae2016-11-28 14:09:09 -08003051 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003052 }
3053
3054 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07003055}
3056
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003057void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07003058 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003059 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08003060 return;
3061 }
3062
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003063 if (mVisibleRegionsDirty || mInputInfoChanged) {
3064 mInputInfoChanged = false;
3065 updateInputWindowInfo();
3066 }
3067
3068 executeInputWindowCommands();
3069}
3070
3071void SurfaceFlinger::updateInputWindowInfo() {
Robert Carr720e5062018-07-30 17:45:14 -07003072 Vector<InputWindowInfo> inputHandles;
3073
3074 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
3075 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08003076 // When calculating the screen bounds we ignore the transparent region since it may
3077 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08003078 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07003079 }
3080 });
3081 mInputFlinger->setInputWindows(inputHandles);
3082}
3083
chaviwfbe5d9c2018-12-26 12:23:37 -08003084void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08003085 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3086 if (transferTouchFocusCommand.fromToken != nullptr &&
3087 transferTouchFocusCommand.toToken != nullptr &&
3088 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3089 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3090 transferTouchFocusCommand.toToken);
3091 }
3092 }
3093
3094 mInputWindowCommands.clear();
3095}
3096
Riley Andrews03414a12014-07-01 14:22:59 -07003097void SurfaceFlinger::updateCursorAsync()
3098{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003099 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003100 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003101 continue;
3102 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003103
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003104 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3105 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003106 }
3107 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003108}
3109
chaviw61626f22018-11-15 16:26:27 -08003110void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3111 if (layer->hasReadyFrame()) {
Ady Abrahamc3e21312019-02-07 14:30:23 -08003112 nsecs_t expectedPresentTime;
3113 if (mUseScheduler) {
3114 expectedPresentTime = mScheduler->expectedPresentTime();
3115 } else {
3116 expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3117 }
chaviw61626f22018-11-15 16:26:27 -08003118 if (layer->shouldPresentNow(expectedPresentTime)) {
3119 bool ignored = false;
3120 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
3121 }
3122 }
3123 layer->releasePendingBuffer(systemTime());
3124}
3125
Mathias Agopian4fec8732012-06-29 14:12:52 -07003126void SurfaceFlinger::commitTransaction()
3127{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003128 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003129 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003130 for (const auto& l : mLayersPendingRemoval) {
3131 recordBufferingStats(l->getName().string(),
3132 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003133
3134 // We need to release the HWC layers when the Layer is removed
3135 // from the current state otherwise the HWC layer just continues
3136 // showing at its last configured state until we eventually
3137 // abandon the buffer queue.
3138 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003139 l->destroyHwcLayersForAllDisplays();
3140 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003141 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003142 }
3143 mLayersPendingRemoval.clear();
3144 }
3145
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003146 // If this transaction is part of a window animation then the next frame
3147 // we composite should be considered an animation as well.
3148 mAnimCompositionPending = mAnimTransactionPending;
3149
Mathias Agopian4fec8732012-06-29 14:12:52 -07003150 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003151 // clear the "changed" flags in current state
3152 mCurrentState.colorMatrixChanged = false;
3153
Robert Carr1f0a16a2016-10-24 16:27:39 -07003154 mDrawingState.traverseInZOrder([](Layer* layer) {
3155 layer->commitChildList();
3156 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003157 mTransactionPending = false;
3158 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003159 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003160}
3161
Lloyd Pique32cbe282018-10-19 13:09:22 -07003162void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003163 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003164 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003165 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003166
Lloyd Pique32cbe282018-10-19 13:09:22 -07003167 auto display = displayDevice->getCompositionDisplay();
3168
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003169 Region aboveOpaqueLayers;
3170 Region aboveCoveredLayers;
3171 Region dirty;
3172
Mathias Agopian87baae12012-07-31 12:38:26 -07003173 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003174
Robert Carr2047fae2016-11-28 14:09:09 -08003175 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003176 // start with the whole surface at its current location
3177 const Layer::State& s(layer->getDrawingState());
3178
Jesse Hall01e29052013-02-19 16:13:35 -08003179 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003180 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003181 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003182 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003183
Mathias Agopianab028732010-03-16 16:41:46 -07003184 /*
3185 * opaqueRegion: area of a surface that is fully opaque.
3186 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003187 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003188
3189 /*
3190 * visibleRegion: area of a surface that is visible on screen
3191 * and not fully transparent. This is essentially the layer's
3192 * footprint minus the opaque regions above it.
3193 * Areas covered by a translucent surface are considered visible.
3194 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003195 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003196
3197 /*
3198 * coveredRegion: area of a surface that is covered by all
3199 * visible regions above it (which includes the translucent areas).
3200 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003201 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003202
Jesse Halla8026d22012-09-25 13:25:04 -07003203 /*
3204 * transparentRegion: area of a surface that is hinted to be completely
3205 * transparent. This is only used to tell when the layer has no visible
3206 * non-transparent regions and can be removed from the layer list. It
3207 * does not affect the visibleRegion of this layer or any layers
3208 * beneath it. The hint may not be correct if apps don't respect the
3209 * SurfaceView restrictions (which, sadly, some don't).
3210 */
3211 Region transparentRegion;
3212
Mathias Agopianab028732010-03-16 16:41:46 -07003213
3214 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003215 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003216 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003217 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003218
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003219 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003220 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003221 if (!visibleRegion.isEmpty()) {
3222 // Remove the transparent area from the visible region
3223 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003224 if (tr.preserveRects()) {
3225 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003226 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003227 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003228 // transformation too complex, can't do the
3229 // transparent region optimization.
3230 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003231 }
Mathias Agopianab028732010-03-16 16:41:46 -07003232 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003233
Mathias Agopianab028732010-03-16 16:41:46 -07003234 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003235 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003236 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003237 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003238 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003239 // the opaque region is the layer's footprint
3240 opaqueRegion = visibleRegion;
3241 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003242 }
3243 }
3244
Robert Carre5f4f692018-01-12 13:12:28 -08003245 if (visibleRegion.isEmpty()) {
3246 layer->clearVisibilityRegions();
3247 return;
3248 }
3249
Mathias Agopianab028732010-03-16 16:41:46 -07003250 // Clip the covered region to the visible region
3251 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3252
3253 // Update aboveCoveredLayers for next (lower) layer
3254 aboveCoveredLayers.orSelf(visibleRegion);
3255
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003256 // subtract the opaque region covered by the layers above us
3257 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003258
3259 // compute this layer's dirty region
3260 if (layer->contentDirty) {
3261 // we need to invalidate the whole region
3262 dirty = visibleRegion;
3263 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003264 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003265 layer->contentDirty = false;
3266 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003267 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003268 * the exposed region consists of two components:
3269 * 1) what's VISIBLE now and was COVERED before
3270 * 2) what's EXPOSED now less what was EXPOSED before
3271 *
3272 * note that (1) is conservative, we start with the whole
3273 * visible region but only keep what used to be covered by
3274 * something -- which mean it may have been exposed.
3275 *
3276 * (2) handles areas that were not covered by anything but got
3277 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003278 */
Mathias Agopianab028732010-03-16 16:41:46 -07003279 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003280 const Region oldVisibleRegion = layer->visibleRegion;
3281 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003282 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3283 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003284 }
3285 dirty.subtractSelf(aboveOpaqueLayers);
3286
3287 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003288 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003289
Mathias Agopianab028732010-03-16 16:41:46 -07003290 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003291 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003292
Jesse Halla8026d22012-09-25 13:25:04 -07003293 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003294 layer->setVisibleRegion(visibleRegion);
3295 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003296 layer->setVisibleNonTransparentRegion(
3297 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003298 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003299
Mathias Agopian87baae12012-07-31 12:38:26 -07003300 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003301}
3302
Chia-I Wuab0c3192017-08-01 11:29:00 -07003303void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003304 for (const auto& [token, displayDevice] : mDisplays) {
3305 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003306 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003307 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003308 }
3309 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003310}
3311
Daniel Solomon42d04562019-01-20 21:03:19 -08003312void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3313 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3314 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3315 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3316 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3317 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3318 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3319 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3320 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3321 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3322 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3323 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3324 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3325}
3326
Dan Stoza6b9454d2014-11-07 16:00:59 -08003327bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003328{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003329 ALOGV("handlePageFlip");
3330
Brian Andersond6927fb2016-07-23 23:37:30 -07003331 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003332
Mathias Agopian4fec8732012-06-29 14:12:52 -07003333 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003334 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003335 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003336
3337 // Store the set of layers that need updates. This set must not change as
3338 // buffers are being latched, as this could result in a deadlock.
3339 // Example: Two producers share the same command stream and:
3340 // 1.) Layer 0 is latched
3341 // 2.) Layer 0 gets a new frame
3342 // 2.) Layer 1 gets a new frame
3343 // 3.) Layer 1 is latched.
3344 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3345 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003346 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003347 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003348 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003349 nsecs_t expectedPresentTime;
3350 if (mUseScheduler) {
3351 expectedPresentTime = mScheduler->expectedPresentTime();
3352 } else {
3353 expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3354 }
Ana Krulec010d2192018-10-08 06:29:54 -07003355 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003356 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003357 } else {
3358 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003359 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003360 } else {
3361 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003362 }
Robert Carr2047fae2016-11-28 14:09:09 -08003363 });
3364
Lloyd Piquef2c79392018-12-20 16:23:33 -08003365 if (!mLayersWithQueuedFrames.empty()) {
3366 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3367 // writes to Layer current state. See also b/119481871
3368 Mutex::Autolock lock(mStateLock);
3369
3370 for (auto& layer : mLayersWithQueuedFrames) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003371 if (layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence)) {
3372 mLayersPendingRefresh.push_back(layer);
3373 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003374 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003375 if (layer->isBufferLatched()) {
3376 newDataLatched = true;
3377 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003378 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003379 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003380
Alec Mouri86770e52018-09-24 22:40:58 +00003381 // Clear the renderengine fence here...
3382 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3383 // clear instead of sp::clear.
3384 getBE().flushFence = Fence::NO_FENCE;
3385
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003386 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003387
3388 // If we will need to wake up at some time in the future to deal with a
3389 // queued frame that shouldn't be displayed during this vsync period, wake
3390 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003391 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003392 signalLayerUpdate();
3393 }
3394
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003395 // enter boot animation on first buffer latch
3396 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3397 ALOGI("Enter boot animation");
3398 mBootStage = BootStage::BOOTANIMATION;
3399 }
3400
Dan Stoza6b9454d2014-11-07 16:00:59 -08003401 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003402 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003403}
3404
Mathias Agopianad456f92011-01-13 17:53:01 -08003405void SurfaceFlinger::invalidateHwcGeometry()
3406{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003407 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003408}
3409
Lloyd Pique32cbe282018-10-19 13:09:22 -07003410void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003411 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003412 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003413 // We only need to actually compose the display if:
3414 // 1) It is being handled by hardware composer, which may need this to
3415 // keep its virtual display state machine in sync, or
3416 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003417 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003418 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003419 return;
3420 }
3421
Dan Stoza9e56aa02015-11-02 13:00:03 -08003422 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003423 base::unique_fd readyFence;
3424 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003425
3426 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003427 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003428}
3429
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003430bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3431 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003432 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003433 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003434
Lloyd Pique32cbe282018-10-19 13:09:22 -07003435 auto display = displayDevice->getCompositionDisplay();
3436 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003437 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003438
3439 const Region bounds(displayState.bounds);
3440 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003441 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003442 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003443
Peiyong Lind3788632018-09-18 16:01:31 -07003444 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003445 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003446
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003447 renderengine::DisplaySettings clientCompositionDisplay;
3448 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3449 sp<GraphicBuffer> buf;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003450
Dan Stoza9e56aa02015-11-02 13:00:03 -08003451 if (hasClientComposition) {
3452 ALOGV("hasClientComposition");
3453
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003454 buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003455
3456 if (buf == nullptr) {
3457 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3458 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003459 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003460 return false;
3461 }
3462
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003463 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3464 clientCompositionDisplay.clip = displayState.scissor;
3465 const ui::Transform& displayTransform = displayState.transform;
3466 mat4 m;
3467 m[0][0] = displayTransform[0][0];
3468 m[0][1] = displayTransform[0][1];
3469 m[0][3] = displayTransform[0][2];
3470 m[1][0] = displayTransform[1][0];
3471 m[1][1] = displayTransform[1][1];
3472 m[1][3] = displayTransform[1][2];
3473 m[3][0] = displayTransform[2][0];
3474 m[3][1] = displayTransform[2][1];
3475 m[3][3] = displayTransform[2][2];
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003476
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003477 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003478
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003479 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003480 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003481 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003482 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003483 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003484 clientCompositionDisplay.outputDataspace = outputDataspace;
3485 clientCompositionDisplay.maxLuminance =
3486 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003487
Lloyd Pique441d5042018-10-18 16:49:51 -07003488 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003489 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003490 getHwComposer()
3491 .hasDisplayCapability(displayId,
3492 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003493
Peiyong Lind3788632018-09-18 16:01:31 -07003494 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003495 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3496 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003497 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003498 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003499 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003500
Mathias Agopian85d751c2012-08-29 16:59:24 -07003501 /*
3502 * and then, render the layers targeted at the framebuffer
3503 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003504
Dan Stoza9e56aa02015-11-02 13:00:03 -08003505 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003506 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003507 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003508 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003509 const Region viewportRegion(displayState.viewport);
3510 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003511 ALOGV("Layer: %s", layer->getName().string());
3512 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003513 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003514 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003515 case HWC2::Composition::Cursor:
3516 case HWC2::Composition::Device:
3517 case HWC2::Composition::Sideband:
3518 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003519 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003520 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003521 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003522 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003523 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003524 // never clear the very first layer since we're
3525 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003526 renderengine::LayerSettings layerSettings;
3527 Region dummyRegion;
3528 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3529 layerSettings);
3530
3531 if (prepared) {
3532 layerSettings.source.buffer.buffer = nullptr;
3533 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3534 layerSettings.alpha = half(0.0);
3535 layerSettings.disableBlending = true;
3536 clientCompositionLayers.push_back(layerSettings);
3537 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003538 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003539 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003540 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003541 case HWC2::Composition::Client: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003542 renderengine::LayerSettings layerSettings;
3543 bool prepared =
3544 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3545 if (prepared) {
3546 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003547 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003548 break;
3549 }
3550 default:
3551 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003552 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003553 } else {
3554 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003555 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003556 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003557 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003558
Alec Mouri820c7402019-01-23 13:02:39 -08003559 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003560 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003561 clientCompositionDisplay.clearRegion = clearRegion;
3562 if (!debugRegion.isEmpty()) {
3563 Region::const_iterator it = debugRegion.begin();
3564 Region::const_iterator end = debugRegion.end();
3565 while (it != end) {
3566 const Rect& rect = *it++;
3567 renderengine::LayerSettings layerSettings;
3568 layerSettings.source.buffer.buffer = nullptr;
3569 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3570 layerSettings.geometry.boundaries = rect.toFloatRect();
3571 layerSettings.alpha = half(1.0);
3572 clientCompositionLayers.push_back(layerSettings);
3573 }
3574 }
3575 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
3576 buf->getNativeBuffer(), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003577 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003578 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003579}
3580
Chia-I Wu28e3a252018-09-07 12:05:02 -07003581void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003582 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003583 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003584}
3585
Dan Stoza7d89d062015-04-30 13:29:25 -07003586status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003587 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003588 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003589 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003590 const sp<Layer>& parent,
3591 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003592{
Dan Stoza7d89d062015-04-30 13:29:25 -07003593 // add this layer to the current state list
3594 {
3595 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003596 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003597 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3598 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003599 return NO_MEMORY;
3600 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003601 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003602 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003603 } else if (parent == nullptr) {
3604 lbc->onRemovedFromCurrentState();
3605 } else if (parent->isRemovedFromCurrentState()) {
3606 parent->addChild(lbc);
3607 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003608 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003609 parent->addChild(lbc);
3610 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003611
Yiwei Zhang243b3782018-05-15 17:40:04 -07003612 if (gbc != nullptr) {
3613 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3614 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3615 mMaxGraphicBufferProducerListSize,
3616 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3617 mGraphicBufferProducerList.size(),
3618 mMaxGraphicBufferProducerListSize, mNumLayers);
3619 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003620 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003621 }
3622
Mathias Agopian96f08192010-06-02 23:28:45 -07003623 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003624 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003625
Dan Stoza7d89d062015-04-30 13:29:25 -07003626 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003627}
3628
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003629uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003630 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003631}
3632
Mathias Agopian3f844832013-08-07 21:24:32 -07003633uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003634 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003635}
3636
Mathias Agopian3f844832013-08-07 21:24:32 -07003637uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003638 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003639}
3640
3641uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003642 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003643 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003644 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003645 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003646 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003647 }
3648 return old;
3649}
3650
Marissa Wall713b63f2018-10-17 15:42:43 -07003651bool SurfaceFlinger::flushTransactionQueues() {
3652 Mutex::Autolock _l(mStateLock);
3653 auto it = mTransactionQueues.begin();
3654 while (it != mTransactionQueues.end()) {
3655 auto& [applyToken, transactionQueue] = *it;
3656
3657 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003658 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3659 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003660 break;
3661 }
chaviw273171b2018-12-26 11:46:30 -08003662 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003663 transactionQueue.pop();
3664 }
3665
3666 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3667 }
3668 return mTransactionQueues.empty();
3669}
3670
chaviwca27f252018-02-06 16:46:39 -08003671bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3672 for (const ComposerState& state : states) {
3673 // Here we need to check that the interface we're given is indeed
3674 // one of our own. A malicious client could give us a nullptr
3675 // IInterface, or one of its own or even one of our own but a
3676 // different type. All these situations would cause us to crash.
3677 if (state.client == nullptr) {
3678 return true;
3679 }
3680
3681 sp<IBinder> binder = IInterface::asBinder(state.client);
3682 if (binder == nullptr) {
3683 return true;
3684 }
3685
3686 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3687 return true;
3688 }
3689 }
3690 return false;
3691}
3692
Marissa Wall17b4e452018-12-26 16:32:34 -08003693bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3694 const Vector<ComposerState>& states) {
Ady Abrahamc3e21312019-02-07 14:30:23 -08003695 nsecs_t expectedPresentTime;
3696 if (mUseScheduler) {
3697 expectedPresentTime = mScheduler->expectedPresentTime();
3698 } else {
3699 expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3700 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003701 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3702 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3703 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3704 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3705 return false;
3706 }
3707
Marissa Wall713b63f2018-10-17 15:42:43 -07003708 for (const ComposerState& state : states) {
3709 const layer_state_t& s = state.state;
3710 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3711 continue;
3712 }
3713 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003714 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003715 }
3716 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003717 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003718}
3719
3720void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3721 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003722 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003723 const InputWindowCommands& inputWindowCommands,
3724 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003725 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003726 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003727
chaviwca27f252018-02-06 16:46:39 -08003728 if (containsAnyInvalidClientState(states)) {
3729 return;
3730 }
3731
Marissa Wall713b63f2018-10-17 15:42:43 -07003732 // If its TransactionQueue already has a pending TransactionState or if it is pending
3733 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003734 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3735 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003736 setTransactionFlags(eTransactionNeeded);
3737 return;
3738 }
3739
chaviw273171b2018-12-26 11:46:30 -08003740 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003741}
3742
3743void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003744 const Vector<DisplayState>& displays, uint32_t flags,
3745 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003746 uint32_t transactionFlags = 0;
3747
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003748 if (flags & eAnimation) {
3749 // For window updates that are part of an animation we must wait for
3750 // previous animation "frames" to be handled.
3751 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003752 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003753 if (CC_UNLIKELY(err != NO_ERROR)) {
3754 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003755 // caller after a few seconds.
3756 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3757 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003758 mAnimTransactionPending = false;
3759 break;
3760 }
3761 }
3762 }
3763
chaviwca27f252018-02-06 16:46:39 -08003764 for (const DisplayState& display : displays) {
3765 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003766 }
3767
Marissa Walle2ffb422018-10-12 11:33:52 -07003768 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003769 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003770 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003771 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003772 // If the state doesn't require a traversal and there are callbacks, send them now
3773 if (!(clientStateFlags & eTraversalNeeded)) {
3774 mTransactionCompletedThread.sendCallbacks();
3775 }
3776 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003777
chaviw273171b2018-12-26 11:46:30 -08003778 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3779
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003780 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3781 // anyway. This can be used as a flush mechanism for previous async transactions.
3782 // Empty animation transaction can be used to simulate back-pressure, so also force a
3783 // transaction for empty animation transactions.
3784 if (transactionFlags == 0 &&
3785 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003786 transactionFlags = eTransactionNeeded;
3787 }
3788
Mathias Agopian386aa982011-11-07 21:58:03 -08003789 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003790 if (mInterceptor->isEnabled()) {
3791 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003792 }
Irvel468051e2016-06-13 16:44:44 -07003793
Mathias Agopian386aa982011-11-07 21:58:03 -08003794 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003795 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3796 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003797 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003798
3799 // if this is a synchronous transaction, wait for it to take effect
3800 // before returning.
3801 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003802 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003803 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003804 if (flags & eAnimation) {
3805 mAnimTransactionPending = true;
3806 }
3807 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003808 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3809 if (CC_UNLIKELY(err != NO_ERROR)) {
3810 // just in case something goes wrong in SF, return to the
3811 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003812 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3813 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003814 break;
3815 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003816 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003817 }
3818}
3819
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003820uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3821 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3822 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003823
Mathias Agopiane57f2922012-08-09 16:29:12 -07003824 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003825 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3826
3827 const uint32_t what = s.what;
3828 if (what & DisplayState::eSurfaceChanged) {
3829 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3830 state.surface = s.surface;
3831 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003832 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003833 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003834 if (what & DisplayState::eLayerStackChanged) {
3835 if (state.layerStack != s.layerStack) {
3836 state.layerStack = s.layerStack;
3837 flags |= eDisplayTransactionNeeded;
3838 }
3839 }
3840 if (what & DisplayState::eDisplayProjectionChanged) {
3841 if (state.orientation != s.orientation) {
3842 state.orientation = s.orientation;
3843 flags |= eDisplayTransactionNeeded;
3844 }
3845 if (state.frame != s.frame) {
3846 state.frame = s.frame;
3847 flags |= eDisplayTransactionNeeded;
3848 }
3849 if (state.viewport != s.viewport) {
3850 state.viewport = s.viewport;
3851 flags |= eDisplayTransactionNeeded;
3852 }
3853 }
3854 if (what & DisplayState::eDisplaySizeChanged) {
3855 if (state.width != s.width) {
3856 state.width = s.width;
3857 flags |= eDisplayTransactionNeeded;
3858 }
3859 if (state.height != s.height) {
3860 state.height = s.height;
3861 flags |= eDisplayTransactionNeeded;
3862 }
3863 }
3864
Mathias Agopiane57f2922012-08-09 16:29:12 -07003865 return flags;
3866}
3867
Robert Carrd4ae7f32018-06-07 16:10:57 -07003868bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3869 IPCThreadState* ipc = IPCThreadState::self();
3870 const int pid = ipc->getCallingPid();
3871 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003872 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003873 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003874 return false;
3875 }
3876 return true;
3877}
3878
chaviwca27f252018-02-06 16:46:39 -08003879uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3880 const layer_state_t& s = composerState.state;
3881 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3882
Mathias Agopian13127d82013-03-05 17:47:11 -08003883 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003884 if (layer == nullptr) {
3885 return 0;
3886 }
3887
chaviw8b3871a2017-11-01 17:41:01 -07003888 uint32_t flags = 0;
3889
Garfield Tan8a3083e2018-12-03 13:21:07 -08003890 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003891 bool geometryAppliesWithResize =
3892 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003893
3894 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3895 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003896 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003897 layer->pushPendingState();
3898 }
3899
chaviw8b3871a2017-11-01 17:41:01 -07003900 if (what & layer_state_t::ePositionChanged) {
3901 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3902 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003903 }
chaviw8b3871a2017-11-01 17:41:01 -07003904 }
3905 if (what & layer_state_t::eLayerChanged) {
3906 // NOTE: index needs to be calculated before we update the state
3907 const auto& p = layer->getParent();
3908 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003909 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003910 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003911 mCurrentState.layersSortedByZ.removeAt(idx);
3912 mCurrentState.layersSortedByZ.add(layer);
3913 // we need traversal (state changed)
3914 // AND transaction (list changed)
3915 flags |= eTransactionNeeded|eTraversalNeeded;
3916 }
chaviw8b3871a2017-11-01 17:41:01 -07003917 } else {
3918 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003919 flags |= eTransactionNeeded|eTraversalNeeded;
3920 }
3921 }
chaviw8b3871a2017-11-01 17:41:01 -07003922 }
3923 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003924 // NOTE: index needs to be calculated before we update the state
3925 const auto& p = layer->getParent();
3926 if (p == nullptr) {
3927 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3928 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3929 mCurrentState.layersSortedByZ.removeAt(idx);
3930 mCurrentState.layersSortedByZ.add(layer);
3931 // we need traversal (state changed)
3932 // AND transaction (list changed)
3933 flags |= eTransactionNeeded|eTraversalNeeded;
3934 }
3935 } else {
3936 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3937 flags |= eTransactionNeeded|eTraversalNeeded;
3938 }
chaviw8b3871a2017-11-01 17:41:01 -07003939 }
3940 }
3941 if (what & layer_state_t::eSizeChanged) {
3942 if (layer->setSize(s.w, s.h)) {
3943 flags |= eTraversalNeeded;
3944 }
3945 }
3946 if (what & layer_state_t::eAlphaChanged) {
3947 if (layer->setAlpha(s.alpha))
3948 flags |= eTraversalNeeded;
3949 }
3950 if (what & layer_state_t::eColorChanged) {
3951 if (layer->setColor(s.color))
3952 flags |= eTraversalNeeded;
3953 }
Peiyong Lind3788632018-09-18 16:01:31 -07003954 if (what & layer_state_t::eColorTransformChanged) {
3955 if (layer->setColorTransform(s.colorTransform)) {
3956 flags |= eTraversalNeeded;
3957 }
3958 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003959 if (what & layer_state_t::eBackgroundColorChanged) {
3960 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3961 flags |= eTraversalNeeded;
3962 }
3963 }
chaviw8b3871a2017-11-01 17:41:01 -07003964 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003965 // TODO: b/109894387
3966 //
3967 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3968 // rotation. To see the problem observe that if we have a square parent, and a child
3969 // of the same size, then we rotate the child 45 degrees around it's center, the child
3970 // must now be cropped to a non rectangular 8 sided region.
3971 //
3972 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3973 // private API, and the WindowManager only uses rotation in one case, which is on a top
3974 // level layer in which cropping is not an issue.
3975 //
3976 // However given that abuse of rotation matrices could lead to surfaces extending outside
3977 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3978 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3979 // transformations.
3980 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003981 flags |= eTraversalNeeded;
3982 }
3983 if (what & layer_state_t::eTransparentRegionChanged) {
3984 if (layer->setTransparentRegionHint(s.transparentRegion))
3985 flags |= eTraversalNeeded;
3986 }
3987 if (what & layer_state_t::eFlagsChanged) {
3988 if (layer->setFlags(s.flags, s.mask))
3989 flags |= eTraversalNeeded;
3990 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003991 if (what & layer_state_t::eCropChanged_legacy) {
3992 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003993 flags |= eTraversalNeeded;
3994 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003995 if (what & layer_state_t::eCornerRadiusChanged) {
3996 if (layer->setCornerRadius(s.cornerRadius))
3997 flags |= eTraversalNeeded;
3998 }
chaviw8b3871a2017-11-01 17:41:01 -07003999 if (what & layer_state_t::eLayerStackChanged) {
4000 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4001 // We only allow setting layer stacks for top level layers,
4002 // everything else inherits layer stack from its parent.
4003 if (layer->hasParent()) {
4004 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
4005 layer->getName().string());
4006 } else if (idx < 0) {
4007 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
4008 "that also does not appear in the top level layer list. Something"
4009 " has gone wrong.", layer->getName().string());
4010 } else if (layer->setLayerStack(s.layerStack)) {
4011 mCurrentState.layersSortedByZ.removeAt(idx);
4012 mCurrentState.layersSortedByZ.add(layer);
4013 // we need traversal (state changed)
4014 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07004015 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07004016 }
4017 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004018 if (what & layer_state_t::eDeferTransaction_legacy) {
4019 if (s.barrierHandle_legacy != nullptr) {
4020 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
4021 } else if (s.barrierGbp_legacy != nullptr) {
4022 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07004023 if (authenticateSurfaceTextureLocked(gbp)) {
4024 const auto& otherLayer =
4025 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07004026 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07004027 } else {
4028 ALOGE("Attempt to defer transaction to to an"
4029 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08004030 }
4031 }
chaviw8b3871a2017-11-01 17:41:01 -07004032 // We don't trigger a traversal here because if no other state is
4033 // changed, we don't want this to cause any more work
4034 }
4035 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08004036 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07004037 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08004038 if (!hadParent) {
4039 mCurrentState.layersSortedByZ.remove(layer);
4040 }
chaviw8b3871a2017-11-01 17:41:01 -07004041 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08004042 }
chaviw8b3871a2017-11-01 17:41:01 -07004043 }
4044 if (what & layer_state_t::eReparentChildren) {
4045 if (layer->reparentChildren(s.reparentHandle)) {
4046 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07004047 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004048 }
chaviw8b3871a2017-11-01 17:41:01 -07004049 if (what & layer_state_t::eDetachChildren) {
4050 layer->detachChildren();
4051 }
4052 if (what & layer_state_t::eOverrideScalingModeChanged) {
4053 layer->setOverrideScalingMode(s.overrideScalingMode);
4054 // We don't trigger a traversal here because if no other state is
4055 // changed, we don't want this to cause any more work
4056 }
Marissa Wall61c58622018-07-18 10:12:20 -07004057 if (what & layer_state_t::eTransformChanged) {
4058 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4059 }
4060 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4061 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4062 flags |= eTraversalNeeded;
4063 }
4064 if (what & layer_state_t::eCropChanged) {
4065 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4066 }
Marissa Wall861616d2018-10-22 12:52:23 -07004067 if (what & layer_state_t::eFrameChanged) {
4068 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4069 }
Marissa Wall61c58622018-07-18 10:12:20 -07004070 if (what & layer_state_t::eAcquireFenceChanged) {
4071 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4072 }
4073 if (what & layer_state_t::eDataspaceChanged) {
4074 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4075 }
4076 if (what & layer_state_t::eHdrMetadataChanged) {
4077 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4078 }
4079 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4080 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4081 }
4082 if (what & layer_state_t::eApiChanged) {
4083 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4084 }
4085 if (what & layer_state_t::eSidebandStreamChanged) {
4086 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4087 }
Robert Carr720e5062018-07-30 17:45:14 -07004088 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004089 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
4090 layer->setInputInfo(s.inputInfo);
4091 flags |= eTraversalNeeded;
4092 } else {
4093 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4094 }
Robert Carr720e5062018-07-30 17:45:14 -07004095 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004096 if (what & layer_state_t::eMetadataChanged) {
4097 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4098 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004099 std::vector<sp<CallbackHandle>> callbackHandles;
4100 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
4101 mTransactionCompletedThread.run();
4102 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
4103 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4104 }
4105 }
Marissa Wall73411622019-01-25 10:45:41 -08004106
4107 if (what & layer_state_t::eBufferChanged) {
4108 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
4109 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
4110 s.buffer);
4111 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004112 if (what & layer_state_t::eCachedBufferChanged) {
4113 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08004114 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
4115 s.cachedBuffer.bufferId);
Marissa Wallebc2c052019-01-16 19:16:55 -08004116 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4117 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004118 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4119 // Do not put anything that updates layer state or modifies flags after
4120 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004121 return flags;
4122}
4123
chaviw273171b2018-12-26 11:46:30 -08004124uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4125 uint32_t flags = 0;
4126 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4127 flags |= eTraversalNeeded;
4128 }
4129
4130 mInputWindowCommands.merge(inputWindowCommands);
4131 return flags;
4132}
4133
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004134status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4135 uint32_t h, PixelFormat format, uint32_t flags,
4136 LayerMetadata metadata, sp<IBinder>* handle,
4137 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004138 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004139 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004140 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004141 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004142 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004143
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004144 status_t result = NO_ERROR;
4145
4146 sp<Layer> layer;
4147
Cody Northropbc755282017-03-31 12:00:08 -06004148 String8 uniqueName = getUniqueLayerName(name);
4149
Mathias Agopian3165cc22012-08-08 19:42:09 -07004150 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004151 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004152 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4153 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004154
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004155 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004156 case ISurfaceComposerClient::eFXSurfaceBufferState:
4157 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4158 break;
chaviw13fdc492017-06-27 12:40:18 -07004159 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004160 // check if buffer size is set for color layer.
4161 if (w > 0 || h > 0) {
4162 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4163 int(w), int(h));
4164 return BAD_VALUE;
4165 }
4166
chaviw13fdc492017-06-27 12:40:18 -07004167 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004168 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004169 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004170 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004171 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004172 // check if buffer size is set for container layer.
4173 if (w > 0 || h > 0) {
4174 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4175 int(w), int(h));
4176 return BAD_VALUE;
4177 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004178 result = createContainerLayer(client,
4179 uniqueName, w, h, flags,
4180 handle, &layer);
4181 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004182 default:
4183 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004184 break;
4185 }
4186
Dan Stoza7d89d062015-04-30 13:29:25 -07004187 if (result != NO_ERROR) {
4188 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004189 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004190
Chia-I Wuab0c3192017-08-01 11:29:00 -07004191 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4192 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004193 if (metadata.has(METADATA_WINDOW_TYPE)) {
4194 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4195 if (windowType == 441731) {
4196 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4197 layer->setPrimaryDisplayOnly();
4198 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004199 }
4200
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004201 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004202
Robert Carrb89ea9d2018-12-10 13:01:14 -08004203 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4204 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4205 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004206 if (result != NO_ERROR) {
4207 return result;
4208 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004209 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004210
4211 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004212 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004213}
4214
Cody Northropbc755282017-03-31 12:00:08 -06004215String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4216{
4217 bool matchFound = true;
4218 uint32_t dupeCounter = 0;
4219
4220 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4221 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4222
Dan Stoza436ccf32018-06-21 12:10:12 -07004223 // Grab the state lock since we're accessing mCurrentState
4224 Mutex::Autolock lock(mStateLock);
4225
Cody Northropbc755282017-03-31 12:00:08 -06004226 // Loop over layers until we're sure there is no matching name
4227 while (matchFound) {
4228 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004229 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004230 if (layer->getName() == uniqueName) {
4231 matchFound = true;
4232 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4233 }
4234 });
4235 }
4236
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004237 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4238 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004239
4240 return uniqueName;
4241}
4242
Marissa Wallfd668622018-05-10 10:21:13 -07004243status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4244 uint32_t w, uint32_t h, uint32_t flags,
4245 PixelFormat& format, sp<IBinder>* handle,
4246 sp<IGraphicBufferProducer>* gbp,
4247 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004248 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004249 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004250 case PIXEL_FORMAT_TRANSPARENT:
4251 case PIXEL_FORMAT_TRANSLUCENT:
4252 format = PIXEL_FORMAT_RGBA_8888;
4253 break;
4254 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004255 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004256 break;
4257 }
4258
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004259 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004260 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004261 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004262 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004263 *handle = layer->getHandle();
4264 *gbp = layer->getProducer();
4265 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004266 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004267
Marissa Wallfd668622018-05-10 10:21:13 -07004268 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004269 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004270}
4271
Marissa Wall61c58622018-07-18 10:12:20 -07004272status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4273 uint32_t w, uint32_t h, uint32_t flags,
4274 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004275 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004276 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004277 *handle = layer->getHandle();
4278 *outLayer = layer;
4279
4280 return NO_ERROR;
4281}
4282
chaviw13fdc492017-06-27 12:40:18 -07004283status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004284 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004285 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004286{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004287 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004288 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004289 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004290}
4291
Robert Carr6b3f6c52018-08-13 13:05:17 -07004292status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4293 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4294 sp<IBinder>* handle, sp<Layer>* outLayer)
4295{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004296 *outLayer =
4297 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004298 *handle = (*outLayer)->getHandle();
4299 return NO_ERROR;
4300}
4301
4302
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004303void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004304 mLayersPendingRemoval.add(layer);
4305 mLayersRemoved = true;
4306 setTransactionFlags(eTransactionNeeded);
4307}
4308
Robert Carr695d5282018-12-18 15:27:58 -08004309void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004310{
Robert Carr2e102c92018-10-23 12:11:15 -07004311 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004312 // If a layer has a parent, we allow it to out-live it's handle
4313 // with the idea that the parent holds a reference and will eventually
4314 // be cleaned up. However no one cleans up the top-level so we do so
4315 // here.
4316 if (layer->getParent() == nullptr) {
4317 mCurrentState.layersSortedByZ.remove(layer);
4318 }
4319 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004320 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004321}
4322
Mathias Agopianb60314a2012-04-10 22:09:54 -07004323// ---------------------------------------------------------------------------
4324
Andy McFadden13a082e2012-08-24 10:16:42 -07004325void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004326 const auto display = getDefaultDisplayDeviceLocked();
4327 if (!display) return;
4328
4329 const sp<IBinder> token = display->getDisplayToken().promote();
4330 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004331
Jesse Hall01e29052013-02-19 16:13:35 -08004332 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004333 Vector<ComposerState> state;
4334 Vector<DisplayState> displays;
4335 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004336 d.what = DisplayState::eDisplayProjectionChanged |
4337 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004338 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004339 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004340 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004341 d.frame.makeInvalid();
4342 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004343 d.width = 0;
4344 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004345 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004346 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004347
Dominik Laskowskie9774092018-12-11 10:04:24 -08004348 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004349
Dominik Laskowski83b88212018-12-11 13:34:06 -08004350 const nsecs_t vsyncPeriod = getVsyncPeriod();
4351 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004352
Brian Andersond0010582017-03-07 13:20:31 -08004353 // Use phase of 0 since phase is not known.
4354 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004355 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004356 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004357}
4358
4359void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004360 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004361 postMessageAsync(
4362 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004363}
4364
Dominik Laskowskie9774092018-12-11 10:04:24 -08004365void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004366 if (display->isVirtual()) {
4367 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004368 return;
4369 }
4370
Dominik Laskowski075d3172018-05-24 15:50:06 -07004371 const auto displayId = display->getId();
4372 LOG_ALWAYS_FATAL_IF(!displayId);
4373
Dominik Laskowski34157762018-10-31 13:07:19 -07004374 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004375
4376 int currentMode = display->getPowerMode();
4377 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004378 return;
4379 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004380
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004381 display->setPowerMode(mode);
4382
Lloyd Pique4dccc412018-01-22 17:21:36 -08004383 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004384 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004385 }
4386
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004387 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004388 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004389 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004390 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004391 if (mUseScheduler) {
4392 mScheduler->onScreenAcquired(mAppConnectionHandle);
4393 } else {
4394 mEventThread->onScreenAcquired();
4395 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004396 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004397 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004398
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004399 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004400 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004401 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004402
4403 struct sched_param param = {0};
4404 param.sched_priority = 1;
4405 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4406 ALOGW("Couldn't set SCHED_FIFO on display on");
4407 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004408 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004409 // Turn off the display
4410 struct sched_param param = {0};
4411 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4412 ALOGW("Couldn't set SCHED_OTHER on display off");
4413 }
4414
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004415 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004416 if (mUseScheduler) {
4417 mScheduler->disableHardwareVsync(true);
4418 } else {
4419 disableHardwareVsync(true); // also cancels any in-progress resync
4420 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004421 if (mUseScheduler) {
4422 mScheduler->onScreenReleased(mAppConnectionHandle);
4423 } else {
4424 mEventThread->onScreenReleased();
4425 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004426 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004427
Dominik Laskowski075d3172018-05-24 15:50:06 -07004428 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004429 mVisibleRegionsDirty = true;
4430 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004431 } else if (mode == HWC_POWER_MODE_DOZE ||
4432 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004433 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004434 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004435 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004436 if (mUseScheduler) {
4437 mScheduler->onScreenAcquired(mAppConnectionHandle);
4438 } else {
4439 mEventThread->onScreenAcquired();
4440 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004441 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004442 }
4443 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4444 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004445 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004446 if (mUseScheduler) {
4447 mScheduler->disableHardwareVsync(true);
4448 } else {
4449 disableHardwareVsync(true); // also cancels any in-progress resync
4450 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004451 if (mUseScheduler) {
4452 mScheduler->onScreenReleased(mAppConnectionHandle);
4453 } else {
4454 mEventThread->onScreenReleased();
4455 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004456 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004457 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004458 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004459 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004460 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004461 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004462
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004463 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004464 mTimeStats->setPowerMode(mode);
Ana Krulec4593b692019-01-11 22:07:25 -08004465 if (mUseScheduler && mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004466 // Update refresh rate stats.
4467 mRefreshRateStats->setPowerMode(mode);
4468 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004469 }
4470
Dominik Laskowski34157762018-10-31 13:07:19 -07004471 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004472}
4473
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004474void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004475 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004476 const auto display = getDisplayDevice(displayToken);
4477 if (!display) {
4478 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4479 displayToken.get());
4480 } else if (display->isVirtual()) {
4481 ALOGW("Attempt to set power mode %d for virtual display", mode);
4482 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004483 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004484 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004485 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004486}
4487
4488// ---------------------------------------------------------------------------
4489
Dominik Laskowskic2867142019-01-21 11:33:38 -08004490status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4491 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004492 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004493
Mathias Agopianbd115332013-04-18 16:41:04 -07004494 IPCThreadState* ipc = IPCThreadState::self();
4495 const int pid = ipc->getCallingPid();
4496 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004497
Mathias Agopianbd115332013-04-18 16:41:04 -07004498 if ((uid != AID_SHELL) &&
4499 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004500 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4501 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004502 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004503 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004504 // (this would indicate SF is stuck, but we want to be able to
4505 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004506 status_t err = mStateLock.timedLock(s2ns(1));
4507 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004508 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004509 StringAppendF(&result,
4510 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4511 "(no locks held)\n",
4512 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004513 }
4514
Dominik Laskowskic2867142019-01-21 11:33:38 -08004515 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004516
Dominik Laskowskic2867142019-01-21 11:33:38 -08004517 static const std::unordered_map<std::string, Dumper> dumpers = {
4518 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4519 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4520 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
4521 {"--dispsync"s, dumper([this](std::string& s) { mPrimaryDispSync->dump(s); })},
4522 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4523 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
4524 {"--frame-composition"s, dumper(&SurfaceFlinger::dumpFrameCompositionInfo)},
4525 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4526 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4527 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4528 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4529 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4530 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004531 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004532 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4533 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004534
Dominik Laskowskic2867142019-01-21 11:33:38 -08004535 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004536
Dominik Laskowskic2867142019-01-21 11:33:38 -08004537 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4538 (it->second)(args, asProto, result);
4539 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004540 if (asProto) {
4541 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4542 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4543 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004544 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004545 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004546 }
4547
Mathias Agopian9795c422009-08-26 16:36:26 -07004548 if (locked) {
4549 mStateLock.unlock();
4550 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004551 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004552 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004553 return NO_ERROR;
4554}
4555
Dominik Laskowskic2867142019-01-21 11:33:38 -08004556void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004557 mCurrentState.traverseInZOrder(
4558 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004559}
4560
Dominik Laskowskic2867142019-01-21 11:33:38 -08004561void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004562 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004563
Dominik Laskowskic2867142019-01-21 11:33:38 -08004564 if (args.size() > 1) {
4565 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004566 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004567 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004568 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004569 }
Robert Carr2047fae2016-11-28 14:09:09 -08004570 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004571 } else {
4572 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004573 }
4574}
4575
Dominik Laskowskic2867142019-01-21 11:33:38 -08004576void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004577 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004578 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004579 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004580 }
Robert Carr2047fae2016-11-28 14:09:09 -08004581 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004582
Svetoslavd85084b2014-03-20 10:28:31 -07004583 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004584}
4585
Dominik Laskowskic2867142019-01-21 11:33:38 -08004586void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4587 mTimeStats->parseArgs(asProto, args, result);
4588}
4589
Jamie Gennis6547ff42013-07-16 20:12:42 -07004590// This should only be called from the main thread. Otherwise it would need
4591// the lock and should use mCurrentState rather than mDrawingState.
4592void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004593 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004594 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004595 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004596
4597 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4598}
4599
Yiwei Zhang5434a782018-12-05 18:06:32 -08004600void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004601 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004602
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004603 if (isLayerTripleBufferingDisabled())
4604 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004605
Yiwei Zhang5434a782018-12-05 18:06:32 -08004606 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4607 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4608 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4609 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4610 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4611 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004612 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004613}
4614
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004615void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004616 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004617 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004618 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004619 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004620
4621 StringAppendF(&result, "Scheduler: %s\n\n", mUseScheduler ? "enabled" : "disabled");
4622
4623 if (mUseScheduler) {
4624 mScheduler->dump(mAppConnectionHandle, result);
4625 } else {
4626 mEventThread->dump(result);
4627 }
4628}
4629
Yiwei Zhang5434a782018-12-05 18:06:32 -08004630void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4631 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004632 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4633 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004634 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004635 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004636 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004637 }
David Sodman4a36e932017-11-07 14:29:47 -08004638 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004639 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004640 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004641 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4642 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004643}
4644
Dan Stozae77c7662016-05-13 11:37:28 -07004645void SurfaceFlinger::recordBufferingStats(const char* layerName,
4646 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004647 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4648 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004649 for (const auto& segment : history) {
4650 if (!segment.usedThirdBuffer) {
4651 stats.twoBufferTime += segment.totalTime;
4652 }
4653 if (segment.occupancyAverage < 1.0f) {
4654 stats.doubleBufferedTime += segment.totalTime;
4655 } else if (segment.occupancyAverage < 2.0f) {
4656 stats.tripleBufferedTime += segment.totalTime;
4657 }
4658 ++stats.numSegments;
4659 stats.totalTime += segment.totalTime;
4660 }
4661}
4662
Yiwei Zhang5434a782018-12-05 18:06:32 -08004663void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4664 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004665
4666 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4667 const size_t count = currentLayers.size();
4668 for (size_t i=0 ; i<count ; i++) {
4669 currentLayers[i]->dumpFrameEvents(result);
4670 }
4671}
4672
Yiwei Zhang5434a782018-12-05 18:06:32 -08004673void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004674 result.append("Buffering stats:\n");
4675 result.append(" [Layer name] <Active time> <Two buffer> "
4676 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004677 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004678 typedef std::tuple<std::string, float, float, float> BufferTuple;
4679 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004680 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004681 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004682 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004683 if (stats.numSegments == 0) {
4684 continue;
4685 }
4686 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4687 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4688 stats.totalTime;
4689 float doubleBufferRatio = static_cast<float>(
4690 stats.doubleBufferedTime) / stats.totalTime;
4691 float tripleBufferRatio = static_cast<float>(
4692 stats.tripleBufferedTime) / stats.totalTime;
4693 sorted.insert({activeTime, {name, twoBufferRatio,
4694 doubleBufferRatio, tripleBufferRatio}});
4695 }
4696 for (const auto& sortedPair : sorted) {
4697 float activeTime = sortedPair.first;
4698 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004699 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4700 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004701 }
4702 result.append("\n");
4703}
4704
Yiwei Zhang5434a782018-12-05 18:06:32 -08004705void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004706 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004707 const auto displayId = display->getId();
4708 if (!displayId) {
4709 continue;
4710 }
4711 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004712 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004713 continue;
4714 }
4715
Yiwei Zhang5434a782018-12-05 18:06:32 -08004716 StringAppendF(&result,
4717 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4718 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004719 uint8_t port;
4720 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004721 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004722 result.append("no identification data\n");
4723 continue;
4724 }
4725
4726 if (!isEdid(data)) {
4727 result.append("unknown identification data: ");
4728 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004729 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004730 }
4731 result.append("\n");
4732 continue;
4733 }
4734
4735 const auto edid = parseEdid(data);
4736 if (!edid) {
4737 result.append("invalid EDID: ");
4738 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004739 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004740 }
4741 result.append("\n");
4742 continue;
4743 }
4744
Yiwei Zhang5434a782018-12-05 18:06:32 -08004745 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004746 result.append(edid->displayName.data(), edid->displayName.length());
4747 result.append("\"\n");
4748 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004749}
4750
Yiwei Zhang5434a782018-12-05 18:06:32 -08004751void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4752 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4753 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4754 StringAppendF(&result, "DisplayColorSetting: %s\n",
4755 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004756
4757 // TODO: print out if wide-color mode is active or not
4758
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004759 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004760 const auto displayId = display->getId();
4761 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004762 continue;
4763 }
4764
Yiwei Zhang5434a782018-12-05 18:06:32 -08004765 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004766 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004767 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004768 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004769 }
4770
Lloyd Pique32cbe282018-10-19 13:09:22 -07004771 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004772 StringAppendF(&result, " Current color mode: %s (%d)\n",
4773 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004774 }
4775 result.append("\n");
4776}
4777
Yiwei Zhang5434a782018-12-05 18:06:32 -08004778void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004779 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004780 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4781 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004782 continue;
4783 }
4784
Dominik Laskowski05275f12018-11-01 15:03:24 -07004785 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004786 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4787 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004788 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004789 compositionInfo.dump(result, nullptr);
4790 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004791 }
4792 }
David Sodman7e4ae112018-02-09 15:02:28 -08004793}
4794
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004795LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004796 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004797 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4798 const State& state = useDrawing ? mDrawingState : mCurrentState;
4799 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004800 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004801 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004802 });
4803
4804 return layersProto;
4805}
4806
Lloyd Pique32cbe282018-10-19 13:09:22 -07004807LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004808 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004809
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004810 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004811 resolution->set_w(displayDevice.getWidth());
4812 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004813
Lloyd Pique32cbe282018-10-19 13:09:22 -07004814 auto display = displayDevice.getCompositionDisplay();
4815 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004816
Lloyd Pique32cbe282018-10-19 13:09:22 -07004817 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4818 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4819 layersProto.set_global_transform(displayState.orientation);
4820
4821 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004822 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004823 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004824 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004825 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004826 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004827 }
4828 });
4829
4830 return layersProto;
4831}
4832
Dominik Laskowskic2867142019-01-21 11:33:38 -08004833void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4834 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004835 Colorizer colorizer(colorize);
4836
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004837 // figure out if we're stuck somewhere
4838 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004839 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004840 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4841
4842 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004843 * Dump library configuration.
4844 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004845
4846 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004847 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004848 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004849 appendSfConfigString(result);
4850 appendUiConfigString(result);
4851 appendGuiConfigString(result);
4852 result.append("\n");
4853
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004854 result.append("\nDisplay identification data:\n");
4855 dumpDisplayIdentificationData(result);
4856
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004857 result.append("\nWide-Color information:\n");
4858 dumpWideColorInfo(result);
4859
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004860 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004861 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004862 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004863 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004864 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004865
Andy McFadden41d67d72014-04-25 16:58:34 -07004866 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004867 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004868 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004869 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004870 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004871
Dan Stozab90cf072015-03-05 11:05:59 -08004872 dumpStaticScreenStats(result);
4873 result.append("\n");
4874
Yiwei Zhang5434a782018-12-05 18:06:32 -08004875 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004876
Dan Stozae77c7662016-05-13 11:37:28 -07004877 dumpBufferingStats(result);
4878
Andy McFadden4803b742012-09-24 19:07:20 -07004879 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004880 * Dump the visible layer list
4881 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004882 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004883 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4884 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4885 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004886 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004887
Chia-I Wu2f884132018-09-13 15:17:58 -07004888 {
4889 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4890 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004891 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004892 result.append("\n");
4893 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004894
David Sodman7e4ae112018-02-09 15:02:28 -08004895 result.append("\nFrame-Composition information:\n");
4896 dumpFrameCompositionInfo(result);
4897 result.append("\n");
4898
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004899 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004900 * Dump Display state
4901 */
4902
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004903 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004904 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004905 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004906 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004907 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004908 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004909 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004910
4911 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004912 * Dump SurfaceFlinger global state
4913 */
4914
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004915 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004916 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004917 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004918
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004919 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004920
Dominik Laskowski075d3172018-05-24 15:50:06 -07004921 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004922 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4923 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004924 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4925 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004926 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004927 StringAppendF(&result,
4928 " transaction-flags : %08x\n"
4929 " gpu_to_cpu_unsupported : %d\n",
4930 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004931
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004932 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004933 displayId && getHwComposer().isConnected(*displayId)) {
4934 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004935 StringAppendF(&result,
4936 " refresh-rate : %f fps\n"
4937 " x-dpi : %f\n"
4938 " y-dpi : %f\n",
4939 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4940 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004941 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004942
Yiwei Zhang5434a782018-12-05 18:06:32 -08004943 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004944
Dan Stozae22aec72016-08-01 13:20:59 -07004945 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004946 * Tracing state
4947 */
4948 mTracing.dump(result);
4949 result.append("\n");
4950
4951 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004952 * HWC layer minidump
4953 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004954 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004955 const auto displayId = display->getId();
4956 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004957 continue;
4958 }
4959
Yiwei Zhang5434a782018-12-05 18:06:32 -08004960 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004961 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004962 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004963 result.append("\n");
4964 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004965
4966 /*
4967 * Dump HWComposer state
4968 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004969 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004970 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004971 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004972 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004973 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004974 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004975
4976 /*
4977 * Dump gralloc state
4978 */
4979 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4980 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004981
4982 /*
4983 * Dump VrFlinger state if in use.
4984 */
4985 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4986 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004987 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004988 result.append("\n");
4989 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004990
4991 /**
4992 * Scheduler dump state.
4993 */
4994 if (mUseScheduler) {
4995 result.append("\nScheduler state:\n");
4996 result.append(mScheduler->doDump() + "\n");
4997 result.append(mRefreshRateStats->doDump() + "\n");
4998 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004999}
5000
Dominik Laskowski075d3172018-05-24 15:50:06 -07005001const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07005002 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005003 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07005004 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005005 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07005006 }
5007 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005008
Dominik Laskowski34157762018-10-31 13:07:19 -07005009 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005010 static const Vector<sp<Layer>> empty;
5011 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07005012}
5013
Chia-I Wu28f320b2018-05-03 11:02:56 -07005014void SurfaceFlinger::updateColorMatrixLocked() {
5015 mat4 colorMatrix;
5016 if (mGlobalSaturationFactor != 1.0f) {
5017 // Rec.709 luma coefficients
5018 float3 luminance{0.213f, 0.715f, 0.072f};
5019 luminance *= 1.0f - mGlobalSaturationFactor;
5020 mat4 saturationMatrix = mat4(
5021 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
5022 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
5023 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
5024 vec4{0.0f, 0.0f, 0.0f, 1.0f}
5025 );
5026 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
5027 } else {
5028 colorMatrix = mClientColorMatrix * mDaltonizer();
5029 }
5030
5031 if (mCurrentState.colorMatrix != colorMatrix) {
5032 mCurrentState.colorMatrix = colorMatrix;
5033 mCurrentState.colorMatrixChanged = true;
5034 setTransactionFlags(eTransactionNeeded);
5035 }
5036}
5037
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005038status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005039#pragma clang diagnostic push
5040#pragma clang diagnostic error "-Wswitch-enum"
5041 switch (static_cast<ISurfaceComposerTag>(code)) {
5042 // These methods should at minimum make sure that the client requested
5043 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005044 case BOOT_FINISHED:
5045 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005046 case CREATE_DISPLAY:
5047 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005048 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005049 case GET_ACTIVE_COLOR_MODE:
5050 case GET_ANIMATION_FRAME_STATS:
5051 case GET_HDR_CAPABILITIES:
5052 case SET_ACTIVE_CONFIG:
5053 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005054 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005055 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005056 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005057 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
5058 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005059 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5060 IPCThreadState* ipc = IPCThreadState::self();
5061 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5062 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005063 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005064 }
Robert Carr1db73f62016-12-21 12:58:51 -08005065 return OK;
5066 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005067 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005068 IPCThreadState* ipc = IPCThreadState::self();
5069 const int pid = ipc->getCallingPid();
5070 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005071 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5072 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005073 return PERMISSION_DENIED;
5074 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005075 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005076 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005077 // Used by apps to hook Choreographer to SurfaceFlinger.
5078 case CREATE_DISPLAY_EVENT_CONNECTION:
5079 // The following calls are currently used by clients that do not
5080 // request necessary permissions. However, they do not expose any secret
5081 // information, so it is OK to pass them.
5082 case AUTHENTICATE_SURFACE:
5083 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005084 case GET_PHYSICAL_DISPLAY_IDS:
5085 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005086 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005087 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005088 case GET_DISPLAY_CONFIGS:
5089 case GET_DISPLAY_STATS:
5090 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5091 // Calling setTransactionState is safe, because you need to have been
5092 // granted a reference to Client* and Handle* to do anything with it.
5093 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005094 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005095 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005096 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005097 case GET_PROTECTED_CONTENT_SUPPORT:
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08005098 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005099 return OK;
5100 }
5101 case CAPTURE_LAYERS:
5102 case CAPTURE_SCREEN: {
5103 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005104 IPCThreadState* ipc = IPCThreadState::self();
5105 const int pid = ipc->getCallingPid();
5106 const int uid = ipc->getCallingUid();
5107 if ((uid != AID_GRAPHICS) &&
5108 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5109 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5110 return PERMISSION_DENIED;
5111 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005112 return OK;
5113 }
5114 // The following codes are deprecated and should never be allowed to access SF.
5115 case CONNECT_DISPLAY_UNUSED:
5116 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5117 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5118 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005119 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005120 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005121
5122 // These codes are used for the IBinder protocol to either interrogate the recipient
5123 // side of the transaction for its canonical interface descriptor or to dump its state.
5124 // We let them pass by default.
5125 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5126 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5127 code == IBinder::SYSPROPS_TRANSACTION) {
5128 return OK;
5129 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005130 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005131 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005132 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005133 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5134 return OK;
5135 }
5136 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5137 return PERMISSION_DENIED;
5138#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005139}
5140
Ana Krulec13be8ad2018-08-21 02:43:56 +00005141status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5142 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005143 status_t credentialCheck = CheckTransactCodeCredentials(code);
5144 if (credentialCheck != OK) {
5145 return credentialCheck;
5146 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005147
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005148 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5149 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005150 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005151 IPCThreadState* ipc = IPCThreadState::self();
5152 const int uid = ipc->getCallingUid();
5153 if (CC_UNLIKELY(uid != AID_SYSTEM
5154 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005155 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005156 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005157 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005158 return PERMISSION_DENIED;
5159 }
5160 int n;
5161 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005162 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005163 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005164 return NO_ERROR;
5165 case 1002: // SHOW_UPDATES
5166 n = data.readInt32();
5167 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005168 invalidateHwcGeometry();
5169 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005170 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005171 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005172 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005173 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005174 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005175 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005176 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005177 setTransactionFlags(
5178 eTransactionNeeded|
5179 eDisplayTransactionNeeded|
5180 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005181 return NO_ERROR;
5182 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005183 case 1006:{ // send empty update
5184 signalRefresh();
5185 return NO_ERROR;
5186 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005187 case 1008: // toggle use of hw composer
5188 n = data.readInt32();
5189 mDebugDisableHWC = n ? 1 : 0;
5190 invalidateHwcGeometry();
5191 repaintEverything();
5192 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005193 case 1009: // toggle use of transform hint
5194 n = data.readInt32();
5195 mDebugDisableTransformHint = n ? 1 : 0;
5196 invalidateHwcGeometry();
5197 repaintEverything();
5198 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005199 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005200 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005201 reply->writeInt32(0);
5202 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005203 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005204 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005205 return NO_ERROR;
5206 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005207 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005208 if (!display) {
5209 return NAME_NOT_FOUND;
5210 }
5211
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005212 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005213 return NO_ERROR;
5214 }
5215 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005216 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005217 // daltonize
5218 n = data.readInt32();
5219 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005220 case 1:
5221 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5222 break;
5223 case 2:
5224 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5225 break;
5226 case 3:
5227 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5228 break;
5229 default:
5230 mDaltonizer.setType(ColorBlindnessType::None);
5231 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005232 }
5233 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005234 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005235 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005236 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005237 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005238
5239 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005240 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005241 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005242 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005243 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005244 // apply a color matrix
5245 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005246 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005247 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005248 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005249 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005250 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005251 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005252 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005253 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005254 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005255 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005256
5257 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5258 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005259 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005260 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5261 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5262 }
5263
Chia-I Wu28f320b2018-05-03 11:02:56 -07005264 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005265 return NO_ERROR;
5266 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005267 // This is an experimental interface
5268 // Needs to be shifted to proper binder interface when we productize
5269 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005270 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005271 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005272 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005273 return NO_ERROR;
5274 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005275 case 1017: {
5276 n = data.readInt32();
5277 mForceFullDamage = static_cast<bool>(n);
5278 return NO_ERROR;
5279 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005280 case 1018: { // Modify Choreographer's phase offset
5281 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005282 if (mUseScheduler) {
5283 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5284 } else {
5285 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5286 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005287 return NO_ERROR;
5288 }
5289 case 1019: { // Modify SurfaceFlinger's phase offset
5290 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005291 if (mUseScheduler) {
5292 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5293 } else {
5294 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5295 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005296 return NO_ERROR;
5297 }
Irvel468051e2016-06-13 16:44:44 -07005298 case 1020: { // Layer updates interceptor
5299 n = data.readInt32();
5300 if (n) {
5301 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005302 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005303 }
5304 else{
5305 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005306 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005307 }
5308 return NO_ERROR;
5309 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005310 case 1021: { // Disable HWC virtual displays
5311 n = data.readInt32();
5312 mUseHwcVirtualDisplays = !n;
5313 return NO_ERROR;
5314 }
Romain Guy0147a172017-06-01 13:53:56 -07005315 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005316 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005317 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005318
Chia-I Wu28f320b2018-05-03 11:02:56 -07005319 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005320 return NO_ERROR;
5321 }
Romain Guy54f154a2017-10-24 21:40:32 +01005322 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005323 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005324 invalidateHwcGeometry();
5325 repaintEverything();
5326 return NO_ERROR;
5327 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005328 // Deprecate, use 1030 to check whether the device is color managed.
5329 case 1024: {
5330 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005331 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005332 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005333 n = data.readInt32();
5334 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005335 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005336 mTracing.enable();
5337 doTracing("tracing.enable");
5338 reply->writeInt32(NO_ERROR);
5339 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005340 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005341 status_t err = mTracing.disable();
5342 reply->writeInt32(err);
5343 }
5344 return NO_ERROR;
5345 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005346 case 1026: { // Get layer tracing status
5347 reply->writeBool(mTracing.isEnabled());
5348 return NO_ERROR;
5349 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005350 // Is a DisplayColorSetting supported?
5351 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005352 const auto display = getDefaultDisplayDevice();
5353 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005354 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005355 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005356
5357 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5358 switch (setting) {
5359 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005360 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005361 break;
5362 case DisplayColorSetting::UNMANAGED:
5363 reply->writeBool(true);
5364 break;
5365 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005366 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005367 break;
5368 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005369 reply->writeBool(
5370 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005371 break;
5372 }
5373 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005374 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005375 // Is VrFlinger active?
5376 case 1028: {
5377 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005378 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005379 return NO_ERROR;
5380 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005381 // Is device color managed?
5382 case 1030: {
5383 reply->writeBool(useColorManagement);
5384 return NO_ERROR;
5385 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005386 // Override default composition data space
5387 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5388 // && adb shell stop zygote && adb shell start zygote
5389 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5390 // adb shell stop zygote && adb shell start zygote
5391 case 1031: {
5392 Mutex::Autolock _l(mStateLock);
5393 n = data.readInt32();
5394 if (n) {
5395 n = data.readInt32();
5396 if (n) {
5397 Dataspace dataspace = static_cast<Dataspace>(n);
5398 if (!validateCompositionDataspace(dataspace)) {
5399 return BAD_VALUE;
5400 }
5401 mDefaultCompositionDataspace = dataspace;
5402 }
5403 n = data.readInt32();
5404 if (n) {
5405 Dataspace dataspace = static_cast<Dataspace>(n);
5406 if (!validateCompositionDataspace(dataspace)) {
5407 return BAD_VALUE;
5408 }
5409 mWideColorGamutCompositionDataspace = dataspace;
5410 }
5411 } else {
5412 // restore composition data space.
5413 mDefaultCompositionDataspace = defaultCompositionDataspace;
5414 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5415 }
5416 return NO_ERROR;
5417 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005418 }
5419 }
5420 return err;
5421}
5422
Steven Thomas6d8110b2017-08-31 18:24:21 -07005423void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005424 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005425 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005426}
5427
Ana Krulec7d1d6832018-12-27 11:10:09 -08005428void SurfaceFlinger::repaintEverythingForHWC() {
5429 mRepaintEverything = true;
5430 mEventQueue->invalidateForHWC();
5431}
5432
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005433// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5434class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005435public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005436 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5437 ~WindowDisconnector() {
5438 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005439 }
5440
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005441private:
5442 ANativeWindow* mWindow;
5443 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005444};
5445
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005446status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005447 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5448 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005449 uint32_t reqWidth, uint32_t reqHeight,
5450 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005451 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005452 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005453
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005454 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005455
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005456 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5457
Chia-I Wu20261cb2018-08-23 12:55:44 -07005458 sp<DisplayDevice> display;
5459 {
5460 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005461
Chia-I Wu20261cb2018-08-23 12:55:44 -07005462 display = getDisplayDeviceLocked(displayToken);
5463 if (!display) return BAD_VALUE;
5464
Chia-I Wucb023152018-08-28 12:57:23 -07005465 // set the requested width/height to the logical display viewport size
5466 // by default
5467 if (reqWidth == 0 || reqHeight == 0) {
5468 reqWidth = uint32_t(display->getViewport().width());
5469 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005470 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005471 }
5472
Peiyong Lin0e003c92018-09-17 11:09:51 -07005473 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5474 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005475
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005476 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5477 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005478 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5479 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005480}
5481
5482status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005483 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5484 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005485 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005486 ATRACE_CALL();
5487
5488 class LayerRenderArea : public RenderArea {
5489 public:
Robert Carr578038f2018-03-09 12:25:24 -08005490 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005491 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5492 bool childrenOnly)
5493 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005494 mLayer(layer),
5495 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005496 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005497 mFlinger(flinger),
5498 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005499 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005500 Rect getBounds() const override {
5501 const Layer::State& layerState(mLayer->getDrawingState());
5502 return mLayer->getBufferSize(layerState);
5503 }
Marissa Wall61c58622018-07-18 10:12:20 -07005504 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005505 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005506 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005507 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005508 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005509 }
chaviwa76b2712017-09-20 12:02:26 -07005510 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005511 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005512 Rect getSourceCrop() const override {
5513 if (mCrop.isEmpty()) {
5514 return getBounds();
5515 } else {
5516 return mCrop;
5517 }
5518 }
Robert Carr578038f2018-03-09 12:25:24 -08005519 class ReparentForDrawing {
5520 public:
5521 const sp<Layer>& oldParent;
5522 const sp<Layer>& newParent;
5523
5524 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5525 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005526 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005527 }
Robert Carr15eae092018-03-23 13:43:53 -07005528 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005529 };
5530
5531 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005532 const Rect sourceCrop = getSourceCrop();
5533 // no need to check rotation because there is none
5534 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5535 sourceCrop.height() != getReqHeight();
5536
Robert Carr578038f2018-03-09 12:25:24 -08005537 if (!mChildrenOnly) {
5538 mTransform = mLayer->getTransform().inverse();
5539 drawLayers();
5540 } else {
5541 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005542 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005543 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5544 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005545
5546 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5547 drawLayers();
5548 }
5549 }
chaviwa76b2712017-09-20 12:02:26 -07005550
chaviwa76b2712017-09-20 12:02:26 -07005551 private:
chaviw7206d492017-11-10 16:16:12 -08005552 const sp<Layer> mLayer;
5553 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005554
5555 // In the "childrenOnly" case we reparent the children to a screenshot
5556 // layer which has no properties set and which does not draw.
5557 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005558 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005559 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005560
5561 SurfaceFlinger* mFlinger;
5562 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005563 };
5564
5565 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5566 auto parent = layerHandle->owner.promote();
5567
Robert Carr2e102c92018-10-23 12:11:15 -07005568 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005569 ALOGE("captureLayers called with a removed parent");
5570 return NAME_NOT_FOUND;
5571 }
5572
Robert Carr578038f2018-03-09 12:25:24 -08005573 const int uid = IPCThreadState::self()->getCallingUid();
5574 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005575 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005576 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5577 return PERMISSION_DENIED;
5578 }
5579
chaviw7206d492017-11-10 16:16:12 -08005580 Rect crop(sourceCrop);
5581 if (sourceCrop.width() <= 0) {
5582 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005583 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005584 }
5585
5586 if (sourceCrop.height() <= 0) {
5587 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005588 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005589 }
5590
5591 int32_t reqWidth = crop.width() * frameScale;
5592 int32_t reqHeight = crop.height() * frameScale;
5593
Chia-I Wu20261cb2018-08-23 12:55:44 -07005594 // really small crop or frameScale
5595 if (reqWidth <= 0) {
5596 reqWidth = 1;
5597 }
5598 if (reqHeight <= 0) {
5599 reqHeight = 1;
5600 }
5601
Peiyong Lin0e003c92018-09-17 11:09:51 -07005602 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005603
Robert Carr578038f2018-03-09 12:25:24 -08005604 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005605 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5606 if (!layer->isVisible()) {
5607 return;
Robert Carr578038f2018-03-09 12:25:24 -08005608 } else if (childrenOnly && layer == parent.get()) {
5609 return;
chaviwa76b2712017-09-20 12:02:26 -07005610 }
5611 visitor(layer);
5612 });
5613 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005614 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005615}
5616
5617status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5618 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005619 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005620 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005621 bool useIdentityTransform) {
5622 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005623
Peiyong Lin0e003c92018-09-17 11:09:51 -07005624 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005625 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5626 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005627 *outBuffer =
5628 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5629 static_cast<android_pixel_format>(reqPixelFormat), 1,
5630 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005631
5632 // This mutex protects syncFd and captureResult for communication of the return values from the
5633 // main thread back to this Binder thread
5634 std::mutex captureMutex;
5635 std::condition_variable captureCondition;
5636 std::unique_lock<std::mutex> captureLock(captureMutex);
5637 int syncFd = -1;
5638 std::optional<status_t> captureResult;
5639
Robert Carr03480e22018-01-04 16:02:06 -08005640 const int uid = IPCThreadState::self()->getCallingUid();
5641 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5642
Dominik Laskowski8c001672018-05-30 16:52:06 -07005643 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005644 // If there is a refresh pending, bug out early and tell the binder thread to try again
5645 // after the refresh.
5646 if (mRefreshPending) {
5647 ATRACE_NAME("Skipping screenshot for now");
5648 std::unique_lock<std::mutex> captureLock(captureMutex);
5649 captureResult = std::make_optional<status_t>(EAGAIN);
5650 captureCondition.notify_one();
5651 return;
5652 }
5653
5654 status_t result = NO_ERROR;
5655 int fd = -1;
5656 {
5657 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005658 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005659 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5660 useIdentityTransform, forSystem, &fd);
5661 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005662 }
5663
5664 {
5665 std::unique_lock<std::mutex> captureLock(captureMutex);
5666 syncFd = fd;
5667 captureResult = std::make_optional<status_t>(result);
5668 captureCondition.notify_one();
5669 }
5670 });
5671
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005672 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005673 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005674 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005675 while (*captureResult == EAGAIN) {
5676 captureResult.reset();
5677 result = postMessageAsync(message);
5678 if (result != NO_ERROR) {
5679 return result;
5680 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005681 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005682 }
5683 result = *captureResult;
5684 }
5685
5686 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005687 sync_wait(syncFd, -1);
5688 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005689 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005690
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005691 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005692}
5693
chaviwa76b2712017-09-20 12:02:26 -07005694void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005695 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005696 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5697 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005698 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005699
chaviwa76b2712017-09-20 12:02:26 -07005700 const auto reqWidth = renderArea.getReqWidth();
5701 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005702 const auto sourceCrop = renderArea.getSourceCrop();
5703 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005704
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005705 renderengine::DisplaySettings clientCompositionDisplay;
5706 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005707
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005708 // assume that bounds are never offset, and that they are the same as the
5709 // buffer bounds.
5710 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5711 ui::Transform transform = renderArea.getTransform();
5712 mat4 m;
5713 m[0][0] = transform[0][0];
5714 m[0][1] = transform[0][1];
5715 m[0][3] = transform[0][2];
5716 m[1][0] = transform[1][0];
5717 m[1][1] = transform[1][1];
5718 m[1][3] = transform[1][2];
5719 m[3][0] = transform[2][0];
5720 m[3][1] = transform[2][1];
5721 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005722
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005723 clientCompositionDisplay.globalTransform = m;
5724 mat4 rotMatrix;
5725 // Displacement for repositioning the clipping rectangle after rotating it
5726 // with the rotation hint.
5727 int displacementX = 0;
5728 int displacementY = 0;
5729 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5730 switch (rotation) {
5731 case ui::Transform::ROT_90:
5732 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5733 displacementX = reqWidth;
5734 break;
5735 case ui::Transform::ROT_180:
5736 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5737 displacementX = reqWidth;
5738 displacementY = reqHeight;
5739 break;
5740 case ui::Transform::ROT_270:
5741 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5742 displacementY = reqHeight;
5743 break;
5744 default:
5745 break;
5746 }
5747 // We need to transform the clipping window into the right spot.
5748 // First, rotate the clipping rectangle by the rotation hint to get the
5749 // right orientation
5750 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5751 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5752 const vec4 rotClipTL = rotMatrix * clipTL;
5753 const vec4 rotClipBR = rotMatrix * clipBR;
5754 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5755 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5756 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5757 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5758
5759 // Now reposition the clipping rectangle with the displacement vector
5760 // computed above.
5761 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5762
5763 clientCompositionDisplay.clip =
5764 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5765 newClipRight + displacementX, newClipBottom + displacementY);
5766
5767 // We need to perform the same transformation in layer space, so propagate
5768 // it to the global transform.
5769 mat4 clipTransform = displacementMat * rotMatrix;
5770 clientCompositionDisplay.globalTransform *= clipTransform;
5771 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5772 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005773
chaviw50da5042018-04-09 13:49:37 -07005774 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005775
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005776 renderengine::LayerSettings fillLayer;
5777 fillLayer.source.buffer.buffer = nullptr;
5778 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5779 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5780 fillLayer.alpha = half(alpha);
5781 clientCompositionLayers.push_back(fillLayer);
5782
5783 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005784 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005785 renderengine::LayerSettings layerSettings;
5786 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5787 layerSettings);
5788 if (prepared) {
5789 clientCompositionLayers.push_back(layerSettings);
5790 }
chaviwa76b2712017-09-20 12:02:26 -07005791 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005792
5793 clientCompositionDisplay.clearRegion = clearRegion;
5794 base::unique_fd drawFence;
5795 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
5796 &drawFence);
5797
5798 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005799}
5800
chaviwa76b2712017-09-20 12:02:26 -07005801status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5802 TraverseLayersFunction traverseLayers,
5803 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005804 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005805 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005806 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005807 ATRACE_CALL();
5808
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005809 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005810
5811 traverseLayers([&](Layer* layer) {
5812 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5813 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005814
Robert Carr03480e22018-01-04 16:02:06 -08005815 // We allow the system server to take screenshots of secure layers for
5816 // use in situations like the Screen-rotation animation and place
5817 // the impetus on WindowManager to not persist them.
5818 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005819 ALOGW("FB is protected: PERMISSION_DENIED");
5820 return PERMISSION_DENIED;
5821 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005822 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005823 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005824}
5825
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005826// ---------------------------------------------------------------------------
5827
Dan Stoza412903f2017-04-27 13:42:17 -07005828void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5829 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005830}
5831
Dan Stoza412903f2017-04-27 13:42:17 -07005832void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5833 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005834}
5835
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005836void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005837 const LayerVector::Visitor& visitor) {
5838 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005839 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005840 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005841 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005842 continue;
5843 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005844 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005845 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005846 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005847 return;
5848 }
chaviwa76b2712017-09-20 12:02:26 -07005849 if (!layer->isVisible()) {
5850 return;
5851 }
5852 visitor(layer);
5853 });
5854 }
5855}
5856
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005857}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005858
Lloyd Pique074e8122018-07-26 12:57:23 -07005859
Mathias Agopian3f844832013-08-07 21:24:32 -07005860#if defined(__gl_h_)
5861#error "don't include gl/gl.h in this file"
5862#endif
5863
5864#if defined(__gl2_h_)
5865#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005866#endif