blob: 89129e9218c34e1443991449c3bc572d6f9521bf [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
Lloyd Pique70d91362018-10-18 16:02:55 -070038#include <compositionengine/CompositionEngine.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070039#include <compositionengine/Display.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070040#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070041#include <compositionengine/impl/OutputCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080042#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070043#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070044#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080046#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080047#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080048#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070049#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070050#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070051#include <ui/ColorSpace.h>
52#include <ui/DebugUtils.h>
53#include <ui/DisplayInfo.h>
54#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070055#include <ui/GraphicBufferAllocator.h>
56#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070057#include <ui/UiConfig.h>
Ady Abraham8164d482019-01-11 14:47:59 -080058#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070060#include <utils/String16.h>
61#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070062#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080063#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070064#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065
Mathias Agopian921e6ac2012-07-23 23:11:29 -070066#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070067#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080068
Robert Carr578038f2018-03-09 12:25:24 -080069#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070070#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070071#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020072#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080073#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020074#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080075#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080076#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080077#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070079#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080080#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070081#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070082#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070084#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085
Steven Thomasb02664d2017-07-26 18:48:28 -070086#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070087#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070088#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070089#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070090#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070091#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070092#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070093#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070094#include "Scheduler/EventControlThread.h"
95#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070096#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070097#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070098#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080099#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700100
Mathias Agopianff2ed702013-09-01 21:36:12 -0700101#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700102
David Sodman7e4ae112018-02-09 15:02:28 -0800103#include "android-base/stringprintf.h"
104
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900105#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800106#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700107#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800108#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900109#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900110
chaviw1d044282017-09-27 12:19:28 -0700111#include <layerproto/LayerProtoParser.h>
112
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800113namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700114
Jaesoo Lee43518572017-01-23 19:03:16 +0900115using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900116using namespace android::hardware::configstore::V1_0;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800117using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700118using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700119using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700120using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700121using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900122
Steven Thomasb02664d2017-07-26 18:48:28 -0700123namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700124
125#pragma clang diagnostic push
126#pragma clang diagnostic error "-Wswitch-enum"
127
128bool isWideColorMode(const ColorMode colorMode) {
129 switch (colorMode) {
130 case ColorMode::DISPLAY_P3:
131 case ColorMode::ADOBE_RGB:
132 case ColorMode::DCI_P3:
133 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700134 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700135 case ColorMode::BT2100_PQ:
136 case ColorMode::BT2100_HLG:
137 return true;
138 case ColorMode::NATIVE:
139 case ColorMode::STANDARD_BT601_625:
140 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
141 case ColorMode::STANDARD_BT601_525:
142 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
143 case ColorMode::STANDARD_BT709:
144 case ColorMode::SRGB:
145 return false;
146 }
147 return false;
148}
149
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700150ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
151 switch (rotation) {
152 case ISurfaceComposer::eRotateNone:
153 return ui::Transform::ROT_0;
154 case ISurfaceComposer::eRotate90:
155 return ui::Transform::ROT_90;
156 case ISurfaceComposer::eRotate180:
157 return ui::Transform::ROT_180;
158 case ISurfaceComposer::eRotate270:
159 return ui::Transform::ROT_270;
160 }
161 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
162 return ui::Transform::ROT_0;
163}
164
Peiyong Linfca547f2018-07-09 13:03:33 -0700165#pragma clang diagnostic pop
166
Steven Thomasb02664d2017-07-26 18:48:28 -0700167class ConditionalLock {
168public:
169 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
170 if (lock) {
171 mMutex.lock();
172 }
173 }
174 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
175private:
176 Mutex& mMutex;
177 bool mLocked;
178};
Peiyong Linfca547f2018-07-09 13:03:33 -0700179
Peiyong Lin9d846a52018-11-05 13:18:20 -0800180// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
181bool validateCompositionDataspace(Dataspace dataspace) {
182 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
183}
184
Steven Thomasb02664d2017-07-26 18:48:28 -0700185} // namespace anonymous
186
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800187// ---------------------------------------------------------------------------
188
Mathias Agopian99b49842011-06-27 16:05:52 -0700189const String16 sHardwareTest("android.permission.HARDWARE_TEST");
190const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
191const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
192const String16 sDump("android.permission.DUMP");
193
194// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800195int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
196int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700197int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700198bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800199uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800200bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800201bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800202int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600203bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700204int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700205bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700206bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700207Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
208ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
209Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
210ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700211
Kalle Raitaa099a242017-01-11 11:17:29 -0800212std::string getHwcServiceName() {
213 char value[PROPERTY_VALUE_MAX] = {};
214 property_get("debug.sf.hwc_service_name", value, "default");
215 ALOGI("Using HWComposer service: '%s'", value);
216 return std::string(value);
217}
218
219bool useTrebleTestingOverride() {
220 char value[PROPERTY_VALUE_MAX] = {};
221 property_get("debug.sf.treble_testing_override", value, "false");
222 ALOGI("Treble testing override: '%s'", value);
223 return std::string(value) == "true";
224}
225
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800226std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
227 switch(displayColorSetting) {
228 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700229 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800230 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700231 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800232 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700233 return std::string("Enhanced");
234 default:
235 return std::string("Unknown ") +
236 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800237 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800238}
239
David Sodmanbc815282017-11-05 18:57:52 -0800240SurfaceFlingerBE::SurfaceFlingerBE()
241 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800242 mFrameBuckets(),
243 mTotalTime(0),
244 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800245 mComposerSequenceId(0) {
246}
247
Lloyd Pique90c115d2018-09-18 21:39:42 -0700248SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
249 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800250 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700251 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700252 mTransactionPending(false),
253 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700254 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700255 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800256 mBootTime(systemTime()),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800258 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800259 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800260 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800261 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700262 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700263 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700264 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700265 mDebugInTransaction(0),
266 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700267 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800268 mTimeStats(factory.createTimeStats()),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700269 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700270 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800271 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800272 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800273 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700274 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700275 mMainThreadId(std::this_thread::get_id()),
276 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800277
Lloyd Pique90c115d2018-09-18 21:39:42 -0700278SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
279 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800280 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800281
282 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
283 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
284
285 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
286 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
287
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800288 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
289 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800290
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700291 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
292 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
293
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700294 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
295 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
296
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800297 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
298 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
299
Steven Thomas050b2c82017-03-06 11:45:16 -0800300 // Vr flinger is only enabled on Daydream ready devices.
301 useVrFlinger = getBool< ISurfaceFlingerConfigs,
302 &ISurfaceFlingerConfigs::useVrFlinger>(false);
303
Fabien Sanglard1971b632017-03-10 14:50:03 -0800304 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
305 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
306
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600307 hasWideColorDisplay =
308 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700309 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700310 getBool<V1_2::ISurfaceFlingerConfigs,
311 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
312
313 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
314 if (surfaceFlingerConfigsServiceV1_2) {
315 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
Peiyong Linc6780972018-10-28 15:24:08 -0700316 [&](auto tmpDefaultDataspace, auto tmpDefaultPixelFormat,
317 auto tmpWideColorGamutDataspace, auto tmpWideColorGamutPixelFormat) {
318 defaultCompositionDataspace = tmpDefaultDataspace;
319 defaultCompositionPixelFormat = tmpDefaultPixelFormat;
320 wideColorGamutCompositionDataspace = tmpWideColorGamutDataspace;
321 wideColorGamutCompositionPixelFormat = tmpWideColorGamutPixelFormat;
322 });
Peiyong Lin0256f722018-08-31 15:45:10 -0700323 }
Peiyong Lin9d846a52018-11-05 13:18:20 -0800324 mDefaultCompositionDataspace = defaultCompositionDataspace;
325 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600326
Peiyong Linb3839ad2018-09-05 15:37:19 -0700327 useContextPriority = getBool<ISurfaceFlingerConfigs,
328 &ISurfaceFlingerConfigs::useContextPriority>(true);
329
Iris Chang7501ed62018-04-30 14:45:42 +0800330 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700331 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
332 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800333 V1_1::DisplayOrientation::ORIENTATION_0);
334
335 switch (primaryDisplayOrientation) {
336 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700337 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800338 break;
339 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700340 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800341 break;
342 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700343 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800344 break;
345 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700346 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800347 break;
348 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700349 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800350
Lloyd Pique90c115d2018-09-18 21:39:42 -0700351 mPrimaryDispSync =
352 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
353 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700354
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800355 // debugging stuff...
356 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700357
Mathias Agopianb4b17302013-03-20 18:36:41 -0700358 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700359 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700360
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800361 property_get("debug.sf.showupdates", value, "0");
362 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700363
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700364 property_get("debug.sf.ddms", value, "0");
365 mDebugDDMS = atoi(value);
366 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700367 if (!startDdmConnection()) {
368 // start failed, and DDMS debugging not enabled
369 mDebugDDMS = 0;
370 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700371 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700372 ALOGI_IF(mDebugRegion, "showupdates enabled");
373 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700374
375 property_get("debug.sf.disable_backpressure", value, "0");
376 mPropagateBackpressure = !atoi(value);
377 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700378
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800379 property_get("debug.sf.enable_hwc_vds", value, "0");
380 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800381 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800382
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800383 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800384 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800385 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700386
Yiwei Zhang243b3782018-05-15 17:40:04 -0700387 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700388 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
389 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
390
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200391 property_get("debug.sf.early_phase_offset_ns", value, "-1");
392 const int earlySfOffsetNs = atoi(value);
393
394 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
395 const int earlyGlSfOffsetNs = atoi(value);
396
397 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
398 const int earlyAppOffsetNs = atoi(value);
399
400 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
401 const int earlyGlAppOffsetNs = atoi(value);
402
Ana Krulec98b5b242018-08-10 15:03:23 -0700403 property_get("debug.sf.use_scheduler", value, "0");
404 mUseScheduler = atoi(value);
405
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200406 const VSyncModulator::Offsets earlyOffsets =
407 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
408 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
409 const VSyncModulator::Offsets earlyGlOffsets =
410 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
411 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
412 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
413 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700414
Romain Guy11d63f42017-07-20 12:47:14 -0700415 // We should be reading 'persist.sys.sf.color_saturation' here
416 // but since /data may be encrypted, we need to wait until after vold
417 // comes online to attempt to read the property. The property is
418 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800419
420 if (useTrebleTestingOverride()) {
421 // Without the override SurfaceFlinger cannot connect to HIDL
422 // services that are not listed in the manifests. Considered
423 // deriving the setting from the set service name, but it
424 // would be brittle if the name that's not 'default' is used
425 // for production purposes later on.
426 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
427 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800428}
429
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800430void SurfaceFlinger::onFirstRef()
431{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800432 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800433}
434
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800435SurfaceFlinger::~SurfaceFlinger()
436{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800437}
438
Dan Stozac7014012014-02-14 15:03:43 -0800439void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800440{
441 // the window manager died on us. prepare its eulogy.
442
Andy McFadden13a082e2012-08-24 10:16:42 -0700443 // restore initial conditions (default device unblank, etc)
444 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800445
446 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700447 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800448}
449
Robert Carr1db73f62016-12-21 12:58:51 -0800450static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700451 status_t err = client->initCheck();
452 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800453 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800454 }
Robert Carr1db73f62016-12-21 12:58:51 -0800455 return nullptr;
456}
457
458sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
459 return initClient(new Client(this));
460}
461
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700462sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
463 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700464{
465 class DisplayToken : public BBinder {
466 sp<SurfaceFlinger> flinger;
467 virtual ~DisplayToken() {
468 // no more references, this display must be terminated
469 Mutex::Autolock _l(flinger->mStateLock);
470 flinger->mCurrentState.displays.removeItem(this);
471 flinger->setTransactionFlags(eDisplayTransactionNeeded);
472 }
473 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700474 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700475 : flinger(flinger) {
476 }
477 };
478
479 sp<BBinder> token = new DisplayToken(this);
480
481 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700482 // Display ID is assigned when virtual display is allocated by HWC.
483 DisplayDeviceState state;
484 state.isSecure = secure;
485 state.displayName = displayName;
486 mCurrentState.displays.add(token, state);
487 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700488 return token;
489}
490
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700491void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700492 Mutex::Autolock _l(mStateLock);
493
Dominik Laskowski075d3172018-05-24 15:50:06 -0700494 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
495 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700496 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700497 return;
498 }
499
Dominik Laskowski075d3172018-05-24 15:50:06 -0700500 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
501 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700502 ALOGE("destroyDisplay called for non-virtual display");
503 return;
504 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700505 mInterceptor->saveDisplayDeletion(state.sequenceId);
506 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700507 setTransactionFlags(eDisplayTransactionNeeded);
508}
509
Mathias Agopiane57f2922012-08-09 16:29:12 -0700510sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700511 std::optional<DisplayId> displayId;
512
513 if (id == HWC_DISPLAY_PRIMARY) {
514 displayId = getInternalDisplayId();
515 } else if (id == HWC_DISPLAY_EXTERNAL) {
516 displayId = getExternalDisplayId();
517 }
518
519 if (!displayId) {
520 ALOGE("%s: Invalid display %d", __FUNCTION__, id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800521 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700522 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700523
524 return getPhysicalDisplayToken(*displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700525}
526
Ady Abraham37965d42018-11-01 13:43:32 -0700527status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
528 if (!outGetColorManagement) {
529 return BAD_VALUE;
530 }
531 *outGetColorManagement = useColorManagement;
532 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700533}
534
Lloyd Pique441d5042018-10-18 16:49:51 -0700535HWComposer& SurfaceFlinger::getHwComposer() const {
536 return mCompositionEngine->getHwComposer();
537}
538
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700539renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
540 return mCompositionEngine->getRenderEngine();
541}
542
Lloyd Pique70d91362018-10-18 16:02:55 -0700543compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
544 return *mCompositionEngine.get();
545}
546
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800547void SurfaceFlinger::bootFinished()
548{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700549 if (mStartPropertySetThread->join() != NO_ERROR) {
550 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800551 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800552 const nsecs_t now = systemTime();
553 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000554 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700555
556 // wait patiently for the window manager death
557 const String16 name("window");
558 sp<IBinder> window(defaultServiceManager()->getService(name));
559 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700560 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700561 }
Robert Carr720e5062018-07-30 17:45:14 -0700562 sp<IBinder> input(defaultServiceManager()->getService(
563 String16("inputflinger")));
564 if (input == nullptr) {
565 ALOGE("Failed to link to input service");
566 } else {
567 mInputFlinger = interface_cast<IInputFlinger>(input);
568 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700569
Steven Thomas050b2c82017-03-06 11:45:16 -0800570 if (mVrFlinger) {
571 mVrFlinger->OnBootFinished();
572 }
573
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700574 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700575 // formerly we would just kill the process, but we now ask it to exit so it
576 // can choose where to stop the animation.
577 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700578
579 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
580 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
581 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700582
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800583 postMessageAsync(new LambdaMessage([this] {
584 readPersistentProperties();
585 mBootStage = BootStage::FINISHED;
586 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800587}
588
Dan Stoza436ccf32018-06-21 12:10:12 -0700589uint32_t SurfaceFlinger::getNewTexture() {
590 {
591 std::lock_guard lock(mTexturePoolMutex);
592 if (!mTexturePool.empty()) {
593 uint32_t name = mTexturePool.back();
594 mTexturePool.pop_back();
595 ATRACE_INT("TexturePoolSize", mTexturePool.size());
596 return name;
597 }
598
599 // The pool was too small, so increase it for the future
600 ++mTexturePoolSize;
601 }
602
603 // The pool was empty, so we need to get a new texture name directly using a
604 // blocking call to the main thread
605 uint32_t name = 0;
606 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
607 return name;
608}
609
Mathias Agopian3f844832013-08-07 21:24:32 -0700610void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700611 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700612}
613
Wei Wangf9b05ee2017-07-19 20:59:39 -0700614// Do not call property_set on main thread which will be blocked by init
615// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700616void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700617 ALOGI( "SurfaceFlinger's main thread ready to run. "
618 "Initializing graphics H/W...");
619
Thierry Strudel2924d012017-08-14 15:19:37 -0700620 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900621
Steven Thomasb02664d2017-07-26 18:48:28 -0700622 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800623
Steven Thomasb02664d2017-07-26 18:48:28 -0700624 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700625 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700626 mScheduler = getFactory().createScheduler([this](bool enabled) {
627 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
628 });
629
Ana Krulec98b5b242018-08-10 15:03:23 -0700630 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700631 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700632 [this] { resyncWithRateLimit(); },
633 impl::EventThread::InterceptVSyncsCallback());
634 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700635 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700636 [this] { resyncWithRateLimit(); },
637 [this](nsecs_t timestamp) {
638 mInterceptor->saveVSyncEvent(timestamp);
639 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800640
Ana Krulec98b5b242018-08-10 15:03:23 -0700641 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700642 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
643 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700644 } else {
645 mEventThreadSource =
646 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
647 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
648 mEventThread =
649 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
650 [this] { resyncWithRateLimit(); },
651 impl::EventThread::InterceptVSyncsCallback(),
652 "appEventThread");
653 mSfEventThreadSource =
654 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
655 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
656
657 mSFEventThread =
658 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
659 [this] { resyncWithRateLimit(); },
660 [this](nsecs_t timestamp) {
661 mInterceptor->saveVSyncEvent(timestamp);
662 },
663 "sfEventThread");
664 mEventQueue->setEventThread(mSFEventThread.get());
665 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
666 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800667
Steven Thomasb02664d2017-07-26 18:48:28 -0700668 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700669 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700670 renderEngineFeature |= (useColorManagement ?
671 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700672 renderEngineFeature |= (useContextPriority ?
673 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700674
675 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700676 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700677 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700678 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700679
680 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
681 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700682 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
683 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800684 // Process any initial hotplug and resulting display changes.
685 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700686 const auto display = getDefaultDisplayDeviceLocked();
687 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700688 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700689 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800690
Steven Thomas050b2c82017-03-06 11:45:16 -0800691 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700692 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700693 // This callback is called from the vr flinger dispatch thread. We
694 // need to call signalTransaction(), which requires holding
695 // mStateLock when we're not on the main thread. Acquiring
696 // mStateLock from the vr flinger dispatch thread might trigger a
697 // deadlock in surface flinger (see b/66916578), so post a message
698 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700699 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700700 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
701 mVrFlingerRequestsDisplay = requestDisplay;
702 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700703 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800704 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700705 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
706 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700707 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700708 .value_or(0),
709 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800710 if (!mVrFlinger) {
711 ALOGE("Failed to start vrflinger");
712 }
713 }
714
Lloyd Pique90c115d2018-09-18 21:39:42 -0700715 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700716 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700717
Mathias Agopian92a979a2012-08-02 18:32:23 -0700718 // initialize our drawing state
719 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700720
Andy McFadden13a082e2012-08-24 10:16:42 -0700721 // set initial conditions (e.g. unblank default device)
722 initializeDisplays();
723
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700724 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700725
Wei Wangf9b05ee2017-07-19 20:59:39 -0700726 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700727
728 const bool presentFenceReliable =
729 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
730 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700731
732 if (mStartPropertySetThread->Start() != NO_ERROR) {
733 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800734 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800735
Ana Krulec7d1d6832018-12-27 11:10:09 -0800736 if (mUseScheduler) {
737 mScheduler->setExpiredIdleTimerCallback([this]() { setRefreshRateTo(60.f /* fps */); });
738 mScheduler->setResetIdleTimerCallback([this]() { setRefreshRateTo(90.f /* fps */); });
739 }
740
Dan Stoza9e56aa02015-11-02 13:00:03 -0800741 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700742}
743
Romain Guy11d63f42017-07-20 12:47:14 -0700744void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700745 Mutex::Autolock _l(mStateLock);
746
Romain Guy11d63f42017-07-20 12:47:14 -0700747 char value[PROPERTY_VALUE_MAX];
748
749 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800750 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700751 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800752 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100753
754 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700755 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700756}
757
Mathias Agopiana67e4182012-06-19 17:26:12 -0700758void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800759 // Start boot animation service by setting a property mailbox
760 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700761 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800762 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700763 if (mStartPropertySetThread->join() != NO_ERROR) {
764 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800765 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700766}
767
Mathias Agopian875d8e12013-06-07 15:35:48 -0700768size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700769 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700770}
771
Mathias Agopian875d8e12013-06-07 15:35:48 -0700772size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700773 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700774}
775
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800776// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800777
Jamie Gennis582270d2011-08-17 18:19:00 -0700778bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800779 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800780 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800781 return authenticateSurfaceTextureLocked(bufferProducer);
782}
783
784bool SurfaceFlinger::authenticateSurfaceTextureLocked(
785 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800786 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800787 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800788}
789
Brian Anderson6b376712017-04-04 10:51:39 -0700790status_t SurfaceFlinger::getSupportedFrameTimestamps(
791 std::vector<FrameEvent>* outSupported) const {
792 *outSupported = {
793 FrameEvent::REQUESTED_PRESENT,
794 FrameEvent::ACQUIRE,
795 FrameEvent::LATCH,
796 FrameEvent::FIRST_REFRESH_START,
797 FrameEvent::LAST_REFRESH_START,
798 FrameEvent::GPU_COMPOSITION_DONE,
799 FrameEvent::DEQUEUE_READY,
800 FrameEvent::RELEASE,
801 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700802 ConditionalLock _l(mStateLock,
803 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700804 if (!getHwComposer().hasCapability(
805 HWC2::Capability::PresentFenceIsNotReliable)) {
806 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
807 }
808 return NO_ERROR;
809}
810
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700811status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
812 Vector<DisplayInfo>* configs) {
813 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700814 return BAD_VALUE;
815 }
816
Dominik Laskowski075d3172018-05-24 15:50:06 -0700817 const auto displayId = getPhysicalDisplayId(displayToken);
818 if (!displayId) {
819 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700820 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700821
Mathias Agopian8b736f12012-08-13 17:54:26 -0700822 // TODO: Not sure if display density should handled by SF any longer
823 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700824 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700825 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700826 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800827 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700828 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700829 }
830 return density;
831 }
832 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700833 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700834 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700835 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700836 return getDensityFromProperty("ro.sf.lcd_density"); }
837 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700838
Dan Stoza7f7da322014-05-02 15:26:25 -0700839 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700840
Steven Thomas6d8110b2017-08-31 18:24:21 -0700841 ConditionalLock _l(mStateLock,
842 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700843 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700844 DisplayInfo info = DisplayInfo();
845
Dan Stoza9e56aa02015-11-02 13:00:03 -0800846 float xdpi = hwConfig->getDpiX();
847 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700848
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700849 info.w = hwConfig->getWidth();
850 info.h = hwConfig->getHeight();
851 // Default display viewport to display width and height
852 info.viewportW = info.w;
853 info.viewportH = info.h;
854
Dominik Laskowski075d3172018-05-24 15:50:06 -0700855 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700856 // The density of the device is provided by a build property
857 float density = Density::getBuildDensity() / 160.0f;
858 if (density == 0) {
859 // the build doesn't provide a density -- this is wrong!
860 // use xdpi instead
861 ALOGE("ro.sf.lcd_density must be defined as a build property");
862 density = xdpi / 160.0f;
863 }
864 if (Density::getEmuDensity()) {
865 // if "qemu.sf.lcd_density" is specified, it overrides everything
866 xdpi = ydpi = density = Density::getEmuDensity();
867 density /= 160.0f;
868 }
869 info.density = density;
870
871 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700872 const auto display = getDefaultDisplayDeviceLocked();
873 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700874
875 // This is for screenrecord
876 const Rect viewport = display->getViewport();
877 if (viewport.isValid()) {
878 info.viewportW = uint32_t(viewport.getWidth());
879 info.viewportH = uint32_t(viewport.getHeight());
880 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700881 } else {
882 // TODO: where should this value come from?
883 static const int TV_DENSITY = 213;
884 info.density = TV_DENSITY / 160.0f;
885 info.orientation = 0;
886 }
887
Dan Stoza7f7da322014-05-02 15:26:25 -0700888 info.xdpi = xdpi;
889 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800890 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900891 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800892
Andy McFadden91b2ca82014-06-13 14:04:23 -0700893 // This is how far in advance a buffer must be queued for
894 // presentation at a given time. If you want a buffer to appear
895 // on the screen at time N, you must submit the buffer before
896 // (N - presentationDeadline).
897 //
898 // Normally it's one full refresh period (to give SF a chance to
899 // latch the buffer), but this can be reduced by configuring a
900 // DispSync offset. Any additional delays introduced by the hardware
901 // composer or panel must be accounted for here.
902 //
903 // We add an additional 1ms to allow for processing time and
904 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800905 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800906 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700907
908 // All non-virtual displays are currently considered secure.
909 info.secure = true;
910
Dominik Laskowski075d3172018-05-24 15:50:06 -0700911 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700912 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800913 std::swap(info.w, info.h);
914 }
915
Michael Wright28f24d02016-07-12 13:30:53 -0700916 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700917 }
918
Dan Stoza7f7da322014-05-02 15:26:25 -0700919 return NO_ERROR;
920}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700921
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700922status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
923 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700924 return BAD_VALUE;
925 }
926
Ana Krulece588e312018-09-18 12:32:24 -0700927 if (mUseScheduler) {
928 mScheduler->getDisplayStatInfo(stats);
929 } else {
930 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
931 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
932 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700933 return NO_ERROR;
934}
935
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700936int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
937 const auto display = getDisplayDevice(displayToken);
938 if (!display) {
939 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800940 return BAD_VALUE;
941 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700942
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700943 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700944}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700945
Ana Krulec7d1d6832018-12-27 11:10:09 -0800946status_t SurfaceFlinger::setActiveConfigAsync(const sp<IBinder>& displayToken, int mode) {
947 ATRACE_NAME("setActiveConfigAsync");
948 postMessageAsync(new LambdaMessage([=] { setActiveConfigInternal(displayToken, mode); }));
949 return NO_ERROR;
950}
951
952status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
953 ATRACE_NAME("setActiveConfigSync");
954 postMessageSync(new LambdaMessage([&] { setActiveConfigInternal(displayToken, mode); }));
955 return NO_ERROR;
956}
957
958void SurfaceFlinger::setActiveConfigInternal(const sp<IBinder>& displayToken, int mode) {
959 Vector<DisplayInfo> configs;
960 getDisplayConfigs(displayToken, &configs);
961 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
962 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
963 return;
964 }
965
966 const auto display = getDisplayDevice(displayToken);
967 if (!display) {
968 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
969 displayToken.get());
970 return;
971 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700972 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800973 ALOGW("Attempt to set active config %d for virtual display", mode);
974 return;
975 }
976 int currentDisplayPowerMode = display->getPowerMode();
977 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
978 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700979 return;
980 }
981
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700982 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700983 if (mode == currentMode) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800984 // Don't update config if we are already running in the desired mode.
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700985 return;
986 }
987
Dominik Laskowski075d3172018-05-24 15:50:06 -0700988 const auto displayId = display->getId();
989 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700990
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700991 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700992 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700993
Ana Krulec7d1d6832018-12-27 11:10:09 -0800994 ATRACE_INT("ActiveConfigMode", mode);
995 resyncToHardwareVsync(true);
Mathias Agopianc666cae2012-07-25 18:56:13 -0700996}
Dominik Laskowski075d3172018-05-24 15:50:06 -0700997
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700998status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
999 Vector<ColorMode>* outColorModes) {
1000 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001001 return BAD_VALUE;
1002 }
1003
Dominik Laskowski075d3172018-05-24 15:50:06 -07001004 const auto displayId = getPhysicalDisplayId(displayToken);
1005 if (!displayId) {
1006 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -07001007 }
1008
Peiyong Lina52f0292018-03-14 17:26:31 -07001009 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001010 {
1011 ConditionalLock _l(mStateLock,
1012 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001013 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001014 }
Michael Wright28f24d02016-07-12 13:30:53 -07001015 outColorModes->clear();
1016 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1017
1018 return NO_ERROR;
1019}
1020
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001021ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1022 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001023 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001024 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001025 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001026}
1027
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001028status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001029 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001030 Vector<ColorMode> modes;
1031 getDisplayColorModes(displayToken, &modes);
1032 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1033 if (mode < ColorMode::NATIVE || !exists) {
1034 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1035 decodeColorMode(mode).c_str(), mode, displayToken.get());
1036 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001037 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001038 const auto display = getDisplayDevice(displayToken);
1039 if (!display) {
1040 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1041 decodeColorMode(mode).c_str(), mode, displayToken.get());
1042 } else if (display->isVirtual()) {
1043 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1044 decodeColorMode(mode).c_str(), mode);
1045 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001046 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1047 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001048 }
1049 }));
1050
Michael Wright28f24d02016-07-12 13:30:53 -07001051 return NO_ERROR;
1052}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001053
Svetoslavd85084b2014-03-20 10:28:31 -07001054status_t SurfaceFlinger::clearAnimationFrameStats() {
1055 Mutex::Autolock _l(mStateLock);
1056 mAnimFrameTracker.clearStats();
1057 return NO_ERROR;
1058}
1059
1060status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1061 Mutex::Autolock _l(mStateLock);
1062 mAnimFrameTracker.getStats(outStats);
1063 return NO_ERROR;
1064}
1065
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001066status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1067 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001068 Mutex::Autolock _l(mStateLock);
1069
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001070 const auto display = getDisplayDeviceLocked(displayToken);
1071 if (!display) {
1072 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001073 return BAD_VALUE;
1074 }
1075
Peiyong Linfb069302018-04-25 14:34:31 -07001076 // At this point the DisplayDeivce should already be set up,
1077 // meaning the luminance information is already queried from
1078 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001079 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001080 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1081 capabilities.getDesiredMaxLuminance(),
1082 capabilities.getDesiredMaxAverageLuminance(),
1083 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001084
1085 return NO_ERROR;
1086}
1087
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001088status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1089 ui::PixelFormat* outFormat,
1090 ui::Dataspace* outDataspace,
1091 uint8_t* outComponentMask) const {
1092 if (!outFormat || !outDataspace || !outComponentMask) {
1093 return BAD_VALUE;
1094 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001095 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001096 if (!display || !display->getId()) {
1097 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1098 return BAD_VALUE;
1099 }
1100 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1101 outDataspace, outComponentMask);
1102}
1103
Kevin DuBois74e53772018-11-19 10:52:38 -08001104status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1105 bool enable, uint8_t componentMask,
1106 uint64_t maxFrames) const {
1107 const auto display = getDisplayDevice(displayToken);
1108 if (!display || !display->getId()) {
1109 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1110 return BAD_VALUE;
1111 }
1112
1113 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1114 componentMask, maxFrames);
1115}
1116
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001117status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1118 uint64_t maxFrames, uint64_t timestamp,
1119 DisplayedFrameStats* outStats) const {
1120 const auto display = getDisplayDevice(displayToken);
1121 if (!display || !display->getId()) {
1122 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1123 return BAD_VALUE;
1124 }
1125
1126 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1127 outStats);
1128}
1129
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001130status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001131 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001132 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001133
Chia-I Wu90f669f2017-10-05 14:24:41 -07001134 if (mInjectVSyncs == enable) {
1135 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001136 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001137
Ana Krulec98b5b242018-08-10 15:03:23 -07001138 // TODO(akrulec): Part of the Injector should be refactored, so that it
1139 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001140 if (enable) {
1141 ALOGV("VSync Injections enabled");
1142 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001143 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001144 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001145 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001146 impl::EventThread::InterceptVSyncsCallback(),
1147 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001148 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001149 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001150 } else {
1151 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001152 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001153 }
1154
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001155 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001156 }));
1157
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001158 return NO_ERROR;
1159}
1160
1161status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001162 Mutex::Autolock _l(mStateLock);
1163
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001164 if (!mInjectVSyncs) {
1165 ALOGE("VSync Injections not enabled");
1166 return BAD_VALUE;
1167 }
1168 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1169 ALOGV("Injecting VSync inside SurfaceFlinger");
1170 mVSyncInjector->onInjectSyncEvent(when);
1171 }
1172 return NO_ERROR;
1173}
1174
Lloyd Pique755e3192018-01-31 16:46:15 -08001175status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1176 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001177 // Try to acquire a lock for 1s, fail gracefully
1178 const status_t err = mStateLock.timedLock(s2ns(1));
1179 const bool locked = (err == NO_ERROR);
1180 if (!locked) {
1181 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1182 return TIMED_OUT;
1183 }
1184
1185 outLayers->clear();
1186 mCurrentState.traverseInZOrder([&](Layer* layer) {
1187 outLayers->push_back(layer->getLayerDebugInfo());
1188 });
1189
1190 mStateLock.unlock();
1191 return NO_ERROR;
1192}
1193
Peiyong Linc6780972018-10-28 15:24:08 -07001194status_t SurfaceFlinger::getCompositionPreference(
1195 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1196 Dataspace* outWideColorGamutDataspace,
1197 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001198 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001199 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001200 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001201 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001202 return NO_ERROR;
1203}
1204
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001205// ----------------------------------------------------------------------------
1206
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001207sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1208 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001209 if (mUseScheduler) {
1210 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1211 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1212 } else {
1213 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1214 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001215 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001216 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1217 return mSFEventThread->createEventConnection();
1218 } else {
1219 return mEventThread->createEventConnection();
1220 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001221 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001222}
1223
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001224// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001225
1226void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001227 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001228}
1229
1230void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001231 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001232}
1233
1234void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001235 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001236}
1237
1238void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001239 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001240 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001241}
1242
1243status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001244 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001245 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001246}
1247
1248status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001249 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001250 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001251 if (res == NO_ERROR) {
1252 msg->wait();
1253 }
1254 return res;
1255}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001256
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001257void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001258 do {
1259 waitForEvent();
1260 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001261}
1262
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001263void SurfaceFlinger::enableHardwareVsync() {
1264 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001265 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001266 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001267 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001268 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001269 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001270}
1271
Jesse Hall948fe0c2013-10-14 12:56:09 -07001272void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001273 Mutex::Autolock _l(mHWVsyncLock);
1274
Jesse Hall948fe0c2013-10-14 12:56:09 -07001275 if (makeAvailable) {
1276 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001277 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1278 if (mUseScheduler) {
1279 mScheduler->makeHWSyncAvailable(true);
1280 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001281 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001282 // Hardware vsync is not currently available, so abort the resync
1283 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001284 return;
1285 }
1286
Dominik Laskowski075d3172018-05-24 15:50:06 -07001287 const auto displayId = getInternalDisplayId();
1288 if (!displayId || !getHwComposer().isConnected(*displayId)) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001289 return;
1290 }
1291
Dominik Laskowski075d3172018-05-24 15:50:06 -07001292 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001293 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001294
Ana Krulece588e312018-09-18 12:32:24 -07001295 if (mUseScheduler) {
1296 mScheduler->setVsyncPeriod(period);
1297 } else {
1298 mPrimaryDispSync->reset();
1299 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001300
Ana Krulece588e312018-09-18 12:32:24 -07001301 if (!mPrimaryHWVsyncEnabled) {
1302 mPrimaryDispSync->beginResync();
1303 mEventControlThread->setVsyncEnabled(true);
1304 mPrimaryHWVsyncEnabled = true;
1305 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001306 }
1307}
1308
Jesse Hall948fe0c2013-10-14 12:56:09 -07001309void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001310 Mutex::Autolock _l(mHWVsyncLock);
1311 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001312 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001313 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001314 mPrimaryHWVsyncEnabled = false;
1315 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001316 if (makeUnavailable) {
1317 mHWVsyncAvailable = false;
1318 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001319}
1320
Tim Murray4a4e4a22016-04-19 16:29:23 +00001321void SurfaceFlinger::resyncWithRateLimit() {
1322 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001323
1324 // No explicit locking is needed here since EventThread holds a lock while calling this method
1325 static nsecs_t sLastResyncAttempted = 0;
1326 const nsecs_t now = systemTime();
1327 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001328 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001329 }
Dan Stoza57164302017-05-08 14:03:54 -07001330 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001331}
1332
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001333void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1334 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001335 ATRACE_NAME("SF onVsync");
1336
Steven Thomas3cfac282017-02-06 12:29:30 -08001337 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001338 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001339 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001340 return;
1341 }
1342
Dominik Laskowski075d3172018-05-24 15:50:06 -07001343 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001344 return;
1345 }
1346
Dominik Laskowski075d3172018-05-24 15:50:06 -07001347 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001348 // For now, we don't do anything with external display vsyncs.
1349 return;
1350 }
1351
Ana Krulece588e312018-09-18 12:32:24 -07001352 if (mUseScheduler) {
1353 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001354 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001355 bool needsHwVsync = false;
1356 { // Scope for the lock
1357 Mutex::Autolock _l(mHWVsyncLock);
1358 if (mPrimaryHWVsyncEnabled) {
1359 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1360 }
1361 }
1362
1363 if (needsHwVsync) {
1364 enableHardwareVsync();
1365 } else {
1366 disableHardwareVsync(false);
1367 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001368 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001369}
1370
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001371void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001372 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1373 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001374}
1375
Ana Krulec7d1d6832018-12-27 11:10:09 -08001376void SurfaceFlinger::setRefreshRateTo(float newFps) {
1377 const auto displayId = getInternalDisplayId();
1378 if (!displayId || mBootStage != BootStage::FINISHED) {
1379 return;
1380 }
1381 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1382 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1383 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1384 // refresh cycle.
1385
1386 // Don't do any updating if the current fps is the same as the new one.
1387 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
1388 const nsecs_t currentVsyncPeriod = activeConfig->getVsyncPeriod();
1389 if (currentVsyncPeriod == 0) {
1390 return;
1391 }
1392 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1393 // floating numbers.
1394 const float currentFps = 1e9 / currentVsyncPeriod;
1395 if (std::abs(currentFps - newFps) <= 1) {
1396 return;
1397 }
1398
1399 auto configs = getHwComposer().getConfigs(*displayId);
1400 for (int i = 0; i < configs.size(); i++) {
1401 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1402 if (vsyncPeriod == 0) {
1403 continue;
1404 }
1405 const float fps = 1e9 / vsyncPeriod;
1406 // TODO(b/113612090): There should be a better way at determining which config
1407 // has the right refresh rate.
1408 if (std::abs(fps - newFps) <= 1) {
1409 const auto display = getBuiltInDisplay(HWC_DISPLAY_PRIMARY);
1410 if (!display) return;
1411 // This is posted in async function to avoid deadlock when getDisplayDevice
1412 // requires mStateLock.
1413 setActiveConfigAsync(display, i);
1414 ATRACE_INT("FPS", newFps);
1415 }
1416 }
1417}
1418
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001419void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001420 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001421 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001422 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001423
Lloyd Piqueba04e622017-12-14 17:11:26 -08001424 // Ignore events that do not have the right sequenceId.
1425 if (sequenceId != getBE().mComposerSequenceId) {
1426 return;
1427 }
1428
Steven Thomasb02664d2017-07-26 18:48:28 -07001429 // Only lock if we're not on the main thread. This function is normally
1430 // called on a hwbinder thread, but for the primary display it's called on
1431 // the main thread with the state lock already held, so don't attempt to
1432 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001433 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001434
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001435 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001436
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001437 if (std::this_thread::get_id() == mMainThreadId) {
1438 // Process all pending hot plug events immediately if we are on the main thread.
1439 processDisplayHotplugEventsLocked();
1440 }
1441
Lloyd Piqueba04e622017-12-14 17:11:26 -08001442 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001443}
1444
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001445void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001446 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001447 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001448 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001449 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001450 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001451}
1452
Dominik Laskowski075d3172018-05-24 15:50:06 -07001453void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001454 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001455 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001456 if (const auto displayId = getInternalDisplayId()) {
1457 getHwComposer().setVsyncEnabled(*displayId,
1458 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1459 }
Mathias Agopian86303202012-07-24 22:46:10 -07001460}
1461
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001462// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001463void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001464 if (mUseScheduler) {
1465 mScheduler->disableHardwareVsync(true);
1466 } else {
1467 disableHardwareVsync(true);
1468 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001469 // Clear the drawing state so that the logic inside of
1470 // handleTransactionLocked will fire. It will determine the delta between
1471 // mCurrentState and mDrawingState and re-apply all changes when we make the
1472 // transition.
1473 mDrawingState.displays.clear();
1474 mDisplays.clear();
1475}
1476
Steven Thomas050b2c82017-03-06 11:45:16 -08001477void SurfaceFlinger::updateVrFlinger() {
1478 if (!mVrFlinger)
1479 return;
1480 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001481 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001482 return;
1483 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001484
Lloyd Pique441d5042018-10-18 16:49:51 -07001485 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001486 ALOGE("Vr flinger is only supported for remote hardware composer"
1487 " service connections. Ignoring request to transition to vr"
1488 " flinger.");
1489 mVrFlingerRequestsDisplay = false;
1490 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001491 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001492
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001493 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001494
Steven Thomas0123ac62018-07-12 11:32:34 -07001495 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001496 LOG_ALWAYS_FATAL_IF(!display);
1497 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001498 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1499 // called below. Clear the reference now so we don't accidentally use it
1500 // later.
1501 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001502
Steven Thomasb02664d2017-07-26 18:48:28 -07001503 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001504 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001505 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001506
Steven Thomasb02664d2017-07-26 18:48:28 -07001507 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001508 // Delete the current instance before creating the new one
1509 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1510 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1511 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1512 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001513
Lloyd Pique441d5042018-10-18 16:49:51 -07001514 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001515 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001516
1517 if (vrFlingerRequestsDisplay) {
1518 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001519 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001520
1521 mVisibleRegionsDirty = true;
1522 invalidateHwcGeometry();
1523
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001524 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001525 display = getDefaultDisplayDeviceLocked();
1526 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001527 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001528
Steven Thomasb02664d2017-07-26 18:48:28 -07001529 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski075d3172018-05-24 15:50:06 -07001530 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001531 const nsecs_t period = activeConfig->getVsyncPeriod();
1532 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001533
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001534 // The present fences returned from vr_hwc are not an accurate
1535 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001536 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001537 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1538 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001539 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001540 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001541 !hasSyncFramework);
1542 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001543
Steven Thomasb02664d2017-07-26 18:48:28 -07001544 // Use phase of 0 since phase is not known.
1545 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001546 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1547 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001548
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001549 resyncToHardwareVsync(false);
1550
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001551 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001552 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001553}
1554
Mathias Agopian4fec8732012-06-29 14:12:52 -07001555void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001556 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001557 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001558 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001559 if (mUseScheduler) {
1560 // This call is made each time SF wakes up and creates a new frame.
1561 mScheduler->incrementFrameCounter();
1562 }
Dan Stoza50182882016-07-08 12:02:20 -07001563 bool frameMissed = !mHadClientComposition &&
1564 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001565 (mPreviousPresentFence->getSignalTime() ==
1566 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001567 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001568 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001569 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001570 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001571 if (mPropagateBackpressure) {
1572 signalLayerUpdate();
1573 break;
1574 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001575 }
Dan Stoza50182882016-07-08 12:02:20 -07001576
Steven Thomas050b2c82017-03-06 11:45:16 -08001577 // Now that we're going to make it to the handleMessageTransaction()
1578 // call below it's safe to call updateVrFlinger(), which will
1579 // potentially trigger a display handoff.
1580 updateVrFlinger();
1581
Dan Stoza6b9454d2014-11-07 16:00:59 -08001582 bool refreshNeeded = handleMessageTransaction();
1583 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001584 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001585 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001586 // Signal a refresh if a transaction modified the window state,
1587 // a new buffer was latched, or if HWC has requested a full
1588 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001589 signalRefresh();
1590 }
1591 break;
1592 }
1593 case MessageQueue::REFRESH: {
1594 handleMessageRefresh();
1595 break;
1596 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001597 }
1598}
1599
Dan Stoza6b9454d2014-11-07 16:00:59 -08001600bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001601 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001602
1603 // Apply any ready transactions in the queues if there are still transactions that have not been
1604 // applied, wake up during the next vsync period and check again
1605 bool transactionNeeded = false;
1606 if (!flushTransactionQueues()) {
1607 transactionNeeded = true;
1608 }
1609
Mathias Agopian4fec8732012-06-29 14:12:52 -07001610 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001611 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001612 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001613
1614 if (transactionNeeded) {
1615 setTransactionFlags(eTransactionNeeded);
1616 }
1617
1618 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001619}
1620
Mathias Agopian4fec8732012-06-29 14:12:52 -07001621void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001622 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001623
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001624 mRefreshPending = false;
1625
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001626 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001627 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001628 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001629 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001630 for (const auto& [token, display] : mDisplays) {
1631 beginFrame(display);
1632 prepareFrame(display);
1633 doDebugFlashRegions(display, repaintEverything);
1634 doComposition(display, repaintEverything);
1635 }
1636
Adrian Roos1e1a1282017-11-01 19:05:31 +01001637 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001638 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001639
1640 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001641 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001642
Dan Stozabfbffeb2016-07-21 14:49:33 -07001643 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001644 for (const auto& [token, displayDevice] : mDisplays) {
1645 auto display = displayDevice->getCompositionDisplay();
1646 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001647 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001648 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001649 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001650
Alec Mouri86770e52018-09-24 22:40:58 +00001651 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001652 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001653 if (mHadClientComposition) {
1654 base::unique_fd flushFence(getRenderEngine().flush());
1655 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1656 getBE().flushFence = new Fence(std::move(flushFence));
1657 } else {
1658 // Cleanup for hygiene.
1659 getBE().flushFence = Fence::NO_FENCE;
1660 }
1661 }
1662
Jorim Jaggi90535212018-05-23 23:44:06 +02001663 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001664
David Sodman7e4ae112018-02-09 15:02:28 -08001665 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001666 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001667 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001668 compositionInfo.hwc.hwcLayer = nullptr;
1669 }
David Sodmanba340492018-08-05 21:51:33 -07001670 }
David Sodman7e4ae112018-02-09 15:02:28 -08001671
1672 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001673}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001674
David Sodmanfa9b2af2017-12-24 13:28:59 -08001675
1676bool SurfaceFlinger::handleMessageInvalidate() {
1677 ATRACE_CALL();
1678 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001679}
1680
David Sodman79bba0e2018-08-05 18:07:49 -07001681void SurfaceFlinger::calculateWorkingSet() {
1682 ATRACE_CALL();
1683 ALOGV(__FUNCTION__);
1684
David Sodman79bba0e2018-08-05 18:07:49 -07001685 // build the h/w work list
1686 if (CC_UNLIKELY(mGeometryInvalid)) {
1687 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001688 for (const auto& [token, displayDevice] : mDisplays) {
1689 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001690 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001691 if (!displayId) {
1692 continue;
1693 }
David Sodman79bba0e2018-08-05 18:07:49 -07001694
Lloyd Pique32cbe282018-10-19 13:09:22 -07001695 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001696 for (size_t i = 0; i < currentLayers.size(); i++) {
1697 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001698
Dominik Laskowski075d3172018-05-24 15:50:06 -07001699 if (!layer->hasHwcLayer(*displayId)) {
1700 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1701 layer->forceClientComposition(*displayId);
1702 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001703 }
1704 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001705
Lloyd Pique32cbe282018-10-19 13:09:22 -07001706 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001707 if (mDebugDisableHWC || mDebugRegion) {
1708 layer->forceClientComposition(*displayId);
1709 }
David Sodman79bba0e2018-08-05 18:07:49 -07001710 }
1711 }
1712 }
1713
1714 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001715 for (const auto& [token, displayDevice] : mDisplays) {
1716 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001717 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001718 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001719 continue;
1720 }
1721
1722 if (mDrawingState.colorMatrixChanged) {
1723 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001724 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001725 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001726 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001727 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001728 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1729 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique32cbe282018-10-19 13:09:22 -07001730 !displayDevice->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001731 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001732 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1733 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique32cbe282018-10-19 13:09:22 -07001734 !displayDevice->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001735 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001736 }
1737
Peiyong Lind3788632018-09-18 16:01:31 -07001738 // TODO(b/111562338) remove when composer 2.3 is shipped.
1739 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001740 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001741 }
1742
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001743 if (layer->getRoundedCornerState().radius > 0.0f) {
1744 layer->forceClientComposition(*displayId);
1745 }
1746
Dominik Laskowski075d3172018-05-24 15:50:06 -07001747 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001748 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001749 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001750 continue;
1751 }
1752
Lloyd Pique32cbe282018-10-19 13:09:22 -07001753 const auto& displayState = display->getState();
1754 layer->setPerFrameData(*displayId, displayState.transform, displayState.viewport,
1755 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001756 }
1757
Peiyong Lin13effd12018-07-24 17:01:47 -07001758 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001759 ColorMode colorMode;
1760 Dataspace dataSpace;
1761 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001762 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001763 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001764 }
1765 }
1766
1767 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001768
1769 for (const auto& [token, display] : mDisplays) {
1770 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001771 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001772 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001773
1774 if (displayId) {
1775 if (!layer->setHwcLayer(*displayId)) {
1776 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1777 }
1778 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001779 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001780
Dominik Laskowski05275f12018-11-01 15:03:24 -07001781 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001782 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1783 }
1784 }
David Sodman79bba0e2018-08-05 18:07:49 -07001785}
1786
Lloyd Pique32cbe282018-10-19 13:09:22 -07001787void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1788 bool repaintEverything) {
1789 auto display = displayDevice->getCompositionDisplay();
1790 const auto& displayState = display->getState();
1791
Mathias Agopiancd60f992012-08-16 16:28:27 -07001792 // is debugging enabled
1793 if (CC_LIKELY(!mDebugRegion))
1794 return;
1795
Lloyd Pique32cbe282018-10-19 13:09:22 -07001796 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001797 // transform the dirty region into this screen's coordinate space
Lloyd Pique32cbe282018-10-19 13:09:22 -07001798 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001799 if (!dirtyRegion.isEmpty()) {
1800 // redraw the whole screen
Lloyd Pique32cbe282018-10-19 13:09:22 -07001801 doComposeSurfaces(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001802
David Sodmanfa9b2af2017-12-24 13:28:59 -08001803 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001804 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001805 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001806
Lloyd Pique31cb2942018-10-19 17:23:03 -07001807 display->getRenderSurface()->queueBuffer();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001808 }
1809 }
1810
Lloyd Pique32cbe282018-10-19 13:09:22 -07001811 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001812
1813 if (mDebugRegion > 1) {
1814 usleep(mDebugRegion * 1000);
1815 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001816
Lloyd Pique32cbe282018-10-19 13:09:22 -07001817 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001818}
1819
Adrian Roos1e1a1282017-11-01 19:05:31 +01001820void SurfaceFlinger::doTracing(const char* where) {
1821 ATRACE_CALL();
1822 ATRACE_NAME(where);
1823 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001824 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001825 }
1826}
1827
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001828void SurfaceFlinger::logLayerStats() {
1829 ATRACE_CALL();
1830 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001831 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001832 if (display->isPrimary()) {
1833 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001834 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001835 }
1836 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001837
1838 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001839 }
1840}
1841
David Sodman2b406362017-12-15 13:33:47 -08001842void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001843{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001844 ATRACE_CALL();
1845 ALOGV("preComposition");
1846
David Sodman2b406362017-12-15 13:33:47 -08001847 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1848
Mathias Agopiancd60f992012-08-16 16:28:27 -07001849 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001850 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001851 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001852 needExtraInvalidate = true;
1853 }
Robert Carr2047fae2016-11-28 14:09:09 -08001854 });
1855
Mathias Agopiancd60f992012-08-16 16:28:27 -07001856 if (needExtraInvalidate) {
1857 signalLayerUpdate();
1858 }
1859}
1860
Ana Krulece588e312018-09-18 12:32:24 -07001861void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1862 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001863 // Update queue of past composite+present times and determine the
1864 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001865 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001866 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001867 while (!getBE().mCompositePresentTimes.empty()) {
1868 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001869 // Cached values should have been updated before calling this method,
1870 // which helps avoid duplicate syscalls.
1871 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1872 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1873 break;
1874 }
1875 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001876 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001877 }
1878
1879 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001880 while (getBE().mCompositePresentTimes.size() > 16) {
1881 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001882 }
1883
Ana Krulece588e312018-09-18 12:32:24 -07001884 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001885}
1886
Ana Krulece588e312018-09-18 12:32:24 -07001887void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1888 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001889 // Integer division and modulo round toward 0 not -inf, so we need to
1890 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001891 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1892 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1893 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001894
Brian Andersond0010582017-03-07 13:20:31 -08001895 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1896 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001897 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001898 }
1899
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001900 // Snap the latency to a value that removes scheduling jitter from the
1901 // composition and present times, which often have >1ms of jitter.
1902 // Reducing jitter is important if an app attempts to extrapolate
1903 // something (such as user input) to an accurate diasplay time.
1904 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1905 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001906 nsecs_t bias = stats.vsyncPeriod / 2;
1907 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1908 nsecs_t snappedCompositeToPresentLatency =
1909 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001910
David Sodman99974d22017-11-28 12:04:33 -08001911 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001912 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1913 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001914 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001915}
1916
Ady Abraham8164d482019-01-11 14:47:59 -08001917// debug patch for b/119477596 - add stack guards to catch stack
1918// corruptions and disable clang optimizations.
1919// The code below is temporary and planned to be removed once stack
1920// corruptions are found.
1921#pragma clang optimize off
1922class StackGuard {
1923public:
1924 StackGuard(const char* name, const char* func, int line) {
1925 guarders.reserve(MIN_CAPACITY);
1926 guarders.push_back({this, name, func, line});
1927 validate();
1928 }
1929 ~StackGuard() {
1930 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1931 if (i->guard == this) {
1932 guarders.erase(i);
1933 break;
1934 }
1935 }
1936 }
1937
1938 static void validate() {
1939 for (const auto& guard : guarders) {
1940 if (guard.guard->cookie != COOKIE_VALUE) {
1941 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1942 CallStack stack(LOG_TAG);
1943 abort();
1944 }
1945 }
1946 }
1947
1948private:
1949 uint64_t cookie = COOKIE_VALUE;
1950 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
1951 static constexpr size_t MIN_CAPACITY = 16;
1952
1953 struct GuarderElement {
1954 StackGuard* guard;
1955 const char* name;
1956 const char* func;
1957 int line;
1958 };
1959
1960 static std::vector<GuarderElement> guarders;
1961};
1962std::vector<StackGuard::GuarderElement> StackGuard::guarders;
1963
1964#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
1965
1966#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08001967void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001968{
Ady Abraham8164d482019-01-11 14:47:59 -08001969 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001970 ATRACE_CALL();
1971 ALOGV("postComposition");
1972
Brian Anderson3546a3f2016-07-14 11:51:14 -07001973 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001974 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08001975 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001976 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001977 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001978 }
Ady Abraham8164d482019-01-11 14:47:59 -08001979 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001980
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001981 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07001982 const auto displayDevice = getDefaultDisplayDeviceLocked();
1983 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001984
David Sodman73beded2017-11-15 11:56:06 -08001985 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001986 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08001987 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
1988
Lloyd Pique32cbe282018-10-19 13:09:22 -07001989 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001990 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07001991 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
1992 ->getRenderSurface()
1993 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001994 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001995 } else {
1996 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1997 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001998
Ady Abraham8164d482019-01-11 14:47:59 -08001999 ASSERT_ON_STACK_GUARD();
2000
David Sodman73beded2017-11-15 11:56:06 -08002001 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002002 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2003 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002004 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002005 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002006 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002007
Ana Krulece588e312018-09-18 12:32:24 -07002008 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002009 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002010 if (mUseScheduler) {
2011 mScheduler->getDisplayStatInfo(&stats);
2012 } else {
2013 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2014 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2015 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002016
Ady Abraham8164d482019-01-11 14:47:59 -08002017 ASSERT_ON_STACK_GUARD();
2018
David Sodman2b406362017-12-15 13:33:47 -08002019 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002020 // when we started doing work for this frame, but that should be okay
2021 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002022 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002023 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002024 DEFINE_STACK_GUARD(compositorTiming);
2025
Brian Andersond0010582017-03-07 13:20:31 -08002026 {
David Sodman99974d22017-11-28 12:04:33 -08002027 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002028 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002029 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002030
2031 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002032 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002033
Robert Carr2047fae2016-11-28 14:09:09 -08002034 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002035 bool frameLatched =
2036 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2037 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002038 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002039 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002040 recordBufferingStats(layer->getName().string(),
2041 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002042 }
Ady Abraham8164d482019-01-11 14:47:59 -08002043 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002044 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002045
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002046 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002047 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002048 if (mUseScheduler) {
2049 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002050 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002051 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002052 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2053 enableHardwareVsync();
2054 } else {
2055 disableHardwareVsync(false);
2056 }
Ady Abraham8164d482019-01-11 14:47:59 -08002057 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002058 }
2059 }
2060
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002061 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002062 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2063 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002064 if (mUseScheduler) {
2065 mScheduler->enableHardwareVsync();
2066 } else {
2067 enableHardwareVsync();
2068 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002069 }
2070 }
2071
Ady Abraham8164d482019-01-11 14:47:59 -08002072 ASSERT_ON_STACK_GUARD();
2073
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002074 if (mAnimCompositionPending) {
2075 mAnimCompositionPending = false;
2076
Brian Anderson4e606e32017-03-16 15:34:57 -07002077 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002078 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002079 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002080
2081 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002082 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002083 // The HWC doesn't support present fences, so use the refresh
2084 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002085 const nsecs_t presentTime =
2086 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002087 DEFINE_STACK_GUARD(presentTime);
2088
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002089 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002090 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002091 }
2092 mAnimFrameTracker.advanceFrame();
2093 }
Dan Stozab90cf072015-03-05 11:05:59 -08002094
Ady Abraham8164d482019-01-11 14:47:59 -08002095 ASSERT_ON_STACK_GUARD();
2096
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002097 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002098 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002099 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002100 }
2101
Ady Abraham8164d482019-01-11 14:47:59 -08002102 ASSERT_ON_STACK_GUARD();
2103
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002104 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002105
Ady Abraham8164d482019-01-11 14:47:59 -08002106 ASSERT_ON_STACK_GUARD();
2107
Lloyd Pique32cbe282018-10-19 13:09:22 -07002108 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2109 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002110 return;
2111 }
2112
2113 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002114 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002115 if (mHasPoweredOff) {
2116 mHasPoweredOff = false;
2117 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002118 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002119 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002120 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002121 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002122 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2123 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002124 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002125 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002126 }
David Sodman4a36e932017-11-07 14:29:47 -08002127 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002128
2129 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002130 }
David Sodman4a36e932017-11-07 14:29:47 -08002131 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002132 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002133
2134 {
2135 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002136 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002137 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002138 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002139 if (refillCount > 0) {
2140 const size_t offset = mTexturePool.size();
2141 mTexturePool.resize(mTexturePoolSize);
2142 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2143 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2144 }
Ady Abraham8164d482019-01-11 14:47:59 -08002145 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002146 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002147
Marissa Wallfda30bb2018-10-12 11:34:28 -07002148 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002149 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002150
2151 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002152}
Ady Abraham8164d482019-01-11 14:47:59 -08002153#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002154
2155void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002156 ATRACE_CALL();
2157 ALOGV("rebuildLayerStacks");
2158
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002159 // We need to clear these out now as these may be holding on to a
2160 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2161 // also holds a reference. When the set of visible layers is recomputed,
2162 // some layers may be destroyed if the only thing keeping them alive was
2163 // that list of visible layers associated with each display. The layer
2164 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2165 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2166 for (const auto& [token, display] : mDisplays) {
2167 getBE().mCompositionInfo[token].clear();
2168 }
2169
Mathias Agopiancd60f992012-08-16 16:28:27 -07002170 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002171 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002172 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002173 mVisibleRegionsDirty = false;
2174 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002175
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002176 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002177 const auto& displayDevice = pair.second;
2178 auto display = displayDevice->getCompositionDisplay();
2179 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002180 Region opaqueRegion;
2181 Region dirtyRegion;
2182 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002183 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002184 const ui::Transform& tr = displayState.transform;
2185 const Rect bounds = displayState.bounds;
2186 if (displayState.isEnabled) {
2187 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002188
Jeff Sharkey76488112017-02-27 14:15:18 -07002189 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002190 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002191 const auto displayId = displayDevice->getId();
2192 if (display->belongsInOutput(layer->getLayerStack())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002193 Region drawRegion(tr.transform(
2194 layer->visibleNonTransparentRegion));
2195 drawRegion.andSelf(bounds);
2196 if (!drawRegion.isEmpty()) {
2197 layersSortedByZ.add(layer);
2198 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002199 // Clear out the HWC layer if this layer was
2200 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002201 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002202 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002203 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002204 // WM changes display->layerStack upon sleep/awake.
2205 // Here we make sure we delete the HWC layers even if
2206 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002207 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002208 }
2209
2210 // If a layer is not going to get a release fence because
2211 // it is invisible, but it is also going to release its
2212 // old buffer, add it to the list of layers needing
2213 // fences.
2214 if (hwcLayerDestroyed) {
2215 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2216 mLayersWithQueuedFrames.cend(), layer);
2217 if (found != mLayersWithQueuedFrames.cend()) {
2218 layersNeedingFences.add(layer);
2219 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002220 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002221 });
2222 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002223 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
2224 displayDevice->setLayersNeedingFences(layersNeedingFences);
2225
2226 Region undefinedRegion{bounds};
2227 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2228
2229 display->editState().undefinedRegion = undefinedRegion;
2230 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002231 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002232 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002233}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002234
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002235// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002236// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002237// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002238// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002239// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002240// The returned HDR data space is one of
2241// - Dataspace::UNKNOWN
2242// - Dataspace::BT2020_HLG
2243// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002244Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2245 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002246 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002247 *outHdrDataSpace = Dataspace::UNKNOWN;
2248
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002249 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002250 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002251 case Dataspace::V0_SCRGB:
2252 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002253 case Dataspace::BT2020:
2254 case Dataspace::BT2020_ITU:
2255 case Dataspace::BT2020_LINEAR:
2256 case Dataspace::DISPLAY_BT2020:
2257 bestDataSpace = Dataspace::DISPLAY_BT2020;
2258 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002259 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002260 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002261 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002262 case Dataspace::BT2020_PQ:
2263 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002264 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002265 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002266 case Dataspace::BT2020_HLG:
2267 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002268 // When there's mixed PQ content and HLG content, we set the HDR
2269 // data space to be BT2020_PQ and convert HLG to PQ.
2270 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2271 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002272 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002273 break;
2274 default:
2275 break;
2276 }
Romain Guy54f154a2017-10-24 21:40:32 +01002277 }
2278
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002279 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002280}
2281
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002282// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002283void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2284 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002285 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2286 *outMode = ColorMode::NATIVE;
2287 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002288 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002289 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002290 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002291
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002292 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002293 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002294
Peiyong Lindfde5112018-06-05 10:58:41 -07002295 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002296 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002297 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002298 if (isHdr) {
2299 bestDataSpace = hdrDataSpace;
2300 }
2301
Chia-I Wu0d711262018-05-21 15:19:35 -07002302 RenderIntent intent;
2303 switch (mDisplayColorSetting) {
2304 case DisplayColorSetting::MANAGED:
2305 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002306 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002307 break;
2308 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002309 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002310 break;
2311 default: // vendor display color setting
2312 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2313 break;
2314 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002315
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002316 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002317}
2318
Lloyd Pique32cbe282018-10-19 13:09:22 -07002319void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2320 auto display = displayDevice->getCompositionDisplay();
2321 const auto& displayState = display->getState();
2322
2323 bool dirty = !display->getPhysicalSpaceDirtyRegion(false).isEmpty();
2324 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2325 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002326
David Sodmanfa9b2af2017-12-24 13:28:59 -08002327 // If nothing has changed (!dirty), don't recompose.
2328 // If something changed, but we don't currently have any visible layers,
2329 // and didn't when we last did a composition, then skip it this time.
2330 // The second rule does two things:
2331 // - When all layers are removed from a display, we'll emit one black
2332 // frame, then nothing more until we get new layers.
2333 // - When a display is created with a private layer stack, we won't
2334 // emit any black frames until a layer is added to the layer stack.
2335 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002336
Dominik Laskowski075d3172018-05-24 15:50:06 -07002337 const char flagPrefix[] = {'-', '+'};
2338 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002339 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2340 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2341 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2342 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002343
Lloyd Pique31cb2942018-10-19 17:23:03 -07002344 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002345
David Sodmanfa9b2af2017-12-24 13:28:59 -08002346 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002347 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002348 }
2349}
2350
Lloyd Pique32cbe282018-10-19 13:09:22 -07002351void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2352 auto display = displayDevice->getCompositionDisplay();
2353 const auto& displayState = display->getState();
2354
2355 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002356 return;
David Sodman2b406362017-12-15 13:33:47 -08002357 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002358
Lloyd Pique31cb2942018-10-19 17:23:03 -07002359 status_t result = display->getRenderSurface()->prepareFrame(
2360 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002361 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002362 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002363}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002364
Lloyd Pique32cbe282018-10-19 13:09:22 -07002365void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002366 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002367 ALOGV("doComposition");
2368
Lloyd Pique32cbe282018-10-19 13:09:22 -07002369 auto display = displayDevice->getCompositionDisplay();
2370 const auto& displayState = display->getState();
2371
2372 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002373 // transform the dirty region into this screen's coordinate space
Lloyd Pique32cbe282018-10-19 13:09:22 -07002374 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002375
David Sodmanfa9b2af2017-12-24 13:28:59 -08002376 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002377 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002378
Lloyd Pique32cbe282018-10-19 13:09:22 -07002379 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002380 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002381 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002382 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002383}
2384
David Sodmanfa9b2af2017-12-24 13:28:59 -08002385void SurfaceFlinger::postFrame()
2386{
2387 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002388 const auto display = getDefaultDisplayDeviceLocked();
2389 if (display && getHwComposer().isConnected(*display->getId())) {
2390 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002391 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2392 logFrameStats();
2393 }
2394 }
2395}
2396
Lloyd Pique32cbe282018-10-19 13:09:22 -07002397void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002398 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002399 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002400
Lloyd Pique32cbe282018-10-19 13:09:22 -07002401 auto display = displayDevice->getCompositionDisplay();
2402 const auto& displayState = display->getState();
2403 const auto displayId = display->getId();
2404
David Sodmanfa9b2af2017-12-24 13:28:59 -08002405 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002406
Lloyd Pique32cbe282018-10-19 13:09:22 -07002407 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002408 if (displayId) {
2409 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002410 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002411 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002412 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002413 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002414
Chia-I Wu7b549592017-11-15 09:14:57 -08002415 // The layer buffer from the previous frame (if any) is released
2416 // by HWC only when the release fence from this frame (if any) is
2417 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002418 if (displayId && layer->hasHwcLayer(*displayId)) {
2419 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2420 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002421 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002422
2423 // If the layer was client composited in the previous frame, we
2424 // need to merge with the previous client target acquire fence.
2425 // Since we do not track that, always merge with the current
2426 // client target acquire fence when it is available, even though
2427 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002428 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002429 releaseFence =
2430 Fence::merge("LayerRelease", releaseFence,
2431 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002432 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002433
David Sodman15094112018-10-11 09:39:37 -07002434 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002435 }
Chia-I Wu83806892017-11-16 10:50:20 -08002436
2437 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002438 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002439 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002440 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002441 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002442 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002443 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002444 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002445 }
2446 }
2447
Dominik Laskowski075d3172018-05-24 15:50:06 -07002448 if (displayId) {
2449 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002450 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002451 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002452}
2453
Mathias Agopian87baae12012-07-31 12:38:26 -07002454void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002455{
Mathias Agopian841cde52012-03-01 15:44:37 -08002456 ATRACE_CALL();
2457
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002458 // here we keep a copy of the drawing state (that is the state that's
2459 // going to be overwritten by handleTransactionLocked()) outside of
2460 // mStateLock so that the side-effects of the State assignment
2461 // don't happen with mStateLock held (which can cause deadlocks).
2462 State drawingState(mDrawingState);
2463
Mathias Agopianca4d3602011-05-19 15:38:14 -07002464 Mutex::Autolock _l(mStateLock);
2465 const nsecs_t now = systemTime();
2466 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002467
Mathias Agopianca4d3602011-05-19 15:38:14 -07002468 // Here we're guaranteed that some transaction flags are set
2469 // so we can call handleTransactionLocked() unconditionally.
2470 // We call getTransactionFlags(), which will also clear the flags,
2471 // with mStateLock held to guarantee that mCurrentState won't change
2472 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002473
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002474 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002475 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002476 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002477
Mathias Agopianca4d3602011-05-19 15:38:14 -07002478 mLastTransactionTime = systemTime() - now;
2479 mDebugInTransaction = 0;
2480 invalidateHwcGeometry();
2481 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002482}
2483
Lloyd Piqueba04e622017-12-14 17:11:26 -08002484void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2485 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002486 const std::optional<DisplayIdentificationInfo> info =
2487 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002488
Dominik Laskowski075d3172018-05-24 15:50:06 -07002489 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002490 continue;
2491 }
2492
Lloyd Piqueba04e622017-12-14 17:11:26 -08002493 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002494 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002495 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002496 mPhysicalDisplayTokens[info->id] = new BBinder();
2497 DisplayDeviceState state;
2498 state.displayId = info->id;
2499 state.isSecure = true; // All physical displays are currently considered secure.
2500 state.displayName = info->name;
2501 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2502 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002503 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002504 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002505 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002506
Dominik Laskowski075d3172018-05-24 15:50:06 -07002507 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2508 if (index >= 0) {
2509 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2510 mInterceptor->saveDisplayDeletion(state.sequenceId);
2511 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002512 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002513 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002514 }
2515
2516 processDisplayChangesLocked();
2517 }
2518
2519 mPendingHotplugEvents.clear();
2520}
2521
Lloyd Pique99d3da52018-01-22 17:48:03 -08002522sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002523 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002524 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002525 const sp<IGraphicBufferProducer>& producer) {
2526 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002527 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002528 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002529 creationArgs.isSecure = state.isSecure;
2530 creationArgs.displaySurface = dispSurface;
2531 creationArgs.hasWideColorGamut = false;
2532 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002533
Dominik Laskowski075d3172018-05-24 15:50:06 -07002534 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2535 creationArgs.isPrimary = isInternalDisplay;
2536
2537 if (useColorManagement && displayId) {
2538 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002539 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002540 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002541 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002542 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002543
Dominik Laskowski7e045462018-05-30 13:02:02 -07002544 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002545 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002546 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002547 }
tangrobin6753a022018-08-10 10:58:54 +08002548 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002549
Dominik Laskowski075d3172018-05-24 15:50:06 -07002550 if (displayId) {
2551 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002552 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002553 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002554 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002555
Lloyd Pique90c115d2018-09-18 21:39:42 -07002556 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002557 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002558 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002559
Lloyd Pique99d3da52018-01-22 17:48:03 -08002560 // Make sure that composition can never be stalled by a virtual display
2561 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002562 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002563 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002564 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2565 }
2566
Dominik Laskowski075d3172018-05-24 15:50:06 -07002567 creationArgs.displayInstallOrientation =
2568 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002569
Lloyd Pique99d3da52018-01-22 17:48:03 -08002570 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002571 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002572
Lloyd Pique90c115d2018-09-18 21:39:42 -07002573 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002574
2575 if (maxFrameBufferAcquiredBuffers >= 3) {
2576 nativeWindowSurface->preallocateBuffers();
2577 }
2578
2579 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002580 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002581 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002582 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002583 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002584 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002585 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2586 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002587 if (!state.isVirtual()) {
2588 LOG_ALWAYS_FATAL_IF(!displayId);
2589 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002590 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002591
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002592 display->setLayerStack(state.layerStack);
2593 display->setProjection(state.orientation, state.viewport, state.frame);
2594 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002595
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002596 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002597}
2598
Lloyd Pique347200f2017-12-14 17:00:15 -08002599void SurfaceFlinger::processDisplayChangesLocked() {
2600 // here we take advantage of Vector's copy-on-write semantics to
2601 // improve performance by skipping the transaction entirely when
2602 // know that the lists are identical
2603 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2604 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2605 if (!curr.isIdenticalTo(draw)) {
2606 mVisibleRegionsDirty = true;
2607 const size_t cc = curr.size();
2608 size_t dc = draw.size();
2609
2610 // find the displays that were removed
2611 // (ie: in drawing state but not in current state)
2612 // also handle displays that changed
2613 // (ie: displays that are in both lists)
2614 for (size_t i = 0; i < dc;) {
2615 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2616 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002617 // Save display IDs before disconnecting.
2618 const auto internalDisplayId = getInternalDisplayId();
2619 const auto externalDisplayId = getExternalDisplayId();
2620
Lloyd Pique347200f2017-12-14 17:00:15 -08002621 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002622 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002623 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002624 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002625 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002626 if (mUseScheduler) {
2627 mScheduler->hotplugReceived(mAppConnectionHandle,
2628 EventThread::DisplayType::Primary, false);
2629 } else {
2630 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2631 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002632 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002633 if (mUseScheduler) {
2634 mScheduler->hotplugReceived(mAppConnectionHandle,
2635 EventThread::DisplayType::External, false);
2636 } else {
2637 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2638 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002639 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002640 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002641 } else {
2642 // this display is in both lists. see if something changed.
2643 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002644 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002645 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2646 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2647 if (state_binder != draw_binder) {
2648 // changing the surface is like destroying and
2649 // recreating the DisplayDevice, so we just remove it
2650 // from the drawing state, so that it get re-added
2651 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002652 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002653 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002654 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002655 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002656 mDrawingState.displays.removeItemsAt(i);
2657 dc--;
2658 // at this point we must loop to the next item
2659 continue;
2660 }
2661
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002662 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002663 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002664 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002665 }
2666 if ((state.orientation != draw[i].orientation) ||
2667 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002668 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002669 }
2670 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002671 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002672 }
2673 }
2674 }
2675 ++i;
2676 }
2677
2678 // find displays that were added
2679 // (ie: in current state but not in drawing state)
2680 for (size_t i = 0; i < cc; i++) {
2681 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2682 const DisplayDeviceState& state(curr[i]);
2683
Lloyd Pique542307f2018-10-19 13:24:08 -07002684 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002685 sp<IGraphicBufferProducer> producer;
2686 sp<IGraphicBufferProducer> bqProducer;
2687 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002688 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002689
Dominik Laskowski075d3172018-05-24 15:50:06 -07002690 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002691 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002692 // Virtual displays without a surface are dormant:
2693 // they have external state (layer stack, projection,
2694 // etc.) but no internal state (i.e. a DisplayDevice).
2695 if (state.surface != nullptr) {
2696 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002697 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002698 int width = 0;
2699 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2700 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2701 int height = 0;
2702 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2703 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2704 int intFormat = 0;
2705 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2706 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002707 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002708
Dominik Laskowski075d3172018-05-24 15:50:06 -07002709 displayId =
2710 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002711 }
2712
2713 // TODO: Plumb requested format back up to consumer
2714
2715 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002716 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002717 bqProducer, bqConsumer,
2718 state.displayName);
2719
2720 dispSurface = vds;
2721 producer = vds;
2722 }
2723 } else {
2724 ALOGE_IF(state.surface != nullptr,
2725 "adding a supported display, but rendering "
2726 "surface is provided (%p), ignoring it",
2727 state.surface.get());
2728
Dominik Laskowski075d3172018-05-24 15:50:06 -07002729 displayId = state.displayId;
2730 LOG_ALWAYS_FATAL_IF(!displayId);
2731 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002732 producer = bqProducer;
2733 }
2734
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002735 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002736 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002737 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002738 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002739 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002740 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002741 LOG_ALWAYS_FATAL_IF(!displayId);
2742
2743 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002744 if (mUseScheduler) {
2745 mScheduler->hotplugReceived(mAppConnectionHandle,
2746 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002747 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002748 } else {
2749 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2750 true);
2751 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002752 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002753 if (mUseScheduler) {
2754 mScheduler->hotplugReceived(mAppConnectionHandle,
2755 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002756 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002757 } else {
2758 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2759 true);
2760 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002761 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002762 }
2763 }
2764 }
2765 }
2766 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002767
2768 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002769}
2770
Mathias Agopian87baae12012-07-31 12:38:26 -07002771void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002772{
Dan Stoza7dde5992015-05-22 09:51:44 -07002773 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002774 mCurrentState.traverseInZOrder([](Layer* layer) {
2775 layer->notifyAvailableFrames();
2776 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002777
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002778 /*
2779 * Traversal of the children
2780 * (perform the transaction for each of them if needed)
2781 */
2782
Robert Carr720e5062018-07-30 17:45:14 -07002783 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002784 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002785 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002786 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002787 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002788
2789 const uint32_t flags = layer->doTransaction(0);
2790 if (flags & Layer::eVisibleRegion)
2791 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002792
2793 if (flags & Layer::eInputInfoChanged) {
2794 inputChanged = true;
2795 }
Robert Carr2047fae2016-11-28 14:09:09 -08002796 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002797 }
2798
2799 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002800 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002801 */
2802
Mathias Agopiane57f2922012-08-09 16:29:12 -07002803 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002804 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002805 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002806 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002807
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002808 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002809 // The transform hint might have changed for some layers
2810 // (either because a display has changed, or because a layer
2811 // as changed).
2812 //
2813 // Walk through all the layers in currentLayers,
2814 // and update their transform hint.
2815 //
2816 // If a layer is visible only on a single display, then that
2817 // display is used to calculate the hint, otherwise we use the
2818 // default display.
2819 //
2820 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2821 // the hint is set before we acquire a buffer from the surface texture.
2822 //
2823 // NOTE: layer transactions have taken place already, so we use their
2824 // drawing state. However, SurfaceFlinger's own transaction has not
2825 // happened yet, so we must use the current state layer list
2826 // (soon to become the drawing state list).
2827 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002828 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002829 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002830 bool first = true;
2831 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002832 // NOTE: we rely on the fact that layers are sorted by
2833 // layerStack first (so we don't have to traverse the list
2834 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002835 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002836 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002837 currentlayerStack = layerStack;
2838 // figure out if this layerstack is mirrored
2839 // (more than one display) if so, pick the default display,
2840 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002841 hintDisplay = nullptr;
2842 for (const auto& [token, display] : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002843 if (display->getCompositionDisplay()->belongsInOutput(layer->getLayerStack())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002844 if (hintDisplay) {
2845 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002846 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002847 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002848 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002849 }
2850 }
2851 }
2852 }
Chet Haase91d25932013-04-11 15:24:55 -07002853
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002854 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002855 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2856 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002857
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002858 // could be null when this layer is using a layerStack
2859 // that is not visible on any display. Also can occur at
2860 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002861 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002862 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002863
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002864 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002865 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002866 if (hintDisplay) {
2867 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002868 }
Robert Carr2047fae2016-11-28 14:09:09 -08002869
2870 first = false;
2871 });
Mathias Agopian84300952012-11-21 16:02:13 -08002872 }
2873
2874
Mathias Agopian3559b072012-08-15 13:46:03 -07002875 /*
2876 * Perform our own transaction if needed
2877 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002878
2879 if (mLayersAdded) {
2880 mLayersAdded = false;
2881 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002882 mVisibleRegionsDirty = true;
2883 }
2884
2885 // some layers might have been removed, so
2886 // we need to update the regions they're exposing.
2887 if (mLayersRemoved) {
2888 mLayersRemoved = false;
2889 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002890 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002891 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002892 // this layer is not visible anymore
2893 // TODO: we could traverse the tree from front to back and
2894 // compute the actual visible region
2895 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002896 Region visibleReg;
2897 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002898 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002899 }
Robert Carr2047fae2016-11-28 14:09:09 -08002900 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002901 }
2902
2903 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002904
Vishnu Nairde19f852018-12-18 16:11:53 -08002905 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002906 updateInputWindows();
2907 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002908 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002909
Riley Andrews03414a12014-07-01 14:22:59 -07002910 updateCursorAsync();
2911}
2912
Robert Carr720e5062018-07-30 17:45:14 -07002913void SurfaceFlinger::updateInputWindows() {
2914 ATRACE_CALL();
2915
Vishnu Nairde19f852018-12-18 16:11:53 -08002916 if (mInputFlinger == nullptr) {
2917 return;
2918 }
2919
Robert Carr720e5062018-07-30 17:45:14 -07002920 Vector<InputWindowInfo> inputHandles;
2921
2922 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2923 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002924 // When calculating the screen bounds we ignore the transparent region since it may
2925 // result in an unwanted offset.
2926 inputHandles.add(layer->fillInputInfo(
2927 layer->computeScreenBounds(false /* reduceTransparentRegion */)));
Robert Carr720e5062018-07-30 17:45:14 -07002928 }
2929 });
2930 mInputFlinger->setInputWindows(inputHandles);
2931}
2932
chaviwfbe5d9c2018-12-26 12:23:37 -08002933void SurfaceFlinger::executeInputWindowCommands() {
2934 if (!mInputFlinger) {
2935 return;
2936 }
2937
2938 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2939 if (transferTouchFocusCommand.fromToken != nullptr &&
2940 transferTouchFocusCommand.toToken != nullptr &&
2941 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2942 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2943 transferTouchFocusCommand.toToken);
2944 }
2945 }
2946
2947 mInputWindowCommands.clear();
2948}
2949
Riley Andrews03414a12014-07-01 14:22:59 -07002950void SurfaceFlinger::updateCursorAsync()
2951{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002952 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002953 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002954 continue;
2955 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002956
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002957 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2958 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002959 }
2960 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002961}
2962
chaviw61626f22018-11-15 16:26:27 -08002963void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2964 if (layer->hasReadyFrame()) {
2965 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2966 if (layer->shouldPresentNow(expectedPresentTime)) {
2967 bool ignored = false;
2968 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
2969 }
2970 }
2971 layer->releasePendingBuffer(systemTime());
2972}
2973
Mathias Agopian4fec8732012-06-29 14:12:52 -07002974void SurfaceFlinger::commitTransaction()
2975{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002976 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002977 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002978 for (const auto& l : mLayersPendingRemoval) {
2979 recordBufferingStats(l->getName().string(),
2980 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002981
2982 // We need to release the HWC layers when the Layer is removed
2983 // from the current state otherwise the HWC layer just continues
2984 // showing at its last configured state until we eventually
2985 // abandon the buffer queue.
2986 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08002987 l->destroyHwcLayersForAllDisplays();
2988 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07002989 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002990 }
2991 mLayersPendingRemoval.clear();
2992 }
2993
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002994 // If this transaction is part of a window animation then the next frame
2995 // we composite should be considered an animation as well.
2996 mAnimCompositionPending = mAnimTransactionPending;
2997
Mathias Agopian4fec8732012-06-29 14:12:52 -07002998 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002999 // clear the "changed" flags in current state
3000 mCurrentState.colorMatrixChanged = false;
3001
Robert Carr1f0a16a2016-10-24 16:27:39 -07003002 mDrawingState.traverseInZOrder([](Layer* layer) {
3003 layer->commitChildList();
3004 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003005 mTransactionPending = false;
3006 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003007 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003008}
3009
Lloyd Pique32cbe282018-10-19 13:09:22 -07003010void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003011 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003012 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003013 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003014
Lloyd Pique32cbe282018-10-19 13:09:22 -07003015 auto display = displayDevice->getCompositionDisplay();
3016
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003017 Region aboveOpaqueLayers;
3018 Region aboveCoveredLayers;
3019 Region dirty;
3020
Mathias Agopian87baae12012-07-31 12:38:26 -07003021 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003022
Robert Carr2047fae2016-11-28 14:09:09 -08003023 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003024 // start with the whole surface at its current location
3025 const Layer::State& s(layer->getDrawingState());
3026
Jesse Hall01e29052013-02-19 16:13:35 -08003027 // only consider the layers on the given layer stack
Lloyd Pique32cbe282018-10-19 13:09:22 -07003028 if (!display->belongsInOutput(layer->getLayerStack())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003029 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003030 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003031
Mathias Agopianab028732010-03-16 16:41:46 -07003032 /*
3033 * opaqueRegion: area of a surface that is fully opaque.
3034 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003035 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003036
3037 /*
3038 * visibleRegion: area of a surface that is visible on screen
3039 * and not fully transparent. This is essentially the layer's
3040 * footprint minus the opaque regions above it.
3041 * Areas covered by a translucent surface are considered visible.
3042 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003043 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003044
3045 /*
3046 * coveredRegion: area of a surface that is covered by all
3047 * visible regions above it (which includes the translucent areas).
3048 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003049 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003050
Jesse Halla8026d22012-09-25 13:25:04 -07003051 /*
3052 * transparentRegion: area of a surface that is hinted to be completely
3053 * transparent. This is only used to tell when the layer has no visible
3054 * non-transparent regions and can be removed from the layer list. It
3055 * does not affect the visibleRegion of this layer or any layers
3056 * beneath it. The hint may not be correct if apps don't respect the
3057 * SurfaceView restrictions (which, sadly, some don't).
3058 */
3059 Region transparentRegion;
3060
Mathias Agopianab028732010-03-16 16:41:46 -07003061
3062 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003063 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003064 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003065 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003066
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003067 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003068 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003069 if (!visibleRegion.isEmpty()) {
3070 // Remove the transparent area from the visible region
3071 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003072 if (tr.preserveRects()) {
3073 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003074 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003075 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003076 // transformation too complex, can't do the
3077 // transparent region optimization.
3078 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003079 }
Mathias Agopianab028732010-03-16 16:41:46 -07003080 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003081
Mathias Agopianab028732010-03-16 16:41:46 -07003082 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003083 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003084 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003085 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003086 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003087 // the opaque region is the layer's footprint
3088 opaqueRegion = visibleRegion;
3089 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003090 }
3091 }
3092
Robert Carre5f4f692018-01-12 13:12:28 -08003093 if (visibleRegion.isEmpty()) {
3094 layer->clearVisibilityRegions();
3095 return;
3096 }
3097
Mathias Agopianab028732010-03-16 16:41:46 -07003098 // Clip the covered region to the visible region
3099 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3100
3101 // Update aboveCoveredLayers for next (lower) layer
3102 aboveCoveredLayers.orSelf(visibleRegion);
3103
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003104 // subtract the opaque region covered by the layers above us
3105 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003106
3107 // compute this layer's dirty region
3108 if (layer->contentDirty) {
3109 // we need to invalidate the whole region
3110 dirty = visibleRegion;
3111 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003112 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003113 layer->contentDirty = false;
3114 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003115 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003116 * the exposed region consists of two components:
3117 * 1) what's VISIBLE now and was COVERED before
3118 * 2) what's EXPOSED now less what was EXPOSED before
3119 *
3120 * note that (1) is conservative, we start with the whole
3121 * visible region but only keep what used to be covered by
3122 * something -- which mean it may have been exposed.
3123 *
3124 * (2) handles areas that were not covered by anything but got
3125 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003126 */
Mathias Agopianab028732010-03-16 16:41:46 -07003127 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003128 const Region oldVisibleRegion = layer->visibleRegion;
3129 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003130 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3131 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003132 }
3133 dirty.subtractSelf(aboveOpaqueLayers);
3134
3135 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003136 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003137
Mathias Agopianab028732010-03-16 16:41:46 -07003138 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003139 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003140
Jesse Halla8026d22012-09-25 13:25:04 -07003141 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003142 layer->setVisibleRegion(visibleRegion);
3143 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003144 layer->setVisibleNonTransparentRegion(
3145 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003146 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003147
Mathias Agopian87baae12012-07-31 12:38:26 -07003148 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003149}
3150
Chia-I Wuab0c3192017-08-01 11:29:00 -07003151void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003152 for (const auto& [token, displayDevice] : mDisplays) {
3153 auto display = displayDevice->getCompositionDisplay();
3154 if (display->belongsInOutput(layer->getLayerStack())) {
3155 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003156 }
3157 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003158}
3159
Dan Stoza6b9454d2014-11-07 16:00:59 -08003160bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003161{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003162 ALOGV("handlePageFlip");
3163
Brian Andersond6927fb2016-07-23 23:37:30 -07003164 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003165
Mathias Agopian4fec8732012-06-29 14:12:52 -07003166 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003167 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003168 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003169
3170 // Store the set of layers that need updates. This set must not change as
3171 // buffers are being latched, as this could result in a deadlock.
3172 // Example: Two producers share the same command stream and:
3173 // 1.) Layer 0 is latched
3174 // 2.) Layer 0 gets a new frame
3175 // 2.) Layer 1 gets a new frame
3176 // 3.) Layer 1 is latched.
3177 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3178 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003179 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003180 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003181 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003182 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3183 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003184 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003185 } else {
3186 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003187 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003188 } else {
3189 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003190 }
Robert Carr2047fae2016-11-28 14:09:09 -08003191 });
3192
Lloyd Piquef2c79392018-12-20 16:23:33 -08003193 if (!mLayersWithQueuedFrames.empty()) {
3194 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3195 // writes to Layer current state. See also b/119481871
3196 Mutex::Autolock lock(mStateLock);
3197
3198 for (auto& layer : mLayersWithQueuedFrames) {
3199 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3200 layer->useSurfaceDamage();
3201 invalidateLayerStack(layer, dirty);
3202 if (layer->isBufferLatched()) {
3203 newDataLatched = true;
3204 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003205 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003206 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003207
Alec Mouri86770e52018-09-24 22:40:58 +00003208 // Clear the renderengine fence here...
3209 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3210 // clear instead of sp::clear.
3211 getBE().flushFence = Fence::NO_FENCE;
3212
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003213 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003214
Vishnu Nairde19f852018-12-18 16:11:53 -08003215 if (visibleRegions) {
3216 // Update input window info if the layer receives its first buffer.
3217 updateInputWindows();
3218 }
3219
Dan Stoza6b9454d2014-11-07 16:00:59 -08003220 // If we will need to wake up at some time in the future to deal with a
3221 // queued frame that shouldn't be displayed during this vsync period, wake
3222 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003223 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003224 signalLayerUpdate();
3225 }
3226
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003227 // enter boot animation on first buffer latch
3228 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3229 ALOGI("Enter boot animation");
3230 mBootStage = BootStage::BOOTANIMATION;
3231 }
3232
Dan Stoza6b9454d2014-11-07 16:00:59 -08003233 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003234 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003235}
3236
Mathias Agopianad456f92011-01-13 17:53:01 -08003237void SurfaceFlinger::invalidateHwcGeometry()
3238{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003239 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003240}
3241
Lloyd Pique32cbe282018-10-19 13:09:22 -07003242void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003243 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003244 auto display = displayDevice->getCompositionDisplay();
3245
Dan Stoza71433162014-02-04 16:22:36 -08003246 // We only need to actually compose the display if:
3247 // 1) It is being handled by hardware composer, which may need this to
3248 // keep its virtual display state machine in sync, or
3249 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003250 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003251 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003252 return;
3253 }
3254
Dan Stoza9e56aa02015-11-02 13:00:03 -08003255 ALOGV("doDisplayComposition");
Lloyd Pique32cbe282018-10-19 13:09:22 -07003256 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003257
3258 // swap buffers (presentation)
Lloyd Pique31cb2942018-10-19 17:23:03 -07003259 display->getRenderSurface()->queueBuffer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003260}
3261
Lloyd Pique32cbe282018-10-19 13:09:22 -07003262bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003263 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003264
Lloyd Pique32cbe282018-10-19 13:09:22 -07003265 auto display = displayDevice->getCompositionDisplay();
3266 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003267 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003268
3269 const Region bounds(displayState.bounds);
3270 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003271 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003272 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003273
Peiyong Lind3788632018-09-18 16:01:31 -07003274 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003275 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003276
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003277 // Framebuffer will live in this scope for GPU composition.
3278 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
3279
Dan Stoza9e56aa02015-11-02 13:00:03 -08003280 if (hasClientComposition) {
3281 ALOGV("hasClientComposition");
3282
Lloyd Pique31cb2942018-10-19 17:23:03 -07003283 sp<GraphicBuffer> buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003284
3285 if (buf == nullptr) {
3286 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3287 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003288 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003289 return false;
3290 }
3291
3292 // Bind the framebuffer in this scope.
3293 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3294 buf->getNativeBuffer());
3295
3296 if (fbo->getStatus() != NO_ERROR) {
3297 ALOGW("Binding buffer for display [%s] failed with status: %d",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003298 displayDevice->getDisplayName().c_str(), fbo->getStatus());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003299 return false;
3300 }
3301
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003302 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003303 if (displayDevice->hasWideColorGamut()) {
3304 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003305 }
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003306 getRenderEngine().setOutputDataSpace(outputDataspace);
3307 getRenderEngine().setDisplayMaxLuminance(
Lloyd Pique32cbe282018-10-19 13:09:22 -07003308 displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003309
Lloyd Pique441d5042018-10-18 16:49:51 -07003310 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003311 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003312 getHwComposer()
3313 .hasDisplayCapability(displayId,
3314 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003315
Peiyong Lind3788632018-09-18 16:01:31 -07003316 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003317 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3318 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003319 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003320 }
3321
Lloyd Pique31cb2942018-10-19 17:23:03 -07003322 display->getRenderSurface()->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003323
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003324 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003325 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003326 // when using overlays, we assume a fully transparent framebuffer
3327 // NOTE: we could reduce how much we need to clear, for instance
3328 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003329 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003330 // We'll revisit later if needed.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003331 getRenderEngine().clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003332 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003333 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003334 // we're left with the letterbox region
3335 // (common case is that letterbox ends-up being empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003336 const Region letterbox = bounds.subtract(displayState.scissor);
Mathias Agopian766dc492012-10-30 18:08:06 -07003337
3338 // compute the area to clear
Lloyd Pique32cbe282018-10-19 13:09:22 -07003339 const Region region = displayState.undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003340
Mathias Agopianb9494d52012-04-18 02:28:45 -07003341 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003342 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003343 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003344 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003345 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003346 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003347
Lloyd Pique32cbe282018-10-19 13:09:22 -07003348 const Rect& bounds = displayState.bounds;
3349 const Rect& scissor = displayState.scissor;
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003350 if (scissor != bounds) {
3351 // scissor doesn't match the screen's dimensions, so we
3352 // need to clear everything outside of it and enable
3353 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003354
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003355 // enable scissor for this frame
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003356 getRenderEngine().setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003357 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003358 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003359
Mathias Agopian85d751c2012-08-29 16:59:24 -07003360 /*
3361 * and then, render the layers targeted at the framebuffer
3362 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003363
Dan Stoza9e56aa02015-11-02 13:00:03 -08003364 ALOGV("Rendering client layers");
Lloyd Pique32cbe282018-10-19 13:09:22 -07003365 const ui::Transform& displayTransform = displayState.transform;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003366 bool firstLayer = true;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003367 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003368 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003369 displayTransform.transform(layer->visibleRegion)));
3370 ALOGV("Layer: %s", layer->getName().string());
3371 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003372 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003373 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003374 case HWC2::Composition::Cursor:
3375 case HWC2::Composition::Device:
3376 case HWC2::Composition::Sideband:
3377 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003378 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003379 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003380 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003381 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003382 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003383 // never clear the very first layer since we're
3384 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003385 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003386 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003387 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003388 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003389 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003390 if (layer->hasColorTransform()) {
3391 mat4 tmpMatrix;
3392 if (applyColorMatrix) {
3393 tmpMatrix = mDrawingState.colorMatrix;
3394 }
3395 tmpMatrix *= layer->getColorTransform();
Peiyong Lind3788632018-09-18 16:01:31 -07003396 getRenderEngine().setColorTransform(tmpMatrix);
3397 } else {
3398 getRenderEngine().setColorTransform(colorMatrix);
3399 }
David Sodmanc1498e62018-09-12 14:36:26 -07003400 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003401 break;
3402 }
3403 default:
3404 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003405 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003406 } else {
3407 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003408 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003409 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003410 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003411
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003412 // Perform some cleanup steps if we used client composition.
3413 if (hasClientComposition) {
3414 getRenderEngine().setColorTransform(mat4());
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003415 getRenderEngine().disableScissor();
Lloyd Pique31cb2942018-10-19 17:23:03 -07003416 display->getRenderSurface()->finishBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003417 // Clear out error flags here so that we don't wait until next
3418 // composition to log.
3419 getRenderEngine().checkErrors();
3420 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003421 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003422}
3423
Chia-I Wu28e3a252018-09-07 12:05:02 -07003424void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003425 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003426 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003427}
3428
Dan Stoza7d89d062015-04-30 13:29:25 -07003429status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003430 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003431 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003432 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003433 const sp<Layer>& parent,
3434 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003435{
Dan Stoza7d89d062015-04-30 13:29:25 -07003436 // add this layer to the current state list
3437 {
3438 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003439 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003440 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3441 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003442 return NO_MEMORY;
3443 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003444 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003445 mCurrentState.layersSortedByZ.add(lbc);
Robert Carrb89ea9d2018-12-10 13:01:14 -08003446 } else if (parent == nullptr || parent->isRemovedFromCurrentState()) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003447 ALOGE("addClientLayer called with a removed parent");
chaviw61626f22018-11-15 16:26:27 -08003448 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003449 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003450 parent->addChild(lbc);
3451 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003452
Yiwei Zhang243b3782018-05-15 17:40:04 -07003453 if (gbc != nullptr) {
3454 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3455 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3456 mMaxGraphicBufferProducerListSize,
3457 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3458 mGraphicBufferProducerList.size(),
3459 mMaxGraphicBufferProducerListSize, mNumLayers);
3460 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003461 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003462 }
3463
Mathias Agopian96f08192010-06-02 23:28:45 -07003464 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003465 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003466
Dan Stoza7d89d062015-04-30 13:29:25 -07003467 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003468}
3469
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003470uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003471 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003472}
3473
Mathias Agopian3f844832013-08-07 21:24:32 -07003474uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003475 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003476}
3477
Mathias Agopian3f844832013-08-07 21:24:32 -07003478uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003479 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003480}
3481
3482uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003483 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003484 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003485 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003486 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003487 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003488 }
3489 return old;
3490}
3491
Marissa Wall713b63f2018-10-17 15:42:43 -07003492bool SurfaceFlinger::flushTransactionQueues() {
3493 Mutex::Autolock _l(mStateLock);
3494 auto it = mTransactionQueues.begin();
3495 while (it != mTransactionQueues.end()) {
3496 auto& [applyToken, transactionQueue] = *it;
3497
3498 while (!transactionQueue.empty()) {
3499 const auto& [states, displays, flags] = transactionQueue.front();
3500 if (composerStateContainsUnsignaledFences(states)) {
3501 break;
3502 }
chaviw273171b2018-12-26 11:46:30 -08003503 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003504 transactionQueue.pop();
3505 }
3506
3507 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3508 }
3509 return mTransactionQueues.empty();
3510}
3511
chaviwca27f252018-02-06 16:46:39 -08003512bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3513 for (const ComposerState& state : states) {
3514 // Here we need to check that the interface we're given is indeed
3515 // one of our own. A malicious client could give us a nullptr
3516 // IInterface, or one of its own or even one of our own but a
3517 // different type. All these situations would cause us to crash.
3518 if (state.client == nullptr) {
3519 return true;
3520 }
3521
3522 sp<IBinder> binder = IInterface::asBinder(state.client);
3523 if (binder == nullptr) {
3524 return true;
3525 }
3526
3527 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3528 return true;
3529 }
3530 }
3531 return false;
3532}
3533
Marissa Wall713b63f2018-10-17 15:42:43 -07003534bool SurfaceFlinger::composerStateContainsUnsignaledFences(const Vector<ComposerState>& states) {
3535 for (const ComposerState& state : states) {
3536 const layer_state_t& s = state.state;
3537 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3538 continue;
3539 }
3540 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
3541 return true;
3542 }
3543 }
3544 return false;
3545}
3546
3547void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3548 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003549 const sp<IBinder>& applyToken,
3550 const InputWindowCommands& inputWindowCommands) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003551 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003552 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003553
chaviwca27f252018-02-06 16:46:39 -08003554 if (containsAnyInvalidClientState(states)) {
3555 return;
3556 }
3557
Marissa Wall713b63f2018-10-17 15:42:43 -07003558 // If its TransactionQueue already has a pending TransactionState or if it is pending
3559 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
3560 composerStateContainsUnsignaledFences(states)) {
3561 mTransactionQueues[applyToken].emplace(states, displays, flags);
3562 setTransactionFlags(eTransactionNeeded);
3563 return;
3564 }
3565
chaviw273171b2018-12-26 11:46:30 -08003566 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003567}
3568
3569void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003570 const Vector<DisplayState>& displays, uint32_t flags,
3571 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003572 uint32_t transactionFlags = 0;
3573
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003574 if (flags & eAnimation) {
3575 // For window updates that are part of an animation we must wait for
3576 // previous animation "frames" to be handled.
3577 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003578 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003579 if (CC_UNLIKELY(err != NO_ERROR)) {
3580 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003581 // caller after a few seconds.
3582 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3583 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003584 mAnimTransactionPending = false;
3585 break;
3586 }
3587 }
3588 }
3589
chaviwca27f252018-02-06 16:46:39 -08003590 for (const DisplayState& display : displays) {
3591 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003592 }
3593
Marissa Walle2ffb422018-10-12 11:33:52 -07003594 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003595 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003596 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003597 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003598 // If the state doesn't require a traversal and there are callbacks, send them now
3599 if (!(clientStateFlags & eTraversalNeeded)) {
3600 mTransactionCompletedThread.sendCallbacks();
3601 }
3602 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003603
chaviw273171b2018-12-26 11:46:30 -08003604 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3605
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003606 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3607 // anyway. This can be used as a flush mechanism for previous async transactions.
3608 // Empty animation transaction can be used to simulate back-pressure, so also force a
3609 // transaction for empty animation transactions.
3610 if (transactionFlags == 0 &&
3611 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003612 transactionFlags = eTransactionNeeded;
3613 }
3614
Mathias Agopian386aa982011-11-07 21:58:03 -08003615 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003616 if (mInterceptor->isEnabled()) {
3617 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003618 }
Irvel468051e2016-06-13 16:44:44 -07003619
Mathias Agopian386aa982011-11-07 21:58:03 -08003620 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003621 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3622 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003623 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003624
3625 // if this is a synchronous transaction, wait for it to take effect
3626 // before returning.
3627 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003628 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003629 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003630 if (flags & eAnimation) {
3631 mAnimTransactionPending = true;
3632 }
3633 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003634 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3635 if (CC_UNLIKELY(err != NO_ERROR)) {
3636 // just in case something goes wrong in SF, return to the
3637 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003638 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3639 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003640 break;
3641 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003642 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003643 }
3644}
3645
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003646uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3647 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3648 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003649
Mathias Agopiane57f2922012-08-09 16:29:12 -07003650 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003651 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3652
3653 const uint32_t what = s.what;
3654 if (what & DisplayState::eSurfaceChanged) {
3655 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3656 state.surface = s.surface;
3657 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003658 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003659 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003660 if (what & DisplayState::eLayerStackChanged) {
3661 if (state.layerStack != s.layerStack) {
3662 state.layerStack = s.layerStack;
3663 flags |= eDisplayTransactionNeeded;
3664 }
3665 }
3666 if (what & DisplayState::eDisplayProjectionChanged) {
3667 if (state.orientation != s.orientation) {
3668 state.orientation = s.orientation;
3669 flags |= eDisplayTransactionNeeded;
3670 }
3671 if (state.frame != s.frame) {
3672 state.frame = s.frame;
3673 flags |= eDisplayTransactionNeeded;
3674 }
3675 if (state.viewport != s.viewport) {
3676 state.viewport = s.viewport;
3677 flags |= eDisplayTransactionNeeded;
3678 }
3679 }
3680 if (what & DisplayState::eDisplaySizeChanged) {
3681 if (state.width != s.width) {
3682 state.width = s.width;
3683 flags |= eDisplayTransactionNeeded;
3684 }
3685 if (state.height != s.height) {
3686 state.height = s.height;
3687 flags |= eDisplayTransactionNeeded;
3688 }
3689 }
3690
Mathias Agopiane57f2922012-08-09 16:29:12 -07003691 return flags;
3692}
3693
Robert Carrd4ae7f32018-06-07 16:10:57 -07003694bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3695 IPCThreadState* ipc = IPCThreadState::self();
3696 const int pid = ipc->getCallingPid();
3697 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003698 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003699 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003700 return false;
3701 }
3702 return true;
3703}
3704
chaviwca27f252018-02-06 16:46:39 -08003705uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3706 const layer_state_t& s = composerState.state;
3707 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3708
Mathias Agopian13127d82013-03-05 17:47:11 -08003709 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003710 if (layer == nullptr) {
3711 return 0;
3712 }
3713
chaviw8b3871a2017-11-01 17:41:01 -07003714 uint32_t flags = 0;
3715
Garfield Tan8a3083e2018-12-03 13:21:07 -08003716 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003717 bool geometryAppliesWithResize =
3718 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003719
3720 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3721 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003722 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003723 layer->pushPendingState();
3724 }
3725
chaviw8b3871a2017-11-01 17:41:01 -07003726 if (what & layer_state_t::ePositionChanged) {
3727 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3728 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003729 }
chaviw8b3871a2017-11-01 17:41:01 -07003730 }
3731 if (what & layer_state_t::eLayerChanged) {
3732 // NOTE: index needs to be calculated before we update the state
3733 const auto& p = layer->getParent();
3734 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003735 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003736 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003737 mCurrentState.layersSortedByZ.removeAt(idx);
3738 mCurrentState.layersSortedByZ.add(layer);
3739 // we need traversal (state changed)
3740 // AND transaction (list changed)
3741 flags |= eTransactionNeeded|eTraversalNeeded;
3742 }
chaviw8b3871a2017-11-01 17:41:01 -07003743 } else {
3744 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003745 flags |= eTransactionNeeded|eTraversalNeeded;
3746 }
3747 }
chaviw8b3871a2017-11-01 17:41:01 -07003748 }
3749 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003750 // NOTE: index needs to be calculated before we update the state
3751 const auto& p = layer->getParent();
3752 if (p == nullptr) {
3753 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3754 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3755 mCurrentState.layersSortedByZ.removeAt(idx);
3756 mCurrentState.layersSortedByZ.add(layer);
3757 // we need traversal (state changed)
3758 // AND transaction (list changed)
3759 flags |= eTransactionNeeded|eTraversalNeeded;
3760 }
3761 } else {
3762 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3763 flags |= eTransactionNeeded|eTraversalNeeded;
3764 }
chaviw8b3871a2017-11-01 17:41:01 -07003765 }
3766 }
3767 if (what & layer_state_t::eSizeChanged) {
3768 if (layer->setSize(s.w, s.h)) {
3769 flags |= eTraversalNeeded;
3770 }
3771 }
3772 if (what & layer_state_t::eAlphaChanged) {
3773 if (layer->setAlpha(s.alpha))
3774 flags |= eTraversalNeeded;
3775 }
3776 if (what & layer_state_t::eColorChanged) {
3777 if (layer->setColor(s.color))
3778 flags |= eTraversalNeeded;
3779 }
Peiyong Lind3788632018-09-18 16:01:31 -07003780 if (what & layer_state_t::eColorTransformChanged) {
3781 if (layer->setColorTransform(s.colorTransform)) {
3782 flags |= eTraversalNeeded;
3783 }
3784 }
chaviw8b3871a2017-11-01 17:41:01 -07003785 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003786 // TODO: b/109894387
3787 //
3788 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3789 // rotation. To see the problem observe that if we have a square parent, and a child
3790 // of the same size, then we rotate the child 45 degrees around it's center, the child
3791 // must now be cropped to a non rectangular 8 sided region.
3792 //
3793 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3794 // private API, and the WindowManager only uses rotation in one case, which is on a top
3795 // level layer in which cropping is not an issue.
3796 //
3797 // However given that abuse of rotation matrices could lead to surfaces extending outside
3798 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3799 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3800 // transformations.
3801 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003802 flags |= eTraversalNeeded;
3803 }
3804 if (what & layer_state_t::eTransparentRegionChanged) {
3805 if (layer->setTransparentRegionHint(s.transparentRegion))
3806 flags |= eTraversalNeeded;
3807 }
3808 if (what & layer_state_t::eFlagsChanged) {
3809 if (layer->setFlags(s.flags, s.mask))
3810 flags |= eTraversalNeeded;
3811 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003812 if (what & layer_state_t::eCropChanged_legacy) {
3813 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003814 flags |= eTraversalNeeded;
3815 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003816 if (what & layer_state_t::eCornerRadiusChanged) {
3817 if (layer->setCornerRadius(s.cornerRadius))
3818 flags |= eTraversalNeeded;
3819 }
chaviw8b3871a2017-11-01 17:41:01 -07003820 if (what & layer_state_t::eLayerStackChanged) {
3821 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3822 // We only allow setting layer stacks for top level layers,
3823 // everything else inherits layer stack from its parent.
3824 if (layer->hasParent()) {
3825 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3826 layer->getName().string());
3827 } else if (idx < 0) {
3828 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3829 "that also does not appear in the top level layer list. Something"
3830 " has gone wrong.", layer->getName().string());
3831 } else if (layer->setLayerStack(s.layerStack)) {
3832 mCurrentState.layersSortedByZ.removeAt(idx);
3833 mCurrentState.layersSortedByZ.add(layer);
3834 // we need traversal (state changed)
3835 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003836 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003837 }
3838 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003839 if (what & layer_state_t::eDeferTransaction_legacy) {
3840 if (s.barrierHandle_legacy != nullptr) {
3841 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3842 } else if (s.barrierGbp_legacy != nullptr) {
3843 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003844 if (authenticateSurfaceTextureLocked(gbp)) {
3845 const auto& otherLayer =
3846 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003847 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003848 } else {
3849 ALOGE("Attempt to defer transaction to to an"
3850 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003851 }
3852 }
chaviw8b3871a2017-11-01 17:41:01 -07003853 // We don't trigger a traversal here because if no other state is
3854 // changed, we don't want this to cause any more work
3855 }
3856 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003857 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003858 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003859 if (!hadParent) {
3860 mCurrentState.layersSortedByZ.remove(layer);
3861 }
chaviw8b3871a2017-11-01 17:41:01 -07003862 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003863 }
chaviw8b3871a2017-11-01 17:41:01 -07003864 }
3865 if (what & layer_state_t::eReparentChildren) {
3866 if (layer->reparentChildren(s.reparentHandle)) {
3867 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003868 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003869 }
chaviw8b3871a2017-11-01 17:41:01 -07003870 if (what & layer_state_t::eDetachChildren) {
3871 layer->detachChildren();
3872 }
3873 if (what & layer_state_t::eOverrideScalingModeChanged) {
3874 layer->setOverrideScalingMode(s.overrideScalingMode);
3875 // We don't trigger a traversal here because if no other state is
3876 // changed, we don't want this to cause any more work
3877 }
Marissa Wall61c58622018-07-18 10:12:20 -07003878 if (what & layer_state_t::eTransformChanged) {
3879 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3880 }
3881 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3882 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3883 flags |= eTraversalNeeded;
3884 }
3885 if (what & layer_state_t::eCropChanged) {
3886 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3887 }
Marissa Wall861616d2018-10-22 12:52:23 -07003888 if (what & layer_state_t::eFrameChanged) {
3889 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3890 }
Marissa Wall61c58622018-07-18 10:12:20 -07003891 if (what & layer_state_t::eBufferChanged) {
3892 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3893 }
3894 if (what & layer_state_t::eAcquireFenceChanged) {
3895 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3896 }
3897 if (what & layer_state_t::eDataspaceChanged) {
3898 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3899 }
3900 if (what & layer_state_t::eHdrMetadataChanged) {
3901 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3902 }
3903 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3904 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3905 }
3906 if (what & layer_state_t::eApiChanged) {
3907 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3908 }
3909 if (what & layer_state_t::eSidebandStreamChanged) {
3910 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3911 }
Robert Carr720e5062018-07-30 17:45:14 -07003912 if (what & layer_state_t::eInputInfoChanged) {
3913 layer->setInputInfo(s.inputInfo);
3914 flags |= eTraversalNeeded;
3915 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003916 std::vector<sp<CallbackHandle>> callbackHandles;
3917 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3918 mTransactionCompletedThread.run();
3919 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3920 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3921 }
3922 }
3923 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3924 // Do not put anything that updates layer state or modifies flags after
3925 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003926 return flags;
3927}
3928
chaviw273171b2018-12-26 11:46:30 -08003929uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3930 uint32_t flags = 0;
3931 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3932 flags |= eTraversalNeeded;
3933 }
3934
3935 mInputWindowCommands.merge(inputWindowCommands);
3936 return flags;
3937}
3938
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003939status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003940 const String8& name,
3941 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003942 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003943 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003944 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003945{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003946 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003947 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003948 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003949 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003950 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003951
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003952 status_t result = NO_ERROR;
3953
3954 sp<Layer> layer;
3955
Cody Northropbc755282017-03-31 12:00:08 -06003956 String8 uniqueName = getUniqueLayerName(name);
3957
Mathias Agopian3165cc22012-08-08 19:42:09 -07003958 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003959 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003960 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3961 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003962
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003963 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003964 case ISurfaceComposerClient::eFXSurfaceBufferState:
3965 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3966 break;
chaviw13fdc492017-06-27 12:40:18 -07003967 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003968 // check if buffer size is set for color layer.
3969 if (w > 0 || h > 0) {
3970 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3971 int(w), int(h));
3972 return BAD_VALUE;
3973 }
3974
chaviw13fdc492017-06-27 12:40:18 -07003975 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003976 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003977 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003978 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003979 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003980 // check if buffer size is set for container layer.
3981 if (w > 0 || h > 0) {
3982 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3983 int(w), int(h));
3984 return BAD_VALUE;
3985 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07003986 result = createContainerLayer(client,
3987 uniqueName, w, h, flags,
3988 handle, &layer);
3989 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003990 default:
3991 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003992 break;
3993 }
3994
Dan Stoza7d89d062015-04-30 13:29:25 -07003995 if (result != NO_ERROR) {
3996 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003997 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003998
Chia-I Wuab0c3192017-08-01 11:29:00 -07003999 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4000 // TODO b/64227542
4001 if (windowType == 441731) {
4002 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
4003 layer->setPrimaryDisplayOnly();
4004 }
4005
Albert Chaulk479c60c2017-01-27 14:21:34 -05004006 layer->setInfo(windowType, ownerUid);
4007
Robert Carrb89ea9d2018-12-10 13:01:14 -08004008 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4009 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4010 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004011 if (result != NO_ERROR) {
4012 return result;
4013 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004014 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004015
4016 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004017 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004018}
4019
Cody Northropbc755282017-03-31 12:00:08 -06004020String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4021{
4022 bool matchFound = true;
4023 uint32_t dupeCounter = 0;
4024
4025 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4026 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4027
Dan Stoza436ccf32018-06-21 12:10:12 -07004028 // Grab the state lock since we're accessing mCurrentState
4029 Mutex::Autolock lock(mStateLock);
4030
Cody Northropbc755282017-03-31 12:00:08 -06004031 // Loop over layers until we're sure there is no matching name
4032 while (matchFound) {
4033 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004034 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004035 if (layer->getName() == uniqueName) {
4036 matchFound = true;
4037 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4038 }
4039 });
4040 }
4041
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004042 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4043 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004044
4045 return uniqueName;
4046}
4047
Marissa Wallfd668622018-05-10 10:21:13 -07004048status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4049 uint32_t w, uint32_t h, uint32_t flags,
4050 PixelFormat& format, sp<IBinder>* handle,
4051 sp<IGraphicBufferProducer>* gbp,
4052 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004053 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004054 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004055 case PIXEL_FORMAT_TRANSPARENT:
4056 case PIXEL_FORMAT_TRANSLUCENT:
4057 format = PIXEL_FORMAT_RGBA_8888;
4058 break;
4059 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004060 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004061 break;
4062 }
4063
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004064 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004065 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004066 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004067 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004068 *handle = layer->getHandle();
4069 *gbp = layer->getProducer();
4070 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004071 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004072
Marissa Wallfd668622018-05-10 10:21:13 -07004073 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004074 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004075}
4076
Marissa Wall61c58622018-07-18 10:12:20 -07004077status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4078 uint32_t w, uint32_t h, uint32_t flags,
4079 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004080 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004081 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004082 *handle = layer->getHandle();
4083 *outLayer = layer;
4084
4085 return NO_ERROR;
4086}
4087
chaviw13fdc492017-06-27 12:40:18 -07004088status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004089 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004090 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004091{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004092 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004093 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004094 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004095}
4096
Robert Carr6b3f6c52018-08-13 13:05:17 -07004097status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4098 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4099 sp<IBinder>* handle, sp<Layer>* outLayer)
4100{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004101 *outLayer =
4102 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004103 *handle = (*outLayer)->getHandle();
4104 return NO_ERROR;
4105}
4106
4107
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004108void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004109 mLayersPendingRemoval.add(layer);
4110 mLayersRemoved = true;
4111 setTransactionFlags(eTransactionNeeded);
4112}
4113
Robert Carr695d5282018-12-18 15:27:58 -08004114void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004115{
Robert Carr2e102c92018-10-23 12:11:15 -07004116 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004117 // If a layer has a parent, we allow it to out-live it's handle
4118 // with the idea that the parent holds a reference and will eventually
4119 // be cleaned up. However no one cleans up the top-level so we do so
4120 // here.
4121 if (layer->getParent() == nullptr) {
4122 mCurrentState.layersSortedByZ.remove(layer);
4123 }
4124 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004125 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004126}
4127
Mathias Agopianb60314a2012-04-10 22:09:54 -07004128// ---------------------------------------------------------------------------
4129
Andy McFadden13a082e2012-08-24 10:16:42 -07004130void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004131 const auto displayToken = getInternalDisplayToken();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004132 if (!displayToken) return;
4133
Jesse Hall01e29052013-02-19 16:13:35 -08004134 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004135 Vector<ComposerState> state;
4136 Vector<DisplayState> displays;
4137 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004138 d.what = DisplayState::eDisplayProjectionChanged |
4139 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004140 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08004141 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004142 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004143 d.frame.makeInvalid();
4144 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004145 d.width = 0;
4146 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004147 displays.add(d);
chaviw273171b2018-12-26 11:46:30 -08004148 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004149
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004150 const auto display = getDisplayDevice(displayToken);
4151 if (!display) return;
4152
Dominik Laskowskie9774092018-12-11 10:04:24 -08004153 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004154
Dominik Laskowski075d3172018-05-24 15:50:06 -07004155 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08004156 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07004157 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004158
Brian Andersond0010582017-03-07 13:20:31 -08004159 // Use phase of 0 since phase is not known.
4160 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07004161 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
4162 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004163}
4164
4165void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004166 // Async since we may be called from the main thread.
4167 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004168}
4169
Dominik Laskowskie9774092018-12-11 10:04:24 -08004170void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004171 if (display->isVirtual()) {
4172 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004173 return;
4174 }
4175
Dominik Laskowski075d3172018-05-24 15:50:06 -07004176 const auto displayId = display->getId();
4177 LOG_ALWAYS_FATAL_IF(!displayId);
4178
Dominik Laskowski34157762018-10-31 13:07:19 -07004179 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004180
4181 int currentMode = display->getPowerMode();
4182 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004183 return;
4184 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004185
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004186 display->setPowerMode(mode);
4187
Lloyd Pique4dccc412018-01-22 17:21:36 -08004188 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004189 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004190 }
4191
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004192 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004193 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004194 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004195 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004196 if (mUseScheduler) {
4197 mScheduler->onScreenAcquired(mAppConnectionHandle);
4198 } else {
4199 mEventThread->onScreenAcquired();
4200 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07004201 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004202 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004203
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004204 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004205 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004206 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004207
4208 struct sched_param param = {0};
4209 param.sched_priority = 1;
4210 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4211 ALOGW("Couldn't set SCHED_FIFO on display on");
4212 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004213 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004214 // Turn off the display
4215 struct sched_param param = {0};
4216 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4217 ALOGW("Couldn't set SCHED_OTHER on display off");
4218 }
4219
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004220 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004221 if (mUseScheduler) {
4222 mScheduler->disableHardwareVsync(true);
4223 } else {
4224 disableHardwareVsync(true); // also cancels any in-progress resync
4225 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004226 if (mUseScheduler) {
4227 mScheduler->onScreenReleased(mAppConnectionHandle);
4228 } else {
4229 mEventThread->onScreenReleased();
4230 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004231 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004232
Dominik Laskowski075d3172018-05-24 15:50:06 -07004233 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004234 mVisibleRegionsDirty = true;
4235 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004236 } else if (mode == HWC_POWER_MODE_DOZE ||
4237 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004238 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004239 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004240 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004241 if (mUseScheduler) {
4242 mScheduler->onScreenAcquired(mAppConnectionHandle);
4243 } else {
4244 mEventThread->onScreenAcquired();
4245 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004246 resyncToHardwareVsync(true);
4247 }
4248 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4249 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004250 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004251 if (mUseScheduler) {
4252 mScheduler->disableHardwareVsync(true);
4253 } else {
4254 disableHardwareVsync(true); // also cancels any in-progress resync
4255 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004256 if (mUseScheduler) {
4257 mScheduler->onScreenReleased(mAppConnectionHandle);
4258 } else {
4259 mEventThread->onScreenReleased();
4260 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004261 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004262 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004263 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004264 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004265 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004266 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004267
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004268 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004269 mTimeStats->setPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004270 }
4271
Dominik Laskowski34157762018-10-31 13:07:19 -07004272 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004273}
4274
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004275void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004276 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004277 const auto display = getDisplayDevice(displayToken);
4278 if (!display) {
4279 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4280 displayToken.get());
4281 } else if (display->isVirtual()) {
4282 ALOGW("Attempt to set power mode %d for virtual display", mode);
4283 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004284 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004285 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004286 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004287}
4288
4289// ---------------------------------------------------------------------------
4290
Lloyd Pique755e3192018-01-31 16:46:15 -08004291status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4292 NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004293 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004294
Mathias Agopianbd115332013-04-18 16:41:04 -07004295 IPCThreadState* ipc = IPCThreadState::self();
4296 const int pid = ipc->getCallingPid();
4297 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004298
Mathias Agopianbd115332013-04-18 16:41:04 -07004299 if ((uid != AID_SHELL) &&
4300 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004301 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4302 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004303 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004304 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004305 // (this would indicate SF is stuck, but we want to be able to
4306 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004307 status_t err = mStateLock.timedLock(s2ns(1));
4308 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004309 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004310 StringAppendF(&result,
4311 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4312 "(no locks held)\n",
4313 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004314 }
4315
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004316 bool dumpAll = true;
4317 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004318 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004319
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004320 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004321 if ((index < numArgs) &&
4322 (args[index] == String16("--list"))) {
4323 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004324 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004325 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004326 }
4327
4328 if ((index < numArgs) &&
4329 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004330 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004331 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004332 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004333 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004334
4335 if ((index < numArgs) &&
4336 (args[index] == String16("--latency-clear"))) {
4337 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004338 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004339 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004340 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004341
4342 if ((index < numArgs) &&
4343 (args[index] == String16("--dispsync"))) {
4344 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004345 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004346 dumpAll = false;
4347 }
Dan Stozab90cf072015-03-05 11:05:59 -08004348
4349 if ((index < numArgs) &&
4350 (args[index] == String16("--static-screen"))) {
4351 index++;
4352 dumpStaticScreenStats(result);
4353 dumpAll = false;
4354 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004355
4356 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004357 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004358 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004359 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004360 dumpAll = false;
4361 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004362
4363 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4364 index++;
4365 dumpWideColorInfo(result);
4366 dumpAll = false;
4367 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004368
4369 if ((index < numArgs) &&
4370 (args[index] == String16("--enable-layer-stats"))) {
4371 index++;
4372 mLayerStats.enable();
4373 dumpAll = false;
4374 }
4375
4376 if ((index < numArgs) &&
4377 (args[index] == String16("--disable-layer-stats"))) {
4378 index++;
4379 mLayerStats.disable();
4380 dumpAll = false;
4381 }
4382
4383 if ((index < numArgs) &&
4384 (args[index] == String16("--clear-layer-stats"))) {
4385 index++;
4386 mLayerStats.clear();
4387 dumpAll = false;
4388 }
4389
4390 if ((index < numArgs) &&
4391 (args[index] == String16("--dump-layer-stats"))) {
4392 index++;
4393 mLayerStats.dump(result);
4394 dumpAll = false;
4395 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004396
4397 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004398 (args[index] == String16("--frame-composition"))) {
4399 index++;
4400 dumpFrameCompositionInfo(result);
4401 dumpAll = false;
4402 }
4403
4404 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004405 (args[index] == String16("--display-identification"))) {
4406 index++;
4407 dumpDisplayIdentificationData(result);
4408 dumpAll = false;
4409 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004410
4411 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4412 index++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004413 mTimeStats->parseArgs(asProto, args, index, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004414 dumpAll = false;
4415 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004416 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004417
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004418 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004419 if (asProto) {
4420 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4421 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4422 } else {
4423 dumpAllLocked(args, index, result);
4424 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004425 }
4426
Mathias Agopian9795c422009-08-26 16:36:26 -07004427 if (locked) {
4428 mStateLock.unlock();
4429 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004430 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004431 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004432 return NO_ERROR;
4433}
4434
Yiwei Zhang5434a782018-12-05 18:06:32 -08004435void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */, size_t& /* index */,
4436 std::string& result) const {
4437 mCurrentState.traverseInZOrder(
4438 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004439}
4440
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004441void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004442 std::string& result) const {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004443 String8 name;
4444 if (index < args.size()) {
4445 name = String8(args[index]);
4446 index++;
4447 }
4448
Dominik Laskowski075d3172018-05-24 15:50:06 -07004449 if (const auto displayId = getInternalDisplayId();
4450 displayId && getHwComposer().isConnected(*displayId)) {
4451 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004452 const nsecs_t period = activeConfig->getVsyncPeriod();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004453 StringAppendF(&result, "%" PRId64 "\n", period);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004454 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004455
4456 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004457 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004458 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004459 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004460 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004461 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004462 }
Robert Carr2047fae2016-11-28 14:09:09 -08004463 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004464 }
4465}
4466
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004467void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004468 std::string& /* result */) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004469 String8 name;
4470 if (index < args.size()) {
4471 name = String8(args[index]);
4472 index++;
4473 }
4474
Robert Carr2047fae2016-11-28 14:09:09 -08004475 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004476 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004477 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004478 }
Robert Carr2047fae2016-11-28 14:09:09 -08004479 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004480
Svetoslavd85084b2014-03-20 10:28:31 -07004481 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004482}
4483
Jamie Gennis6547ff42013-07-16 20:12:42 -07004484// This should only be called from the main thread. Otherwise it would need
4485// the lock and should use mCurrentState rather than mDrawingState.
4486void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004487 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004488 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004489 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004490
4491 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4492}
4493
Yiwei Zhang5434a782018-12-05 18:06:32 -08004494void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004495 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004496
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004497 if (isLayerTripleBufferingDisabled())
4498 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004499
Yiwei Zhang5434a782018-12-05 18:06:32 -08004500 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4501 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4502 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4503 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4504 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4505 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004506 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004507}
4508
Yiwei Zhang5434a782018-12-05 18:06:32 -08004509void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4510 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004511 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4512 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004513 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004514 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004515 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004516 }
David Sodman4a36e932017-11-07 14:29:47 -08004517 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004518 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004519 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004520 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4521 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004522}
4523
Dan Stozae77c7662016-05-13 11:37:28 -07004524void SurfaceFlinger::recordBufferingStats(const char* layerName,
4525 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004526 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4527 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004528 for (const auto& segment : history) {
4529 if (!segment.usedThirdBuffer) {
4530 stats.twoBufferTime += segment.totalTime;
4531 }
4532 if (segment.occupancyAverage < 1.0f) {
4533 stats.doubleBufferedTime += segment.totalTime;
4534 } else if (segment.occupancyAverage < 2.0f) {
4535 stats.tripleBufferedTime += segment.totalTime;
4536 }
4537 ++stats.numSegments;
4538 stats.totalTime += segment.totalTime;
4539 }
4540}
4541
Yiwei Zhang5434a782018-12-05 18:06:32 -08004542void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4543 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004544
4545 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4546 const size_t count = currentLayers.size();
4547 for (size_t i=0 ; i<count ; i++) {
4548 currentLayers[i]->dumpFrameEvents(result);
4549 }
4550}
4551
Yiwei Zhang5434a782018-12-05 18:06:32 -08004552void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004553 result.append("Buffering stats:\n");
4554 result.append(" [Layer name] <Active time> <Two buffer> "
4555 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004556 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004557 typedef std::tuple<std::string, float, float, float> BufferTuple;
4558 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004559 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004560 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004561 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004562 if (stats.numSegments == 0) {
4563 continue;
4564 }
4565 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4566 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4567 stats.totalTime;
4568 float doubleBufferRatio = static_cast<float>(
4569 stats.doubleBufferedTime) / stats.totalTime;
4570 float tripleBufferRatio = static_cast<float>(
4571 stats.tripleBufferedTime) / stats.totalTime;
4572 sorted.insert({activeTime, {name, twoBufferRatio,
4573 doubleBufferRatio, tripleBufferRatio}});
4574 }
4575 for (const auto& sortedPair : sorted) {
4576 float activeTime = sortedPair.first;
4577 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004578 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4579 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004580 }
4581 result.append("\n");
4582}
4583
Yiwei Zhang5434a782018-12-05 18:06:32 -08004584void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004585 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004586 const auto displayId = display->getId();
4587 if (!displayId) {
4588 continue;
4589 }
4590 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004591 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004592 continue;
4593 }
4594
Yiwei Zhang5434a782018-12-05 18:06:32 -08004595 StringAppendF(&result,
4596 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4597 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004598 uint8_t port;
4599 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004600 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004601 result.append("no identification data\n");
4602 continue;
4603 }
4604
4605 if (!isEdid(data)) {
4606 result.append("unknown identification data: ");
4607 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004608 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004609 }
4610 result.append("\n");
4611 continue;
4612 }
4613
4614 const auto edid = parseEdid(data);
4615 if (!edid) {
4616 result.append("invalid EDID: ");
4617 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004618 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004619 }
4620 result.append("\n");
4621 continue;
4622 }
4623
Yiwei Zhang5434a782018-12-05 18:06:32 -08004624 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004625 result.append(edid->displayName.data(), edid->displayName.length());
4626 result.append("\"\n");
4627 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004628}
4629
Yiwei Zhang5434a782018-12-05 18:06:32 -08004630void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4631 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4632 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4633 StringAppendF(&result, "DisplayColorSetting: %s\n",
4634 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004635
4636 // TODO: print out if wide-color mode is active or not
4637
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004638 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004639 const auto displayId = display->getId();
4640 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004641 continue;
4642 }
4643
Yiwei Zhang5434a782018-12-05 18:06:32 -08004644 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004645 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004646 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004647 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004648 }
4649
Lloyd Pique32cbe282018-10-19 13:09:22 -07004650 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004651 StringAppendF(&result, " Current color mode: %s (%d)\n",
4652 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004653 }
4654 result.append("\n");
4655}
4656
Yiwei Zhang5434a782018-12-05 18:06:32 -08004657void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004658 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004659 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4660 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004661 continue;
4662 }
4663
Dominik Laskowski05275f12018-11-01 15:03:24 -07004664 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004665 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4666 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004667 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004668 compositionInfo.dump(result, nullptr);
4669 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004670 }
4671 }
David Sodman7e4ae112018-02-09 15:02:28 -08004672}
4673
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004674LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004675 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004676 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4677 const State& state = useDrawing ? mDrawingState : mCurrentState;
4678 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004679 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004680 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004681 });
4682
4683 return layersProto;
4684}
4685
Lloyd Pique32cbe282018-10-19 13:09:22 -07004686LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004687 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004688
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004689 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004690 resolution->set_w(displayDevice.getWidth());
4691 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004692
Lloyd Pique32cbe282018-10-19 13:09:22 -07004693 auto display = displayDevice.getCompositionDisplay();
4694 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004695
Lloyd Pique32cbe282018-10-19 13:09:22 -07004696 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4697 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4698 layersProto.set_global_transform(displayState.orientation);
4699
4700 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004701 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004702 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004703 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004704 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004705 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004706 }
4707 });
4708
4709 return layersProto;
4710}
4711
Mathias Agopian74d211a2013-04-22 16:55:35 +02004712void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004713 std::string& result) const {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004714 bool colorize = false;
4715 if (index < args.size()
4716 && (args[index] == String16("--color"))) {
4717 colorize = true;
4718 index++;
4719 }
4720
4721 Colorizer colorizer(colorize);
4722
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004723 // figure out if we're stuck somewhere
4724 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004725 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004726 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4727
4728 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004729 * Dump library configuration.
4730 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004731
4732 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004733 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004734 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004735 appendSfConfigString(result);
4736 appendUiConfigString(result);
4737 appendGuiConfigString(result);
4738 result.append("\n");
4739
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004740 result.append("\nDisplay identification data:\n");
4741 dumpDisplayIdentificationData(result);
4742
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004743 result.append("\nWide-Color information:\n");
4744 dumpWideColorInfo(result);
4745
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004746 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004747 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004748 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004749 result.append(SyncFeatures::getInstance().toString());
4750 result.append("\n");
4751
Andy McFadden41d67d72014-04-25 16:58:34 -07004752 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004753 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004754 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004755
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004756 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4757 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004758 if (const auto displayId = getInternalDisplayId();
4759 displayId && getHwComposer().isConnected(*displayId)) {
4760 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004761 StringAppendF(&result,
4762 "Display %s: app phase %" PRId64 " ns, "
4763 "sf phase %" PRId64 " ns, "
4764 "early app phase %" PRId64 " ns, "
4765 "early sf phase %" PRId64 " ns, "
4766 "early app gl phase %" PRId64 " ns, "
4767 "early sf gl phase %" PRId64 " ns, "
4768 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4769 to_string(*displayId).c_str(), vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
4770 appEarlyOffset, sfEarlyOffset, appEarlyGlOffset, sfEarlyGlOffset,
4771 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004772 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004773 result.append("\n");
4774
Dan Stozab90cf072015-03-05 11:05:59 -08004775 // Dump static screen stats
4776 result.append("\n");
4777 dumpStaticScreenStats(result);
4778 result.append("\n");
4779
Yiwei Zhang5434a782018-12-05 18:06:32 -08004780 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004781
Dan Stozae77c7662016-05-13 11:37:28 -07004782 dumpBufferingStats(result);
4783
Andy McFadden4803b742012-09-24 19:07:20 -07004784 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004785 * Dump the visible layer list
4786 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004787 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004788 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4789 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4790 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004791 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004792
Chia-I Wu2f884132018-09-13 15:17:58 -07004793 {
4794 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4795 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004796 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004797 result.append("\n");
4798 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004799
David Sodman7e4ae112018-02-09 15:02:28 -08004800 result.append("\nFrame-Composition information:\n");
4801 dumpFrameCompositionInfo(result);
4802 result.append("\n");
4803
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004804 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004805 * Dump Display state
4806 */
4807
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004808 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004809 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004810 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004811 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004812 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004813 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004814 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004815
4816 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004817 * Dump SurfaceFlinger global state
4818 */
4819
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004820 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004821 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004822 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004823
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004824 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004825
Dominik Laskowski075d3172018-05-24 15:50:06 -07004826 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004827 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4828 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004829 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4830 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004831 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004832 StringAppendF(&result,
4833 " transaction-flags : %08x\n"
4834 " gpu_to_cpu_unsupported : %d\n",
4835 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004836
Dominik Laskowski075d3172018-05-24 15:50:06 -07004837 if (const auto displayId = getInternalDisplayId();
4838 displayId && getHwComposer().isConnected(*displayId)) {
4839 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004840 StringAppendF(&result,
4841 " refresh-rate : %f fps\n"
4842 " x-dpi : %f\n"
4843 " y-dpi : %f\n",
4844 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4845 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004846 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004847
Yiwei Zhang5434a782018-12-05 18:06:32 -08004848 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004849
Yiwei Zhang5434a782018-12-05 18:06:32 -08004850 StringAppendF(&result, " use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004851 /*
4852 * VSYNC state
4853 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004854 if (mUseScheduler) {
4855 mScheduler->dump(mAppConnectionHandle, result);
4856 } else {
4857 mEventThread->dump(result);
4858 }
Dan Stozae22aec72016-08-01 13:20:59 -07004859 result.append("\n");
4860
4861 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004862 * Tracing state
4863 */
4864 mTracing.dump(result);
4865 result.append("\n");
4866
4867 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004868 * HWC layer minidump
4869 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004870 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004871 const auto displayId = display->getId();
4872 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004873 continue;
4874 }
4875
Yiwei Zhang5434a782018-12-05 18:06:32 -08004876 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004877 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004878 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004879 result.append("\n");
4880 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004881
4882 /*
4883 * Dump HWComposer state
4884 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004885 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004886 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004887 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004888 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004889 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004890 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004891
4892 /*
4893 * Dump gralloc state
4894 */
4895 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4896 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004897
4898 /*
4899 * Dump VrFlinger state if in use.
4900 */
4901 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4902 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004903 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004904 result.append("\n");
4905 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004906}
4907
Dominik Laskowski075d3172018-05-24 15:50:06 -07004908const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004909 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004910 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004911 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004912 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004913 }
4914 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004915
Dominik Laskowski34157762018-10-31 13:07:19 -07004916 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004917 static const Vector<sp<Layer>> empty;
4918 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004919}
4920
Keun young Park63f165f2012-08-31 10:53:36 -07004921bool SurfaceFlinger::startDdmConnection()
4922{
4923 void* libddmconnection_dso =
4924 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4925 if (!libddmconnection_dso) {
4926 return false;
4927 }
4928 void (*DdmConnection_start)(const char* name);
4929 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004930 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004931 if (!DdmConnection_start) {
4932 dlclose(libddmconnection_dso);
4933 return false;
4934 }
4935 (*DdmConnection_start)(getServiceName());
4936 return true;
4937}
4938
Chia-I Wu28f320b2018-05-03 11:02:56 -07004939void SurfaceFlinger::updateColorMatrixLocked() {
4940 mat4 colorMatrix;
4941 if (mGlobalSaturationFactor != 1.0f) {
4942 // Rec.709 luma coefficients
4943 float3 luminance{0.213f, 0.715f, 0.072f};
4944 luminance *= 1.0f - mGlobalSaturationFactor;
4945 mat4 saturationMatrix = mat4(
4946 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4947 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4948 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4949 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4950 );
4951 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4952 } else {
4953 colorMatrix = mClientColorMatrix * mDaltonizer();
4954 }
4955
4956 if (mCurrentState.colorMatrix != colorMatrix) {
4957 mCurrentState.colorMatrix = colorMatrix;
4958 mCurrentState.colorMatrixChanged = true;
4959 setTransactionFlags(eTransactionNeeded);
4960 }
4961}
4962
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004963status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004964#pragma clang diagnostic push
4965#pragma clang diagnostic error "-Wswitch-enum"
4966 switch (static_cast<ISurfaceComposerTag>(code)) {
4967 // These methods should at minimum make sure that the client requested
4968 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004969 case BOOT_FINISHED:
4970 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004971 case CREATE_DISPLAY:
4972 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004973 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004974 case GET_ACTIVE_COLOR_MODE:
4975 case GET_ANIMATION_FRAME_STATS:
4976 case GET_HDR_CAPABILITIES:
4977 case SET_ACTIVE_CONFIG:
4978 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004979 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004980 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004981 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004982 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4983 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004984 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4985 IPCThreadState* ipc = IPCThreadState::self();
4986 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4987 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004988 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004989 }
Robert Carr1db73f62016-12-21 12:58:51 -08004990 return OK;
4991 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004992 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004993 IPCThreadState* ipc = IPCThreadState::self();
4994 const int pid = ipc->getCallingPid();
4995 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004996 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4997 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004998 return PERMISSION_DENIED;
4999 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005000 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005001 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005002 // Used by apps to hook Choreographer to SurfaceFlinger.
5003 case CREATE_DISPLAY_EVENT_CONNECTION:
5004 // The following calls are currently used by clients that do not
5005 // request necessary permissions. However, they do not expose any secret
5006 // information, so it is OK to pass them.
5007 case AUTHENTICATE_SURFACE:
5008 case GET_ACTIVE_CONFIG:
5009 case GET_BUILT_IN_DISPLAY:
5010 case GET_DISPLAY_COLOR_MODES:
5011 case GET_DISPLAY_CONFIGS:
5012 case GET_DISPLAY_STATS:
5013 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5014 // Calling setTransactionState is safe, because you need to have been
5015 // granted a reference to Client* and Handle* to do anything with it.
5016 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005017 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005018 case GET_COLOR_MANAGEMENT:
Peiyong Lin0256f722018-08-31 15:45:10 -07005019 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005020 return OK;
5021 }
5022 case CAPTURE_LAYERS:
5023 case CAPTURE_SCREEN: {
5024 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005025 IPCThreadState* ipc = IPCThreadState::self();
5026 const int pid = ipc->getCallingPid();
5027 const int uid = ipc->getCallingUid();
5028 if ((uid != AID_GRAPHICS) &&
5029 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5030 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5031 return PERMISSION_DENIED;
5032 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005033 return OK;
5034 }
5035 // The following codes are deprecated and should never be allowed to access SF.
5036 case CONNECT_DISPLAY_UNUSED:
5037 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5038 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5039 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005040 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005041 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005042
5043 // These codes are used for the IBinder protocol to either interrogate the recipient
5044 // side of the transaction for its canonical interface descriptor or to dump its state.
5045 // We let them pass by default.
5046 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5047 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5048 code == IBinder::SYSPROPS_TRANSACTION) {
5049 return OK;
5050 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005051 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005052 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005053 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005054 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5055 return OK;
5056 }
5057 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5058 return PERMISSION_DENIED;
5059#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005060}
5061
Ana Krulec13be8ad2018-08-21 02:43:56 +00005062status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5063 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005064 status_t credentialCheck = CheckTransactCodeCredentials(code);
5065 if (credentialCheck != OK) {
5066 return credentialCheck;
5067 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005068
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005069 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5070 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005071 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005072 IPCThreadState* ipc = IPCThreadState::self();
5073 const int uid = ipc->getCallingUid();
5074 if (CC_UNLIKELY(uid != AID_SYSTEM
5075 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005076 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005077 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005078 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005079 return PERMISSION_DENIED;
5080 }
5081 int n;
5082 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005083 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005084 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005085 return NO_ERROR;
5086 case 1002: // SHOW_UPDATES
5087 n = data.readInt32();
5088 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005089 invalidateHwcGeometry();
5090 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005091 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005092 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005093 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005094 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005095 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005096 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005097 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005098 setTransactionFlags(
5099 eTransactionNeeded|
5100 eDisplayTransactionNeeded|
5101 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005102 return NO_ERROR;
5103 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005104 case 1006:{ // send empty update
5105 signalRefresh();
5106 return NO_ERROR;
5107 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005108 case 1008: // toggle use of hw composer
5109 n = data.readInt32();
5110 mDebugDisableHWC = n ? 1 : 0;
5111 invalidateHwcGeometry();
5112 repaintEverything();
5113 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005114 case 1009: // toggle use of transform hint
5115 n = data.readInt32();
5116 mDebugDisableTransformHint = n ? 1 : 0;
5117 invalidateHwcGeometry();
5118 repaintEverything();
5119 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005120 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005121 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005122 reply->writeInt32(0);
5123 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005124 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005125 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005126 return NO_ERROR;
5127 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005128 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005129 if (!display) {
5130 return NAME_NOT_FOUND;
5131 }
5132
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005133 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005134 return NO_ERROR;
5135 }
5136 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005137 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005138 // daltonize
5139 n = data.readInt32();
5140 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005141 case 1:
5142 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5143 break;
5144 case 2:
5145 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5146 break;
5147 case 3:
5148 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5149 break;
5150 default:
5151 mDaltonizer.setType(ColorBlindnessType::None);
5152 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005153 }
5154 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005155 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005156 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005157 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005158 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005159
5160 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005161 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005162 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005163 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005164 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005165 // apply a color matrix
5166 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005167 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005168 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005169 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005170 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005171 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005172 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005173 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005174 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005175 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005176 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005177
5178 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5179 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005180 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005181 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5182 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5183 }
5184
Chia-I Wu28f320b2018-05-03 11:02:56 -07005185 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005186 return NO_ERROR;
5187 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005188 // This is an experimental interface
5189 // Needs to be shifted to proper binder interface when we productize
5190 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005191 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005192 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005193 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005194 return NO_ERROR;
5195 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005196 case 1017: {
5197 n = data.readInt32();
5198 mForceFullDamage = static_cast<bool>(n);
5199 return NO_ERROR;
5200 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005201 case 1018: { // Modify Choreographer's phase offset
5202 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005203 if (mUseScheduler) {
5204 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5205 } else {
5206 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5207 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005208 return NO_ERROR;
5209 }
5210 case 1019: { // Modify SurfaceFlinger's phase offset
5211 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005212 if (mUseScheduler) {
5213 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5214 } else {
5215 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5216 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005217 return NO_ERROR;
5218 }
Irvel468051e2016-06-13 16:44:44 -07005219 case 1020: { // Layer updates interceptor
5220 n = data.readInt32();
5221 if (n) {
5222 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005223 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005224 }
5225 else{
5226 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005227 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005228 }
5229 return NO_ERROR;
5230 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005231 case 1021: { // Disable HWC virtual displays
5232 n = data.readInt32();
5233 mUseHwcVirtualDisplays = !n;
5234 return NO_ERROR;
5235 }
Romain Guy0147a172017-06-01 13:53:56 -07005236 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005237 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005238 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005239
Chia-I Wu28f320b2018-05-03 11:02:56 -07005240 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005241 return NO_ERROR;
5242 }
Romain Guy54f154a2017-10-24 21:40:32 +01005243 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005244 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005245 invalidateHwcGeometry();
5246 repaintEverything();
5247 return NO_ERROR;
5248 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005249 // Deprecate, use 1030 to check whether the device is color managed.
5250 case 1024: {
5251 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005252 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005253 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005254 n = data.readInt32();
5255 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005256 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005257 mTracing.enable();
5258 doTracing("tracing.enable");
5259 reply->writeInt32(NO_ERROR);
5260 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005261 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005262 status_t err = mTracing.disable();
5263 reply->writeInt32(err);
5264 }
5265 return NO_ERROR;
5266 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005267 case 1026: { // Get layer tracing status
5268 reply->writeBool(mTracing.isEnabled());
5269 return NO_ERROR;
5270 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005271 // Is a DisplayColorSetting supported?
5272 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005273 const auto display = getDefaultDisplayDevice();
5274 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005275 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005276 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005277
5278 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5279 switch (setting) {
5280 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005281 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005282 break;
5283 case DisplayColorSetting::UNMANAGED:
5284 reply->writeBool(true);
5285 break;
5286 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005287 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005288 break;
5289 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005290 reply->writeBool(
5291 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005292 break;
5293 }
5294 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005295 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005296 // Is VrFlinger active?
5297 case 1028: {
5298 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005299 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005300 return NO_ERROR;
5301 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005302 // Is device color managed?
5303 case 1030: {
5304 reply->writeBool(useColorManagement);
5305 return NO_ERROR;
5306 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005307 // Override default composition data space
5308 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5309 // && adb shell stop zygote && adb shell start zygote
5310 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5311 // adb shell stop zygote && adb shell start zygote
5312 case 1031: {
5313 Mutex::Autolock _l(mStateLock);
5314 n = data.readInt32();
5315 if (n) {
5316 n = data.readInt32();
5317 if (n) {
5318 Dataspace dataspace = static_cast<Dataspace>(n);
5319 if (!validateCompositionDataspace(dataspace)) {
5320 return BAD_VALUE;
5321 }
5322 mDefaultCompositionDataspace = dataspace;
5323 }
5324 n = data.readInt32();
5325 if (n) {
5326 Dataspace dataspace = static_cast<Dataspace>(n);
5327 if (!validateCompositionDataspace(dataspace)) {
5328 return BAD_VALUE;
5329 }
5330 mWideColorGamutCompositionDataspace = dataspace;
5331 }
5332 } else {
5333 // restore composition data space.
5334 mDefaultCompositionDataspace = defaultCompositionDataspace;
5335 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5336 }
5337 return NO_ERROR;
5338 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005339 }
5340 }
5341 return err;
5342}
5343
Steven Thomas6d8110b2017-08-31 18:24:21 -07005344void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005345 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005346 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005347}
5348
Ana Krulec7d1d6832018-12-27 11:10:09 -08005349void SurfaceFlinger::repaintEverythingForHWC() {
5350 mRepaintEverything = true;
5351 mEventQueue->invalidateForHWC();
5352}
5353
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005354// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5355class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005356public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005357 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5358 ~WindowDisconnector() {
5359 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005360 }
5361
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005362private:
5363 ANativeWindow* mWindow;
5364 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005365};
5366
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005367status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005368 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5369 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005370 uint32_t reqWidth, uint32_t reqHeight,
5371 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005372 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005373 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005374
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005375 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005376
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005377 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5378
Chia-I Wu20261cb2018-08-23 12:55:44 -07005379 sp<DisplayDevice> display;
5380 {
5381 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005382
Chia-I Wu20261cb2018-08-23 12:55:44 -07005383 display = getDisplayDeviceLocked(displayToken);
5384 if (!display) return BAD_VALUE;
5385
Chia-I Wucb023152018-08-28 12:57:23 -07005386 // set the requested width/height to the logical display viewport size
5387 // by default
5388 if (reqWidth == 0 || reqHeight == 0) {
5389 reqWidth = uint32_t(display->getViewport().width());
5390 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005391 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005392 }
5393
Peiyong Lin0e003c92018-09-17 11:09:51 -07005394 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5395 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005396
5397 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005398 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005399 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5400 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005401}
5402
5403status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005404 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5405 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005406 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005407 ATRACE_CALL();
5408
5409 class LayerRenderArea : public RenderArea {
5410 public:
Robert Carr578038f2018-03-09 12:25:24 -08005411 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005412 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5413 bool childrenOnly)
5414 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005415 mLayer(layer),
5416 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005417 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005418 mFlinger(flinger),
5419 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005420 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005421 Rect getBounds() const override {
5422 const Layer::State& layerState(mLayer->getDrawingState());
5423 return mLayer->getBufferSize(layerState);
5424 }
Marissa Wall61c58622018-07-18 10:12:20 -07005425 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005426 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005427 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005428 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005429 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005430 }
chaviwa76b2712017-09-20 12:02:26 -07005431 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005432 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005433 Rect getSourceCrop() const override {
5434 if (mCrop.isEmpty()) {
5435 return getBounds();
5436 } else {
5437 return mCrop;
5438 }
5439 }
Robert Carr578038f2018-03-09 12:25:24 -08005440 class ReparentForDrawing {
5441 public:
5442 const sp<Layer>& oldParent;
5443 const sp<Layer>& newParent;
5444
5445 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5446 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005447 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005448 }
Robert Carr15eae092018-03-23 13:43:53 -07005449 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005450 };
5451
5452 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005453 const Rect sourceCrop = getSourceCrop();
5454 // no need to check rotation because there is none
5455 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5456 sourceCrop.height() != getReqHeight();
5457
Robert Carr578038f2018-03-09 12:25:24 -08005458 if (!mChildrenOnly) {
5459 mTransform = mLayer->getTransform().inverse();
5460 drawLayers();
5461 } else {
5462 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005463 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005464 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5465 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005466
5467 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5468 drawLayers();
5469 }
5470 }
chaviwa76b2712017-09-20 12:02:26 -07005471
chaviwa76b2712017-09-20 12:02:26 -07005472 private:
chaviw7206d492017-11-10 16:16:12 -08005473 const sp<Layer> mLayer;
5474 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005475
5476 // In the "childrenOnly" case we reparent the children to a screenshot
5477 // layer which has no properties set and which does not draw.
5478 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005479 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005480 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005481
5482 SurfaceFlinger* mFlinger;
5483 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005484 };
5485
5486 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5487 auto parent = layerHandle->owner.promote();
5488
Robert Carr2e102c92018-10-23 12:11:15 -07005489 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005490 ALOGE("captureLayers called with a removed parent");
5491 return NAME_NOT_FOUND;
5492 }
5493
Robert Carr578038f2018-03-09 12:25:24 -08005494 const int uid = IPCThreadState::self()->getCallingUid();
5495 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005496 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005497 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5498 return PERMISSION_DENIED;
5499 }
5500
chaviw7206d492017-11-10 16:16:12 -08005501 Rect crop(sourceCrop);
5502 if (sourceCrop.width() <= 0) {
5503 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005504 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005505 }
5506
5507 if (sourceCrop.height() <= 0) {
5508 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005509 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005510 }
5511
5512 int32_t reqWidth = crop.width() * frameScale;
5513 int32_t reqHeight = crop.height() * frameScale;
5514
Chia-I Wu20261cb2018-08-23 12:55:44 -07005515 // really small crop or frameScale
5516 if (reqWidth <= 0) {
5517 reqWidth = 1;
5518 }
5519 if (reqHeight <= 0) {
5520 reqHeight = 1;
5521 }
5522
Peiyong Lin0e003c92018-09-17 11:09:51 -07005523 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005524
Robert Carr578038f2018-03-09 12:25:24 -08005525 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005526 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5527 if (!layer->isVisible()) {
5528 return;
Robert Carr578038f2018-03-09 12:25:24 -08005529 } else if (childrenOnly && layer == parent.get()) {
5530 return;
chaviwa76b2712017-09-20 12:02:26 -07005531 }
5532 visitor(layer);
5533 });
5534 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005535 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005536}
5537
5538status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5539 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005540 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005541 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005542 bool useIdentityTransform) {
5543 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005544
Peiyong Lin0e003c92018-09-17 11:09:51 -07005545 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005546 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5547 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005548 *outBuffer =
5549 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5550 static_cast<android_pixel_format>(reqPixelFormat), 1,
5551 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005552
5553 // This mutex protects syncFd and captureResult for communication of the return values from the
5554 // main thread back to this Binder thread
5555 std::mutex captureMutex;
5556 std::condition_variable captureCondition;
5557 std::unique_lock<std::mutex> captureLock(captureMutex);
5558 int syncFd = -1;
5559 std::optional<status_t> captureResult;
5560
Robert Carr03480e22018-01-04 16:02:06 -08005561 const int uid = IPCThreadState::self()->getCallingUid();
5562 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5563
Dominik Laskowski8c001672018-05-30 16:52:06 -07005564 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005565 // If there is a refresh pending, bug out early and tell the binder thread to try again
5566 // after the refresh.
5567 if (mRefreshPending) {
5568 ATRACE_NAME("Skipping screenshot for now");
5569 std::unique_lock<std::mutex> captureLock(captureMutex);
5570 captureResult = std::make_optional<status_t>(EAGAIN);
5571 captureCondition.notify_one();
5572 return;
5573 }
5574
5575 status_t result = NO_ERROR;
5576 int fd = -1;
5577 {
5578 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005579 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005580 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5581 useIdentityTransform, forSystem, &fd);
5582 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005583 }
5584
5585 {
5586 std::unique_lock<std::mutex> captureLock(captureMutex);
5587 syncFd = fd;
5588 captureResult = std::make_optional<status_t>(result);
5589 captureCondition.notify_one();
5590 }
5591 });
5592
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005593 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005594 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005595 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005596 while (*captureResult == EAGAIN) {
5597 captureResult.reset();
5598 result = postMessageAsync(message);
5599 if (result != NO_ERROR) {
5600 return result;
5601 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005602 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005603 }
5604 result = *captureResult;
5605 }
5606
5607 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005608 sync_wait(syncFd, -1);
5609 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005610 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005611
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005612 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005613}
5614
chaviwa76b2712017-09-20 12:02:26 -07005615void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005616 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005617 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005618 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005619
Lloyd Pique144e1162017-12-20 16:44:52 -08005620 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005621
chaviwa76b2712017-09-20 12:02:26 -07005622 const auto reqWidth = renderArea.getReqWidth();
5623 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005624 const auto sourceCrop = renderArea.getSourceCrop();
5625 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005626
Peiyong Lin0e003c92018-09-17 11:09:51 -07005627 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005628 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005629
Mathias Agopian180f10d2013-04-10 22:55:41 -07005630 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005631 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005632
5633 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005634 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005635 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005636
chaviw50da5042018-04-09 13:49:37 -07005637 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005638 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005639 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005640
chaviwa76b2712017-09-20 12:02:26 -07005641 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005642 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005643 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005644 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005645 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005646}
5647
chaviwa76b2712017-09-20 12:02:26 -07005648status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5649 TraverseLayersFunction traverseLayers,
5650 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005651 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005652 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005653 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005654 ATRACE_CALL();
5655
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005656 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005657
5658 traverseLayers([&](Layer* layer) {
5659 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5660 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005661
Robert Carr03480e22018-01-04 16:02:06 -08005662 // We allow the system server to take screenshots of secure layers for
5663 // use in situations like the Screen-rotation animation and place
5664 // the impetus on WindowManager to not persist them.
5665 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005666 ALOGW("FB is protected: PERMISSION_DENIED");
5667 return PERMISSION_DENIED;
5668 }
Peiyong Linfb530cf2018-12-15 05:07:38 +00005669 auto& engine(getRenderEngine());
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005670
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005671 // this binds the given EGLImage as a framebuffer for the
5672 // duration of this scope.
Peiyong Linfb530cf2018-12-15 05:07:38 +00005673 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005674 if (bufferBond.getStatus() != NO_ERROR) {
5675 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005676 return INVALID_OPERATION;
5677 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005678
Dan Stozaabcda352017-06-01 14:37:39 -07005679 // this will in fact render into our dequeued buffer
5680 // via an FBO, which means we didn't have to create
5681 // an EGLSurface and therefore we're not
5682 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005683 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005684
Peiyong Linfb530cf2018-12-15 05:07:38 +00005685 base::unique_fd syncFd = engine.flush();
Alec Mouri492bc572018-09-11 21:40:04 +00005686 if (syncFd < 0) {
Peiyong Linfb530cf2018-12-15 05:07:38 +00005687 engine.finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005688 }
Alec Mouri492bc572018-09-11 21:40:04 +00005689 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005690
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005691 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005692}
5693
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005694// ---------------------------------------------------------------------------
5695
Dan Stoza412903f2017-04-27 13:42:17 -07005696void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5697 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005698}
5699
Dan Stoza412903f2017-04-27 13:42:17 -07005700void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5701 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005702}
5703
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005704void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005705 const LayerVector::Visitor& visitor) {
5706 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005707 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005708 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005709 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005710 continue;
5711 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005712 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005713 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005714 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005715 return;
5716 }
chaviwa76b2712017-09-20 12:02:26 -07005717 if (!layer->isVisible()) {
5718 return;
5719 }
5720 visitor(layer);
5721 });
5722 }
5723}
5724
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005725}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005726
Lloyd Pique074e8122018-07-26 12:57:23 -07005727
Mathias Agopian3f844832013-08-07 21:24:32 -07005728#if defined(__gl_h_)
5729#error "don't include gl/gl.h in this file"
5730#endif
5731
5732#if defined(__gl2_h_)
5733#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005734#endif