blob: bd28978bb2e609365fcb6858712ca7e7cee21605 [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
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Chia-I Wud49d6692018-06-27 07:17:41 +080040#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070050#include <renderengine/RenderEngine.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070051#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Robert Carr578038f2018-03-09 12:25:24 -080065#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070066#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070067#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020070#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080072#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080073#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070077#include "NativeWindowSurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070081#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070082#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070083#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070084#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070086#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070087#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070088#include "Scheduler/EventControlThread.h"
89#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070090#include "Scheduler/InjectVSyncSource.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070091#include "Scheduler/Scheduler.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070092
Mathias Agopianff2ed702013-09-01 21:36:12 -070093#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070094
David Sodman7e4ae112018-02-09 15:02:28 -080095#include "android-base/stringprintf.h"
96
Jiyong Park4b20c2e2017-01-14 19:45:11 +090097#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080098#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -070099#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800100#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900101#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900102
chaviw1d044282017-09-27 12:19:28 -0700103#include <layerproto/LayerProtoParser.h>
104
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800105#define DISPLAY_COUNT 1
106
107namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700108
Jaesoo Lee43518572017-01-23 19:03:16 +0900109using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900110using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700111using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700112using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700113using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700114using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900115
Steven Thomasb02664d2017-07-26 18:48:28 -0700116namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700117
118#pragma clang diagnostic push
119#pragma clang diagnostic error "-Wswitch-enum"
120
121bool isWideColorMode(const ColorMode colorMode) {
122 switch (colorMode) {
123 case ColorMode::DISPLAY_P3:
124 case ColorMode::ADOBE_RGB:
125 case ColorMode::DCI_P3:
126 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700127 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700128 case ColorMode::BT2100_PQ:
129 case ColorMode::BT2100_HLG:
130 return true;
131 case ColorMode::NATIVE:
132 case ColorMode::STANDARD_BT601_625:
133 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
134 case ColorMode::STANDARD_BT601_525:
135 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
136 case ColorMode::STANDARD_BT709:
137 case ColorMode::SRGB:
138 return false;
139 }
140 return false;
141}
142
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700143ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
144 switch (rotation) {
145 case ISurfaceComposer::eRotateNone:
146 return ui::Transform::ROT_0;
147 case ISurfaceComposer::eRotate90:
148 return ui::Transform::ROT_90;
149 case ISurfaceComposer::eRotate180:
150 return ui::Transform::ROT_180;
151 case ISurfaceComposer::eRotate270:
152 return ui::Transform::ROT_270;
153 }
154 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
155 return ui::Transform::ROT_0;
156}
157
Peiyong Linfca547f2018-07-09 13:03:33 -0700158#pragma clang diagnostic pop
159
Steven Thomasb02664d2017-07-26 18:48:28 -0700160class ConditionalLock {
161public:
162 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
163 if (lock) {
164 mMutex.lock();
165 }
166 }
167 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
168private:
169 Mutex& mMutex;
170 bool mLocked;
171};
Peiyong Linfca547f2018-07-09 13:03:33 -0700172
Steven Thomasb02664d2017-07-26 18:48:28 -0700173} // namespace anonymous
174
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800175// ---------------------------------------------------------------------------
176
Mathias Agopian99b49842011-06-27 16:05:52 -0700177const String16 sHardwareTest("android.permission.HARDWARE_TEST");
178const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
179const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
180const String16 sDump("android.permission.DUMP");
181
182// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800183int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
184int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700185int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700186bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800187uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800188bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800189bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800190int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800191// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600192bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700193int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700194bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700195bool SurfaceFlinger::useContextPriority;
Peiyong Lin0256f722018-08-31 15:45:10 -0700196Dataspace SurfaceFlinger::compositionDataSpace = Dataspace::V0_SRGB;
197ui::PixelFormat SurfaceFlinger::compositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700198
Kalle Raitaa099a242017-01-11 11:17:29 -0800199std::string getHwcServiceName() {
200 char value[PROPERTY_VALUE_MAX] = {};
201 property_get("debug.sf.hwc_service_name", value, "default");
202 ALOGI("Using HWComposer service: '%s'", value);
203 return std::string(value);
204}
205
206bool useTrebleTestingOverride() {
207 char value[PROPERTY_VALUE_MAX] = {};
208 property_get("debug.sf.treble_testing_override", value, "false");
209 ALOGI("Treble testing override: '%s'", value);
210 return std::string(value) == "true";
211}
212
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800213std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
214 switch(displayColorSetting) {
215 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700216 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800217 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700218 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800219 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700220 return std::string("Enhanced");
221 default:
222 return std::string("Unknown ") +
223 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800224 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800225}
226
David Sodmanbc815282017-11-05 18:57:52 -0800227SurfaceFlingerBE::SurfaceFlingerBE()
228 : mHwcServiceName(getHwcServiceName()),
229 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800230 mFrameBuckets(),
231 mTotalTime(0),
232 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800233 mComposerSequenceId(0) {
234}
235
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800236SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800237 : BnSurfaceComposer(),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700238 mTransactionPending(false),
239 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700240 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700241 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800242 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700243 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800244 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800245 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800246 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800247 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800248 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700249 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700250 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700251 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700252 mDebugInTransaction(0),
253 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700254 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700255 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700256 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800257 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800258 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800259 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700260 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800261 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800262 mCreateBufferQueue(&BufferQueue::createBufferQueue),
Lloyd Pique22098362018-09-13 11:46:49 -0700263 mCreateNativeWindowSurface(&surfaceflinger::impl::createNativeWindowSurface) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800264
265SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800266 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800267
268 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
269 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
270
271 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
272 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
273
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800274 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
275 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700277 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
278 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
279
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700280 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
281 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
282
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800283 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
284 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
285
Steven Thomas050b2c82017-03-06 11:45:16 -0800286 // Vr flinger is only enabled on Daydream ready devices.
287 useVrFlinger = getBool< ISurfaceFlingerConfigs,
288 &ISurfaceFlingerConfigs::useVrFlinger>(false);
289
Fabien Sanglard1971b632017-03-10 14:50:03 -0800290 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
291 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
292
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600293 hasWideColorDisplay =
294 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700295 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700296 getBool<V1_2::ISurfaceFlingerConfigs,
297 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
298
299 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
300 if (surfaceFlingerConfigsServiceV1_2) {
301 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
302 [&](Dataspace tmpDataSpace, ui::PixelFormat tmpPixelFormat) {
303 compositionDataSpace = tmpDataSpace;
304 compositionPixelFormat = tmpPixelFormat;
305 });
306 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600307
Peiyong Linb3839ad2018-09-05 15:37:19 -0700308 useContextPriority = getBool<ISurfaceFlingerConfigs,
309 &ISurfaceFlingerConfigs::useContextPriority>(true);
310
Iris Chang7501ed62018-04-30 14:45:42 +0800311 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700312 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
313 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800314 V1_1::DisplayOrientation::ORIENTATION_0);
315
316 switch (primaryDisplayOrientation) {
317 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700318 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800319 break;
320 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700321 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800322 break;
323 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700324 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800325 break;
326 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700327 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800328 break;
329 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700330 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800331
Lloyd Pique41be5d22018-06-21 13:11:48 -0700332 // Note: We create a local temporary with the real DispSync implementation
333 // type temporarily so we can initialize it with the configured values,
334 // before storing it for more generic use using the interface type.
335 auto primaryDispSync = std::make_unique<impl::DispSync>("PrimaryDispSync");
336 primaryDispSync->init(SurfaceFlinger::hasSyncFramework,
337 SurfaceFlinger::dispSyncPresentTimeOffset);
338 mPrimaryDispSync = std::move(primaryDispSync);
Saurabh Shahf4174532017-07-13 10:45:07 -0700339
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800340 // debugging stuff...
341 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700342
Mathias Agopianb4b17302013-03-20 18:36:41 -0700343 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700344 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700345
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800346 property_get("debug.sf.showupdates", value, "0");
347 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700348
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700349 property_get("debug.sf.ddms", value, "0");
350 mDebugDDMS = atoi(value);
351 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700352 if (!startDdmConnection()) {
353 // start failed, and DDMS debugging not enabled
354 mDebugDDMS = 0;
355 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700356 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700357 ALOGI_IF(mDebugRegion, "showupdates enabled");
358 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700359
360 property_get("debug.sf.disable_backpressure", value, "0");
361 mPropagateBackpressure = !atoi(value);
362 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700363
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800364 property_get("debug.sf.enable_hwc_vds", value, "0");
365 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800366 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800367
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800368 property_get("ro.sf.disable_triple_buffer", value, "1");
369 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800370 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700371
Yiwei Zhang243b3782018-05-15 17:40:04 -0700372 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700373 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
374 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
375
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200376 property_get("debug.sf.early_phase_offset_ns", value, "-1");
377 const int earlySfOffsetNs = atoi(value);
378
379 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
380 const int earlyGlSfOffsetNs = atoi(value);
381
382 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
383 const int earlyAppOffsetNs = atoi(value);
384
385 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
386 const int earlyGlAppOffsetNs = atoi(value);
387
Ana Krulec98b5b242018-08-10 15:03:23 -0700388 property_get("debug.sf.use_scheduler", value, "0");
389 mUseScheduler = atoi(value);
390
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200391 const VSyncModulator::Offsets earlyOffsets =
392 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
393 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
394 const VSyncModulator::Offsets earlyGlOffsets =
395 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
396 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
397 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
398 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700399
Romain Guy11d63f42017-07-20 12:47:14 -0700400 // We should be reading 'persist.sys.sf.color_saturation' here
401 // but since /data may be encrypted, we need to wait until after vold
402 // comes online to attempt to read the property. The property is
403 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800404
405 if (useTrebleTestingOverride()) {
406 // Without the override SurfaceFlinger cannot connect to HIDL
407 // services that are not listed in the manifests. Considered
408 // deriving the setting from the set service name, but it
409 // would be brittle if the name that's not 'default' is used
410 // for production purposes later on.
411 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
412 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800413}
414
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800415void SurfaceFlinger::onFirstRef()
416{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800417 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800418}
419
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800420SurfaceFlinger::~SurfaceFlinger()
421{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800422}
423
Dan Stozac7014012014-02-14 15:03:43 -0800424void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800425{
426 // the window manager died on us. prepare its eulogy.
427
Andy McFadden13a082e2012-08-24 10:16:42 -0700428 // restore initial conditions (default device unblank, etc)
429 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800430
431 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700432 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800433}
434
Robert Carr1db73f62016-12-21 12:58:51 -0800435static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700436 status_t err = client->initCheck();
437 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800438 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800439 }
Robert Carr1db73f62016-12-21 12:58:51 -0800440 return nullptr;
441}
442
443sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
444 return initClient(new Client(this));
445}
446
447sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
448 const sp<IGraphicBufferProducer>& gbp) {
449 if (authenticateSurfaceTexture(gbp) == false) {
450 return nullptr;
451 }
452 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
453 if (layer == nullptr) {
454 return nullptr;
455 }
456
457 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800458}
459
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700460sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
461 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700462{
463 class DisplayToken : public BBinder {
464 sp<SurfaceFlinger> flinger;
465 virtual ~DisplayToken() {
466 // no more references, this display must be terminated
467 Mutex::Autolock _l(flinger->mStateLock);
468 flinger->mCurrentState.displays.removeItem(this);
469 flinger->setTransactionFlags(eDisplayTransactionNeeded);
470 }
471 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700472 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700473 : flinger(flinger) {
474 }
475 };
476
477 sp<BBinder> token = new DisplayToken(this);
478
479 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700480 DisplayDeviceState info;
481 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700482 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700483 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700484 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800485 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700486 return token;
487}
488
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700489void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700490 Mutex::Autolock _l(mStateLock);
491
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700492 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700493 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700494 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700495 return;
496 }
497
498 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700499 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700500 ALOGE("destroyDisplay called for non-virtual display");
501 return;
502 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700503 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700504 mCurrentState.displays.removeItemsAt(idx);
505 setTransactionFlags(eDisplayTransactionNeeded);
506}
507
Mathias Agopiane57f2922012-08-09 16:29:12 -0700508sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700509 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700510 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800511 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700512 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700513 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700514}
515
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800516void SurfaceFlinger::bootFinished()
517{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700518 if (mStartPropertySetThread->join() != NO_ERROR) {
519 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800520 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800521 const nsecs_t now = systemTime();
522 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000523 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700524
525 // wait patiently for the window manager death
526 const String16 name("window");
527 sp<IBinder> window(defaultServiceManager()->getService(name));
528 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700529 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700530 }
531
Steven Thomas050b2c82017-03-06 11:45:16 -0800532 if (mVrFlinger) {
533 mVrFlinger->OnBootFinished();
534 }
535
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700536 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700537 // formerly we would just kill the process, but we now ask it to exit so it
538 // can choose where to stop the animation.
539 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700540
541 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
542 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
543 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700544
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800545 postMessageAsync(new LambdaMessage([this] {
546 readPersistentProperties();
547 mBootStage = BootStage::FINISHED;
548 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800549}
550
Dan Stoza436ccf32018-06-21 12:10:12 -0700551uint32_t SurfaceFlinger::getNewTexture() {
552 {
553 std::lock_guard lock(mTexturePoolMutex);
554 if (!mTexturePool.empty()) {
555 uint32_t name = mTexturePool.back();
556 mTexturePool.pop_back();
557 ATRACE_INT("TexturePoolSize", mTexturePool.size());
558 return name;
559 }
560
561 // The pool was too small, so increase it for the future
562 ++mTexturePoolSize;
563 }
564
565 // The pool was empty, so we need to get a new texture name directly using a
566 // blocking call to the main thread
567 uint32_t name = 0;
568 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
569 return name;
570}
571
Mathias Agopian3f844832013-08-07 21:24:32 -0700572void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700573 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700574}
575
Wei Wangf9b05ee2017-07-19 20:59:39 -0700576// Do not call property_set on main thread which will be blocked by init
577// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700578void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700579 ALOGI( "SurfaceFlinger's main thread ready to run. "
580 "Initializing graphics H/W...");
581
Thierry Strudel2924d012017-08-14 15:19:37 -0700582 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900583
Steven Thomasb02664d2017-07-26 18:48:28 -0700584 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800585
Steven Thomasb02664d2017-07-26 18:48:28 -0700586 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700587 if (mUseScheduler) {
Ana Krulece588e312018-09-18 12:32:24 -0700588 mScheduler = std::make_unique<Scheduler>(
589 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Ana Krulec98b5b242018-08-10 15:03:23 -0700590 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700591 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700592 [this] { resyncWithRateLimit(); },
593 impl::EventThread::InterceptVSyncsCallback());
594 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700595 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700596 [this] { resyncWithRateLimit(); },
597 [this](nsecs_t timestamp) {
598 mInterceptor->saveVSyncEvent(timestamp);
599 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800600
Ana Krulec98b5b242018-08-10 15:03:23 -0700601 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700602 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
603 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700604 } else {
605 mEventThreadSource =
606 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
607 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
608 mEventThread =
609 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
610 [this] { resyncWithRateLimit(); },
611 impl::EventThread::InterceptVSyncsCallback(),
612 "appEventThread");
613 mSfEventThreadSource =
614 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
615 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
616
617 mSFEventThread =
618 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
619 [this] { resyncWithRateLimit(); },
620 [this](nsecs_t timestamp) {
621 mInterceptor->saveVSyncEvent(timestamp);
622 },
623 "sfEventThread");
624 mEventQueue->setEventThread(mSFEventThread.get());
625 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
626 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800627
Steven Thomasb02664d2017-07-26 18:48:28 -0700628 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700629 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700630 renderEngineFeature |= (useColorManagement ?
631 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700632 renderEngineFeature |= (useContextPriority ?
633 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700634
635 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
636 getBE().mRenderEngine =
Peiyong Linf11f39b2018-09-05 14:37:41 -0700637 renderengine::RenderEngine::create(static_cast<int32_t>(compositionPixelFormat),
638 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800639 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700640
641 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
642 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800643 getBE().mHwc.reset(
644 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700645 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800646 // Process any initial hotplug and resulting display changes.
647 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700648 const auto display = getDefaultDisplayDeviceLocked();
649 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
650 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
651 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800652
Lloyd Piquefcd86612017-12-14 17:15:36 -0800653 // make the default display GLContext current so that we can create textures
654 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700655 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800656
Steven Thomas050b2c82017-03-06 11:45:16 -0800657 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700658 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700659 // This callback is called from the vr flinger dispatch thread. We
660 // need to call signalTransaction(), which requires holding
661 // mStateLock when we're not on the main thread. Acquiring
662 // mStateLock from the vr flinger dispatch thread might trigger a
663 // deadlock in surface flinger (see b/66916578), so post a message
664 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700665 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700666 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
667 mVrFlingerRequestsDisplay = requestDisplay;
668 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700669 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800670 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700671 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
672 getHwComposer()
673 .getHwcDisplayId(display->getId())
674 .value_or(0),
675 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800676 if (!mVrFlinger) {
677 ALOGE("Failed to start vrflinger");
678 }
679 }
680
Lloyd Pique379adc12018-01-22 17:31:47 -0800681 mEventControlThread = std::make_unique<impl::EventControlThread>(
682 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700683
Mathias Agopian92a979a2012-08-02 18:32:23 -0700684 // initialize our drawing state
685 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700686
Andy McFadden13a082e2012-08-24 10:16:42 -0700687 // set initial conditions (e.g. unblank default device)
688 initializeDisplays();
689
David Sodmanbc815282017-11-05 18:57:52 -0800690 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700691
Wei Wangf9b05ee2017-07-19 20:59:39 -0700692 // Inform native graphics APIs whether the present timestamp is supported:
693 if (getHwComposer().hasCapability(
694 HWC2::Capability::PresentFenceIsNotReliable)) {
695 mStartPropertySetThread = new StartPropertySetThread(false);
696 } else {
697 mStartPropertySetThread = new StartPropertySetThread(true);
698 }
699
700 if (mStartPropertySetThread->Start() != NO_ERROR) {
701 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800702 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800703
Chia-I Wud49d6692018-06-27 07:17:41 +0800704 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
705 // is used to saturate legacy sRGB content. However, to make sure the same color under
706 // Display P3 will be saturated to the same color, we intentionally break the API spec
707 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
708 // such saturation matrix on Display P3 is understood fully, the API should always return
709 // identify matrix.
710 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
711 Dataspace::SRGB_LINEAR);
712
713 // we will apply this on Display P3.
714 if (mEnhancedSaturationMatrix != mat4()) {
715 ColorSpace srgb(ColorSpace::sRGB());
716 ColorSpace displayP3(ColorSpace::DisplayP3());
717 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
718 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
719 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
720 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800721
Dan Stoza9e56aa02015-11-02 13:00:03 -0800722 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700723}
724
Romain Guy11d63f42017-07-20 12:47:14 -0700725void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700726 Mutex::Autolock _l(mStateLock);
727
Romain Guy11d63f42017-07-20 12:47:14 -0700728 char value[PROPERTY_VALUE_MAX];
729
730 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800731 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700732 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800733 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100734
735 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700736 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700737}
738
Mathias Agopiana67e4182012-06-19 17:26:12 -0700739void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800740 // Start boot animation service by setting a property mailbox
741 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700742 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800743 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700744 if (mStartPropertySetThread->join() != NO_ERROR) {
745 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800746 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700747}
748
Mathias Agopian875d8e12013-06-07 15:35:48 -0700749size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800750 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700751}
752
Mathias Agopian875d8e12013-06-07 15:35:48 -0700753size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800754 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700755}
756
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800757// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800758
Jamie Gennis582270d2011-08-17 18:19:00 -0700759bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800760 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800761 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800762 return authenticateSurfaceTextureLocked(bufferProducer);
763}
764
765bool SurfaceFlinger::authenticateSurfaceTextureLocked(
766 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800767 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800768 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800769}
770
Brian Anderson6b376712017-04-04 10:51:39 -0700771status_t SurfaceFlinger::getSupportedFrameTimestamps(
772 std::vector<FrameEvent>* outSupported) const {
773 *outSupported = {
774 FrameEvent::REQUESTED_PRESENT,
775 FrameEvent::ACQUIRE,
776 FrameEvent::LATCH,
777 FrameEvent::FIRST_REFRESH_START,
778 FrameEvent::LAST_REFRESH_START,
779 FrameEvent::GPU_COMPOSITION_DONE,
780 FrameEvent::DEQUEUE_READY,
781 FrameEvent::RELEASE,
782 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700783 ConditionalLock _l(mStateLock,
784 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700785 if (!getHwComposer().hasCapability(
786 HWC2::Capability::PresentFenceIsNotReliable)) {
787 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
788 }
789 return NO_ERROR;
790}
791
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700792status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
793 Vector<DisplayInfo>* configs) {
794 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700795 return BAD_VALUE;
796 }
797
Jesse Hall692c7232012-11-08 15:41:56 -0800798 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700799 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
800 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700801 type = i;
802 break;
803 }
804 }
805
806 if (type < 0) {
807 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700808 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700809
Mathias Agopian8b736f12012-08-13 17:54:26 -0700810 // TODO: Not sure if display density should handled by SF any longer
811 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700812 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700813 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700814 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800815 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700816 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700817 }
818 return density;
819 }
820 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700821 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700822 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700823 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700824 return getDensityFromProperty("ro.sf.lcd_density"); }
825 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700826
Dan Stoza7f7da322014-05-02 15:26:25 -0700827 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700828
Steven Thomas6d8110b2017-08-31 18:24:21 -0700829 ConditionalLock _l(mStateLock,
830 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800831 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700832 DisplayInfo info = DisplayInfo();
833
Dan Stoza9e56aa02015-11-02 13:00:03 -0800834 float xdpi = hwConfig->getDpiX();
835 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700836
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700837 info.w = hwConfig->getWidth();
838 info.h = hwConfig->getHeight();
839 // Default display viewport to display width and height
840 info.viewportW = info.w;
841 info.viewportH = info.h;
842
Dan Stoza7f7da322014-05-02 15:26:25 -0700843 if (type == DisplayDevice::DISPLAY_PRIMARY) {
844 // The density of the device is provided by a build property
845 float density = Density::getBuildDensity() / 160.0f;
846 if (density == 0) {
847 // the build doesn't provide a density -- this is wrong!
848 // use xdpi instead
849 ALOGE("ro.sf.lcd_density must be defined as a build property");
850 density = xdpi / 160.0f;
851 }
852 if (Density::getEmuDensity()) {
853 // if "qemu.sf.lcd_density" is specified, it overrides everything
854 xdpi = ydpi = density = Density::getEmuDensity();
855 density /= 160.0f;
856 }
857 info.density = density;
858
859 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700860 const auto display = getDefaultDisplayDeviceLocked();
861 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700862
863 // This is for screenrecord
864 const Rect viewport = display->getViewport();
865 if (viewport.isValid()) {
866 info.viewportW = uint32_t(viewport.getWidth());
867 info.viewportH = uint32_t(viewport.getHeight());
868 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700869 } else {
870 // TODO: where should this value come from?
871 static const int TV_DENSITY = 213;
872 info.density = TV_DENSITY / 160.0f;
873 info.orientation = 0;
874 }
875
Dan Stoza7f7da322014-05-02 15:26:25 -0700876 info.xdpi = xdpi;
877 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800878 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900879 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800880
Andy McFadden91b2ca82014-06-13 14:04:23 -0700881 // This is how far in advance a buffer must be queued for
882 // presentation at a given time. If you want a buffer to appear
883 // on the screen at time N, you must submit the buffer before
884 // (N - presentationDeadline).
885 //
886 // Normally it's one full refresh period (to give SF a chance to
887 // latch the buffer), but this can be reduced by configuring a
888 // DispSync offset. Any additional delays introduced by the hardware
889 // composer or panel must be accounted for here.
890 //
891 // We add an additional 1ms to allow for processing time and
892 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800893 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800894 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700895
896 // All non-virtual displays are currently considered secure.
897 info.secure = true;
898
Iris Chang7501ed62018-04-30 14:45:42 +0800899 if (type == DisplayDevice::DISPLAY_PRIMARY &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700900 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800901 std::swap(info.w, info.h);
902 }
903
Michael Wright28f24d02016-07-12 13:30:53 -0700904 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700905 }
906
Dan Stoza7f7da322014-05-02 15:26:25 -0700907 return NO_ERROR;
908}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700909
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700910status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
911 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700912 return BAD_VALUE;
913 }
914
Ana Krulece588e312018-09-18 12:32:24 -0700915 // FIXME for now we always return stats for the primary display.
916 if (mUseScheduler) {
917 mScheduler->getDisplayStatInfo(stats);
918 } else {
919 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
920 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
921 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700922 return NO_ERROR;
923}
924
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700925int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
926 const auto display = getDisplayDevice(displayToken);
927 if (!display) {
928 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800929 return BAD_VALUE;
930 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700931
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700932 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700933}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700934
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700935void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
936 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700937 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700938 return;
939 }
940
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700941 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700942 ALOGW("Trying to set config for virtual display");
943 return;
944 }
945
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700946 display->setActiveConfig(mode);
947 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700948}
949
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700950status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700951 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700952 Vector<DisplayInfo> configs;
953 getDisplayConfigs(displayToken, &configs);
954 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
955 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
956 configs.size());
957 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700958 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700959 const auto display = getDisplayDevice(displayToken);
960 if (!display) {
961 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
962 displayToken.get());
963 } else if (display->isVirtual()) {
964 ALOGW("Attempt to set active config %d for virtual display", mode);
965 } else {
966 setActiveConfigInternal(display, mode);
967 }
968 }));
969
Mathias Agopian888c8222012-08-04 21:10:38 -0700970 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700971}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700972status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
973 Vector<ColorMode>* outColorModes) {
974 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700975 return BAD_VALUE;
976 }
977
Michael Wright28f24d02016-07-12 13:30:53 -0700978 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700979 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
980 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700981 type = i;
982 break;
983 }
984 }
985
986 if (type < 0) {
987 return type;
988 }
989
Peiyong Lina52f0292018-03-14 17:26:31 -0700990 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700991 {
992 ConditionalLock _l(mStateLock,
993 std::this_thread::get_id() != mMainThreadId);
994 modes = getHwComposer().getColorModes(type);
995 }
Michael Wright28f24d02016-07-12 13:30:53 -0700996 outColorModes->clear();
997 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
998
999 return NO_ERROR;
1000}
1001
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001002ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1003 if (const auto display = getDisplayDevice(displayToken)) {
1004 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001005 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001006 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001007}
1008
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001009void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1010 Dataspace dataSpace, RenderIntent renderIntent) {
1011 ColorMode currentMode = display->getActiveColorMode();
1012 Dataspace currentDataSpace = display->getCompositionDataSpace();
1013 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001014
Peiyong Lin38e9a562018-04-10 16:24:20 -07001015 if (mode == currentMode && dataSpace == currentDataSpace &&
1016 renderIntent == currentRenderIntent) {
1017 return;
1018 }
1019
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001020 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001021 ALOGW("Trying to set config for virtual display");
1022 return;
1023 }
1024
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001025 display->setActiveColorMode(mode);
1026 display->setCompositionDataSpace(dataSpace);
1027 display->setActiveRenderIntent(renderIntent);
1028 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001029
1030 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001031 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1032 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001033}
1034
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001035status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001036 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001037 Vector<ColorMode> modes;
1038 getDisplayColorModes(displayToken, &modes);
1039 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1040 if (mode < ColorMode::NATIVE || !exists) {
1041 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1042 decodeColorMode(mode).c_str(), mode, displayToken.get());
1043 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001044 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001045 const auto display = getDisplayDevice(displayToken);
1046 if (!display) {
1047 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1048 decodeColorMode(mode).c_str(), mode, displayToken.get());
1049 } else if (display->isVirtual()) {
1050 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1051 decodeColorMode(mode).c_str(), mode);
1052 } else {
1053 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1054 RenderIntent::COLORIMETRIC);
1055 }
1056 }));
1057
Michael Wright28f24d02016-07-12 13:30:53 -07001058 return NO_ERROR;
1059}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001060
Svetoslavd85084b2014-03-20 10:28:31 -07001061status_t SurfaceFlinger::clearAnimationFrameStats() {
1062 Mutex::Autolock _l(mStateLock);
1063 mAnimFrameTracker.clearStats();
1064 return NO_ERROR;
1065}
1066
1067status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1068 Mutex::Autolock _l(mStateLock);
1069 mAnimFrameTracker.getStats(outStats);
1070 return NO_ERROR;
1071}
1072
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001073status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1074 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001075 Mutex::Autolock _l(mStateLock);
1076
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001077 const auto display = getDisplayDeviceLocked(displayToken);
1078 if (!display) {
1079 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001080 return BAD_VALUE;
1081 }
1082
Peiyong Linfb069302018-04-25 14:34:31 -07001083 // At this point the DisplayDeivce should already be set up,
1084 // meaning the luminance information is already queried from
1085 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001086 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001087 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1088 capabilities.getDesiredMaxLuminance(),
1089 capabilities.getDesiredMaxAverageLuminance(),
1090 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001091
1092 return NO_ERROR;
1093}
1094
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001095status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001096 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001097 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001098
Chia-I Wu90f669f2017-10-05 14:24:41 -07001099 if (mInjectVSyncs == enable) {
1100 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001101 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001102
Ana Krulec98b5b242018-08-10 15:03:23 -07001103 // TODO(akrulec): Part of the Injector should be refactored, so that it
1104 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001105 if (enable) {
1106 ALOGV("VSync Injections enabled");
1107 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001108 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001109 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001110 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001111 impl::EventThread::InterceptVSyncsCallback(),
1112 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001113 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001114 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001115 } else {
1116 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001117 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001118 }
1119
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001120 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001121 }));
1122
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001123 return NO_ERROR;
1124}
1125
1126status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001127 Mutex::Autolock _l(mStateLock);
1128
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001129 if (!mInjectVSyncs) {
1130 ALOGE("VSync Injections not enabled");
1131 return BAD_VALUE;
1132 }
1133 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1134 ALOGV("Injecting VSync inside SurfaceFlinger");
1135 mVSyncInjector->onInjectSyncEvent(when);
1136 }
1137 return NO_ERROR;
1138}
1139
Lloyd Pique755e3192018-01-31 16:46:15 -08001140status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1141 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001142 // Try to acquire a lock for 1s, fail gracefully
1143 const status_t err = mStateLock.timedLock(s2ns(1));
1144 const bool locked = (err == NO_ERROR);
1145 if (!locked) {
1146 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1147 return TIMED_OUT;
1148 }
1149
1150 outLayers->clear();
1151 mCurrentState.traverseInZOrder([&](Layer* layer) {
1152 outLayers->push_back(layer->getLayerDebugInfo());
1153 });
1154
1155 mStateLock.unlock();
1156 return NO_ERROR;
1157}
1158
Peiyong Lin0256f722018-08-31 15:45:10 -07001159status_t SurfaceFlinger::getCompositionPreference(Dataspace* outDataSpace,
1160 ui::PixelFormat* outPixelFormat) const {
1161 *outDataSpace = compositionDataSpace;
1162 *outPixelFormat = compositionPixelFormat;
1163 return NO_ERROR;
1164}
1165
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001166// ----------------------------------------------------------------------------
1167
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001168sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1169 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001170 if (mUseScheduler) {
1171 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1172 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1173 } else {
1174 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1175 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001176 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001177 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1178 return mSFEventThread->createEventConnection();
1179 } else {
1180 return mEventThread->createEventConnection();
1181 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001182 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001183}
1184
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001185// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001186
1187void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001188 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001189}
1190
1191void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001192 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001193}
1194
1195void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001196 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001197}
1198
1199void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001200 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001201 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001202}
1203
1204status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001205 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001206 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001207}
1208
1209status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001210 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001211 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001212 if (res == NO_ERROR) {
1213 msg->wait();
1214 }
1215 return res;
1216}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001217
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001218void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001219 do {
1220 waitForEvent();
1221 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001222}
1223
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001224void SurfaceFlinger::enableHardwareVsync() {
1225 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001226 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001227 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001228 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001229 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001230 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001231}
1232
Jesse Hall948fe0c2013-10-14 12:56:09 -07001233void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001234 Mutex::Autolock _l(mHWVsyncLock);
1235
Jesse Hall948fe0c2013-10-14 12:56:09 -07001236 if (makeAvailable) {
1237 mHWVsyncAvailable = true;
1238 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001239 // Hardware vsync is not currently available, so abort the resync
1240 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001241 return;
1242 }
1243
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001244 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1245 if (!getHwComposer().isConnected(displayId)) {
1246 return;
1247 }
1248
1249 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001250 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001251
Ana Krulece588e312018-09-18 12:32:24 -07001252 if (mUseScheduler) {
1253 mScheduler->setVsyncPeriod(period);
1254 } else {
1255 mPrimaryDispSync->reset();
1256 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001257
Ana Krulece588e312018-09-18 12:32:24 -07001258 if (!mPrimaryHWVsyncEnabled) {
1259 mPrimaryDispSync->beginResync();
1260 mEventControlThread->setVsyncEnabled(true);
1261 mPrimaryHWVsyncEnabled = true;
1262 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001263 }
1264}
1265
Jesse Hall948fe0c2013-10-14 12:56:09 -07001266void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001267 Mutex::Autolock _l(mHWVsyncLock);
1268 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001269 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001270 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001271 mPrimaryHWVsyncEnabled = false;
1272 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001273 if (makeUnavailable) {
1274 mHWVsyncAvailable = false;
1275 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001276}
1277
Tim Murray4a4e4a22016-04-19 16:29:23 +00001278void SurfaceFlinger::resyncWithRateLimit() {
1279 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001280
1281 // No explicit locking is needed here since EventThread holds a lock while calling this method
1282 static nsecs_t sLastResyncAttempted = 0;
1283 const nsecs_t now = systemTime();
1284 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001285 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001286 }
Dan Stoza57164302017-05-08 14:03:54 -07001287 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001288}
1289
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001290void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1291 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001292 ATRACE_NAME("SF onVsync");
1293
Steven Thomas3cfac282017-02-06 12:29:30 -08001294 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001295 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001296 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001297 return;
1298 }
1299
1300 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001301 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001302 return;
1303 }
1304
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001305 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1306 // For now, we don't do anything with external display vsyncs.
1307 return;
1308 }
1309
Ana Krulece588e312018-09-18 12:32:24 -07001310 if (mUseScheduler) {
1311 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001312 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001313 bool needsHwVsync = false;
1314 { // Scope for the lock
1315 Mutex::Autolock _l(mHWVsyncLock);
1316 if (mPrimaryHWVsyncEnabled) {
1317 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1318 }
1319 }
1320
1321 if (needsHwVsync) {
1322 enableHardwareVsync();
1323 } else {
1324 disableHardwareVsync(false);
1325 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001326 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001327}
1328
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001329void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001330 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1331 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001332}
1333
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001334void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001335 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001336 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001337 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001338
Lloyd Piqueba04e622017-12-14 17:11:26 -08001339 // Ignore events that do not have the right sequenceId.
1340 if (sequenceId != getBE().mComposerSequenceId) {
1341 return;
1342 }
1343
Steven Thomasb02664d2017-07-26 18:48:28 -07001344 // Only lock if we're not on the main thread. This function is normally
1345 // called on a hwbinder thread, but for the primary display it's called on
1346 // the main thread with the state lock already held, so don't attempt to
1347 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001348 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001349
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001350 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001351
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001352 if (std::this_thread::get_id() == mMainThreadId) {
1353 // Process all pending hot plug events immediately if we are on the main thread.
1354 processDisplayHotplugEventsLocked();
1355 }
1356
Lloyd Piqueba04e622017-12-14 17:11:26 -08001357 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001358}
1359
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001360void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001361 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001362 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001363 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001364 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001365 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001366}
1367
Dan Stoza9e56aa02015-11-02 13:00:03 -08001368void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001369 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001370 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001371 getHwComposer().setVsyncEnabled(disp,
1372 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001373}
1374
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001375// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001376void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001377 if (mUseScheduler) {
1378 mScheduler->disableHardwareVsync(true);
1379 } else {
1380 disableHardwareVsync(true);
1381 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001382 // Clear the drawing state so that the logic inside of
1383 // handleTransactionLocked will fire. It will determine the delta between
1384 // mCurrentState and mDrawingState and re-apply all changes when we make the
1385 // transition.
1386 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001387 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001388 mDisplays.clear();
1389}
1390
Steven Thomas050b2c82017-03-06 11:45:16 -08001391void SurfaceFlinger::updateVrFlinger() {
1392 if (!mVrFlinger)
1393 return;
1394 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001395 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001396 return;
1397 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001398
David Sodman105b7dc2017-11-04 20:28:14 -07001399 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001400 ALOGE("Vr flinger is only supported for remote hardware composer"
1401 " service connections. Ignoring request to transition to vr"
1402 " flinger.");
1403 mVrFlingerRequestsDisplay = false;
1404 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001405 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001406
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001407 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001408
Steven Thomas0123ac62018-07-12 11:32:34 -07001409 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001410 LOG_ALWAYS_FATAL_IF(!display);
1411 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001412 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1413 // called below. Clear the reference now so we don't accidentally use it
1414 // later.
1415 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001416
Steven Thomasb02664d2017-07-26 18:48:28 -07001417 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001418 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001419 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001420
Steven Thomasb02664d2017-07-26 18:48:28 -07001421 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001422 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001423 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1424 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001425 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001426
David Sodman105b7dc2017-11-04 20:28:14 -07001427 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1428 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001429
1430 if (vrFlingerRequestsDisplay) {
1431 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001432 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001433
1434 mVisibleRegionsDirty = true;
1435 invalidateHwcGeometry();
1436
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001437 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001438 display = getDefaultDisplayDeviceLocked();
1439 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001440 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001441
Steven Thomasb02664d2017-07-26 18:48:28 -07001442 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001443 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001444 const nsecs_t period = activeConfig->getVsyncPeriod();
1445 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001446
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001447 // The present fences returned from vr_hwc are not an accurate
1448 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001449 if (mUseScheduler) {
1450 mScheduler->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() || !hasSyncFramework);
1451 } else {
1452 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1453 !hasSyncFramework);
1454 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001455
Steven Thomasb02664d2017-07-26 18:48:28 -07001456 // Use phase of 0 since phase is not known.
1457 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001458 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1459 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001460
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001461 resyncToHardwareVsync(false);
1462
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001463 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001464 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001465}
1466
Mathias Agopian4fec8732012-06-29 14:12:52 -07001467void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001468 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001469 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001470 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001471 bool frameMissed = !mHadClientComposition &&
1472 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001473 (mPreviousPresentFence->getSignalTime() ==
1474 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001475 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001476 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001477 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001478 mTimeStats.incrementMissedFrames();
1479 if (mPropagateBackpressure) {
1480 signalLayerUpdate();
1481 break;
1482 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001483 }
Dan Stoza50182882016-07-08 12:02:20 -07001484
Steven Thomas050b2c82017-03-06 11:45:16 -08001485 // Now that we're going to make it to the handleMessageTransaction()
1486 // call below it's safe to call updateVrFlinger(), which will
1487 // potentially trigger a display handoff.
1488 updateVrFlinger();
1489
Dan Stoza6b9454d2014-11-07 16:00:59 -08001490 bool refreshNeeded = handleMessageTransaction();
1491 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001492 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001493 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001494 // Signal a refresh if a transaction modified the window state,
1495 // a new buffer was latched, or if HWC has requested a full
1496 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001497 signalRefresh();
1498 }
1499 break;
1500 }
1501 case MessageQueue::REFRESH: {
1502 handleMessageRefresh();
1503 break;
1504 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001505 }
1506}
1507
Dan Stoza6b9454d2014-11-07 16:00:59 -08001508bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001509 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001510 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001511 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001512 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001513 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001514 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001515}
1516
Mathias Agopian4fec8732012-06-29 14:12:52 -07001517void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001518 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001519
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001520 mRefreshPending = false;
1521
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001522 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001523 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001524 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001525 calculateWorkingSet();
David Sodman10a41ff2018-08-05 12:14:17 -07001526
David Sodmanfa9b2af2017-12-24 13:28:59 -08001527 for (const auto& [token, display] : mDisplays) {
David Sodman10a41ff2018-08-05 12:14:17 -07001528 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001529 beginFrame(display);
David Sodman10a41ff2018-08-05 12:14:17 -07001530 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
1531 setUpHWComposer(compositionInfo);
1532 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001533 prepareFrame(display);
1534 doDebugFlashRegions(display, repaintEverything);
1535 doComposition(display, repaintEverything);
1536 }
1537
Adrian Roos1e1a1282017-11-01 19:05:31 +01001538 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001539 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001540
1541 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001542 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001543
Dan Stozabfbffeb2016-07-21 14:49:33 -07001544 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001545 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001546 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001547 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001548 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001549
Alec Mouri86770e52018-09-24 22:40:58 +00001550 // Setup RenderEngine sync fences if native sync is supported.
1551 if (getBE().mRenderEngine->useNativeFenceSync()) {
1552 if (mHadClientComposition) {
1553 base::unique_fd flushFence(getRenderEngine().flush());
1554 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1555 getBE().flushFence = new Fence(std::move(flushFence));
1556 } else {
1557 // Cleanup for hygiene.
1558 getBE().flushFence = Fence::NO_FENCE;
1559 }
1560 }
1561
Jorim Jaggi90535212018-05-23 23:44:06 +02001562 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001563
David Sodman7e4ae112018-02-09 15:02:28 -08001564 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001565 for (const auto& [token, display] : mDisplays) {
1566 const auto displayId = display->getId();
David Sodman7e4ae112018-02-09 15:02:28 -08001567 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[displayId]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001568 compositionInfo.hwc.hwcLayer = nullptr;
1569 }
David Sodmanba340492018-08-05 21:51:33 -07001570 }
David Sodman7e4ae112018-02-09 15:02:28 -08001571
1572 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001573}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001574
David Sodmanfa9b2af2017-12-24 13:28:59 -08001575
1576bool SurfaceFlinger::handleMessageInvalidate() {
1577 ATRACE_CALL();
1578 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001579}
1580
David Sodman79bba0e2018-08-05 18:07:49 -07001581void SurfaceFlinger::calculateWorkingSet() {
1582 ATRACE_CALL();
1583 ALOGV(__FUNCTION__);
1584
David Sodman79bba0e2018-08-05 18:07:49 -07001585 // build the h/w work list
1586 if (CC_UNLIKELY(mGeometryInvalid)) {
1587 mGeometryInvalid = false;
1588 for (const auto& [token, display] : mDisplays) {
1589 const auto displayId = display->getId();
1590 if (displayId >= 0) {
1591 const Vector<sp<Layer>>& currentLayers(
1592 display->getVisibleLayersSortedByZ());
1593 for (size_t i = 0; i < currentLayers.size(); i++) {
1594 const auto& layer = currentLayers[i];
1595
1596 if (!layer->hasHwcLayer(displayId)) {
1597 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1598 layer->forceClientComposition(displayId);
1599 continue;
1600 }
1601 }
1602
1603 layer->setGeometry(display, i);
1604 if (mDebugDisableHWC || mDebugRegion) {
1605 layer->forceClientComposition(displayId);
1606 }
1607 }
1608 }
1609 }
1610 }
1611
1612 // Set the per-frame data
1613 for (const auto& [token, display] : mDisplays) {
1614 const auto displayId = display->getId();
1615 if (displayId < 0) {
1616 continue;
1617 }
1618
1619 if (mDrawingState.colorMatrixChanged) {
1620 display->setColorTransform(mDrawingState.colorMatrix);
1621 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1622 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1623 "display %d: %d", displayId, result);
1624 }
1625 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1626 if (layer->isHdrY410()) {
1627 layer->forceClientComposition(displayId);
1628 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1629 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1630 !display->hasHDR10Support()) {
1631 layer->forceClientComposition(displayId);
1632 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1633 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1634 !display->hasHLGSupport()) {
1635 layer->forceClientComposition(displayId);
1636 }
1637
Peiyong Lind3788632018-09-18 16:01:31 -07001638 // TODO(b/111562338) remove when composer 2.3 is shipped.
1639 if (layer->hasColorTransform()) {
1640 layer->forceClientComposition(displayId);
1641 }
1642
David Sodman79bba0e2018-08-05 18:07:49 -07001643 if (layer->getForceClientComposition(displayId)) {
1644 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1645 layer->setCompositionType(displayId, HWC2::Composition::Client);
1646 continue;
1647 }
1648
1649 layer->setPerFrameData(display);
1650 }
1651
Peiyong Lin13effd12018-07-24 17:01:47 -07001652 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001653 ColorMode colorMode;
1654 Dataspace dataSpace;
1655 RenderIntent renderIntent;
1656 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1657 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1658 }
1659 }
1660
1661 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001662
1663 for (const auto& [token, display] : mDisplays) {
David Sodman15fb96e2018-01-07 10:23:24 -08001664 const auto displayId = display->getId();
1665 getBE().mCompositionInfo[displayId].clear();
David Sodmanba340492018-08-05 21:51:33 -07001666 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1667 auto displayId = display->getId();
1668 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1669 if (!layer->setHwcLayer(displayId)) {
1670 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1671 }
David Sodman15fb96e2018-01-07 10:23:24 -08001672 layer->getBE().compositionInfo.hwc.displayId = displayId;
1673 getBE().mCompositionInfo[displayId].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001674 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1675 }
1676 }
David Sodman79bba0e2018-08-05 18:07:49 -07001677}
1678
David Sodmanfa9b2af2017-12-24 13:28:59 -08001679void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001680{
David Sodmanfb95bcc2017-12-22 15:45:30 -08001681 const auto displayId = display->getId();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001682 // is debugging enabled
1683 if (CC_LIKELY(!mDebugRegion))
1684 return;
1685
David Sodmanfa9b2af2017-12-24 13:28:59 -08001686 if (display->isPoweredOn()) {
1687 // transform the dirty region into this screen's coordinate space
1688 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1689 if (!dirtyRegion.isEmpty()) {
1690 // redraw the whole screen
1691 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001692
David Sodmanfa9b2af2017-12-24 13:28:59 -08001693 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001694 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001695 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001696
David Sodmanfa9b2af2017-12-24 13:28:59 -08001697 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001698 }
1699 }
1700
David Sodmanfa9b2af2017-12-24 13:28:59 -08001701 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001702
1703 if (mDebugRegion > 1) {
1704 usleep(mDebugRegion * 1000);
1705 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001706
David Sodmanfa9b2af2017-12-24 13:28:59 -08001707 if (display->isPoweredOn()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08001708 status_t result = display->prepareFrame(
1709 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001710 ALOGE_IF(result != NO_ERROR,
1711 "prepareFrame for display %d failed:"
1712 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001713 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001714 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001715}
1716
Adrian Roos1e1a1282017-11-01 19:05:31 +01001717void SurfaceFlinger::doTracing(const char* where) {
1718 ATRACE_CALL();
1719 ATRACE_NAME(where);
1720 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001721 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001722 }
1723}
1724
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001725void SurfaceFlinger::logLayerStats() {
1726 ATRACE_CALL();
1727 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001728 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001729 if (display->isPrimary()) {
1730 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001731 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001732 }
1733 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001734
1735 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001736 }
1737}
1738
David Sodman2b406362017-12-15 13:33:47 -08001739void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001740{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001741 ATRACE_CALL();
1742 ALOGV("preComposition");
1743
David Sodman2b406362017-12-15 13:33:47 -08001744 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1745
Mathias Agopiancd60f992012-08-16 16:28:27 -07001746 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001747 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001748 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001749 needExtraInvalidate = true;
1750 }
Robert Carr2047fae2016-11-28 14:09:09 -08001751 });
1752
Mathias Agopiancd60f992012-08-16 16:28:27 -07001753 if (needExtraInvalidate) {
1754 signalLayerUpdate();
1755 }
1756}
1757
Ana Krulece588e312018-09-18 12:32:24 -07001758void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1759 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001760 // Update queue of past composite+present times and determine the
1761 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001762 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001763 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001764 while (!getBE().mCompositePresentTimes.empty()) {
1765 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001766 // Cached values should have been updated before calling this method,
1767 // which helps avoid duplicate syscalls.
1768 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1769 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1770 break;
1771 }
1772 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001773 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001774 }
1775
1776 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001777 while (getBE().mCompositePresentTimes.size() > 16) {
1778 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001779 }
1780
Ana Krulece588e312018-09-18 12:32:24 -07001781 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001782}
1783
Ana Krulece588e312018-09-18 12:32:24 -07001784void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1785 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001786 // Integer division and modulo round toward 0 not -inf, so we need to
1787 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001788 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1789 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1790 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001791
Brian Andersond0010582017-03-07 13:20:31 -08001792 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1793 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001794 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001795 }
1796
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001797 // Snap the latency to a value that removes scheduling jitter from the
1798 // composition and present times, which often have >1ms of jitter.
1799 // Reducing jitter is important if an app attempts to extrapolate
1800 // something (such as user input) to an accurate diasplay time.
1801 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1802 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001803 nsecs_t bias = stats.vsyncPeriod / 2;
1804 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1805 nsecs_t snappedCompositeToPresentLatency =
1806 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001807
David Sodman99974d22017-11-28 12:04:33 -08001808 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001809 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1810 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001811 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001812}
1813
David Sodman2b406362017-12-15 13:33:47 -08001814void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001815{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001816 ATRACE_CALL();
1817 ALOGV("postComposition");
1818
Brian Anderson3546a3f2016-07-14 11:51:14 -07001819 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001820 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001821 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001822 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001823 }
1824
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001825 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001826 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001827
David Sodman73beded2017-11-15 11:56:06 -08001828 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001829 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001830 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001831 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001832 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001833 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001834 } else {
1835 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1836 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001837
David Sodman73beded2017-11-15 11:56:06 -08001838 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001839 mPreviousPresentFence =
1840 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1841 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001842 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001843
Ana Krulece588e312018-09-18 12:32:24 -07001844 DisplayStatInfo stats;
1845 if (mUseScheduler) {
1846 mScheduler->getDisplayStatInfo(&stats);
1847 } else {
1848 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1849 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
1850 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001851
David Sodman2b406362017-12-15 13:33:47 -08001852 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001853 // when we started doing work for this frame, but that should be okay
1854 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07001855 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001856 CompositorTiming compositorTiming;
1857 {
David Sodman99974d22017-11-28 12:04:33 -08001858 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1859 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001860 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001861
Robert Carr2047fae2016-11-28 14:09:09 -08001862 mDrawingState.traverseInZOrder([&](Layer* layer) {
1863 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001864 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001865 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001866 recordBufferingStats(layer->getName().string(),
1867 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001868 }
Robert Carr2047fae2016-11-28 14:09:09 -08001869 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001870
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001871 if (presentFenceTime->isValid()) {
Ana Krulece588e312018-09-18 12:32:24 -07001872 if (mUseScheduler) {
1873 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001874 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001875 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
1876 enableHardwareVsync();
1877 } else {
1878 disableHardwareVsync(false);
1879 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001880 }
1881 }
1882
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001883 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001884 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07001885 if (mUseScheduler) {
1886 mScheduler->enableHardwareVsync();
1887 } else {
1888 enableHardwareVsync();
1889 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001890 }
1891 }
1892
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001893 if (mAnimCompositionPending) {
1894 mAnimCompositionPending = false;
1895
Brian Anderson4e606e32017-03-16 15:34:57 -07001896 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001897 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001898 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001899 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001900 // The HWC doesn't support present fences, so use the refresh
1901 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001902 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001903 mAnimFrameTracker.setActualPresentTime(presentTime);
1904 }
1905 mAnimFrameTracker.advanceFrame();
1906 }
Dan Stozab90cf072015-03-05 11:05:59 -08001907
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001908 mTimeStats.incrementTotalFrames();
1909 if (mHadClientComposition) {
1910 mTimeStats.incrementClientCompositionFrames();
1911 }
1912
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001913 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001914 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001915 return;
1916 }
1917
1918 nsecs_t currentTime = systemTime();
1919 if (mHasPoweredOff) {
1920 mHasPoweredOff = false;
1921 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001922 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001923 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001924 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1925 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001926 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001927 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001928 }
David Sodman4a36e932017-11-07 14:29:47 -08001929 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001930 }
David Sodman4a36e932017-11-07 14:29:47 -08001931 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001932
1933 {
1934 std::lock_guard lock(mTexturePoolMutex);
1935 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1936 if (refillCount > 0) {
1937 const size_t offset = mTexturePool.size();
1938 mTexturePool.resize(mTexturePoolSize);
1939 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1940 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1941 }
1942 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001943}
1944
1945void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001946 ATRACE_CALL();
1947 ALOGV("rebuildLayerStacks");
1948
Mathias Agopiancd60f992012-08-16 16:28:27 -07001949 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001950 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001951 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001952 mVisibleRegionsDirty = false;
1953 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001954
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001955 for (const auto& pair : mDisplays) {
1956 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001957 Region opaqueRegion;
1958 Region dirtyRegion;
1959 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001960 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001961 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001962 const Rect bounds = display->getBounds();
1963 if (display->isPoweredOn()) {
1964 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001965
Jeff Sharkey76488112017-02-27 14:15:18 -07001966 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001967 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001968 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001969 Region drawRegion(tr.transform(
1970 layer->visibleNonTransparentRegion));
1971 drawRegion.andSelf(bounds);
1972 if (!drawRegion.isEmpty()) {
1973 layersSortedByZ.add(layer);
1974 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001975 // Clear out the HWC layer if this layer was
1976 // previously visible, but no longer is
1977 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001978 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001979 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001980 // WM changes display->layerStack upon sleep/awake.
1981 // Here we make sure we delete the HWC layers even if
1982 // WM changed their layer stack.
1983 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001984 }
1985
1986 // If a layer is not going to get a release fence because
1987 // it is invisible, but it is also going to release its
1988 // old buffer, add it to the list of layers needing
1989 // fences.
1990 if (hwcLayerDestroyed) {
1991 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1992 mLayersWithQueuedFrames.cend(), layer);
1993 if (found != mLayersWithQueuedFrames.cend()) {
1994 layersNeedingFences.add(layer);
1995 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001996 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001997 });
1998 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001999 display->setVisibleLayersSortedByZ(layersSortedByZ);
2000 display->setLayersNeedingFences(layersNeedingFences);
2001 display->undefinedRegion.set(bounds);
2002 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2003 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002004 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002005 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002006}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002007
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002008// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002009// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002010// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002011// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002012// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002013// The returned HDR data space is one of
2014// - Dataspace::UNKNOWN
2015// - Dataspace::BT2020_HLG
2016// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002017Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2018 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07002019 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002020 *outHdrDataSpace = Dataspace::UNKNOWN;
2021
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002022 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002023 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002024 case Dataspace::V0_SCRGB:
2025 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002026 case Dataspace::BT2020:
2027 case Dataspace::BT2020_ITU:
2028 case Dataspace::BT2020_LINEAR:
2029 case Dataspace::DISPLAY_BT2020:
2030 bestDataSpace = Dataspace::DISPLAY_BT2020;
2031 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002032 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002033 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002034 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002035 case Dataspace::BT2020_PQ:
2036 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002037 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002038 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002039 case Dataspace::BT2020_HLG:
2040 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002041 // When there's mixed PQ content and HLG content, we set the HDR
2042 // data space to be BT2020_PQ and convert HLG to PQ.
2043 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2044 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002045 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002046 break;
2047 default:
2048 break;
2049 }
Romain Guy54f154a2017-10-24 21:40:32 +01002050 }
2051
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002052 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002053}
2054
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002055// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002056void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2057 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002058 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2059 *outMode = ColorMode::NATIVE;
2060 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002061 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002062 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002063 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002064
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002065 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002066 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002067
Peiyong Lindfde5112018-06-05 10:58:41 -07002068 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002069 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002070 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002071 if (isHdr) {
2072 bestDataSpace = hdrDataSpace;
2073 }
2074
Chia-I Wu0d711262018-05-21 15:19:35 -07002075 RenderIntent intent;
2076 switch (mDisplayColorSetting) {
2077 case DisplayColorSetting::MANAGED:
2078 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002079 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002080 break;
2081 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002082 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002083 break;
2084 default: // vendor display color setting
2085 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2086 break;
2087 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002088
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002089 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002090}
2091
David Sodman10a41ff2018-08-05 12:14:17 -07002092void SurfaceFlinger::configureSidebandComposition(const CompositionInfo& compositionInfo) const
2093{
2094 HWC2::Error error;
2095 LOG_ALWAYS_FATAL_IF(compositionInfo.hwc.sidebandStream == nullptr,
2096 "CompositionType is sideband, but sideband stream is nullptr");
2097 error = (compositionInfo.hwc.hwcLayer)
2098 ->setSidebandStream(compositionInfo.hwc.sidebandStream->handle());
2099 if (error != HWC2::Error::None) {
2100 ALOGE("[SF] Failed to set sideband stream %p: %s (%d)",
2101 compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
2102 static_cast<int32_t>(error));
2103 }
2104}
2105
2106void SurfaceFlinger::configureHwcCommonData(const CompositionInfo& compositionInfo) const
2107{
2108 HWC2::Error error;
2109
2110 if (!compositionInfo.hwc.skipGeometry) {
2111 error = (compositionInfo.hwc.hwcLayer)->setBlendMode(compositionInfo.hwc.blendMode);
2112 ALOGE_IF(error != HWC2::Error::None,
2113 "[SF] Failed to set blend mode %s:"
2114 " %s (%d)",
2115 to_string(compositionInfo.hwc.blendMode).c_str(), to_string(error).c_str(),
2116 static_cast<int32_t>(error));
2117
2118 error = (compositionInfo.hwc.hwcLayer)->setDisplayFrame(compositionInfo.hwc.displayFrame);
2119 ALOGE_IF(error != HWC2::Error::None,
2120 "[SF] Failed to set the display frame [%d, %d, %d, %d] %s (%d)",
2121 compositionInfo.hwc.displayFrame.left,
2122 compositionInfo.hwc.displayFrame.right,
2123 compositionInfo.hwc.displayFrame.top,
2124 compositionInfo.hwc.displayFrame.bottom,
2125 to_string(error).c_str(), static_cast<int32_t>(error));
2126
2127 error = (compositionInfo.hwc.hwcLayer)->setSourceCrop(compositionInfo.hwc.sourceCrop);
2128 ALOGE_IF(error != HWC2::Error::None,
2129 "[SF] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: %s (%d)",
2130 compositionInfo.hwc.sourceCrop.left,
2131 compositionInfo.hwc.sourceCrop.right,
2132 compositionInfo.hwc.sourceCrop.top,
2133 compositionInfo.hwc.sourceCrop.bottom,
2134 to_string(error).c_str(), static_cast<int32_t>(error));
2135
2136 error = (compositionInfo.hwc.hwcLayer)->setPlaneAlpha(compositionInfo.hwc.alpha);
2137 ALOGE_IF(error != HWC2::Error::None,
2138 "[SF] Failed to set plane alpha %.3f: "
2139 "%s (%d)",
2140 compositionInfo.hwc.alpha,
2141 to_string(error).c_str(), static_cast<int32_t>(error));
2142
2143
2144 error = (compositionInfo.hwc.hwcLayer)->setZOrder(compositionInfo.hwc.z);
2145 ALOGE_IF(error != HWC2::Error::None,
2146 "[SF] Failed to set Z %u: %s (%d)",
2147 compositionInfo.hwc.z,
2148 to_string(error).c_str(), static_cast<int32_t>(error));
2149
2150 error = (compositionInfo.hwc.hwcLayer)
2151 ->setInfo(compositionInfo.hwc.type, compositionInfo.hwc.appId);
2152 ALOGE_IF(error != HWC2::Error::None,
2153 "[SF] Failed to set info (%d)",
2154 static_cast<int32_t>(error));
2155
2156 error = (compositionInfo.hwc.hwcLayer)->setTransform(compositionInfo.hwc.transform);
2157 ALOGE_IF(error != HWC2::Error::None,
2158 "[SF] Failed to set transform %s: "
2159 "%s (%d)",
2160 to_string(compositionInfo.hwc.transform).c_str(), to_string(error).c_str(),
2161 static_cast<int32_t>(error));
2162 }
2163
2164 error = (compositionInfo.hwc.hwcLayer)->setCompositionType(compositionInfo.compositionType);
2165 ALOGE_IF(error != HWC2::Error::None,
2166 "[SF] Failed to set composition type: %s (%d)",
2167 to_string(error).c_str(), static_cast<int32_t>(error));
2168
2169 error = (compositionInfo.hwc.hwcLayer)->setDataspace(compositionInfo.hwc.dataspace);
2170 ALOGE_IF(error != HWC2::Error::None,
2171 "[SF] Failed to set dataspace: %s (%d)",
2172 to_string(error).c_str(), static_cast<int32_t>(error));
2173
2174 error = (compositionInfo.hwc.hwcLayer)->setPerFrameMetadata(
2175 compositionInfo.hwc.supportedPerFrameMetadata, compositionInfo.hwc.hdrMetadata);
2176 ALOGE_IF(error != HWC2::Error::None && error != HWC2::Error::Unsupported,
2177 "[SF] Failed to set hdrMetadata: %s (%d)",
2178 to_string(error).c_str(), static_cast<int32_t>(error));
2179
2180 if (compositionInfo.compositionType == HWC2::Composition::SolidColor) {
2181 error = (compositionInfo.hwc.hwcLayer)->setColor(compositionInfo.hwc.color);
2182 ALOGE_IF(error != HWC2::Error::None,
2183 "[SF] Failed to set color: %s (%d)",
2184 to_string(error).c_str(), static_cast<int32_t>(error));
2185 }
2186
2187 error = (compositionInfo.hwc.hwcLayer)->setVisibleRegion(compositionInfo.hwc.visibleRegion);
2188 ALOGE_IF(error != HWC2::Error::None,
2189 "[SF] Failed to set visible region: %s (%d)",
2190 to_string(error).c_str(), static_cast<int32_t>(error));
2191
2192 error = (compositionInfo.hwc.hwcLayer)->setSurfaceDamage(compositionInfo.hwc.surfaceDamage);
2193 ALOGE_IF(error != HWC2::Error::None,
2194 "[SF] Failed to set surface damage: %s (%d)",
2195 to_string(error).c_str(), static_cast<int32_t>(error));
Peiyong Lind3788632018-09-18 16:01:31 -07002196
2197 error = (compositionInfo.hwc.hwcLayer)->setColorTransform(compositionInfo.hwc.colorTransform);
David Sodman10a41ff2018-08-05 12:14:17 -07002198}
2199
2200void SurfaceFlinger::configureDeviceComposition(const CompositionInfo& compositionInfo) const
2201{
2202 HWC2::Error error;
2203
2204 if (compositionInfo.hwc.fence) {
2205 error = (compositionInfo.hwc.hwcLayer)->setBuffer(compositionInfo.mBufferSlot,
2206 compositionInfo.mBuffer, compositionInfo.hwc.fence);
2207 ALOGE_IF(error != HWC2::Error::None,
2208 "[SF] Failed to set buffer: %s (%d)",
2209 to_string(error).c_str(), static_cast<int32_t>(error));
2210 }
2211}
2212
David Sodmanfa9b2af2017-12-24 13:28:59 -08002213void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002214{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002215 bool dirty = !display->getDirtyRegion(false).isEmpty();
2216 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2217 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002218
David Sodmanfa9b2af2017-12-24 13:28:59 -08002219 // If nothing has changed (!dirty), don't recompose.
2220 // If something changed, but we don't currently have any visible layers,
2221 // and didn't when we last did a composition, then skip it this time.
2222 // The second rule does two things:
2223 // - When all layers are removed from a display, we'll emit one black
2224 // frame, then nothing more until we get new layers.
2225 // - When a display is created with a private layer stack, we won't
2226 // emit any black frames until a layer is added to the layer stack.
2227 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002228
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002229 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2230 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002231 mustRecompose ? "doing" : "skipping",
2232 dirty ? "+" : "-",
2233 empty ? "+" : "-",
2234 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002235
David Sodmanfa9b2af2017-12-24 13:28:59 -08002236 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002237
David Sodmanfa9b2af2017-12-24 13:28:59 -08002238 if (mustRecompose) {
2239 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002240 }
2241}
2242
David Sodmanfa9b2af2017-12-24 13:28:59 -08002243void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002244{
David Sodmanfb95bcc2017-12-22 15:45:30 -08002245 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002246 if (!display->isPoweredOn()) {
2247 return;
David Sodman2b406362017-12-15 13:33:47 -08002248 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002249
David Sodmanfb95bcc2017-12-22 15:45:30 -08002250 status_t result = display->prepareFrame(
2251 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08002252 ALOGE_IF(result != NO_ERROR,
2253 "prepareFrame for display %d failed:"
2254 " %d (%s)",
2255 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002256}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002257
David Sodman10a41ff2018-08-05 12:14:17 -07002258void SurfaceFlinger::setUpHWComposer(const CompositionInfo& compositionInfo) {
2259 ATRACE_CALL();
2260 ALOGV("setUpHWComposer");
2261
2262 switch (compositionInfo.compositionType)
2263 {
2264 case HWC2::Composition::Invalid:
David Sodmana6d42332018-08-29 14:07:04 -07002265 break;
2266
David Sodman10a41ff2018-08-05 12:14:17 -07002267 case HWC2::Composition::Client:
David Sodmana6d42332018-08-29 14:07:04 -07002268 if (compositionInfo.hwc.hwcLayer) {
2269 auto error = (compositionInfo.hwc.hwcLayer)->
2270 setCompositionType(compositionInfo.compositionType);
2271 ALOGE_IF(error != HWC2::Error::None,
2272 "[SF] Failed to set composition type: %s (%d)",
2273 to_string(error).c_str(), static_cast<int32_t>(error));
2274 }
David Sodman10a41ff2018-08-05 12:14:17 -07002275 break;
2276
2277 case HWC2::Composition::Sideband:
2278 configureHwcCommonData(compositionInfo);
2279 configureSidebandComposition(compositionInfo);
2280 break;
2281
2282 case HWC2::Composition::SolidColor:
2283 configureHwcCommonData(compositionInfo);
2284 break;
2285
2286 case HWC2::Composition::Device:
2287 case HWC2::Composition::Cursor:
2288 configureHwcCommonData(compositionInfo);
2289 configureDeviceComposition(compositionInfo);
2290 break;
2291 }
2292}
2293
David Sodmanfa9b2af2017-12-24 13:28:59 -08002294void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002295 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002296 ALOGV("doComposition");
2297
David Sodmanfa9b2af2017-12-24 13:28:59 -08002298 if (display->isPoweredOn()) {
2299 // transform the dirty region into this screen's coordinate space
2300 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002301
David Sodmanfa9b2af2017-12-24 13:28:59 -08002302 // repaint the framebuffer (if needed)
2303 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002304
David Sodmanfa9b2af2017-12-24 13:28:59 -08002305 display->dirtyRegion.clear();
2306 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002307 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002308 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002309}
2310
David Sodmanfa9b2af2017-12-24 13:28:59 -08002311void SurfaceFlinger::postFrame()
2312{
2313 // |mStateLock| not needed as we are on the main thread
2314 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2315 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2316 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2317 logFrameStats();
2318 }
2319 }
2320}
2321
2322void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002323{
Mathias Agopian841cde52012-03-01 15:44:37 -08002324 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002325 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002326
David Sodmanfa9b2af2017-12-24 13:28:59 -08002327 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002328
David Sodmanfa9b2af2017-12-24 13:28:59 -08002329 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002330 const auto displayId = display->getId();
2331 if (displayId >= 0) {
2332 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002333 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002334 display->onSwapBuffersCompleted();
2335 display->makeCurrent();
David Sodman10a41ff2018-08-05 12:14:17 -07002336 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002337 sp<Fence> releaseFence = Fence::NO_FENCE;
Chia-I Wu7b549592017-11-15 09:14:57 -08002338 // The layer buffer from the previous frame (if any) is released
2339 // by HWC only when the release fence from this frame (if any) is
2340 // signaled. Always get the release fence from HWC first.
David Sodman10a41ff2018-08-05 12:14:17 -07002341 auto hwcLayer = compositionInfo.hwc.hwcLayer;
2342 if ((displayId >= 0) && hwcLayer) {
2343 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer.get());
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002344 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002345
2346 // If the layer was client composited in the previous frame, we
2347 // need to merge with the previous client target acquire fence.
2348 // Since we do not track that, always merge with the current
2349 // client target acquire fence when it is available, even though
2350 // this is suboptimal.
David Sodman10a41ff2018-08-05 12:14:17 -07002351 if (compositionInfo.compositionType == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002352 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002353 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002354 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002355
David Sodman10a41ff2018-08-05 12:14:17 -07002356 if (compositionInfo.layer) {
2357 compositionInfo.layer->onLayerDisplayed(releaseFence);
2358 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002359 }
Chia-I Wu83806892017-11-16 10:50:20 -08002360
2361 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002362 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002363 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002364 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002365 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002366 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002367 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002368 }
2369 }
2370
Dominik Laskowski7e045462018-05-30 13:02:02 -07002371 if (displayId >= 0) {
2372 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002373 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002374 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002375}
2376
Mathias Agopian87baae12012-07-31 12:38:26 -07002377void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002378{
Mathias Agopian841cde52012-03-01 15:44:37 -08002379 ATRACE_CALL();
2380
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002381 // here we keep a copy of the drawing state (that is the state that's
2382 // going to be overwritten by handleTransactionLocked()) outside of
2383 // mStateLock so that the side-effects of the State assignment
2384 // don't happen with mStateLock held (which can cause deadlocks).
2385 State drawingState(mDrawingState);
2386
Mathias Agopianca4d3602011-05-19 15:38:14 -07002387 Mutex::Autolock _l(mStateLock);
2388 const nsecs_t now = systemTime();
2389 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002390
Mathias Agopianca4d3602011-05-19 15:38:14 -07002391 // Here we're guaranteed that some transaction flags are set
2392 // so we can call handleTransactionLocked() unconditionally.
2393 // We call getTransactionFlags(), which will also clear the flags,
2394 // with mStateLock held to guarantee that mCurrentState won't change
2395 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002396
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002397 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002398 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002399 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002400
Mathias Agopianca4d3602011-05-19 15:38:14 -07002401 mLastTransactionTime = systemTime() - now;
2402 mDebugInTransaction = 0;
2403 invalidateHwcGeometry();
2404 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002405}
2406
Dominik Laskowski7e045462018-05-30 13:02:02 -07002407DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002408 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002409 // Figure out whether the event is for the primary display or an
2410 // external display by matching the Hwc display id against one for a
2411 // connected display. If we did not find a match, we then check what
2412 // displays are not already connected to determine the type. If we don't
2413 // have a connected primary display, we assume the new display is meant to
2414 // be the primary display, and then if we don't have an external display,
2415 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002416 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2417 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002418 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002419 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002420 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002421 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002422 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002423 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002424 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002425 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002426 return DisplayDevice::DISPLAY_EXTERNAL;
2427 }
2428
2429 return DisplayDevice::DISPLAY_ID_INVALID;
2430}
2431
Lloyd Piqueba04e622017-12-14 17:11:26 -08002432void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2433 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002434 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002435 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002436 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002437 continue;
2438 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002439
2440 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2441 ALOGE("External displays are not supported by the vr hardware composer.");
2442 continue;
2443 }
2444
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002445 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002446 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002447 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002448 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002449 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002450
2451 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002452 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002453 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002454 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002455 DisplayDeviceState info;
2456 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002457 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2458 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002459 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002460 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002461 mInterceptor->saveDisplayCreation(info);
2462 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002463 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002464 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002465
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002466 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002467 if (idx >= 0) {
2468 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002469 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002470 mCurrentState.displays.removeItemsAt(idx);
2471 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002472 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002473 }
2474
2475 processDisplayChangesLocked();
2476 }
2477
2478 mPendingHotplugEvents.clear();
2479}
2480
Lloyd Pique99d3da52018-01-22 17:48:03 -08002481sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002482 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002483 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002484 DisplayDeviceCreationArgs creationArgs(this, displayToken, state.type, displayId);
2485 creationArgs.isSecure = state.isSecure;
2486 creationArgs.displaySurface = dispSurface;
2487 creationArgs.hasWideColorGamut = false;
2488 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002489
Peiyong Lin13effd12018-07-24 17:01:47 -07002490 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002491 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002492 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002493 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002494 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002495 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002496
Dominik Laskowski7e045462018-05-30 13:02:02 -07002497 std::vector<RenderIntent> renderIntents =
2498 getHwComposer().getRenderIntents(displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002499 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002500 }
tangrobin6753a022018-08-10 10:58:54 +08002501 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002502
tangrobin6753a022018-08-10 10:58:54 +08002503 if (displayId >= 0) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002504 getHwComposer().getHdrCapabilities(displayId, &creationArgs.hdrCapabilities);
2505 creationArgs.supportedPerFrameMetadata =
2506 getHwComposer().getSupportedPerFrameMetadata(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002507 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002508
2509 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2510 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002511 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002512
2513 /*
2514 * Create our display's surface
2515 */
Peiyong Lin833074a2018-08-28 11:53:54 -07002516 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002517 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002518 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002519 renderSurface->setNativeWindow(nativeWindow.get());
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002520 creationArgs.displayWidth = renderSurface->getWidth();
2521 creationArgs.displayHeight = renderSurface->getHeight();
2522 creationArgs.renderSurface = std::move(renderSurface);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002523
2524 // Make sure that composition can never be stalled by a virtual display
2525 // consumer that isn't processing buffers fast enough. We have to do this
2526 // in two places:
2527 // * Here, in case the display is composed entirely by HWC.
2528 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2529 // window's swap interval in eglMakeCurrent, so they'll override the
2530 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002531 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002532 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2533 }
2534
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002535 creationArgs.displayInstallOrientation = state.type == DisplayDevice::DISPLAY_PRIMARY
2536 ? primaryDisplayOrientation
2537 : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002538
Lloyd Pique99d3da52018-01-22 17:48:03 -08002539 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002540 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002541
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002542 sp<DisplayDevice> display = new DisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002543
2544 if (maxFrameBufferAcquiredBuffers >= 3) {
2545 nativeWindowSurface->preallocateBuffers();
2546 }
2547
2548 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002549 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002550 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002551 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002552 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002553 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002554 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002555 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002556 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002557 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002558 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002559 display->setLayerStack(state.layerStack);
2560 display->setProjection(state.orientation, state.viewport, state.frame);
2561 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002562
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002563 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002564}
2565
Lloyd Pique347200f2017-12-14 17:00:15 -08002566void SurfaceFlinger::processDisplayChangesLocked() {
2567 // here we take advantage of Vector's copy-on-write semantics to
2568 // improve performance by skipping the transaction entirely when
2569 // know that the lists are identical
2570 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2571 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2572 if (!curr.isIdenticalTo(draw)) {
2573 mVisibleRegionsDirty = true;
2574 const size_t cc = curr.size();
2575 size_t dc = draw.size();
2576
2577 // find the displays that were removed
2578 // (ie: in drawing state but not in current state)
2579 // also handle displays that changed
2580 // (ie: displays that are in both lists)
2581 for (size_t i = 0; i < dc;) {
2582 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2583 if (j < 0) {
2584 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002585 // Call makeCurrent() on the primary display so we can
2586 // be sure that nothing associated with this display
2587 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002588 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2589 defaultDisplay->makeCurrent();
2590 }
2591 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2592 display->disconnect(getHwComposer());
2593 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002594 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002595 if (mUseScheduler) {
2596 mScheduler->hotplugReceived(mAppConnectionHandle,
2597 EventThread::DisplayType::Primary, false);
2598 } else {
2599 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2600 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002601 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002602 if (mUseScheduler) {
2603 mScheduler->hotplugReceived(mAppConnectionHandle,
2604 EventThread::DisplayType::External, false);
2605 } else {
2606 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2607 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002608 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002609 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002610 } else {
2611 // this display is in both lists. see if something changed.
2612 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002613 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002614 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2615 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2616 if (state_binder != draw_binder) {
2617 // changing the surface is like destroying and
2618 // recreating the DisplayDevice, so we just remove it
2619 // from the drawing state, so that it get re-added
2620 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002621 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2622 display->disconnect(getHwComposer());
2623 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002624 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002625 mDrawingState.displays.removeItemsAt(i);
2626 dc--;
2627 // at this point we must loop to the next item
2628 continue;
2629 }
2630
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002631 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002632 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002633 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002634 }
2635 if ((state.orientation != draw[i].orientation) ||
2636 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002637 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002638 }
2639 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002640 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002641 }
2642 }
2643 }
2644 ++i;
2645 }
2646
2647 // find displays that were added
2648 // (ie: in current state but not in drawing state)
2649 for (size_t i = 0; i < cc; i++) {
2650 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2651 const DisplayDeviceState& state(curr[i]);
2652
2653 sp<DisplaySurface> dispSurface;
2654 sp<IGraphicBufferProducer> producer;
2655 sp<IGraphicBufferProducer> bqProducer;
2656 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002657 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002658
Dominik Laskowski7e045462018-05-30 13:02:02 -07002659 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002660 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002661 // Virtual displays without a surface are dormant:
2662 // they have external state (layer stack, projection,
2663 // etc.) but no internal state (i.e. a DisplayDevice).
2664 if (state.surface != nullptr) {
2665 // Allow VR composer to use virtual displays.
2666 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2667 int width = 0;
2668 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2669 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2670 int height = 0;
2671 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2672 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2673 int intFormat = 0;
2674 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2675 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002676 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002677
Dominik Laskowski7e045462018-05-30 13:02:02 -07002678 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2679 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002680 }
2681
2682 // TODO: Plumb requested format back up to consumer
2683
2684 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002685 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002686 bqProducer, bqConsumer,
2687 state.displayName);
2688
2689 dispSurface = vds;
2690 producer = vds;
2691 }
2692 } else {
2693 ALOGE_IF(state.surface != nullptr,
2694 "adding a supported display, but rendering "
2695 "surface is provided (%p), ignoring it",
2696 state.surface.get());
2697
Dominik Laskowski7e045462018-05-30 13:02:02 -07002698 displayId = state.type;
2699 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002700 producer = bqProducer;
2701 }
2702
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002703 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002704 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002705 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002706 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002707 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002708 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002709 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002710 if (mUseScheduler) {
2711 mScheduler->hotplugReceived(mAppConnectionHandle,
2712 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002713 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002714 } else {
2715 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2716 true);
2717 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002718 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002719 if (mUseScheduler) {
2720 mScheduler->hotplugReceived(mAppConnectionHandle,
2721 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002722 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002723 } else {
2724 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2725 true);
2726 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002727 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002728 }
2729 }
2730 }
2731 }
2732 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002733
2734 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002735}
2736
Mathias Agopian87baae12012-07-31 12:38:26 -07002737void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002738{
Dan Stoza7dde5992015-05-22 09:51:44 -07002739 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002740 mCurrentState.traverseInZOrder([](Layer* layer) {
2741 layer->notifyAvailableFrames();
2742 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002743
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002744 /*
2745 * Traversal of the children
2746 * (perform the transaction for each of them if needed)
2747 */
2748
Mathias Agopian3559b072012-08-15 13:46:03 -07002749 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002750 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002751 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002752 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002753
2754 const uint32_t flags = layer->doTransaction(0);
2755 if (flags & Layer::eVisibleRegion)
2756 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002757 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002758 }
2759
2760 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002761 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002762 */
2763
Mathias Agopiane57f2922012-08-09 16:29:12 -07002764 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002765 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002766 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002767 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002768
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002769 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002770 // The transform hint might have changed for some layers
2771 // (either because a display has changed, or because a layer
2772 // as changed).
2773 //
2774 // Walk through all the layers in currentLayers,
2775 // and update their transform hint.
2776 //
2777 // If a layer is visible only on a single display, then that
2778 // display is used to calculate the hint, otherwise we use the
2779 // default display.
2780 //
2781 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2782 // the hint is set before we acquire a buffer from the surface texture.
2783 //
2784 // NOTE: layer transactions have taken place already, so we use their
2785 // drawing state. However, SurfaceFlinger's own transaction has not
2786 // happened yet, so we must use the current state layer list
2787 // (soon to become the drawing state list).
2788 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002789 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002790 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002791 bool first = true;
2792 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002793 // NOTE: we rely on the fact that layers are sorted by
2794 // layerStack first (so we don't have to traverse the list
2795 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002796 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002797 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002798 currentlayerStack = layerStack;
2799 // figure out if this layerstack is mirrored
2800 // (more than one display) if so, pick the default display,
2801 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002802 hintDisplay = nullptr;
2803 for (const auto& [token, display] : mDisplays) {
2804 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2805 if (hintDisplay) {
2806 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002807 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002808 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002809 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002810 }
2811 }
2812 }
2813 }
Chet Haase91d25932013-04-11 15:24:55 -07002814
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002815 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002816 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2817 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002818
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002819 // could be null when this layer is using a layerStack
2820 // that is not visible on any display. Also can occur at
2821 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002822 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002823 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002824
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002825 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002826 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002827 if (hintDisplay) {
2828 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002829 }
Robert Carr2047fae2016-11-28 14:09:09 -08002830
2831 first = false;
2832 });
Mathias Agopian84300952012-11-21 16:02:13 -08002833 }
2834
2835
Mathias Agopian3559b072012-08-15 13:46:03 -07002836 /*
2837 * Perform our own transaction if needed
2838 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002839
2840 if (mLayersAdded) {
2841 mLayersAdded = false;
2842 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002843 mVisibleRegionsDirty = true;
2844 }
2845
2846 // some layers might have been removed, so
2847 // we need to update the regions they're exposing.
2848 if (mLayersRemoved) {
2849 mLayersRemoved = false;
2850 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002851 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002852 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002853 // this layer is not visible anymore
2854 // TODO: we could traverse the tree from front to back and
2855 // compute the actual visible region
2856 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002857 Region visibleReg;
2858 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002859 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002860 }
Robert Carr2047fae2016-11-28 14:09:09 -08002861 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002862 }
2863
2864 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002865
2866 updateCursorAsync();
2867}
2868
2869void SurfaceFlinger::updateCursorAsync()
2870{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002871 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002872 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002873 continue;
2874 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002875
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002876 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2877 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002878 }
2879 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002880}
2881
2882void SurfaceFlinger::commitTransaction()
2883{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002884 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002885 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002886 for (const auto& l : mLayersPendingRemoval) {
2887 recordBufferingStats(l->getName().string(),
2888 l->getOccupancyHistory(true));
2889 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002890 }
2891 mLayersPendingRemoval.clear();
2892 }
2893
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002894 // If this transaction is part of a window animation then the next frame
2895 // we composite should be considered an animation as well.
2896 mAnimCompositionPending = mAnimTransactionPending;
2897
Mathias Agopian4fec8732012-06-29 14:12:52 -07002898 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002899 // clear the "changed" flags in current state
2900 mCurrentState.colorMatrixChanged = false;
2901
Robert Carr1f0a16a2016-10-24 16:27:39 -07002902 mDrawingState.traverseInZOrder([](Layer* layer) {
2903 layer->commitChildList();
2904 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002905 mTransactionPending = false;
2906 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002907 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002908}
2909
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002910void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2911 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002912 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002913 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002914
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002915 Region aboveOpaqueLayers;
2916 Region aboveCoveredLayers;
2917 Region dirty;
2918
Mathias Agopian87baae12012-07-31 12:38:26 -07002919 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002920
Robert Carr2047fae2016-11-28 14:09:09 -08002921 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002922 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002923 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002924
Jesse Hall01e29052013-02-19 16:13:35 -08002925 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002926 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002927 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002928 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002929
Mathias Agopianab028732010-03-16 16:41:46 -07002930 /*
2931 * opaqueRegion: area of a surface that is fully opaque.
2932 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002933 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002934
2935 /*
2936 * visibleRegion: area of a surface that is visible on screen
2937 * and not fully transparent. This is essentially the layer's
2938 * footprint minus the opaque regions above it.
2939 * Areas covered by a translucent surface are considered visible.
2940 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002941 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002942
2943 /*
2944 * coveredRegion: area of a surface that is covered by all
2945 * visible regions above it (which includes the translucent areas).
2946 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002947 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002948
Jesse Halla8026d22012-09-25 13:25:04 -07002949 /*
2950 * transparentRegion: area of a surface that is hinted to be completely
2951 * transparent. This is only used to tell when the layer has no visible
2952 * non-transparent regions and can be removed from the layer list. It
2953 * does not affect the visibleRegion of this layer or any layers
2954 * beneath it. The hint may not be correct if apps don't respect the
2955 * SurfaceView restrictions (which, sadly, some don't).
2956 */
2957 Region transparentRegion;
2958
Mathias Agopianab028732010-03-16 16:41:46 -07002959
2960 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002961 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002962 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002963 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002964 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002965 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002966 if (!visibleRegion.isEmpty()) {
2967 // Remove the transparent area from the visible region
2968 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002969 if (tr.preserveRects()) {
2970 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002971 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002972 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002973 // transformation too complex, can't do the
2974 // transparent region optimization.
2975 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002976 }
Mathias Agopianab028732010-03-16 16:41:46 -07002977 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002978
Mathias Agopianab028732010-03-16 16:41:46 -07002979 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002980 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002981 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002982 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002983 // the opaque region is the layer's footprint
2984 opaqueRegion = visibleRegion;
2985 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002986 }
2987 }
2988
Robert Carre5f4f692018-01-12 13:12:28 -08002989 if (visibleRegion.isEmpty()) {
2990 layer->clearVisibilityRegions();
2991 return;
2992 }
2993
Mathias Agopianab028732010-03-16 16:41:46 -07002994 // Clip the covered region to the visible region
2995 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2996
2997 // Update aboveCoveredLayers for next (lower) layer
2998 aboveCoveredLayers.orSelf(visibleRegion);
2999
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003000 // subtract the opaque region covered by the layers above us
3001 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003002
3003 // compute this layer's dirty region
3004 if (layer->contentDirty) {
3005 // we need to invalidate the whole region
3006 dirty = visibleRegion;
3007 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003008 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003009 layer->contentDirty = false;
3010 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003011 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003012 * the exposed region consists of two components:
3013 * 1) what's VISIBLE now and was COVERED before
3014 * 2) what's EXPOSED now less what was EXPOSED before
3015 *
3016 * note that (1) is conservative, we start with the whole
3017 * visible region but only keep what used to be covered by
3018 * something -- which mean it may have been exposed.
3019 *
3020 * (2) handles areas that were not covered by anything but got
3021 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003022 */
Mathias Agopianab028732010-03-16 16:41:46 -07003023 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003024 const Region oldVisibleRegion = layer->visibleRegion;
3025 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003026 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3027 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003028 }
3029 dirty.subtractSelf(aboveOpaqueLayers);
3030
3031 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003032 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003033
Mathias Agopianab028732010-03-16 16:41:46 -07003034 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003035 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003036
Jesse Halla8026d22012-09-25 13:25:04 -07003037 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003038 layer->setVisibleRegion(visibleRegion);
3039 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003040 layer->setVisibleNonTransparentRegion(
3041 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003042 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003043
Mathias Agopian87baae12012-07-31 12:38:26 -07003044 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003045}
3046
Chia-I Wuab0c3192017-08-01 11:29:00 -07003047void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003048 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003049 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
3050 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003051 }
3052 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003053}
3054
Dan Stoza6b9454d2014-11-07 16:00:59 -08003055bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003056{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003057 ALOGV("handlePageFlip");
3058
Brian Andersond6927fb2016-07-23 23:37:30 -07003059 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003060
Mathias Agopian4fec8732012-06-29 14:12:52 -07003061 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003062 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003063 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003064
3065 // Store the set of layers that need updates. This set must not change as
3066 // buffers are being latched, as this could result in a deadlock.
3067 // Example: Two producers share the same command stream and:
3068 // 1.) Layer 0 is latched
3069 // 2.) Layer 0 gets a new frame
3070 // 2.) Layer 1 gets a new frame
3071 // 3.) Layer 1 is latched.
3072 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3073 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003074 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003075 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003076 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003077 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3078 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003079 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003080 } else {
3081 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003082 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003083 } else {
3084 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003085 }
Robert Carr2047fae2016-11-28 14:09:09 -08003086 });
3087
Dan Stoza9e56aa02015-11-02 13:00:03 -08003088 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri86770e52018-09-24 22:40:58 +00003089 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
Dan Stozaee44edd2015-03-23 15:50:23 -07003090 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003091 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07003092 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06003093 newDataLatched = true;
3094 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003095 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003096
Alec Mouri86770e52018-09-24 22:40:58 +00003097 // Clear the renderengine fence here...
3098 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3099 // clear instead of sp::clear.
3100 getBE().flushFence = Fence::NO_FENCE;
3101
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003102 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003103
3104 // If we will need to wake up at some time in the future to deal with a
3105 // queued frame that shouldn't be displayed during this vsync period, wake
3106 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003107 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003108 signalLayerUpdate();
3109 }
3110
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003111 // enter boot animation on first buffer latch
3112 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3113 ALOGI("Enter boot animation");
3114 mBootStage = BootStage::BOOTANIMATION;
3115 }
3116
Dan Stoza6b9454d2014-11-07 16:00:59 -08003117 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003118 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003119}
3120
Mathias Agopianad456f92011-01-13 17:53:01 -08003121void SurfaceFlinger::invalidateHwcGeometry()
3122{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003123 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003124}
3125
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003126void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
3127 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003128 // We only need to actually compose the display if:
3129 // 1) It is being handled by hardware composer, which may need this to
3130 // keep its virtual display state machine in sync, or
3131 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07003132 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08003133 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003134 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003135 return;
3136 }
3137
Dan Stoza9e56aa02015-11-02 13:00:03 -08003138 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003139 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003140
3141 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003142 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003143}
3144
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003145bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003146 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003147
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003148 const Region bounds(display->bounds());
3149 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003150 const auto displayId = display->getId();
3151 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003152 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003153
Peiyong Lind3788632018-09-18 16:01:31 -07003154 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003155 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003156 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003157
Dan Stoza9e56aa02015-11-02 13:00:03 -08003158 if (hasClientComposition) {
3159 ALOGV("hasClientComposition");
3160
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003161 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003162 if (display->hasWideColorGamut()) {
3163 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003164 }
3165 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003166 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003167 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003168
Dominik Laskowski7e045462018-05-30 13:02:02 -07003169 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003170 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3171 HWC2::Capability::SkipClientColorTransform);
3172
Peiyong Lind3788632018-09-18 16:01:31 -07003173 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003174 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3175 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003176 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003177 }
3178
Chia-I Wud49d6692018-06-27 07:17:41 +08003179 // The current enhanced saturation matrix is designed to enhance Display P3,
3180 // thus we only apply this matrix when the render intent is not colorimetric
3181 // and the output color space is Display P3.
3182 needsEnhancedColorMatrix =
3183 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3184 outputDataspace == Dataspace::DISPLAY_P3);
3185 if (needsEnhancedColorMatrix) {
3186 colorMatrix *= mEnhancedSaturationMatrix;
3187 }
3188
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003189 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003190 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003191 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003192 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003193
3194 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003195 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3196 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3197 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003198 }
3199 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003200 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003201
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003202 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003203 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003204 // when using overlays, we assume a fully transparent framebuffer
3205 // NOTE: we could reduce how much we need to clear, for instance
3206 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003207 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003208 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003209 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003210 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003211 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003212 // we're left with the letterbox region
3213 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003214 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003215
3216 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003217 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003218
Mathias Agopianb9494d52012-04-18 02:28:45 -07003219 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003220 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003221 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003222 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003223 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003224 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003225
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003226 const Rect& bounds = display->getBounds();
3227 const Rect& scissor = display->getScissor();
3228 if (scissor != bounds) {
3229 // scissor doesn't match the screen's dimensions, so we
3230 // need to clear everything outside of it and enable
3231 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003232
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003233 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003234 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003235 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003236 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003237
Mathias Agopian85d751c2012-08-29 16:59:24 -07003238 /*
3239 * and then, render the layers targeted at the framebuffer
3240 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003241
Dan Stoza9e56aa02015-11-02 13:00:03 -08003242 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003243 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003244 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003245 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003246 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003247 displayTransform.transform(layer->visibleRegion)));
3248 ALOGV("Layer: %s", layer->getName().string());
3249 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003250 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003251 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003252 case HWC2::Composition::Cursor:
3253 case HWC2::Composition::Device:
3254 case HWC2::Composition::Sideband:
3255 case HWC2::Composition::SolidColor: {
David Sodmanc1498e62018-09-12 14:36:26 -07003256 const Layer::State& state(layer->getDrawingState());
3257 if (layer->getClearClientTarget(displayId) && !firstLayer &&
3258 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3259 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003260 // never clear the very first layer since we're
3261 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003262 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003263 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003264 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003265 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003266 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003267 if (layer->hasColorTransform()) {
3268 mat4 tmpMatrix;
3269 if (applyColorMatrix) {
3270 tmpMatrix = mDrawingState.colorMatrix;
3271 }
3272 tmpMatrix *= layer->getColorTransform();
3273 if (needsEnhancedColorMatrix) {
3274 tmpMatrix *= mEnhancedSaturationMatrix;
3275 }
3276 getRenderEngine().setColorTransform(tmpMatrix);
3277 } else {
3278 getRenderEngine().setColorTransform(colorMatrix);
3279 }
David Sodmanc1498e62018-09-12 14:36:26 -07003280 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003281 break;
3282 }
3283 default:
3284 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003285 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003286 } else {
3287 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003288 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003289 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003290 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003291
Peiyong Lind3788632018-09-18 16:01:31 -07003292 // Clear color transform matrix at the end of the frame.
3293 getRenderEngine().setColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003294
Mathias Agopianf45c5102012-10-24 16:29:17 -07003295 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003296 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003297 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003298}
3299
Chia-I Wu28e3a252018-09-07 12:05:02 -07003300void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003301 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003302 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003303}
3304
Dan Stoza7d89d062015-04-30 13:29:25 -07003305status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003306 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003307 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003308 const sp<Layer>& lbc,
3309 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003310{
Dan Stoza7d89d062015-04-30 13:29:25 -07003311 // add this layer to the current state list
3312 {
3313 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003314 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003315 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3316 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003317 return NO_MEMORY;
3318 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003319 if (parent == nullptr) {
3320 mCurrentState.layersSortedByZ.add(lbc);
3321 } else {
Rob Carr4bba3702018-10-08 21:53:30 +00003322 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003323 ALOGE("addClientLayer called with a removed parent");
3324 return NAME_NOT_FOUND;
3325 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003326 parent->addChild(lbc);
3327 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003328
Yiwei Zhang243b3782018-05-15 17:40:04 -07003329 if (gbc != nullptr) {
3330 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3331 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3332 mMaxGraphicBufferProducerListSize,
3333 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3334 mGraphicBufferProducerList.size(),
3335 mMaxGraphicBufferProducerListSize, mNumLayers);
3336 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003337 mLayersAdded = true;
3338 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003339 }
3340
Mathias Agopian96f08192010-06-02 23:28:45 -07003341 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003342 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003343
Dan Stoza7d89d062015-04-30 13:29:25 -07003344 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003345}
3346
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003347status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003348 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003349 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3350}
Robert Carr7f9b8992017-03-10 11:08:39 -08003351
chaviwca27f252018-02-06 16:46:39 -08003352status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3353 bool topLevelOnly) {
Rob Carr4bba3702018-10-08 21:53:30 +00003354 if (layer->isPendingRemoval()) {
chaviw8b3871a2017-11-01 17:41:01 -07003355 return NO_ERROR;
3356 }
3357
Robert Carr1f0a16a2016-10-24 16:27:39 -07003358 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003359 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003360 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003361 if (topLevelOnly) {
3362 return NO_ERROR;
3363 }
Rob Carr4bba3702018-10-08 21:53:30 +00003364
3365 sp<Layer> ancestor = p;
3366 while (ancestor->getParent() != nullptr) {
3367 ancestor = ancestor->getParent();
3368 }
3369 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3370 ALOGE("removeLayer called with a layer whose parent has been removed");
3371 return NAME_NOT_FOUND;
3372 }
3373
Chia-I Wufae51c42017-06-15 12:53:59 -07003374 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003375 } else {
3376 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003377 }
3378
Rob Carr4bba3702018-10-08 21:53:30 +00003379 // As a matter of normal operation, the LayerCleaner will produce a second
3380 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3381 // so we will succeed in promoting it, but it's already been removed
3382 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3383 // otherwise something has gone wrong and we are leaking the layer.
3384 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
3385 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3386 layer->getName().string(),
3387 (p != nullptr) ? p->getName().string() : "no-parent");
3388 return BAD_VALUE;
3389 } else if (index < 0) {
3390 return NO_ERROR;
3391 }
3392
Chia-I Wuc6657022017-08-15 11:18:17 -07003393 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003394 mLayersPendingRemoval.add(layer);
3395 mLayersRemoved = true;
Rob Carr4bba3702018-10-08 21:53:30 +00003396 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003397 setTransactionFlags(eTransactionNeeded);
3398 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003399}
3400
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003401uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003402 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003403}
3404
Mathias Agopian3f844832013-08-07 21:24:32 -07003405uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003406 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003407}
3408
Mathias Agopian3f844832013-08-07 21:24:32 -07003409uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003410 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003411}
3412
3413uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003414 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003415 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003416 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003417 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003418 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003419 }
3420 return old;
3421}
3422
chaviwca27f252018-02-06 16:46:39 -08003423bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3424 for (const ComposerState& state : states) {
3425 // Here we need to check that the interface we're given is indeed
3426 // one of our own. A malicious client could give us a nullptr
3427 // IInterface, or one of its own or even one of our own but a
3428 // different type. All these situations would cause us to crash.
3429 if (state.client == nullptr) {
3430 return true;
3431 }
3432
3433 sp<IBinder> binder = IInterface::asBinder(state.client);
3434 if (binder == nullptr) {
3435 return true;
3436 }
3437
3438 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3439 return true;
3440 }
3441 }
3442 return false;
3443}
3444
Mathias Agopian8b33f032012-07-24 20:43:54 -07003445void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003446 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003447 const Vector<DisplayState>& displays,
3448 uint32_t flags)
3449{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003450 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003451 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003452 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003453
chaviwca27f252018-02-06 16:46:39 -08003454 if (containsAnyInvalidClientState(states)) {
3455 return;
3456 }
3457
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003458 if (flags & eAnimation) {
3459 // For window updates that are part of an animation we must wait for
3460 // previous animation "frames" to be handled.
3461 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003462 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003463 if (CC_UNLIKELY(err != NO_ERROR)) {
3464 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003465 // caller after a few seconds.
3466 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3467 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003468 mAnimTransactionPending = false;
3469 break;
3470 }
3471 }
3472 }
3473
chaviwca27f252018-02-06 16:46:39 -08003474 for (const DisplayState& display : displays) {
3475 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003476 }
3477
chaviwca27f252018-02-06 16:46:39 -08003478 for (const ComposerState& state : states) {
3479 transactionFlags |= setClientStateLocked(state);
3480 }
3481
3482 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3483 // as destroyed should only occur after setting all other states. This is to allow for a
3484 // child re-parent to happen before marking its original parent as destroyed (which would
3485 // then mark the child as destroyed).
3486 for (const ComposerState& state : states) {
3487 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003488 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003489
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003490 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3491 // anyway. This can be used as a flush mechanism for previous async transactions.
3492 // Empty animation transaction can be used to simulate back-pressure, so also force a
3493 // transaction for empty animation transactions.
3494 if (transactionFlags == 0 &&
3495 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003496 transactionFlags = eTransactionNeeded;
3497 }
3498
Mathias Agopian386aa982011-11-07 21:58:03 -08003499 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003500 if (mInterceptor->isEnabled()) {
3501 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003502 }
Irvel468051e2016-06-13 16:44:44 -07003503
Mathias Agopian386aa982011-11-07 21:58:03 -08003504 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003505 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3506 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003507 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003508
3509 // if this is a synchronous transaction, wait for it to take effect
3510 // before returning.
3511 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003512 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003513 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003514 if (flags & eAnimation) {
3515 mAnimTransactionPending = true;
3516 }
3517 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003518 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3519 if (CC_UNLIKELY(err != NO_ERROR)) {
3520 // just in case something goes wrong in SF, return to the
3521 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003522 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3523 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003524 break;
3525 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003526 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003527 }
3528}
3529
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003530uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3531 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3532 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003533
Mathias Agopiane57f2922012-08-09 16:29:12 -07003534 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003535 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3536
3537 const uint32_t what = s.what;
3538 if (what & DisplayState::eSurfaceChanged) {
3539 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3540 state.surface = s.surface;
3541 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003542 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003543 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003544 if (what & DisplayState::eLayerStackChanged) {
3545 if (state.layerStack != s.layerStack) {
3546 state.layerStack = s.layerStack;
3547 flags |= eDisplayTransactionNeeded;
3548 }
3549 }
3550 if (what & DisplayState::eDisplayProjectionChanged) {
3551 if (state.orientation != s.orientation) {
3552 state.orientation = s.orientation;
3553 flags |= eDisplayTransactionNeeded;
3554 }
3555 if (state.frame != s.frame) {
3556 state.frame = s.frame;
3557 flags |= eDisplayTransactionNeeded;
3558 }
3559 if (state.viewport != s.viewport) {
3560 state.viewport = s.viewport;
3561 flags |= eDisplayTransactionNeeded;
3562 }
3563 }
3564 if (what & DisplayState::eDisplaySizeChanged) {
3565 if (state.width != s.width) {
3566 state.width = s.width;
3567 flags |= eDisplayTransactionNeeded;
3568 }
3569 if (state.height != s.height) {
3570 state.height = s.height;
3571 flags |= eDisplayTransactionNeeded;
3572 }
3573 }
3574
Mathias Agopiane57f2922012-08-09 16:29:12 -07003575 return flags;
3576}
3577
Robert Carrd4ae7f32018-06-07 16:10:57 -07003578bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3579 IPCThreadState* ipc = IPCThreadState::self();
3580 const int pid = ipc->getCallingPid();
3581 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003582 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003583 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003584 return false;
3585 }
3586 return true;
3587}
3588
chaviwca27f252018-02-06 16:46:39 -08003589uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3590 const layer_state_t& s = composerState.state;
3591 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3592
Mathias Agopian13127d82013-03-05 17:47:11 -08003593 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003594 if (layer == nullptr) {
3595 return 0;
3596 }
3597
Rob Carr4bba3702018-10-08 21:53:30 +00003598 if (layer->isPendingRemoval()) {
chaviw8b3871a2017-11-01 17:41:01 -07003599 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3600 return 0;
3601 }
3602
3603 uint32_t flags = 0;
3604
3605 const uint32_t what = s.what;
3606 bool geometryAppliesWithResize =
3607 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003608
3609 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3610 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003611 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003612 layer->pushPendingState();
3613 }
3614
chaviw8b3871a2017-11-01 17:41:01 -07003615 if (what & layer_state_t::ePositionChanged) {
3616 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3617 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003618 }
chaviw8b3871a2017-11-01 17:41:01 -07003619 }
3620 if (what & layer_state_t::eLayerChanged) {
3621 // NOTE: index needs to be calculated before we update the state
3622 const auto& p = layer->getParent();
3623 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003624 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003625 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003626 mCurrentState.layersSortedByZ.removeAt(idx);
3627 mCurrentState.layersSortedByZ.add(layer);
3628 // we need traversal (state changed)
3629 // AND transaction (list changed)
3630 flags |= eTransactionNeeded|eTraversalNeeded;
3631 }
chaviw8b3871a2017-11-01 17:41:01 -07003632 } else {
3633 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003634 flags |= eTransactionNeeded|eTraversalNeeded;
3635 }
3636 }
chaviw8b3871a2017-11-01 17:41:01 -07003637 }
3638 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003639 // NOTE: index needs to be calculated before we update the state
3640 const auto& p = layer->getParent();
3641 if (p == nullptr) {
3642 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3643 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3644 mCurrentState.layersSortedByZ.removeAt(idx);
3645 mCurrentState.layersSortedByZ.add(layer);
3646 // we need traversal (state changed)
3647 // AND transaction (list changed)
3648 flags |= eTransactionNeeded|eTraversalNeeded;
3649 }
3650 } else {
3651 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3652 flags |= eTransactionNeeded|eTraversalNeeded;
3653 }
chaviw8b3871a2017-11-01 17:41:01 -07003654 }
3655 }
3656 if (what & layer_state_t::eSizeChanged) {
3657 if (layer->setSize(s.w, s.h)) {
3658 flags |= eTraversalNeeded;
3659 }
3660 }
3661 if (what & layer_state_t::eAlphaChanged) {
3662 if (layer->setAlpha(s.alpha))
3663 flags |= eTraversalNeeded;
3664 }
3665 if (what & layer_state_t::eColorChanged) {
3666 if (layer->setColor(s.color))
3667 flags |= eTraversalNeeded;
3668 }
Peiyong Lind3788632018-09-18 16:01:31 -07003669 if (what & layer_state_t::eColorTransformChanged) {
3670 if (layer->setColorTransform(s.colorTransform)) {
3671 flags |= eTraversalNeeded;
3672 }
3673 }
chaviw8b3871a2017-11-01 17:41:01 -07003674 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003675 // TODO: b/109894387
3676 //
3677 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3678 // rotation. To see the problem observe that if we have a square parent, and a child
3679 // of the same size, then we rotate the child 45 degrees around it's center, the child
3680 // must now be cropped to a non rectangular 8 sided region.
3681 //
3682 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3683 // private API, and the WindowManager only uses rotation in one case, which is on a top
3684 // level layer in which cropping is not an issue.
3685 //
3686 // However given that abuse of rotation matrices could lead to surfaces extending outside
3687 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3688 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3689 // transformations.
3690 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003691 flags |= eTraversalNeeded;
3692 }
3693 if (what & layer_state_t::eTransparentRegionChanged) {
3694 if (layer->setTransparentRegionHint(s.transparentRegion))
3695 flags |= eTraversalNeeded;
3696 }
3697 if (what & layer_state_t::eFlagsChanged) {
3698 if (layer->setFlags(s.flags, s.mask))
3699 flags |= eTraversalNeeded;
3700 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003701 if (what & layer_state_t::eCropChanged_legacy) {
3702 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003703 flags |= eTraversalNeeded;
3704 }
chaviw8b3871a2017-11-01 17:41:01 -07003705 if (what & layer_state_t::eLayerStackChanged) {
3706 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3707 // We only allow setting layer stacks for top level layers,
3708 // everything else inherits layer stack from its parent.
3709 if (layer->hasParent()) {
3710 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3711 layer->getName().string());
3712 } else if (idx < 0) {
3713 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3714 "that also does not appear in the top level layer list. Something"
3715 " has gone wrong.", layer->getName().string());
3716 } else if (layer->setLayerStack(s.layerStack)) {
3717 mCurrentState.layersSortedByZ.removeAt(idx);
3718 mCurrentState.layersSortedByZ.add(layer);
3719 // we need traversal (state changed)
3720 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003721 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003722 }
3723 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003724 if (what & layer_state_t::eDeferTransaction_legacy) {
3725 if (s.barrierHandle_legacy != nullptr) {
3726 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3727 } else if (s.barrierGbp_legacy != nullptr) {
3728 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003729 if (authenticateSurfaceTextureLocked(gbp)) {
3730 const auto& otherLayer =
3731 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003732 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003733 } else {
3734 ALOGE("Attempt to defer transaction to to an"
3735 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003736 }
3737 }
chaviw8b3871a2017-11-01 17:41:01 -07003738 // We don't trigger a traversal here because if no other state is
3739 // changed, we don't want this to cause any more work
3740 }
3741 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003742 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003743 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003744 if (!hadParent) {
3745 mCurrentState.layersSortedByZ.remove(layer);
3746 }
chaviw8b3871a2017-11-01 17:41:01 -07003747 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003748 }
chaviw8b3871a2017-11-01 17:41:01 -07003749 }
3750 if (what & layer_state_t::eReparentChildren) {
3751 if (layer->reparentChildren(s.reparentHandle)) {
3752 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003753 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003754 }
chaviw8b3871a2017-11-01 17:41:01 -07003755 if (what & layer_state_t::eDetachChildren) {
3756 layer->detachChildren();
3757 }
3758 if (what & layer_state_t::eOverrideScalingModeChanged) {
3759 layer->setOverrideScalingMode(s.overrideScalingMode);
3760 // We don't trigger a traversal here because if no other state is
3761 // changed, we don't want this to cause any more work
3762 }
Marissa Wall61c58622018-07-18 10:12:20 -07003763 if (what & layer_state_t::eTransformChanged) {
3764 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3765 }
3766 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3767 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3768 flags |= eTraversalNeeded;
3769 }
3770 if (what & layer_state_t::eCropChanged) {
3771 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3772 }
3773 if (what & layer_state_t::eBufferChanged) {
3774 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3775 }
3776 if (what & layer_state_t::eAcquireFenceChanged) {
3777 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3778 }
3779 if (what & layer_state_t::eDataspaceChanged) {
3780 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3781 }
3782 if (what & layer_state_t::eHdrMetadataChanged) {
3783 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3784 }
3785 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3786 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3787 }
3788 if (what & layer_state_t::eApiChanged) {
3789 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3790 }
3791 if (what & layer_state_t::eSidebandStreamChanged) {
3792 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3793 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003794 return flags;
3795}
3796
chaviwca27f252018-02-06 16:46:39 -08003797void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3798 const layer_state_t& state = composerState.state;
3799 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3800
3801 sp<Layer> layer(client->getLayerUser(state.surface));
3802 if (layer == nullptr) {
3803 return;
3804 }
3805
Rob Carr4bba3702018-10-08 21:53:30 +00003806 if (layer->isPendingRemoval()) {
chaviwca27f252018-02-06 16:46:39 -08003807 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3808 return;
3809 }
3810
3811 if (state.what & layer_state_t::eDestroySurface) {
3812 removeLayerLocked(mStateLock, layer);
3813 }
3814}
3815
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003816status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003817 const String8& name,
3818 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003819 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003820 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003821 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003822{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003823 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003824 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003825 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003826 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003827 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003828
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003829 status_t result = NO_ERROR;
3830
3831 sp<Layer> layer;
3832
Cody Northropbc755282017-03-31 12:00:08 -06003833 String8 uniqueName = getUniqueLayerName(name);
3834
Mathias Agopian3165cc22012-08-08 19:42:09 -07003835 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003836 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003837 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3838 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003839
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003840 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003841 case ISurfaceComposerClient::eFXSurfaceBufferState:
3842 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3843 break;
chaviw13fdc492017-06-27 12:40:18 -07003844 case ISurfaceComposerClient::eFXSurfaceColor:
3845 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003846 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003847 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003848 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003849 case ISurfaceComposerClient::eFXSurfaceContainer:
3850 result = createContainerLayer(client,
3851 uniqueName, w, h, flags,
3852 handle, &layer);
3853 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003854 default:
3855 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003856 break;
3857 }
3858
Dan Stoza7d89d062015-04-30 13:29:25 -07003859 if (result != NO_ERROR) {
3860 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003861 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003862
Chia-I Wuab0c3192017-08-01 11:29:00 -07003863 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3864 // TODO b/64227542
3865 if (windowType == 441731) {
3866 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3867 layer->setPrimaryDisplayOnly();
3868 }
3869
Albert Chaulk479c60c2017-01-27 14:21:34 -05003870 layer->setInfo(windowType, ownerUid);
3871
Robert Carr1f0a16a2016-10-24 16:27:39 -07003872 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003873 if (result != NO_ERROR) {
3874 return result;
3875 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003876 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003877
3878 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003879 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003880}
3881
Cody Northropbc755282017-03-31 12:00:08 -06003882String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3883{
3884 bool matchFound = true;
3885 uint32_t dupeCounter = 0;
3886
3887 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3888 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3889
Dan Stoza436ccf32018-06-21 12:10:12 -07003890 // Grab the state lock since we're accessing mCurrentState
3891 Mutex::Autolock lock(mStateLock);
3892
Cody Northropbc755282017-03-31 12:00:08 -06003893 // Loop over layers until we're sure there is no matching name
3894 while (matchFound) {
3895 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003896 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003897 if (layer->getName() == uniqueName) {
3898 matchFound = true;
3899 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3900 }
3901 });
3902 }
3903
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003904 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3905 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003906
3907 return uniqueName;
3908}
3909
Marissa Wallfd668622018-05-10 10:21:13 -07003910status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3911 uint32_t w, uint32_t h, uint32_t flags,
3912 PixelFormat& format, sp<IBinder>* handle,
3913 sp<IGraphicBufferProducer>* gbp,
3914 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003915 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003916 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003917 case PIXEL_FORMAT_TRANSPARENT:
3918 case PIXEL_FORMAT_TRANSLUCENT:
3919 format = PIXEL_FORMAT_RGBA_8888;
3920 break;
3921 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003922 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003923 break;
3924 }
3925
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003926 sp<BufferQueueLayer> layer =
3927 new BufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003928 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003929 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003930 *handle = layer->getHandle();
3931 *gbp = layer->getProducer();
3932 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003933 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003934
Marissa Wallfd668622018-05-10 10:21:13 -07003935 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003936 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003937}
3938
Marissa Wall61c58622018-07-18 10:12:20 -07003939status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3940 uint32_t w, uint32_t h, uint32_t flags,
3941 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003942 sp<BufferStateLayer> layer =
3943 new BufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003944 *handle = layer->getHandle();
3945 *outLayer = layer;
3946
3947 return NO_ERROR;
3948}
3949
chaviw13fdc492017-06-27 12:40:18 -07003950status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003951 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003952 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003953{
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003954 *outLayer = new ColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003955 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003956 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003957}
3958
Robert Carr6b3f6c52018-08-13 13:05:17 -07003959status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3960 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3961 sp<IBinder>* handle, sp<Layer>* outLayer)
3962{
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003963 *outLayer = new ContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003964 *handle = (*outLayer)->getHandle();
3965 return NO_ERROR;
3966}
3967
3968
Mathias Agopianac9fa422013-02-11 16:40:36 -08003969status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003970{
Robert Carr9524cb32017-02-13 11:32:32 -08003971 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003972 status_t err = NO_ERROR;
3973 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003974 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003975 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003976 err = removeLayer(l);
3977 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3978 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003979 }
3980 return err;
3981}
3982
Rob Carr4bba3702018-10-08 21:53:30 +00003983status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
3984{
3985 // called by ~LayerCleaner() when all references to the IBinder (handle)
3986 // are gone
3987 sp<Layer> l = layer.promote();
3988 if (l == nullptr) {
3989 // The layer has already been removed, carry on
3990 return NO_ERROR;
3991 }
3992 // If we have a parent, then we can continue to live as long as it does.
3993 return removeLayer(l, true);
3994}
3995
Mathias Agopianb60314a2012-04-10 22:09:54 -07003996// ---------------------------------------------------------------------------
3997
Andy McFadden13a082e2012-08-24 10:16:42 -07003998void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003999 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
4000 if (!displayToken) return;
4001
Jesse Hall01e29052013-02-19 16:13:35 -08004002 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004003 Vector<ComposerState> state;
4004 Vector<DisplayState> displays;
4005 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004006 d.what = DisplayState::eDisplayProjectionChanged |
4007 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004008 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08004009 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004010 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004011 d.frame.makeInvalid();
4012 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004013 d.width = 0;
4014 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004015 displays.add(d);
4016 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004017
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004018 const auto display = getDisplayDevice(displayToken);
4019 if (!display) return;
4020
4021 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
4022
4023 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08004024 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07004025 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004026
Brian Andersond0010582017-03-07 13:20:31 -08004027 // Use phase of 0 since phase is not known.
4028 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07004029 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
4030 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004031}
4032
4033void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004034 // Async since we may be called from the main thread.
4035 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004036}
4037
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004038void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
4039 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004040 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004041 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07004042
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004043 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004044 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004045 return;
4046 }
4047
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004048 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004049 ALOGW("Trying to set power mode for virtual display");
4050 return;
4051 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004052
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004053 display->setPowerMode(mode);
4054
Lloyd Pique4dccc412018-01-22 17:21:36 -08004055 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07004056 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004057 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07004058 if (idx < 0) {
4059 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
4060 return;
4061 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07004062 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07004063 }
4064
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004065 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004066 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004067 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004068 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004069 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004070 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004071 if (mUseScheduler) {
4072 mScheduler->onScreenAcquired(mAppConnectionHandle);
4073 } else {
4074 mEventThread->onScreenAcquired();
4075 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07004076 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004077 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004078
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004079 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004080 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004081 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004082
4083 struct sched_param param = {0};
4084 param.sched_priority = 1;
4085 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4086 ALOGW("Couldn't set SCHED_FIFO on display on");
4087 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004088 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004089 // Turn off the display
4090 struct sched_param param = {0};
4091 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4092 ALOGW("Couldn't set SCHED_OTHER on display off");
4093 }
4094
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004095 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004096 if (mUseScheduler) {
4097 mScheduler->disableHardwareVsync(true);
4098 } else {
4099 disableHardwareVsync(true); // also cancels any in-progress resync
4100 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004101 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004102 if (mUseScheduler) {
4103 mScheduler->onScreenReleased(mAppConnectionHandle);
4104 } else {
4105 mEventThread->onScreenReleased();
4106 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004107 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004108
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004109 getHwComposer().setPowerMode(type, mode);
4110 mVisibleRegionsDirty = true;
4111 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004112 } else if (mode == HWC_POWER_MODE_DOZE ||
4113 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004114 // Update display while dozing
4115 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004116 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004117 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004118 if (mUseScheduler) {
4119 mScheduler->onScreenAcquired(mAppConnectionHandle);
4120 } else {
4121 mEventThread->onScreenAcquired();
4122 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004123 resyncToHardwareVsync(true);
4124 }
4125 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4126 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004127 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004128 if (mUseScheduler) {
4129 mScheduler->disableHardwareVsync(true);
4130 } else {
4131 disableHardwareVsync(true); // also cancels any in-progress resync
4132 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004133 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004134 if (mUseScheduler) {
4135 mScheduler->onScreenReleased(mAppConnectionHandle);
4136 } else {
4137 mEventThread->onScreenReleased();
4138 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004139 }
4140 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004141 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004142 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004143 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004144 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004145
4146 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004147}
4148
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004149void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004150 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004151 const auto display = getDisplayDevice(displayToken);
4152 if (!display) {
4153 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4154 displayToken.get());
4155 } else if (display->isVirtual()) {
4156 ALOGW("Attempt to set power mode %d for virtual display", mode);
4157 } else {
4158 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004159 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004160 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004161}
4162
4163// ---------------------------------------------------------------------------
4164
Lloyd Pique755e3192018-01-31 16:46:15 -08004165status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4166 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004167 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004168
Mathias Agopianbd115332013-04-18 16:41:04 -07004169 IPCThreadState* ipc = IPCThreadState::self();
4170 const int pid = ipc->getCallingPid();
4171 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004172
Mathias Agopianbd115332013-04-18 16:41:04 -07004173 if ((uid != AID_SHELL) &&
4174 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004175 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07004176 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004177 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004178 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004179 // (this would indicate SF is stuck, but we want to be able to
4180 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004181 status_t err = mStateLock.timedLock(s2ns(1));
4182 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004183 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004184 result.appendFormat(
4185 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4186 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004187 }
4188
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004189 bool dumpAll = true;
4190 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004191 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004192
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004193 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004194 if ((index < numArgs) &&
4195 (args[index] == String16("--list"))) {
4196 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004197 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004198 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004199 }
4200
4201 if ((index < numArgs) &&
4202 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004203 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004204 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004205 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004206 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004207
4208 if ((index < numArgs) &&
4209 (args[index] == String16("--latency-clear"))) {
4210 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004211 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004212 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004213 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004214
4215 if ((index < numArgs) &&
4216 (args[index] == String16("--dispsync"))) {
4217 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004218 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004219 dumpAll = false;
4220 }
Dan Stozab90cf072015-03-05 11:05:59 -08004221
4222 if ((index < numArgs) &&
4223 (args[index] == String16("--static-screen"))) {
4224 index++;
4225 dumpStaticScreenStats(result);
4226 dumpAll = false;
4227 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004228
4229 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004230 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004231 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004232 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004233 dumpAll = false;
4234 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004235
4236 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4237 index++;
4238 dumpWideColorInfo(result);
4239 dumpAll = false;
4240 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004241
4242 if ((index < numArgs) &&
4243 (args[index] == String16("--enable-layer-stats"))) {
4244 index++;
4245 mLayerStats.enable();
4246 dumpAll = false;
4247 }
4248
4249 if ((index < numArgs) &&
4250 (args[index] == String16("--disable-layer-stats"))) {
4251 index++;
4252 mLayerStats.disable();
4253 dumpAll = false;
4254 }
4255
4256 if ((index < numArgs) &&
4257 (args[index] == String16("--clear-layer-stats"))) {
4258 index++;
4259 mLayerStats.clear();
4260 dumpAll = false;
4261 }
4262
4263 if ((index < numArgs) &&
4264 (args[index] == String16("--dump-layer-stats"))) {
4265 index++;
4266 mLayerStats.dump(result);
4267 dumpAll = false;
4268 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004269
4270 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004271 (args[index] == String16("--frame-composition"))) {
4272 index++;
4273 dumpFrameCompositionInfo(result);
4274 dumpAll = false;
4275 }
4276
4277 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004278 (args[index] == String16("--display-identification"))) {
4279 index++;
4280 dumpDisplayIdentificationData(result);
4281 dumpAll = false;
4282 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004283
4284 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4285 index++;
4286 mTimeStats.parseArgs(asProto, args, index, result);
4287 dumpAll = false;
4288 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004289 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004290
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004291 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004292 if (asProto) {
4293 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4294 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4295 } else {
4296 dumpAllLocked(args, index, result);
4297 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004298 }
4299
Mathias Agopian9795c422009-08-26 16:36:26 -07004300 if (locked) {
4301 mStateLock.unlock();
4302 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004303 }
4304 write(fd, result.string(), result.size());
4305 return NO_ERROR;
4306}
4307
Dan Stozac7014012014-02-14 15:03:43 -08004308void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4309 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004310{
Robert Carr2047fae2016-11-28 14:09:09 -08004311 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004312 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004313 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004314}
4315
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004316void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004317 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004318{
4319 String8 name;
4320 if (index < args.size()) {
4321 name = String8(args[index]);
4322 index++;
4323 }
4324
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004325 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4326 getHwComposer().isConnected(displayId)) {
4327 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4328 const nsecs_t period = activeConfig->getVsyncPeriod();
4329 result.appendFormat("%" PRId64 "\n", period);
4330 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004331
4332 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004333 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004334 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004335 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004336 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004337 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004338 }
Robert Carr2047fae2016-11-28 14:09:09 -08004339 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004340 }
4341}
4342
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004343void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004344 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004345{
4346 String8 name;
4347 if (index < args.size()) {
4348 name = String8(args[index]);
4349 index++;
4350 }
4351
Robert Carr2047fae2016-11-28 14:09:09 -08004352 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004353 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004354 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004355 }
Robert Carr2047fae2016-11-28 14:09:09 -08004356 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004357
Svetoslavd85084b2014-03-20 10:28:31 -07004358 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004359}
4360
Jamie Gennis6547ff42013-07-16 20:12:42 -07004361// This should only be called from the main thread. Otherwise it would need
4362// the lock and should use mCurrentState rather than mDrawingState.
4363void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004364 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004365 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004366 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004367
4368 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4369}
4370
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004371void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004372{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004373 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004374
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004375 if (isLayerTripleBufferingDisabled())
4376 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004377
4378 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004379 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004380 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004381 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004382 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4383 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004384 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004385}
4386
Dan Stozab90cf072015-03-05 11:05:59 -08004387void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4388{
4389 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004390 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4391 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004392 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004393 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004394 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4395 b + 1, bucketTimeSec, percent);
4396 }
David Sodman4a36e932017-11-07 14:29:47 -08004397 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004398 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004399 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004400 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004401 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004402}
4403
Dan Stozae77c7662016-05-13 11:37:28 -07004404void SurfaceFlinger::recordBufferingStats(const char* layerName,
4405 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004406 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4407 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004408 for (const auto& segment : history) {
4409 if (!segment.usedThirdBuffer) {
4410 stats.twoBufferTime += segment.totalTime;
4411 }
4412 if (segment.occupancyAverage < 1.0f) {
4413 stats.doubleBufferedTime += segment.totalTime;
4414 } else if (segment.occupancyAverage < 2.0f) {
4415 stats.tripleBufferedTime += segment.totalTime;
4416 }
4417 ++stats.numSegments;
4418 stats.totalTime += segment.totalTime;
4419 }
4420}
4421
Brian Andersond6927fb2016-07-23 23:37:30 -07004422void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4423 result.appendFormat("Layer frame timestamps:\n");
4424
4425 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4426 const size_t count = currentLayers.size();
4427 for (size_t i=0 ; i<count ; i++) {
4428 currentLayers[i]->dumpFrameEvents(result);
4429 }
4430}
4431
Dan Stozae77c7662016-05-13 11:37:28 -07004432void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4433 result.append("Buffering stats:\n");
4434 result.append(" [Layer name] <Active time> <Two buffer> "
4435 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004436 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004437 typedef std::tuple<std::string, float, float, float> BufferTuple;
4438 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004439 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004440 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004441 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004442 if (stats.numSegments == 0) {
4443 continue;
4444 }
4445 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4446 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4447 stats.totalTime;
4448 float doubleBufferRatio = static_cast<float>(
4449 stats.doubleBufferedTime) / stats.totalTime;
4450 float tripleBufferRatio = static_cast<float>(
4451 stats.tripleBufferedTime) / stats.totalTime;
4452 sorted.insert({activeTime, {name, twoBufferRatio,
4453 doubleBufferRatio, tripleBufferRatio}});
4454 }
4455 for (const auto& sortedPair : sorted) {
4456 float activeTime = sortedPair.first;
4457 const BufferTuple& values = sortedPair.second;
4458 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4459 std::get<0>(values).c_str(), activeTime,
4460 std::get<1>(values), std::get<2>(values),
4461 std::get<3>(values));
4462 }
4463 result.append("\n");
4464}
4465
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004466void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004467 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004468 const int32_t displayId = display->getId();
4469 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4470 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004471 continue;
4472 }
4473
Dominik Laskowski7e045462018-05-30 13:02:02 -07004474 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004475 uint8_t port;
4476 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004477 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004478 result.append("no identification data\n");
4479 continue;
4480 }
4481
4482 if (!isEdid(data)) {
4483 result.append("unknown identification data: ");
4484 for (uint8_t byte : data) {
4485 result.appendFormat("%x ", byte);
4486 }
4487 result.append("\n");
4488 continue;
4489 }
4490
4491 const auto edid = parseEdid(data);
4492 if (!edid) {
4493 result.append("invalid EDID: ");
4494 for (uint8_t byte : data) {
4495 result.appendFormat("%x ", byte);
4496 }
4497 result.append("\n");
4498 continue;
4499 }
4500
4501 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4502 result.append(edid->displayName.data(), edid->displayName.length());
4503 result.append("\"\n");
4504 }
4505 result.append("\n");
4506}
4507
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004508void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004509 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4510 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004511 result.appendFormat("DisplayColorSetting: %s\n",
4512 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004513
4514 // TODO: print out if wide-color mode is active or not
4515
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004516 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004517 const int32_t displayId = display->getId();
4518 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004519 continue;
4520 }
4521
Dominik Laskowski7e045462018-05-30 13:02:02 -07004522 result.appendFormat("Display %d color modes:\n", displayId);
4523 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004524 for (auto&& mode : modes) {
4525 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4526 }
4527
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004528 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004529 result.appendFormat(" Current color mode: %s (%d)\n",
4530 decodeColorMode(currentMode).c_str(), currentMode);
4531 }
4532 result.append("\n");
4533}
4534
David Sodman7e4ae112018-02-09 15:02:28 -08004535void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4536 std::string stringResult;
4537
4538 for (const auto& [token, display] : mDisplays) {
4539 const auto displayId = display->getId();
4540 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
4541 continue;
4542 }
4543
4544 const auto& compositionInfoIt = getBE().mEndOfFrameCompositionInfo.find(displayId);
4545 if (compositionInfoIt == getBE().mEndOfFrameCompositionInfo.end()) {
4546 break;
4547 }
4548 const auto& compositionInfoList = compositionInfoIt->second;
4549 stringResult += base::StringPrintf("Display: %d\n", displayId);
4550 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4551 for (const auto& compositionInfo : compositionInfoList) {
4552 compositionInfo.dump(stringResult, nullptr);
4553 stringResult += base::StringPrintf("\n");
4554 }
4555 }
4556
4557 result.append(stringResult.c_str());
4558}
4559
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004560LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004561 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004562 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4563 const State& state = useDrawing ? mDrawingState : mCurrentState;
4564 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004565 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004566 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004567 });
4568
4569 return layersProto;
4570}
4571
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004572LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004573 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004574
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004575 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004576 resolution->set_w(display.getWidth());
4577 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004578
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004579 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4580 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4581 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004582
Dominik Laskowski7e045462018-05-30 13:02:02 -07004583 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004584 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004585 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004586 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004587 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004588 }
4589 });
4590
4591 return layersProto;
4592}
4593
Mathias Agopian74d211a2013-04-22 16:55:35 +02004594void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4595 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004596{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004597 bool colorize = false;
4598 if (index < args.size()
4599 && (args[index] == String16("--color"))) {
4600 colorize = true;
4601 index++;
4602 }
4603
4604 Colorizer colorizer(colorize);
4605
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004606 // figure out if we're stuck somewhere
4607 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004608 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004609 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4610
4611 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004612 * Dump library configuration.
4613 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004614
4615 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004616 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004617 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004618 appendSfConfigString(result);
4619 appendUiConfigString(result);
4620 appendGuiConfigString(result);
4621 result.append("\n");
4622
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004623 result.append("\nDisplay identification data:\n");
4624 dumpDisplayIdentificationData(result);
4625
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004626 result.append("\nWide-Color information:\n");
4627 dumpWideColorInfo(result);
4628
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004629 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004630 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004631 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004632 result.append(SyncFeatures::getInstance().toString());
4633 result.append("\n");
4634
Andy McFadden41d67d72014-04-25 16:58:34 -07004635 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004636 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004637 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004638
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004639 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4640 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004641 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4642 getHwComposer().isConnected(displayId)) {
4643 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004644 result.appendFormat("Display %d: "
4645 "app phase %" PRId64 " ns, "
4646 "sf phase %" PRId64 " ns, "
4647 "early app phase %" PRId64 " ns, "
4648 "early sf phase %" PRId64 " ns, "
4649 "early app gl phase %" PRId64 " ns, "
4650 "early sf gl phase %" PRId64 " ns, "
4651 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4652 displayId,
4653 vsyncPhaseOffsetNs,
4654 sfVsyncPhaseOffsetNs,
4655 appEarlyOffset,
4656 sfEarlyOffset,
4657 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004658 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004659 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004660 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004661 result.append("\n");
4662
Dan Stozab90cf072015-03-05 11:05:59 -08004663 // Dump static screen stats
4664 result.append("\n");
4665 dumpStaticScreenStats(result);
4666 result.append("\n");
4667
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004668 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4669
Dan Stozae77c7662016-05-13 11:37:28 -07004670 dumpBufferingStats(result);
4671
Andy McFadden4803b742012-09-24 19:07:20 -07004672 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004673 * Dump the visible layer list
4674 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004675 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004676 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004677 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4678 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004679 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004680
Chia-I Wu2f884132018-09-13 15:17:58 -07004681 {
4682 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4683 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4684 result.append(LayerProtoParser::layerTreeToString(layerTree).c_str());
4685 result.append("\n");
4686 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004687
David Sodman7e4ae112018-02-09 15:02:28 -08004688 result.append("\nFrame-Composition information:\n");
4689 dumpFrameCompositionInfo(result);
4690 result.append("\n");
4691
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004692 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004693 * Dump Display state
4694 */
4695
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004696 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004697 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004698 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004699 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004700 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004701 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004702 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004703
4704 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004705 * Dump SurfaceFlinger global state
4706 */
4707
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004708 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004709 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004710 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004711
Mathias Agopian888c8222012-08-04 21:10:38 -07004712 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004713 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004714
David Sodmanbc815282017-11-05 18:57:52 -08004715 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004716
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004717 if (display) {
4718 display->undefinedRegion.dump(result, "undefinedRegion");
4719 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4720 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004721 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004722 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004723 " gpu_to_cpu_unsupported : %d\n",
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004724 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004725
4726 if (display) {
4727 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4728 result.appendFormat(" refresh-rate : %f fps\n"
4729 " x-dpi : %f\n"
4730 " y-dpi : %f\n",
4731 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4732 activeConfig->getDpiY());
4733 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004734
Mathias Agopian74d211a2013-04-22 16:55:35 +02004735 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004736 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004737
Ana Krulec98b5b242018-08-10 15:03:23 -07004738 result.appendFormat(" use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004739 /*
4740 * VSYNC state
4741 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004742 if (mUseScheduler) {
4743 mScheduler->dump(mAppConnectionHandle, result);
4744 } else {
4745 mEventThread->dump(result);
4746 }
Dan Stozae22aec72016-08-01 13:20:59 -07004747 result.append("\n");
4748
4749 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004750 * Tracing state
4751 */
4752 mTracing.dump(result);
4753 result.append("\n");
4754
4755 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004756 * HWC layer minidump
4757 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004758 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004759 const int32_t displayId = display->getId();
4760 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004761 continue;
4762 }
4763
Dominik Laskowski7e045462018-05-30 13:02:02 -07004764 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004765 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004766 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004767 result.append("\n");
4768 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004769
4770 /*
4771 * Dump HWComposer state
4772 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004773 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004774 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004775 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004776 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004777 result.appendFormat(" h/w composer %s\n",
4778 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004779 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004780
4781 /*
4782 * Dump gralloc state
4783 */
4784 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4785 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004786
4787 /*
4788 * Dump VrFlinger state if in use.
4789 */
4790 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4791 result.append("VrFlinger state:\n");
4792 result.append(mVrFlinger->Dump().c_str());
4793 result.append("\n");
4794 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004795}
4796
Dominik Laskowski7e045462018-05-30 13:02:02 -07004797const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004798 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004799 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004800 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004801 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004802 }
4803 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004804
4805 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4806 static const Vector<sp<Layer>> empty;
4807 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004808}
4809
Keun young Park63f165f2012-08-31 10:53:36 -07004810bool SurfaceFlinger::startDdmConnection()
4811{
4812 void* libddmconnection_dso =
4813 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4814 if (!libddmconnection_dso) {
4815 return false;
4816 }
4817 void (*DdmConnection_start)(const char* name);
4818 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004819 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004820 if (!DdmConnection_start) {
4821 dlclose(libddmconnection_dso);
4822 return false;
4823 }
4824 (*DdmConnection_start)(getServiceName());
4825 return true;
4826}
4827
Chia-I Wu28f320b2018-05-03 11:02:56 -07004828void SurfaceFlinger::updateColorMatrixLocked() {
4829 mat4 colorMatrix;
4830 if (mGlobalSaturationFactor != 1.0f) {
4831 // Rec.709 luma coefficients
4832 float3 luminance{0.213f, 0.715f, 0.072f};
4833 luminance *= 1.0f - mGlobalSaturationFactor;
4834 mat4 saturationMatrix = mat4(
4835 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4836 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4837 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4838 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4839 );
4840 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4841 } else {
4842 colorMatrix = mClientColorMatrix * mDaltonizer();
4843 }
4844
4845 if (mCurrentState.colorMatrix != colorMatrix) {
4846 mCurrentState.colorMatrix = colorMatrix;
4847 mCurrentState.colorMatrixChanged = true;
4848 setTransactionFlags(eTransactionNeeded);
4849 }
4850}
4851
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004852status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004853#pragma clang diagnostic push
4854#pragma clang diagnostic error "-Wswitch-enum"
4855 switch (static_cast<ISurfaceComposerTag>(code)) {
4856 // These methods should at minimum make sure that the client requested
4857 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004858 case BOOT_FINISHED:
4859 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004860 case CREATE_CONNECTION:
4861 case CREATE_DISPLAY:
4862 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004863 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004864 case GET_ACTIVE_COLOR_MODE:
4865 case GET_ANIMATION_FRAME_STATS:
4866 case GET_HDR_CAPABILITIES:
4867 case SET_ACTIVE_CONFIG:
4868 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004869 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004870 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004871 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4872 IPCThreadState* ipc = IPCThreadState::self();
4873 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4874 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004875 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004876 }
Robert Carr1db73f62016-12-21 12:58:51 -08004877 return OK;
4878 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004879 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004880 IPCThreadState* ipc = IPCThreadState::self();
4881 const int pid = ipc->getCallingPid();
4882 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004883 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4884 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004885 return PERMISSION_DENIED;
4886 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004887 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004888 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004889 // Used by apps to hook Choreographer to SurfaceFlinger.
4890 case CREATE_DISPLAY_EVENT_CONNECTION:
4891 // The following calls are currently used by clients that do not
4892 // request necessary permissions. However, they do not expose any secret
4893 // information, so it is OK to pass them.
4894 case AUTHENTICATE_SURFACE:
4895 case GET_ACTIVE_CONFIG:
4896 case GET_BUILT_IN_DISPLAY:
4897 case GET_DISPLAY_COLOR_MODES:
4898 case GET_DISPLAY_CONFIGS:
4899 case GET_DISPLAY_STATS:
4900 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4901 // Calling setTransactionState is safe, because you need to have been
4902 // granted a reference to Client* and Handle* to do anything with it.
4903 case SET_TRANSACTION_STATE:
4904 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004905 case CREATE_SCOPED_CONNECTION:
4906 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004907 return OK;
4908 }
4909 case CAPTURE_LAYERS:
4910 case CAPTURE_SCREEN: {
4911 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004912 IPCThreadState* ipc = IPCThreadState::self();
4913 const int pid = ipc->getCallingPid();
4914 const int uid = ipc->getCallingUid();
4915 if ((uid != AID_GRAPHICS) &&
4916 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4917 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4918 return PERMISSION_DENIED;
4919 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004920 return OK;
4921 }
4922 // The following codes are deprecated and should never be allowed to access SF.
4923 case CONNECT_DISPLAY_UNUSED:
4924 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4925 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4926 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004927 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004928 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004929
4930 // These codes are used for the IBinder protocol to either interrogate the recipient
4931 // side of the transaction for its canonical interface descriptor or to dump its state.
4932 // We let them pass by default.
4933 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4934 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4935 code == IBinder::SYSPROPS_TRANSACTION) {
4936 return OK;
4937 }
4938 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4939 // in onTransact verifies that the user is root, and has access to use SF.
4940 if (code >= 1000 && code <= 1029) {
4941 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4942 return OK;
4943 }
4944 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4945 return PERMISSION_DENIED;
4946#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004947}
4948
Ana Krulec13be8ad2018-08-21 02:43:56 +00004949status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4950 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004951 status_t credentialCheck = CheckTransactCodeCredentials(code);
4952 if (credentialCheck != OK) {
4953 return credentialCheck;
4954 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004955
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004956 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4957 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004958 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004959 IPCThreadState* ipc = IPCThreadState::self();
4960 const int uid = ipc->getCallingUid();
4961 if (CC_UNLIKELY(uid != AID_SYSTEM
4962 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004963 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004964 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004965 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004966 return PERMISSION_DENIED;
4967 }
4968 int n;
4969 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004970 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004971 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004972 return NO_ERROR;
4973 case 1002: // SHOW_UPDATES
4974 n = data.readInt32();
4975 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004976 invalidateHwcGeometry();
4977 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004978 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004979 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004980 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004981 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004982 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004983 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004984 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004985 setTransactionFlags(
4986 eTransactionNeeded|
4987 eDisplayTransactionNeeded|
4988 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004989 return NO_ERROR;
4990 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004991 case 1006:{ // send empty update
4992 signalRefresh();
4993 return NO_ERROR;
4994 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004995 case 1008: // toggle use of hw composer
4996 n = data.readInt32();
4997 mDebugDisableHWC = n ? 1 : 0;
4998 invalidateHwcGeometry();
4999 repaintEverything();
5000 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005001 case 1009: // toggle use of transform hint
5002 n = data.readInt32();
5003 mDebugDisableTransformHint = n ? 1 : 0;
5004 invalidateHwcGeometry();
5005 repaintEverything();
5006 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005007 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005008 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005009 reply->writeInt32(0);
5010 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005011 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005012 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005013 return NO_ERROR;
5014 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005015 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005016 if (!display) {
5017 return NAME_NOT_FOUND;
5018 }
5019
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005020 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005021 return NO_ERROR;
5022 }
5023 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005024 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005025 // daltonize
5026 n = data.readInt32();
5027 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005028 case 1:
5029 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5030 break;
5031 case 2:
5032 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5033 break;
5034 case 3:
5035 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5036 break;
5037 default:
5038 mDaltonizer.setType(ColorBlindnessType::None);
5039 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005040 }
5041 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005042 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005043 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005044 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005045 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005046
5047 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005048 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005049 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005050 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005051 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005052 // apply a color matrix
5053 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005054 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005055 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005056 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005057 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005058 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005059 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005060 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005061 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005062 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005063 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005064
5065 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5066 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005067 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005068 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5069 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5070 }
5071
Chia-I Wu28f320b2018-05-03 11:02:56 -07005072 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005073 return NO_ERROR;
5074 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005075 // This is an experimental interface
5076 // Needs to be shifted to proper binder interface when we productize
5077 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005078 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005079 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005080 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005081 return NO_ERROR;
5082 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005083 case 1017: {
5084 n = data.readInt32();
5085 mForceFullDamage = static_cast<bool>(n);
5086 return NO_ERROR;
5087 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005088 case 1018: { // Modify Choreographer's phase offset
5089 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005090 if (mUseScheduler) {
5091 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5092 } else {
5093 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5094 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005095 return NO_ERROR;
5096 }
5097 case 1019: { // Modify SurfaceFlinger's phase offset
5098 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005099 if (mUseScheduler) {
5100 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5101 } else {
5102 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5103 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005104 return NO_ERROR;
5105 }
Irvel468051e2016-06-13 16:44:44 -07005106 case 1020: { // Layer updates interceptor
5107 n = data.readInt32();
5108 if (n) {
5109 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005110 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005111 }
5112 else{
5113 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005114 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005115 }
5116 return NO_ERROR;
5117 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005118 case 1021: { // Disable HWC virtual displays
5119 n = data.readInt32();
5120 mUseHwcVirtualDisplays = !n;
5121 return NO_ERROR;
5122 }
Romain Guy0147a172017-06-01 13:53:56 -07005123 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005124 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005125 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005126
Chia-I Wu28f320b2018-05-03 11:02:56 -07005127 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005128 return NO_ERROR;
5129 }
Romain Guy54f154a2017-10-24 21:40:32 +01005130 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005131 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005132 invalidateHwcGeometry();
5133 repaintEverything();
5134 return NO_ERROR;
5135 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005136 // TODO(b/111505327): Find out whether the usage of 1024 can switch to 1030,
5137 // deprecate 1024 if they can.
5138 case 1024: { // Does device have wide color gamut display?
Romain Guy54f154a2017-10-24 21:40:32 +01005139 reply->writeBool(hasWideColorDisplay);
5140 return NO_ERROR;
5141 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005142 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005143 n = data.readInt32();
5144 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005145 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005146 mTracing.enable();
5147 doTracing("tracing.enable");
5148 reply->writeInt32(NO_ERROR);
5149 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005150 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005151 status_t err = mTracing.disable();
5152 reply->writeInt32(err);
5153 }
5154 return NO_ERROR;
5155 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005156 case 1026: { // Get layer tracing status
5157 reply->writeBool(mTracing.isEnabled());
5158 return NO_ERROR;
5159 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005160 // Is a DisplayColorSetting supported?
5161 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005162 const auto display = getDefaultDisplayDevice();
5163 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005164 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005165 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005166
5167 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5168 switch (setting) {
5169 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005170 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005171 break;
5172 case DisplayColorSetting::UNMANAGED:
5173 reply->writeBool(true);
5174 break;
5175 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005176 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005177 break;
5178 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005179 reply->writeBool(
5180 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005181 break;
5182 }
5183 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005184 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005185 // Is VrFlinger active?
5186 case 1028: {
5187 Mutex::Autolock _l(mStateLock);
5188 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5189 return NO_ERROR;
5190 }
David Sodman6d46c1e2018-07-13 12:59:48 -07005191 case 1029: {
5192 // Code 1029 is an experimental feature that allows applications to
5193 // simulate a high frequency panel by setting a multiplier and divisor
5194 // on the VSYNC-sf clock. If either the multiplier or divisor are
David Sodman44b5de02018-08-21 16:28:53 -07005195 // 0, then the code simply return the current multiplier and divisor.
5196 HWC2::Device::FrequencyScaler frequencyScaler;
5197 frequencyScaler.multiplier = data.readInt32();
5198 frequencyScaler.divisor = data.readInt32();
David Sodman6d46c1e2018-07-13 12:59:48 -07005199
David Sodman44b5de02018-08-21 16:28:53 -07005200 if ((frequencyScaler.multiplier == 0) || (frequencyScaler.divisor == 0)) {
5201 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5202 reply->writeInt32(frequencyScaler.multiplier);
5203 reply->writeInt32(frequencyScaler.divisor);
5204 return NO_ERROR;
David Sodman6d46c1e2018-07-13 12:59:48 -07005205 }
5206
David Sodman44b5de02018-08-21 16:28:53 -07005207 if ((frequencyScaler.multiplier == 1) && (frequencyScaler.divisor == 1)) {
Ana Krulece588e312018-09-18 12:32:24 -07005208 if (mUseScheduler) {
5209 mScheduler->enableHardwareVsync();
5210 } else {
5211 enableHardwareVsync();
5212 }
David Sodman6d46c1e2018-07-13 12:59:48 -07005213 } else {
Ana Krulece588e312018-09-18 12:32:24 -07005214 if (mUseScheduler) {
5215 mScheduler->disableHardwareVsync(true);
5216 } else {
5217 disableHardwareVsync(true);
5218 }
David Sodman6d46c1e2018-07-13 12:59:48 -07005219 }
David Sodman44b5de02018-08-21 16:28:53 -07005220 mPrimaryDispSync->scalePeriod(frequencyScaler);
5221 getBE().mHwc->setDisplayFrequencyScaleParameters(frequencyScaler);
David Sodman6d46c1e2018-07-13 12:59:48 -07005222
David Sodman44b5de02018-08-21 16:28:53 -07005223 ATRACE_INT("PeriodMultiplier", frequencyScaler.multiplier);
5224 ATRACE_INT("PeriodDivisor", frequencyScaler.divisor);
5225
5226 const hwc2_display_t hwcDisplayId = getBE().mHwc->getActiveConfig(
5227 DisplayDevice::DISPLAY_PRIMARY)->getDisplayId();
5228
5229 onHotplugReceived(getBE().mComposerSequenceId,
5230 hwcDisplayId, HWC2::Connection::Disconnected);
5231 onHotplugReceived(getBE().mComposerSequenceId,
5232 hwcDisplayId, HWC2::Connection::Connected);
5233 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5234 reply->writeInt32(frequencyScaler.multiplier);
5235 reply->writeInt32(frequencyScaler.divisor);
5236
David Sodman6d46c1e2018-07-13 12:59:48 -07005237 return NO_ERROR;
5238 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005239 // Is device color managed?
5240 case 1030: {
5241 reply->writeBool(useColorManagement);
5242 return NO_ERROR;
5243 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005244 }
5245 }
5246 return err;
5247}
5248
Steven Thomas6d8110b2017-08-31 18:24:21 -07005249void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005250 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005251 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005252}
5253
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005254// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5255class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005256public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005257 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5258 ~WindowDisconnector() {
5259 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005260 }
5261
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005262private:
5263 ANativeWindow* mWindow;
5264 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005265};
5266
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005267status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
5268 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005269 uint32_t reqWidth, uint32_t reqHeight,
5270 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005271 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005272 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005273
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005274 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005275
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005276 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5277
Chia-I Wu20261cb2018-08-23 12:55:44 -07005278 sp<DisplayDevice> display;
5279 {
5280 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005281
Chia-I Wu20261cb2018-08-23 12:55:44 -07005282 display = getDisplayDeviceLocked(displayToken);
5283 if (!display) return BAD_VALUE;
5284
Chia-I Wu8730ba82018-08-29 09:25:59 -07005285 // ignore sourceCrop (i.e., use the projected logical display
5286 // viewport) until the framework is fixed
5287 sourceCrop.clear();
Chia-I Wucb023152018-08-28 12:57:23 -07005288
5289 // set the requested width/height to the logical display viewport size
5290 // by default
5291 if (reqWidth == 0 || reqHeight == 0) {
5292 reqWidth = uint32_t(display->getViewport().width());
5293 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005294 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005295 }
5296
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005297 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005298
5299 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005300 display, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005301 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005302}
5303
5304status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08005305 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005306 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005307 ATRACE_CALL();
5308
5309 class LayerRenderArea : public RenderArea {
5310 public:
Robert Carr578038f2018-03-09 12:25:24 -08005311 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
5312 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
Chia-I Wu9d1abea2018-08-23 13:44:43 -07005313 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08005314 mLayer(layer),
5315 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005316 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005317 mFlinger(flinger),
5318 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005319 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005320 Rect getBounds() const override {
5321 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005322 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005323 }
Marissa Wall61c58622018-07-18 10:12:20 -07005324 int getHeight() const override {
5325 return mLayer->getActiveHeight(mLayer->getDrawingState());
5326 }
5327 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005328 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005329 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005330 Rect getSourceCrop() const override {
5331 if (mCrop.isEmpty()) {
5332 return getBounds();
5333 } else {
5334 return mCrop;
5335 }
5336 }
Robert Carr578038f2018-03-09 12:25:24 -08005337 class ReparentForDrawing {
5338 public:
5339 const sp<Layer>& oldParent;
5340 const sp<Layer>& newParent;
5341
5342 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5343 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005344 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005345 }
Robert Carr15eae092018-03-23 13:43:53 -07005346 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005347 };
5348
5349 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005350 const Rect sourceCrop = getSourceCrop();
5351 // no need to check rotation because there is none
5352 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5353 sourceCrop.height() != getReqHeight();
5354
Robert Carr578038f2018-03-09 12:25:24 -08005355 if (!mChildrenOnly) {
5356 mTransform = mLayer->getTransform().inverse();
5357 drawLayers();
5358 } else {
5359 Rect bounds = getBounds();
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005360 screenshotParentLayer = new ContainerLayer(
5361 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5362 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005363
5364 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5365 drawLayers();
5366 }
5367 }
chaviwa76b2712017-09-20 12:02:26 -07005368
chaviwa76b2712017-09-20 12:02:26 -07005369 private:
chaviw7206d492017-11-10 16:16:12 -08005370 const sp<Layer> mLayer;
5371 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005372
5373 // In the "childrenOnly" case we reparent the children to a screenshot
5374 // layer which has no properties set and which does not draw.
5375 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005376 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005377 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005378
5379 SurfaceFlinger* mFlinger;
5380 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005381 };
5382
5383 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5384 auto parent = layerHandle->owner.promote();
5385
Rob Carr4bba3702018-10-08 21:53:30 +00005386 if (parent == nullptr || parent->isPendingRemoval()) {
chaviw7206d492017-11-10 16:16:12 -08005387 ALOGE("captureLayers called with a removed parent");
5388 return NAME_NOT_FOUND;
5389 }
5390
Robert Carr578038f2018-03-09 12:25:24 -08005391 const int uid = IPCThreadState::self()->getCallingUid();
5392 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5393 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5394 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5395 return PERMISSION_DENIED;
5396 }
5397
chaviw7206d492017-11-10 16:16:12 -08005398 Rect crop(sourceCrop);
5399 if (sourceCrop.width() <= 0) {
5400 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005401 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005402 }
5403
5404 if (sourceCrop.height() <= 0) {
5405 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005406 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005407 }
5408
5409 int32_t reqWidth = crop.width() * frameScale;
5410 int32_t reqHeight = crop.height() * frameScale;
5411
Chia-I Wu20261cb2018-08-23 12:55:44 -07005412 // really small crop or frameScale
5413 if (reqWidth <= 0) {
5414 reqWidth = 1;
5415 }
5416 if (reqHeight <= 0) {
5417 reqHeight = 1;
5418 }
5419
Robert Carr578038f2018-03-09 12:25:24 -08005420 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005421
Robert Carr578038f2018-03-09 12:25:24 -08005422 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005423 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5424 if (!layer->isVisible()) {
5425 return;
Robert Carr578038f2018-03-09 12:25:24 -08005426 } else if (childrenOnly && layer == parent.get()) {
5427 return;
chaviwa76b2712017-09-20 12:02:26 -07005428 }
5429 visitor(layer);
5430 });
5431 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005432 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005433}
5434
5435status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5436 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005437 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005438 bool useIdentityTransform) {
5439 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005440
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005441 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5442 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5443 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5444 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005445
5446 // This mutex protects syncFd and captureResult for communication of the return values from the
5447 // main thread back to this Binder thread
5448 std::mutex captureMutex;
5449 std::condition_variable captureCondition;
5450 std::unique_lock<std::mutex> captureLock(captureMutex);
5451 int syncFd = -1;
5452 std::optional<status_t> captureResult;
5453
Robert Carr03480e22018-01-04 16:02:06 -08005454 const int uid = IPCThreadState::self()->getCallingUid();
5455 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5456
Dominik Laskowski8c001672018-05-30 16:52:06 -07005457 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005458 // If there is a refresh pending, bug out early and tell the binder thread to try again
5459 // after the refresh.
5460 if (mRefreshPending) {
5461 ATRACE_NAME("Skipping screenshot for now");
5462 std::unique_lock<std::mutex> captureLock(captureMutex);
5463 captureResult = std::make_optional<status_t>(EAGAIN);
5464 captureCondition.notify_one();
5465 return;
5466 }
5467
5468 status_t result = NO_ERROR;
5469 int fd = -1;
5470 {
5471 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005472 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005473 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5474 useIdentityTransform, forSystem, &fd);
5475 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005476 }
5477
5478 {
5479 std::unique_lock<std::mutex> captureLock(captureMutex);
5480 syncFd = fd;
5481 captureResult = std::make_optional<status_t>(result);
5482 captureCondition.notify_one();
5483 }
5484 });
5485
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005486 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005487 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005488 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005489 while (*captureResult == EAGAIN) {
5490 captureResult.reset();
5491 result = postMessageAsync(message);
5492 if (result != NO_ERROR) {
5493 return result;
5494 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005495 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005496 }
5497 result = *captureResult;
5498 }
5499
5500 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005501 sync_wait(syncFd, -1);
5502 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005503 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005504
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005505 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005506}
5507
chaviwa76b2712017-09-20 12:02:26 -07005508void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005509 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005510 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005511 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005512
Lloyd Pique144e1162017-12-20 16:44:52 -08005513 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005514
chaviwa76b2712017-09-20 12:02:26 -07005515 const auto reqWidth = renderArea.getReqWidth();
5516 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005517 const auto sourceCrop = renderArea.getSourceCrop();
5518 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005519
Chia-I Wu36574d92018-05-16 10:54:36 -07005520 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5521 engine.setOutputDataSpace(Dataspace::SRGB);
5522 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005523
Mathias Agopian180f10d2013-04-10 22:55:41 -07005524 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005525 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005526
5527 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005528 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005529 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005530
chaviw50da5042018-04-09 13:49:37 -07005531 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005532 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005533 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005534
chaviwa76b2712017-09-20 12:02:26 -07005535 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005536 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005537 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005538 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005539 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005540}
5541
chaviwa76b2712017-09-20 12:02:26 -07005542status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5543 TraverseLayersFunction traverseLayers,
5544 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005545 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005546 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005547 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005548 ATRACE_CALL();
5549
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005550 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005551
5552 traverseLayers([&](Layer* layer) {
5553 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5554 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005555
Robert Carr03480e22018-01-04 16:02:06 -08005556 // We allow the system server to take screenshots of secure layers for
5557 // use in situations like the Screen-rotation animation and place
5558 // the impetus on WindowManager to not persist them.
5559 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005560 ALOGW("FB is protected: PERMISSION_DENIED");
5561 return PERMISSION_DENIED;
5562 }
5563
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005564 // this binds the given EGLImage as a framebuffer for the
5565 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005566 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005567 if (bufferBond.getStatus() != NO_ERROR) {
5568 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005569 return INVALID_OPERATION;
5570 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005571
Dan Stozaabcda352017-06-01 14:37:39 -07005572 // this will in fact render into our dequeued buffer
5573 // via an FBO, which means we didn't have to create
5574 // an EGLSurface and therefore we're not
5575 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005576 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005577
Alec Mouri492bc572018-09-11 21:40:04 +00005578 base::unique_fd syncFd = getRenderEngine().flush();
5579 if (syncFd < 0) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005580 getRenderEngine().finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005581 }
Alec Mouri492bc572018-09-11 21:40:04 +00005582 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005583
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005584 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005585}
5586
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005587// ---------------------------------------------------------------------------
5588
Dan Stoza412903f2017-04-27 13:42:17 -07005589void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5590 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005591}
5592
Dan Stoza412903f2017-04-27 13:42:17 -07005593void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5594 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005595}
5596
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005597void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005598 const LayerVector::Visitor& visitor) {
5599 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005600 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005601 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005602 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005603 continue;
5604 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005605 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005606 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005607 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005608 return;
5609 }
chaviwa76b2712017-09-20 12:02:26 -07005610 if (!layer->isVisible()) {
5611 return;
5612 }
5613 visitor(layer);
5614 });
5615 }
5616}
5617
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005618}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005619
Lloyd Pique074e8122018-07-26 12:57:23 -07005620
Mathias Agopian3f844832013-08-07 21:24:32 -07005621#if defined(__gl_h_)
5622#error "don't include gl/gl.h in this file"
5623#endif
5624
5625#if defined(__gl2_h_)
5626#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005627#endif