blob: 3531296830e502b526e873b425fb73d6cf9f27fd [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
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070022#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080023
24#include <algorithm>
25#include <cinttypes>
26#include <cmath>
27#include <cstdint>
28#include <functional>
29#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070030#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080031#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Lloyd Pique70d91362018-10-18 16:02:55 -070040#include <compositionengine/CompositionEngine.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070041#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070042#include <compositionengine/DisplayColorProfile.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070043#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070044#include <compositionengine/impl/OutputCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080045#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070047#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080049#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080050#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080051#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070052#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070053#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070054#include <ui/ColorSpace.h>
55#include <ui/DebugUtils.h>
56#include <ui/DisplayInfo.h>
57#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070058#include <ui/GraphicBufferAllocator.h>
59#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070060#include <ui/UiConfig.h>
Ady Abraham8164d482019-01-11 14:47:59 -080061#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070063#include <utils/String16.h>
64#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070065#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080066#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070067#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080068
Mathias Agopian921e6ac2012-07-23 23:11:29 -070069#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070070#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071
Robert Carr578038f2018-03-09 12:25:24 -080072#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070073#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070074#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020075#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080076#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020077#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080079#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080080#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070082#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080083#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070084#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070085#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080086#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070087#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080088
Steven Thomasb02664d2017-07-26 18:48:28 -070089#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070090#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070091#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070092#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070093#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070094#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070095#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070096#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070097#include "Scheduler/EventControlThread.h"
98#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070099#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700100#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700101#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800102#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700103
Mathias Agopianff2ed702013-09-01 21:36:12 -0700104#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700105
David Sodman7e4ae112018-02-09 15:02:28 -0800106#include "android-base/stringprintf.h"
107
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900108#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800109#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700110#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800111#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900112#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900113
chaviw1d044282017-09-27 12:19:28 -0700114#include <layerproto/LayerProtoParser.h>
115
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800116namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700117
Jaesoo Lee43518572017-01-23 19:03:16 +0900118using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900119using namespace android::hardware::configstore::V1_0;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800120using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700121using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700122using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700123using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700124using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900125
Steven Thomasb02664d2017-07-26 18:48:28 -0700126namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700127
128#pragma clang diagnostic push
129#pragma clang diagnostic error "-Wswitch-enum"
130
131bool isWideColorMode(const ColorMode colorMode) {
132 switch (colorMode) {
133 case ColorMode::DISPLAY_P3:
134 case ColorMode::ADOBE_RGB:
135 case ColorMode::DCI_P3:
136 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700137 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700138 case ColorMode::BT2100_PQ:
139 case ColorMode::BT2100_HLG:
140 return true;
141 case ColorMode::NATIVE:
142 case ColorMode::STANDARD_BT601_625:
143 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
144 case ColorMode::STANDARD_BT601_525:
145 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
146 case ColorMode::STANDARD_BT709:
147 case ColorMode::SRGB:
148 return false;
149 }
150 return false;
151}
152
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700153ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
154 switch (rotation) {
155 case ISurfaceComposer::eRotateNone:
156 return ui::Transform::ROT_0;
157 case ISurfaceComposer::eRotate90:
158 return ui::Transform::ROT_90;
159 case ISurfaceComposer::eRotate180:
160 return ui::Transform::ROT_180;
161 case ISurfaceComposer::eRotate270:
162 return ui::Transform::ROT_270;
163 }
164 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
165 return ui::Transform::ROT_0;
166}
167
Peiyong Linfca547f2018-07-09 13:03:33 -0700168#pragma clang diagnostic pop
169
Steven Thomasb02664d2017-07-26 18:48:28 -0700170class ConditionalLock {
171public:
172 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
173 if (lock) {
174 mMutex.lock();
175 }
176 }
177 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
178private:
179 Mutex& mMutex;
180 bool mLocked;
181};
Peiyong Linfca547f2018-07-09 13:03:33 -0700182
Peiyong Lin9d846a52018-11-05 13:18:20 -0800183// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
184bool validateCompositionDataspace(Dataspace dataspace) {
185 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
186}
187
Steven Thomasb02664d2017-07-26 18:48:28 -0700188} // namespace anonymous
189
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800190// ---------------------------------------------------------------------------
191
Mathias Agopian99b49842011-06-27 16:05:52 -0700192const String16 sHardwareTest("android.permission.HARDWARE_TEST");
193const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
194const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
195const String16 sDump("android.permission.DUMP");
196
197// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800198int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
199int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700200int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700201bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800202uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800203bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800204bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800205int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600206bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700207int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700208bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700209bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700210Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
211ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
212Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
213ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700214
Kalle Raitaa099a242017-01-11 11:17:29 -0800215std::string getHwcServiceName() {
216 char value[PROPERTY_VALUE_MAX] = {};
217 property_get("debug.sf.hwc_service_name", value, "default");
218 ALOGI("Using HWComposer service: '%s'", value);
219 return std::string(value);
220}
221
222bool useTrebleTestingOverride() {
223 char value[PROPERTY_VALUE_MAX] = {};
224 property_get("debug.sf.treble_testing_override", value, "false");
225 ALOGI("Treble testing override: '%s'", value);
226 return std::string(value) == "true";
227}
228
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800229std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
230 switch(displayColorSetting) {
231 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700232 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800233 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700234 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800235 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700236 return std::string("Enhanced");
237 default:
238 return std::string("Unknown ") +
239 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800240 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800241}
242
David Sodmanbc815282017-11-05 18:57:52 -0800243SurfaceFlingerBE::SurfaceFlingerBE()
244 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800245 mFrameBuckets(),
246 mTotalTime(0),
247 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800248 mComposerSequenceId(0) {
249}
250
Lloyd Pique90c115d2018-09-18 21:39:42 -0700251SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
252 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800253 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700254 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700255 mTransactionPending(false),
256 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700257 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700258 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800259 mBootTime(systemTime()),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800260 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800261 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800262 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800263 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800264 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700265 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700266 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700267 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700268 mDebugInTransaction(0),
269 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700270 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800271 mTimeStats(factory.createTimeStats()),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700272 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700273 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800274 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800275 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800276 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700277 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700278 mMainThreadId(std::this_thread::get_id()),
279 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800280
Lloyd Pique90c115d2018-09-18 21:39:42 -0700281SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
282 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800283 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800284
285 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
286 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
287
288 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
289 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
290
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800291 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
292 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800293
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700294 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
295 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
296
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700297 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
298 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
299
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800300 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
301 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
302
Steven Thomas050b2c82017-03-06 11:45:16 -0800303 // Vr flinger is only enabled on Daydream ready devices.
304 useVrFlinger = getBool< ISurfaceFlingerConfigs,
305 &ISurfaceFlingerConfigs::useVrFlinger>(false);
306
Fabien Sanglard1971b632017-03-10 14:50:03 -0800307 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
308 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
309
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600310 hasWideColorDisplay =
311 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700312 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700313 getBool<V1_2::ISurfaceFlingerConfigs,
314 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
315
316 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
317 if (surfaceFlingerConfigsServiceV1_2) {
318 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
Peiyong Linc6780972018-10-28 15:24:08 -0700319 [&](auto tmpDefaultDataspace, auto tmpDefaultPixelFormat,
320 auto tmpWideColorGamutDataspace, auto tmpWideColorGamutPixelFormat) {
321 defaultCompositionDataspace = tmpDefaultDataspace;
322 defaultCompositionPixelFormat = tmpDefaultPixelFormat;
323 wideColorGamutCompositionDataspace = tmpWideColorGamutDataspace;
324 wideColorGamutCompositionPixelFormat = tmpWideColorGamutPixelFormat;
325 });
Peiyong Lin0256f722018-08-31 15:45:10 -0700326 }
Peiyong Lin9d846a52018-11-05 13:18:20 -0800327 mDefaultCompositionDataspace = defaultCompositionDataspace;
328 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600329
Peiyong Linb3839ad2018-09-05 15:37:19 -0700330 useContextPriority = getBool<ISurfaceFlingerConfigs,
331 &ISurfaceFlingerConfigs::useContextPriority>(true);
332
Iris Chang7501ed62018-04-30 14:45:42 +0800333 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700334 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
335 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800336 V1_1::DisplayOrientation::ORIENTATION_0);
337
338 switch (primaryDisplayOrientation) {
339 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700340 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800341 break;
342 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700343 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800344 break;
345 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700346 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800347 break;
348 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700349 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800350 break;
351 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700352 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800353
Lloyd Pique90c115d2018-09-18 21:39:42 -0700354 mPrimaryDispSync =
355 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
356 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700357
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800358 // debugging stuff...
359 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700360
Mathias Agopianb4b17302013-03-20 18:36:41 -0700361 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700362 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700363
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800364 property_get("debug.sf.showupdates", value, "0");
365 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700366
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700367 property_get("debug.sf.ddms", value, "0");
368 mDebugDDMS = atoi(value);
369 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700370 if (!startDdmConnection()) {
371 // start failed, and DDMS debugging not enabled
372 mDebugDDMS = 0;
373 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700374 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700375 ALOGI_IF(mDebugRegion, "showupdates enabled");
376 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700377
378 property_get("debug.sf.disable_backpressure", value, "0");
379 mPropagateBackpressure = !atoi(value);
380 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700381
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800382 property_get("debug.sf.enable_hwc_vds", value, "0");
383 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800384 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800385
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800386 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800387 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800388 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700389
Yiwei Zhang243b3782018-05-15 17:40:04 -0700390 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700391 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
392 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
393
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200394 property_get("debug.sf.early_phase_offset_ns", value, "-1");
395 const int earlySfOffsetNs = atoi(value);
396
397 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
398 const int earlyGlSfOffsetNs = atoi(value);
399
400 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
401 const int earlyAppOffsetNs = atoi(value);
402
403 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
404 const int earlyGlAppOffsetNs = atoi(value);
405
Ana Krulec98b5b242018-08-10 15:03:23 -0700406 property_get("debug.sf.use_scheduler", value, "0");
407 mUseScheduler = atoi(value);
408
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200409 const VSyncModulator::Offsets earlyOffsets =
410 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
411 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
412 const VSyncModulator::Offsets earlyGlOffsets =
413 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
414 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
415 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
416 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700417
Romain Guy11d63f42017-07-20 12:47:14 -0700418 // We should be reading 'persist.sys.sf.color_saturation' here
419 // but since /data may be encrypted, we need to wait until after vold
420 // comes online to attempt to read the property. The property is
421 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800422
423 if (useTrebleTestingOverride()) {
424 // Without the override SurfaceFlinger cannot connect to HIDL
425 // services that are not listed in the manifests. Considered
426 // deriving the setting from the set service name, but it
427 // would be brittle if the name that's not 'default' is used
428 // for production purposes later on.
429 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
430 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800431}
432
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800433void SurfaceFlinger::onFirstRef()
434{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800435 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800436}
437
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800438SurfaceFlinger::~SurfaceFlinger()
439{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800440}
441
Dan Stozac7014012014-02-14 15:03:43 -0800442void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800443{
444 // the window manager died on us. prepare its eulogy.
445
Andy McFadden13a082e2012-08-24 10:16:42 -0700446 // restore initial conditions (default device unblank, etc)
447 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800448
449 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700450 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800451}
452
Robert Carr1db73f62016-12-21 12:58:51 -0800453static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700454 status_t err = client->initCheck();
455 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800456 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800457 }
Robert Carr1db73f62016-12-21 12:58:51 -0800458 return nullptr;
459}
460
461sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
462 return initClient(new Client(this));
463}
464
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700465sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
466 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700467{
468 class DisplayToken : public BBinder {
469 sp<SurfaceFlinger> flinger;
470 virtual ~DisplayToken() {
471 // no more references, this display must be terminated
472 Mutex::Autolock _l(flinger->mStateLock);
473 flinger->mCurrentState.displays.removeItem(this);
474 flinger->setTransactionFlags(eDisplayTransactionNeeded);
475 }
476 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700477 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700478 : flinger(flinger) {
479 }
480 };
481
482 sp<BBinder> token = new DisplayToken(this);
483
484 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700485 // Display ID is assigned when virtual display is allocated by HWC.
486 DisplayDeviceState state;
487 state.isSecure = secure;
488 state.displayName = displayName;
489 mCurrentState.displays.add(token, state);
490 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700491 return token;
492}
493
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700494void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700495 Mutex::Autolock _l(mStateLock);
496
Dominik Laskowski075d3172018-05-24 15:50:06 -0700497 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
498 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700499 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700500 return;
501 }
502
Dominik Laskowski075d3172018-05-24 15:50:06 -0700503 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
504 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700505 ALOGE("destroyDisplay called for non-virtual display");
506 return;
507 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700508 mInterceptor->saveDisplayDeletion(state.sequenceId);
509 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700510 setTransactionFlags(eDisplayTransactionNeeded);
511}
512
Mathias Agopiane57f2922012-08-09 16:29:12 -0700513sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700514 std::optional<DisplayId> displayId;
515
516 if (id == HWC_DISPLAY_PRIMARY) {
517 displayId = getInternalDisplayId();
518 } else if (id == HWC_DISPLAY_EXTERNAL) {
519 displayId = getExternalDisplayId();
520 }
521
522 if (!displayId) {
523 ALOGE("%s: Invalid display %d", __FUNCTION__, id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800524 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700525 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700526
527 return getPhysicalDisplayToken(*displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700528}
529
Ady Abraham37965d42018-11-01 13:43:32 -0700530status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
531 if (!outGetColorManagement) {
532 return BAD_VALUE;
533 }
534 *outGetColorManagement = useColorManagement;
535 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700536}
537
Lloyd Pique441d5042018-10-18 16:49:51 -0700538HWComposer& SurfaceFlinger::getHwComposer() const {
539 return mCompositionEngine->getHwComposer();
540}
541
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700542renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
543 return mCompositionEngine->getRenderEngine();
544}
545
Lloyd Pique70d91362018-10-18 16:02:55 -0700546compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
547 return *mCompositionEngine.get();
548}
549
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800550void SurfaceFlinger::bootFinished()
551{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700552 if (mStartPropertySetThread->join() != NO_ERROR) {
553 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800554 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800555 const nsecs_t now = systemTime();
556 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000557 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700558
559 // wait patiently for the window manager death
560 const String16 name("window");
561 sp<IBinder> window(defaultServiceManager()->getService(name));
562 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700563 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700564 }
Robert Carr720e5062018-07-30 17:45:14 -0700565 sp<IBinder> input(defaultServiceManager()->getService(
566 String16("inputflinger")));
567 if (input == nullptr) {
568 ALOGE("Failed to link to input service");
569 } else {
570 mInputFlinger = interface_cast<IInputFlinger>(input);
571 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700572
Steven Thomas050b2c82017-03-06 11:45:16 -0800573 if (mVrFlinger) {
574 mVrFlinger->OnBootFinished();
575 }
576
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700577 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700578 // formerly we would just kill the process, but we now ask it to exit so it
579 // can choose where to stop the animation.
580 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700581
582 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
583 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
584 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700585
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800586 postMessageAsync(new LambdaMessage([this] {
587 readPersistentProperties();
588 mBootStage = BootStage::FINISHED;
589 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800590}
591
Dan Stoza436ccf32018-06-21 12:10:12 -0700592uint32_t SurfaceFlinger::getNewTexture() {
593 {
594 std::lock_guard lock(mTexturePoolMutex);
595 if (!mTexturePool.empty()) {
596 uint32_t name = mTexturePool.back();
597 mTexturePool.pop_back();
598 ATRACE_INT("TexturePoolSize", mTexturePool.size());
599 return name;
600 }
601
602 // The pool was too small, so increase it for the future
603 ++mTexturePoolSize;
604 }
605
606 // The pool was empty, so we need to get a new texture name directly using a
607 // blocking call to the main thread
608 uint32_t name = 0;
609 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
610 return name;
611}
612
Mathias Agopian3f844832013-08-07 21:24:32 -0700613void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700614 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700615}
616
Wei Wangf9b05ee2017-07-19 20:59:39 -0700617// Do not call property_set on main thread which will be blocked by init
618// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700619void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700620 ALOGI( "SurfaceFlinger's main thread ready to run. "
621 "Initializing graphics H/W...");
622
Thierry Strudel2924d012017-08-14 15:19:37 -0700623 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900624
Steven Thomasb02664d2017-07-26 18:48:28 -0700625 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800626
Dominik Laskowski83b88212018-12-11 13:34:06 -0800627 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -0800628
Steven Thomasb02664d2017-07-26 18:48:28 -0700629 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700630 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700631 mScheduler = getFactory().createScheduler([this](bool enabled) {
632 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
633 });
634
Ana Krulec98b5b242018-08-10 15:03:23 -0700635 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700636 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Dominik Laskowskif654d572018-12-20 11:03:06 -0800637 resyncCallback,
Ana Krulec98b5b242018-08-10 15:03:23 -0700638 impl::EventThread::InterceptVSyncsCallback());
639 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700640 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Dominik Laskowskif654d572018-12-20 11:03:06 -0800641 resyncCallback, [this](nsecs_t timestamp) {
Ana Krulec98b5b242018-08-10 15:03:23 -0700642 mInterceptor->saveVSyncEvent(timestamp);
643 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800644
Ana Krulec98b5b242018-08-10 15:03:23 -0700645 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700646 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
647 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700648 } else {
649 mEventThreadSource =
650 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
651 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
652 mEventThread =
653 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700654 impl::EventThread::InterceptVSyncsCallback(),
655 "appEventThread");
656 mSfEventThreadSource =
657 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
658 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
659
660 mSFEventThread =
661 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700662 [this](nsecs_t timestamp) {
663 mInterceptor->saveVSyncEvent(timestamp);
664 },
665 "sfEventThread");
Dominik Laskowskif654d572018-12-20 11:03:06 -0800666 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Ana Krulec98b5b242018-08-10 15:03:23 -0700667 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
668 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800669
Steven Thomasb02664d2017-07-26 18:48:28 -0700670 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700671 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700672 renderEngineFeature |= (useColorManagement ?
673 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700674 renderEngineFeature |= (useContextPriority ?
675 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700676
677 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700678 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700679 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700680 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700681
682 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
683 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700684 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
685 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800686 // Process any initial hotplug and resulting display changes.
687 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700688 const auto display = getDefaultDisplayDeviceLocked();
689 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700690 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700691 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800692
Steven Thomas050b2c82017-03-06 11:45:16 -0800693 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700694 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700695 // This callback is called from the vr flinger dispatch thread. We
696 // need to call signalTransaction(), which requires holding
697 // mStateLock when we're not on the main thread. Acquiring
698 // mStateLock from the vr flinger dispatch thread might trigger a
699 // deadlock in surface flinger (see b/66916578), so post a message
700 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700701 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700702 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
703 mVrFlingerRequestsDisplay = requestDisplay;
704 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700705 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800706 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700707 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
708 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700709 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700710 .value_or(0),
711 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800712 if (!mVrFlinger) {
713 ALOGE("Failed to start vrflinger");
714 }
715 }
716
Lloyd Pique90c115d2018-09-18 21:39:42 -0700717 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700718 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700719
Mathias Agopian92a979a2012-08-02 18:32:23 -0700720 // initialize our drawing state
721 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700722
Andy McFadden13a082e2012-08-24 10:16:42 -0700723 // set initial conditions (e.g. unblank default device)
724 initializeDisplays();
725
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700726 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700727
Wei Wangf9b05ee2017-07-19 20:59:39 -0700728 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700729
730 const bool presentFenceReliable =
731 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
732 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700733
734 if (mStartPropertySetThread->Start() != NO_ERROR) {
735 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800736 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800737
Ana Krulec7d1d6832018-12-27 11:10:09 -0800738 if (mUseScheduler) {
739 mScheduler->setExpiredIdleTimerCallback([this]() { setRefreshRateTo(60.f /* fps */); });
740 mScheduler->setResetIdleTimerCallback([this]() { setRefreshRateTo(90.f /* fps */); });
741 }
742
Dan Stoza9e56aa02015-11-02 13:00:03 -0800743 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700744}
745
Romain Guy11d63f42017-07-20 12:47:14 -0700746void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700747 Mutex::Autolock _l(mStateLock);
748
Romain Guy11d63f42017-07-20 12:47:14 -0700749 char value[PROPERTY_VALUE_MAX];
750
751 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800752 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700753 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800754 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100755
756 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700757 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700758}
759
Mathias Agopiana67e4182012-06-19 17:26:12 -0700760void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800761 // Start boot animation service by setting a property mailbox
762 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700763 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800764 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700765 if (mStartPropertySetThread->join() != NO_ERROR) {
766 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800767 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700768}
769
Mathias Agopian875d8e12013-06-07 15:35:48 -0700770size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700771 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700772}
773
Mathias Agopian875d8e12013-06-07 15:35:48 -0700774size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700775 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700776}
777
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800778// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800779
Jamie Gennis582270d2011-08-17 18:19:00 -0700780bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800781 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800782 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800783 return authenticateSurfaceTextureLocked(bufferProducer);
784}
785
786bool SurfaceFlinger::authenticateSurfaceTextureLocked(
787 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800788 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800789 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800790}
791
Brian Anderson6b376712017-04-04 10:51:39 -0700792status_t SurfaceFlinger::getSupportedFrameTimestamps(
793 std::vector<FrameEvent>* outSupported) const {
794 *outSupported = {
795 FrameEvent::REQUESTED_PRESENT,
796 FrameEvent::ACQUIRE,
797 FrameEvent::LATCH,
798 FrameEvent::FIRST_REFRESH_START,
799 FrameEvent::LAST_REFRESH_START,
800 FrameEvent::GPU_COMPOSITION_DONE,
801 FrameEvent::DEQUEUE_READY,
802 FrameEvent::RELEASE,
803 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700804 ConditionalLock _l(mStateLock,
805 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700806 if (!getHwComposer().hasCapability(
807 HWC2::Capability::PresentFenceIsNotReliable)) {
808 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
809 }
810 return NO_ERROR;
811}
812
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700813status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
814 Vector<DisplayInfo>* configs) {
815 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700816 return BAD_VALUE;
817 }
818
Dominik Laskowski075d3172018-05-24 15:50:06 -0700819 const auto displayId = getPhysicalDisplayId(displayToken);
820 if (!displayId) {
821 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700822 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700823
Mathias Agopian8b736f12012-08-13 17:54:26 -0700824 // TODO: Not sure if display density should handled by SF any longer
825 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700826 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700827 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700828 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800829 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700830 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700831 }
832 return density;
833 }
834 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700835 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700836 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700837 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700838 return getDensityFromProperty("ro.sf.lcd_density"); }
839 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700840
Dan Stoza7f7da322014-05-02 15:26:25 -0700841 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700842
Steven Thomas6d8110b2017-08-31 18:24:21 -0700843 ConditionalLock _l(mStateLock,
844 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700845 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700846 DisplayInfo info = DisplayInfo();
847
Dan Stoza9e56aa02015-11-02 13:00:03 -0800848 float xdpi = hwConfig->getDpiX();
849 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700850
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700851 info.w = hwConfig->getWidth();
852 info.h = hwConfig->getHeight();
853 // Default display viewport to display width and height
854 info.viewportW = info.w;
855 info.viewportH = info.h;
856
Dominik Laskowski075d3172018-05-24 15:50:06 -0700857 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700858 // The density of the device is provided by a build property
859 float density = Density::getBuildDensity() / 160.0f;
860 if (density == 0) {
861 // the build doesn't provide a density -- this is wrong!
862 // use xdpi instead
863 ALOGE("ro.sf.lcd_density must be defined as a build property");
864 density = xdpi / 160.0f;
865 }
866 if (Density::getEmuDensity()) {
867 // if "qemu.sf.lcd_density" is specified, it overrides everything
868 xdpi = ydpi = density = Density::getEmuDensity();
869 density /= 160.0f;
870 }
871 info.density = density;
872
873 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700874 const auto display = getDefaultDisplayDeviceLocked();
875 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700876
877 // This is for screenrecord
878 const Rect viewport = display->getViewport();
879 if (viewport.isValid()) {
880 info.viewportW = uint32_t(viewport.getWidth());
881 info.viewportH = uint32_t(viewport.getHeight());
882 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700883 } else {
884 // TODO: where should this value come from?
885 static const int TV_DENSITY = 213;
886 info.density = TV_DENSITY / 160.0f;
887 info.orientation = 0;
888 }
889
Dan Stoza7f7da322014-05-02 15:26:25 -0700890 info.xdpi = xdpi;
891 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800892 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900893 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800894
Andy McFadden91b2ca82014-06-13 14:04:23 -0700895 // This is how far in advance a buffer must be queued for
896 // presentation at a given time. If you want a buffer to appear
897 // on the screen at time N, you must submit the buffer before
898 // (N - presentationDeadline).
899 //
900 // Normally it's one full refresh period (to give SF a chance to
901 // latch the buffer), but this can be reduced by configuring a
902 // DispSync offset. Any additional delays introduced by the hardware
903 // composer or panel must be accounted for here.
904 //
905 // We add an additional 1ms to allow for processing time and
906 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800907 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800908 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700909
910 // All non-virtual displays are currently considered secure.
911 info.secure = true;
912
Dominik Laskowski075d3172018-05-24 15:50:06 -0700913 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700914 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800915 std::swap(info.w, info.h);
916 }
917
Michael Wright28f24d02016-07-12 13:30:53 -0700918 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700919 }
920
Dan Stoza7f7da322014-05-02 15:26:25 -0700921 return NO_ERROR;
922}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700923
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700924status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
925 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700926 return BAD_VALUE;
927 }
928
Ana Krulece588e312018-09-18 12:32:24 -0700929 if (mUseScheduler) {
930 mScheduler->getDisplayStatInfo(stats);
931 } else {
932 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
933 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
934 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700935 return NO_ERROR;
936}
937
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700938int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
939 const auto display = getDisplayDevice(displayToken);
940 if (!display) {
941 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800942 return BAD_VALUE;
943 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700944
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700945 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700946}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700947
Ana Krulec7d1d6832018-12-27 11:10:09 -0800948status_t SurfaceFlinger::setActiveConfigAsync(const sp<IBinder>& displayToken, int mode) {
949 ATRACE_NAME("setActiveConfigAsync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800950 postMessageAsync(new LambdaMessage(
951 [=]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800952 return NO_ERROR;
953}
954
955status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
956 ATRACE_NAME("setActiveConfigSync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800957 postMessageSync(new LambdaMessage(
958 [&]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800959 return NO_ERROR;
960}
961
962void SurfaceFlinger::setActiveConfigInternal(const sp<IBinder>& displayToken, int mode) {
963 Vector<DisplayInfo> configs;
964 getDisplayConfigs(displayToken, &configs);
965 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
966 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
967 return;
968 }
969
970 const auto display = getDisplayDevice(displayToken);
971 if (!display) {
972 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
973 displayToken.get());
974 return;
975 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700976 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800977 ALOGW("Attempt to set active config %d for virtual display", mode);
978 return;
979 }
980 int currentDisplayPowerMode = display->getPowerMode();
981 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
982 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700983 return;
984 }
985
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700986 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700987 if (mode == currentMode) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800988 // Don't update config if we are already running in the desired mode.
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700989 return;
990 }
991
Dominik Laskowski075d3172018-05-24 15:50:06 -0700992 const auto displayId = display->getId();
993 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700994
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700995 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700996 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700997
Ana Krulec7d1d6832018-12-27 11:10:09 -0800998 ATRACE_INT("ActiveConfigMode", mode);
Dominik Laskowski83b88212018-12-11 13:34:06 -0800999 resyncToHardwareVsync(true, getVsyncPeriod());
Mathias Agopianc666cae2012-07-25 18:56:13 -07001000}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001001
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001002status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1003 Vector<ColorMode>* outColorModes) {
1004 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001005 return BAD_VALUE;
1006 }
1007
Dominik Laskowski075d3172018-05-24 15:50:06 -07001008 const auto displayId = getPhysicalDisplayId(displayToken);
1009 if (!displayId) {
1010 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -07001011 }
1012
Peiyong Lina52f0292018-03-14 17:26:31 -07001013 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001014 {
1015 ConditionalLock _l(mStateLock,
1016 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001017 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001018 }
Michael Wright28f24d02016-07-12 13:30:53 -07001019 outColorModes->clear();
1020 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1021
1022 return NO_ERROR;
1023}
1024
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001025ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1026 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001027 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001028 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001029 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001030}
1031
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001032status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001033 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001034 Vector<ColorMode> modes;
1035 getDisplayColorModes(displayToken, &modes);
1036 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1037 if (mode < ColorMode::NATIVE || !exists) {
1038 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1039 decodeColorMode(mode).c_str(), mode, displayToken.get());
1040 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001041 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001042 const auto display = getDisplayDevice(displayToken);
1043 if (!display) {
1044 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1045 decodeColorMode(mode).c_str(), mode, displayToken.get());
1046 } else if (display->isVirtual()) {
1047 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1048 decodeColorMode(mode).c_str(), mode);
1049 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001050 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1051 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001052 }
1053 }));
1054
Michael Wright28f24d02016-07-12 13:30:53 -07001055 return NO_ERROR;
1056}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001057
Svetoslavd85084b2014-03-20 10:28:31 -07001058status_t SurfaceFlinger::clearAnimationFrameStats() {
1059 Mutex::Autolock _l(mStateLock);
1060 mAnimFrameTracker.clearStats();
1061 return NO_ERROR;
1062}
1063
1064status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1065 Mutex::Autolock _l(mStateLock);
1066 mAnimFrameTracker.getStats(outStats);
1067 return NO_ERROR;
1068}
1069
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001070status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1071 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001072 Mutex::Autolock _l(mStateLock);
1073
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001074 const auto display = getDisplayDeviceLocked(displayToken);
1075 if (!display) {
1076 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001077 return BAD_VALUE;
1078 }
1079
Peiyong Linfb069302018-04-25 14:34:31 -07001080 // At this point the DisplayDeivce should already be set up,
1081 // meaning the luminance information is already queried from
1082 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001083 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001084 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1085 capabilities.getDesiredMaxLuminance(),
1086 capabilities.getDesiredMaxAverageLuminance(),
1087 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001088
1089 return NO_ERROR;
1090}
1091
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001092status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1093 ui::PixelFormat* outFormat,
1094 ui::Dataspace* outDataspace,
1095 uint8_t* outComponentMask) const {
1096 if (!outFormat || !outDataspace || !outComponentMask) {
1097 return BAD_VALUE;
1098 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001099 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001100 if (!display || !display->getId()) {
1101 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1102 return BAD_VALUE;
1103 }
1104 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1105 outDataspace, outComponentMask);
1106}
1107
Kevin DuBois74e53772018-11-19 10:52:38 -08001108status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1109 bool enable, uint8_t componentMask,
1110 uint64_t maxFrames) const {
1111 const auto display = getDisplayDevice(displayToken);
1112 if (!display || !display->getId()) {
1113 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1114 return BAD_VALUE;
1115 }
1116
1117 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1118 componentMask, maxFrames);
1119}
1120
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001121status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1122 uint64_t maxFrames, uint64_t timestamp,
1123 DisplayedFrameStats* outStats) const {
1124 const auto display = getDisplayDevice(displayToken);
1125 if (!display || !display->getId()) {
1126 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1127 return BAD_VALUE;
1128 }
1129
1130 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1131 outStats);
1132}
1133
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001134status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1135 if (!outSupported) {
1136 return BAD_VALUE;
1137 }
1138 *outSupported = getRenderEngine().supportsProtectedContent();
1139 return NO_ERROR;
1140}
1141
Marissa Wallebc2c052019-01-16 19:16:55 -08001142status_t SurfaceFlinger::cacheBuffer(const sp<IBinder>& token, const sp<GraphicBuffer>& buffer,
1143 int32_t* outBufferId) {
1144 if (!outBufferId) {
1145 return BAD_VALUE;
1146 }
1147 *outBufferId = mBufferStateLayerCache.add(token, buffer);
1148 return NO_ERROR;
1149}
1150
1151status_t SurfaceFlinger::uncacheBuffer(const sp<IBinder>& token, int32_t bufferId) {
1152 mBufferStateLayerCache.release(token, bufferId);
1153 return NO_ERROR;
1154}
1155
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001156status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001157 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001158 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001159
Chia-I Wu90f669f2017-10-05 14:24:41 -07001160 if (mInjectVSyncs == enable) {
1161 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001162 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001163
Dominik Laskowski83b88212018-12-11 13:34:06 -08001164 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001165
Ana Krulec98b5b242018-08-10 15:03:23 -07001166 // TODO(akrulec): Part of the Injector should be refactored, so that it
1167 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001168 if (enable) {
1169 ALOGV("VSync Injections enabled");
1170 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001171 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001172 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001173 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001174 impl::EventThread::InterceptVSyncsCallback(),
1175 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001176 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001177 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001178 } else {
1179 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001180 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001181 }
1182
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001183 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001184 }));
1185
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001186 return NO_ERROR;
1187}
1188
1189status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001190 Mutex::Autolock _l(mStateLock);
1191
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001192 if (!mInjectVSyncs) {
1193 ALOGE("VSync Injections not enabled");
1194 return BAD_VALUE;
1195 }
1196 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1197 ALOGV("Injecting VSync inside SurfaceFlinger");
1198 mVSyncInjector->onInjectSyncEvent(when);
1199 }
1200 return NO_ERROR;
1201}
1202
Lloyd Pique755e3192018-01-31 16:46:15 -08001203status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1204 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001205 // Try to acquire a lock for 1s, fail gracefully
1206 const status_t err = mStateLock.timedLock(s2ns(1));
1207 const bool locked = (err == NO_ERROR);
1208 if (!locked) {
1209 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1210 return TIMED_OUT;
1211 }
1212
1213 outLayers->clear();
1214 mCurrentState.traverseInZOrder([&](Layer* layer) {
1215 outLayers->push_back(layer->getLayerDebugInfo());
1216 });
1217
1218 mStateLock.unlock();
1219 return NO_ERROR;
1220}
1221
Peiyong Linc6780972018-10-28 15:24:08 -07001222status_t SurfaceFlinger::getCompositionPreference(
1223 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1224 Dataspace* outWideColorGamutDataspace,
1225 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001226 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001227 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001228 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001229 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001230 return NO_ERROR;
1231}
1232
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001233// ----------------------------------------------------------------------------
1234
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001235sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1236 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001237 auto resyncCallback = makeResyncCallback([this] {
1238 Mutex::Autolock lock(mStateLock);
1239 return getVsyncPeriod();
1240 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001241
Ana Krulec98b5b242018-08-10 15:03:23 -07001242 if (mUseScheduler) {
1243 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001244 return mScheduler->createDisplayEventConnection(mSfConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001245 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001246 return mScheduler->createDisplayEventConnection(mAppConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001247 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001248 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001249 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001250 return mSFEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001251 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001252 return mEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001253 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001254 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001255}
1256
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001257// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001258
1259void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001260 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001261}
1262
1263void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001264 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001265}
1266
1267void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001268 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001269}
1270
1271void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001272 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001273 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001274}
1275
1276status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001277 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001278 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001279}
1280
1281status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001282 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001283 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001284 if (res == NO_ERROR) {
1285 msg->wait();
1286 }
1287 return res;
1288}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001289
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001290void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001291 do {
1292 waitForEvent();
1293 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001294}
1295
Dominik Laskowski83b88212018-12-11 13:34:06 -08001296nsecs_t SurfaceFlinger::getVsyncPeriod() const {
1297 const auto displayId = getInternalDisplayId();
1298 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1299 return 0;
1300 }
1301
1302 const auto config = getHwComposer().getActiveConfig(*displayId);
1303 return config ? config->getVsyncPeriod() : 0;
1304}
1305
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001306void SurfaceFlinger::enableHardwareVsync() {
1307 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001308 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001309 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001310 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001311 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001312 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001313}
1314
Dominik Laskowski83b88212018-12-11 13:34:06 -08001315void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001316 Mutex::Autolock _l(mHWVsyncLock);
1317
Jesse Hall948fe0c2013-10-14 12:56:09 -07001318 if (makeAvailable) {
1319 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001320 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1321 if (mUseScheduler) {
1322 mScheduler->makeHWSyncAvailable(true);
1323 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001324 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001325 // Hardware vsync is not currently available, so abort the resync
1326 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001327 return;
1328 }
1329
Dominik Laskowski83b88212018-12-11 13:34:06 -08001330 if (period <= 0) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001331 return;
1332 }
1333
Ana Krulece588e312018-09-18 12:32:24 -07001334 if (mUseScheduler) {
1335 mScheduler->setVsyncPeriod(period);
1336 } else {
1337 mPrimaryDispSync->reset();
1338 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001339
Ana Krulece588e312018-09-18 12:32:24 -07001340 if (!mPrimaryHWVsyncEnabled) {
1341 mPrimaryDispSync->beginResync();
1342 mEventControlThread->setVsyncEnabled(true);
1343 mPrimaryHWVsyncEnabled = true;
1344 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001345 }
1346}
1347
Jesse Hall948fe0c2013-10-14 12:56:09 -07001348void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001349 Mutex::Autolock _l(mHWVsyncLock);
1350 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001351 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001352 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001353 mPrimaryHWVsyncEnabled = false;
1354 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001355 if (makeUnavailable) {
1356 mHWVsyncAvailable = false;
1357 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001358}
1359
Dominik Laskowski83b88212018-12-11 13:34:06 -08001360void SurfaceFlinger::VsyncState::resync(const GetVsyncPeriod& getVsyncPeriod) {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001361 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001362
Dan Stoza57164302017-05-08 14:03:54 -07001363 const nsecs_t now = systemTime();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001364 const nsecs_t last = lastResyncTime.exchange(now);
1365
1366 if (now - last > kIgnoreDelay) {
1367 flinger.resyncToHardwareVsync(false, getVsyncPeriod());
Tim Murray4a4e4a22016-04-19 16:29:23 +00001368 }
1369}
1370
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001371void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1372 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001373 ATRACE_NAME("SF onVsync");
1374
Steven Thomas3cfac282017-02-06 12:29:30 -08001375 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001376 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001377 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001378 return;
1379 }
1380
Dominik Laskowski075d3172018-05-24 15:50:06 -07001381 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001382 return;
1383 }
1384
Dominik Laskowski075d3172018-05-24 15:50:06 -07001385 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001386 // For now, we don't do anything with external display vsyncs.
1387 return;
1388 }
1389
Ana Krulece588e312018-09-18 12:32:24 -07001390 if (mUseScheduler) {
1391 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001392 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001393 bool needsHwVsync = false;
1394 { // Scope for the lock
1395 Mutex::Autolock _l(mHWVsyncLock);
1396 if (mPrimaryHWVsyncEnabled) {
1397 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1398 }
1399 }
1400
1401 if (needsHwVsync) {
1402 enableHardwareVsync();
1403 } else {
1404 disableHardwareVsync(false);
1405 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001406 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001407}
1408
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001409void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001410 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1411 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001412}
1413
Ana Krulec7d1d6832018-12-27 11:10:09 -08001414void SurfaceFlinger::setRefreshRateTo(float newFps) {
1415 const auto displayId = getInternalDisplayId();
1416 if (!displayId || mBootStage != BootStage::FINISHED) {
1417 return;
1418 }
1419 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1420 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1421 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1422 // refresh cycle.
1423
1424 // Don't do any updating if the current fps is the same as the new one.
1425 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
1426 const nsecs_t currentVsyncPeriod = activeConfig->getVsyncPeriod();
1427 if (currentVsyncPeriod == 0) {
1428 return;
1429 }
1430 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1431 // floating numbers.
1432 const float currentFps = 1e9 / currentVsyncPeriod;
1433 if (std::abs(currentFps - newFps) <= 1) {
1434 return;
1435 }
1436
1437 auto configs = getHwComposer().getConfigs(*displayId);
1438 for (int i = 0; i < configs.size(); i++) {
1439 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1440 if (vsyncPeriod == 0) {
1441 continue;
1442 }
1443 const float fps = 1e9 / vsyncPeriod;
1444 // TODO(b/113612090): There should be a better way at determining which config
1445 // has the right refresh rate.
1446 if (std::abs(fps - newFps) <= 1) {
1447 const auto display = getBuiltInDisplay(HWC_DISPLAY_PRIMARY);
1448 if (!display) return;
1449 // This is posted in async function to avoid deadlock when getDisplayDevice
1450 // requires mStateLock.
1451 setActiveConfigAsync(display, i);
1452 ATRACE_INT("FPS", newFps);
1453 }
1454 }
1455}
1456
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001457void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001458 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001459 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001460 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001461
Lloyd Piqueba04e622017-12-14 17:11:26 -08001462 // Ignore events that do not have the right sequenceId.
1463 if (sequenceId != getBE().mComposerSequenceId) {
1464 return;
1465 }
1466
Steven Thomasb02664d2017-07-26 18:48:28 -07001467 // Only lock if we're not on the main thread. This function is normally
1468 // called on a hwbinder thread, but for the primary display it's called on
1469 // the main thread with the state lock already held, so don't attempt to
1470 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001471 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001472
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001473 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001474
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001475 if (std::this_thread::get_id() == mMainThreadId) {
1476 // Process all pending hot plug events immediately if we are on the main thread.
1477 processDisplayHotplugEventsLocked();
1478 }
1479
Lloyd Piqueba04e622017-12-14 17:11:26 -08001480 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001481}
1482
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001483void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001484 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001485 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001486 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001487 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001488 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001489}
1490
Dominik Laskowski075d3172018-05-24 15:50:06 -07001491void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001492 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001493 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001494 if (const auto displayId = getInternalDisplayId()) {
1495 getHwComposer().setVsyncEnabled(*displayId,
1496 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1497 }
Mathias Agopian86303202012-07-24 22:46:10 -07001498}
1499
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001500// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001501void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001502 if (mUseScheduler) {
1503 mScheduler->disableHardwareVsync(true);
1504 } else {
1505 disableHardwareVsync(true);
1506 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001507 // Clear the drawing state so that the logic inside of
1508 // handleTransactionLocked will fire. It will determine the delta between
1509 // mCurrentState and mDrawingState and re-apply all changes when we make the
1510 // transition.
1511 mDrawingState.displays.clear();
1512 mDisplays.clear();
1513}
1514
Steven Thomas050b2c82017-03-06 11:45:16 -08001515void SurfaceFlinger::updateVrFlinger() {
1516 if (!mVrFlinger)
1517 return;
1518 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001519 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001520 return;
1521 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001522
Lloyd Pique441d5042018-10-18 16:49:51 -07001523 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001524 ALOGE("Vr flinger is only supported for remote hardware composer"
1525 " service connections. Ignoring request to transition to vr"
1526 " flinger.");
1527 mVrFlingerRequestsDisplay = false;
1528 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001529 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001530
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001531 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001532
Steven Thomas0123ac62018-07-12 11:32:34 -07001533 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001534 LOG_ALWAYS_FATAL_IF(!display);
1535 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001536 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1537 // called below. Clear the reference now so we don't accidentally use it
1538 // later.
1539 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001540
Steven Thomasb02664d2017-07-26 18:48:28 -07001541 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001542 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001543 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001544
Steven Thomasb02664d2017-07-26 18:48:28 -07001545 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001546 // Delete the current instance before creating the new one
1547 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1548 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1549 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1550 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001551
Lloyd Pique441d5042018-10-18 16:49:51 -07001552 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001553 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001554
1555 if (vrFlingerRequestsDisplay) {
1556 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001557 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001558
1559 mVisibleRegionsDirty = true;
1560 invalidateHwcGeometry();
1561
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001562 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001563 display = getDefaultDisplayDeviceLocked();
1564 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001565 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001566
Steven Thomasb02664d2017-07-26 18:48:28 -07001567 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001568 const nsecs_t vsyncPeriod = getVsyncPeriod();
1569 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001570
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001571 // The present fences returned from vr_hwc are not an accurate
1572 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001573 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001574 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1575 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001576 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001577 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001578 !hasSyncFramework);
1579 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001580
Steven Thomasb02664d2017-07-26 18:48:28 -07001581 // Use phase of 0 since phase is not known.
1582 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001583 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001584 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001585
Dominik Laskowski83b88212018-12-11 13:34:06 -08001586 resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001587
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001588 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001589 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001590}
1591
Mathias Agopian4fec8732012-06-29 14:12:52 -07001592void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001593 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001594 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001595 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001596 if (mUseScheduler) {
1597 // This call is made each time SF wakes up and creates a new frame.
1598 mScheduler->incrementFrameCounter();
1599 }
Dan Stoza50182882016-07-08 12:02:20 -07001600 bool frameMissed = !mHadClientComposition &&
1601 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001602 (mPreviousPresentFence->getSignalTime() ==
1603 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001604 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001605 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001606 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001607 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001608 if (mPropagateBackpressure) {
1609 signalLayerUpdate();
1610 break;
1611 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001612 }
Dan Stoza50182882016-07-08 12:02:20 -07001613
Steven Thomas050b2c82017-03-06 11:45:16 -08001614 // Now that we're going to make it to the handleMessageTransaction()
1615 // call below it's safe to call updateVrFlinger(), which will
1616 // potentially trigger a display handoff.
1617 updateVrFlinger();
1618
Dan Stoza6b9454d2014-11-07 16:00:59 -08001619 bool refreshNeeded = handleMessageTransaction();
1620 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001621 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001622 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001623 // Signal a refresh if a transaction modified the window state,
1624 // a new buffer was latched, or if HWC has requested a full
1625 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001626 signalRefresh();
1627 }
1628 break;
1629 }
1630 case MessageQueue::REFRESH: {
1631 handleMessageRefresh();
1632 break;
1633 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001634 }
1635}
1636
Dan Stoza6b9454d2014-11-07 16:00:59 -08001637bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001638 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001639
1640 // Apply any ready transactions in the queues if there are still transactions that have not been
1641 // applied, wake up during the next vsync period and check again
1642 bool transactionNeeded = false;
1643 if (!flushTransactionQueues()) {
1644 transactionNeeded = true;
1645 }
1646
Mathias Agopian4fec8732012-06-29 14:12:52 -07001647 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001648 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001649 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001650
1651 if (transactionNeeded) {
1652 setTransactionFlags(eTransactionNeeded);
1653 }
1654
1655 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001656}
1657
Mathias Agopian4fec8732012-06-29 14:12:52 -07001658void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001659 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001660
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001661 mRefreshPending = false;
1662
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001663 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001664 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001665 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001666 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001667 for (const auto& [token, display] : mDisplays) {
1668 beginFrame(display);
1669 prepareFrame(display);
1670 doDebugFlashRegions(display, repaintEverything);
1671 doComposition(display, repaintEverything);
1672 }
1673
Adrian Roos1e1a1282017-11-01 19:05:31 +01001674 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001675 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001676
1677 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001678 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001679
Dan Stozabfbffeb2016-07-21 14:49:33 -07001680 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001681 for (const auto& [token, displayDevice] : mDisplays) {
1682 auto display = displayDevice->getCompositionDisplay();
1683 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001684 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001685 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001686 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001687
Alec Mouri86770e52018-09-24 22:40:58 +00001688 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001689 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001690 if (mHadClientComposition) {
1691 base::unique_fd flushFence(getRenderEngine().flush());
1692 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1693 getBE().flushFence = new Fence(std::move(flushFence));
1694 } else {
1695 // Cleanup for hygiene.
1696 getBE().flushFence = Fence::NO_FENCE;
1697 }
1698 }
1699
Jorim Jaggi90535212018-05-23 23:44:06 +02001700 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001701
David Sodman7e4ae112018-02-09 15:02:28 -08001702 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001703 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001704 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001705 compositionInfo.hwc.hwcLayer = nullptr;
1706 }
David Sodmanba340492018-08-05 21:51:33 -07001707 }
David Sodman7e4ae112018-02-09 15:02:28 -08001708
1709 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001710}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001711
David Sodmanfa9b2af2017-12-24 13:28:59 -08001712
1713bool SurfaceFlinger::handleMessageInvalidate() {
1714 ATRACE_CALL();
1715 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001716}
1717
David Sodman79bba0e2018-08-05 18:07:49 -07001718void SurfaceFlinger::calculateWorkingSet() {
1719 ATRACE_CALL();
1720 ALOGV(__FUNCTION__);
1721
David Sodman79bba0e2018-08-05 18:07:49 -07001722 // build the h/w work list
1723 if (CC_UNLIKELY(mGeometryInvalid)) {
1724 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001725 for (const auto& [token, displayDevice] : mDisplays) {
1726 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001727 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001728 if (!displayId) {
1729 continue;
1730 }
David Sodman79bba0e2018-08-05 18:07:49 -07001731
Lloyd Pique32cbe282018-10-19 13:09:22 -07001732 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001733 for (size_t i = 0; i < currentLayers.size(); i++) {
1734 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001735
Dominik Laskowski075d3172018-05-24 15:50:06 -07001736 if (!layer->hasHwcLayer(*displayId)) {
1737 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1738 layer->forceClientComposition(*displayId);
1739 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001740 }
1741 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001742
Lloyd Pique32cbe282018-10-19 13:09:22 -07001743 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001744 if (mDebugDisableHWC || mDebugRegion) {
1745 layer->forceClientComposition(*displayId);
1746 }
David Sodman79bba0e2018-08-05 18:07:49 -07001747 }
1748 }
1749 }
1750
1751 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001752 for (const auto& [token, displayDevice] : mDisplays) {
1753 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001754 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001755 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001756 continue;
1757 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001758 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001759
1760 if (mDrawingState.colorMatrixChanged) {
1761 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001762 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001763 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001764 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001765 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001766 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1767 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001768 !profile->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001769 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001770 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1771 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001772 !profile->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001773 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001774 }
1775
Peiyong Lind3788632018-09-18 16:01:31 -07001776 // TODO(b/111562338) remove when composer 2.3 is shipped.
1777 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001778 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001779 }
1780
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001781 if (layer->getRoundedCornerState().radius > 0.0f) {
1782 layer->forceClientComposition(*displayId);
1783 }
1784
Dominik Laskowski075d3172018-05-24 15:50:06 -07001785 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001786 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001787 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001788 continue;
1789 }
1790
Lloyd Pique32cbe282018-10-19 13:09:22 -07001791 const auto& displayState = display->getState();
1792 layer->setPerFrameData(*displayId, displayState.transform, displayState.viewport,
1793 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001794 }
1795
Peiyong Lin13effd12018-07-24 17:01:47 -07001796 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001797 ColorMode colorMode;
1798 Dataspace dataSpace;
1799 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001800 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001801 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001802 }
1803 }
1804
1805 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001806
1807 for (const auto& [token, display] : mDisplays) {
1808 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001809 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001810 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001811
1812 if (displayId) {
1813 if (!layer->setHwcLayer(*displayId)) {
1814 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1815 }
1816 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001817 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001818
Dominik Laskowski05275f12018-11-01 15:03:24 -07001819 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001820 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1821 }
1822 }
David Sodman79bba0e2018-08-05 18:07:49 -07001823}
1824
Lloyd Pique32cbe282018-10-19 13:09:22 -07001825void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1826 bool repaintEverything) {
1827 auto display = displayDevice->getCompositionDisplay();
1828 const auto& displayState = display->getState();
1829
Mathias Agopiancd60f992012-08-16 16:28:27 -07001830 // is debugging enabled
1831 if (CC_LIKELY(!mDebugRegion))
1832 return;
1833
Lloyd Pique32cbe282018-10-19 13:09:22 -07001834 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001835 // transform the dirty region into this screen's coordinate space
Lloyd Pique32cbe282018-10-19 13:09:22 -07001836 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001837 if (!dirtyRegion.isEmpty()) {
1838 // redraw the whole screen
Lloyd Pique32cbe282018-10-19 13:09:22 -07001839 doComposeSurfaces(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001840
David Sodmanfa9b2af2017-12-24 13:28:59 -08001841 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001842 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001843 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001844
Lloyd Pique31cb2942018-10-19 17:23:03 -07001845 display->getRenderSurface()->queueBuffer();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001846 }
1847 }
1848
Lloyd Pique32cbe282018-10-19 13:09:22 -07001849 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001850
1851 if (mDebugRegion > 1) {
1852 usleep(mDebugRegion * 1000);
1853 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001854
Lloyd Pique32cbe282018-10-19 13:09:22 -07001855 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001856}
1857
Adrian Roos1e1a1282017-11-01 19:05:31 +01001858void SurfaceFlinger::doTracing(const char* where) {
1859 ATRACE_CALL();
1860 ATRACE_NAME(where);
1861 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001862 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001863 }
1864}
1865
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001866void SurfaceFlinger::logLayerStats() {
1867 ATRACE_CALL();
1868 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001869 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001870 if (display->isPrimary()) {
1871 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001872 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001873 }
1874 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001875
1876 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001877 }
1878}
1879
David Sodman2b406362017-12-15 13:33:47 -08001880void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001881{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001882 ATRACE_CALL();
1883 ALOGV("preComposition");
1884
David Sodman2b406362017-12-15 13:33:47 -08001885 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1886
Mathias Agopiancd60f992012-08-16 16:28:27 -07001887 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001888 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001889 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001890 needExtraInvalidate = true;
1891 }
Robert Carr2047fae2016-11-28 14:09:09 -08001892 });
1893
Mathias Agopiancd60f992012-08-16 16:28:27 -07001894 if (needExtraInvalidate) {
1895 signalLayerUpdate();
1896 }
1897}
1898
Ana Krulece588e312018-09-18 12:32:24 -07001899void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1900 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001901 // Update queue of past composite+present times and determine the
1902 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001903 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001904 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001905 while (!getBE().mCompositePresentTimes.empty()) {
1906 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001907 // Cached values should have been updated before calling this method,
1908 // which helps avoid duplicate syscalls.
1909 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1910 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1911 break;
1912 }
1913 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001914 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001915 }
1916
1917 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001918 while (getBE().mCompositePresentTimes.size() > 16) {
1919 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001920 }
1921
Ana Krulece588e312018-09-18 12:32:24 -07001922 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001923}
1924
Ana Krulece588e312018-09-18 12:32:24 -07001925void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1926 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001927 // Integer division and modulo round toward 0 not -inf, so we need to
1928 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001929 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1930 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1931 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001932
Brian Andersond0010582017-03-07 13:20:31 -08001933 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1934 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001935 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001936 }
1937
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001938 // Snap the latency to a value that removes scheduling jitter from the
1939 // composition and present times, which often have >1ms of jitter.
1940 // Reducing jitter is important if an app attempts to extrapolate
1941 // something (such as user input) to an accurate diasplay time.
1942 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1943 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001944 nsecs_t bias = stats.vsyncPeriod / 2;
1945 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1946 nsecs_t snappedCompositeToPresentLatency =
1947 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001948
David Sodman99974d22017-11-28 12:04:33 -08001949 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001950 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1951 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001952 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001953}
1954
Ady Abraham8164d482019-01-11 14:47:59 -08001955// debug patch for b/119477596 - add stack guards to catch stack
1956// corruptions and disable clang optimizations.
1957// The code below is temporary and planned to be removed once stack
1958// corruptions are found.
1959#pragma clang optimize off
1960class StackGuard {
1961public:
1962 StackGuard(const char* name, const char* func, int line) {
1963 guarders.reserve(MIN_CAPACITY);
1964 guarders.push_back({this, name, func, line});
1965 validate();
1966 }
1967 ~StackGuard() {
1968 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1969 if (i->guard == this) {
1970 guarders.erase(i);
1971 break;
1972 }
1973 }
1974 }
1975
1976 static void validate() {
1977 for (const auto& guard : guarders) {
1978 if (guard.guard->cookie != COOKIE_VALUE) {
1979 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1980 CallStack stack(LOG_TAG);
1981 abort();
1982 }
1983 }
1984 }
1985
1986private:
1987 uint64_t cookie = COOKIE_VALUE;
1988 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
1989 static constexpr size_t MIN_CAPACITY = 16;
1990
1991 struct GuarderElement {
1992 StackGuard* guard;
1993 const char* name;
1994 const char* func;
1995 int line;
1996 };
1997
1998 static std::vector<GuarderElement> guarders;
1999};
2000std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2001
2002#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2003
2004#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002005void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002006{
Ady Abraham8164d482019-01-11 14:47:59 -08002007 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002008 ATRACE_CALL();
2009 ALOGV("postComposition");
2010
Brian Anderson3546a3f2016-07-14 11:51:14 -07002011 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002012 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002013 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002014 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002015 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002016 }
Ady Abraham8164d482019-01-11 14:47:59 -08002017 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002018
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002019 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002020 const auto displayDevice = getDefaultDisplayDeviceLocked();
2021 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002022
David Sodman73beded2017-11-15 11:56:06 -08002023 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002024 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002025 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2026
Lloyd Pique32cbe282018-10-19 13:09:22 -07002027 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002028 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002029 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2030 ->getRenderSurface()
2031 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002032 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002033 } else {
2034 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2035 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002036
Ady Abraham8164d482019-01-11 14:47:59 -08002037 ASSERT_ON_STACK_GUARD();
2038
David Sodman73beded2017-11-15 11:56:06 -08002039 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002040 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2041 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002042 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002043 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002044 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002045
Ana Krulece588e312018-09-18 12:32:24 -07002046 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002047 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002048 if (mUseScheduler) {
2049 mScheduler->getDisplayStatInfo(&stats);
2050 } else {
2051 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2052 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2053 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002054
Ady Abraham8164d482019-01-11 14:47:59 -08002055 ASSERT_ON_STACK_GUARD();
2056
David Sodman2b406362017-12-15 13:33:47 -08002057 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002058 // when we started doing work for this frame, but that should be okay
2059 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002060 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002061 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002062 DEFINE_STACK_GUARD(compositorTiming);
2063
Brian Andersond0010582017-03-07 13:20:31 -08002064 {
David Sodman99974d22017-11-28 12:04:33 -08002065 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002066 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002067 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002068
2069 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002070 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002071
Robert Carr2047fae2016-11-28 14:09:09 -08002072 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002073 bool frameLatched =
2074 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2075 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002076 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002077 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002078 recordBufferingStats(layer->getName().string(),
2079 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002080 }
Ady Abraham8164d482019-01-11 14:47:59 -08002081 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002082 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002083
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002084 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002085 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002086 if (mUseScheduler) {
2087 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002088 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002089 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002090 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2091 enableHardwareVsync();
2092 } else {
2093 disableHardwareVsync(false);
2094 }
Ady Abraham8164d482019-01-11 14:47:59 -08002095 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002096 }
2097 }
2098
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002099 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002100 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2101 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002102 if (mUseScheduler) {
2103 mScheduler->enableHardwareVsync();
2104 } else {
2105 enableHardwareVsync();
2106 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002107 }
2108 }
2109
Ady Abraham8164d482019-01-11 14:47:59 -08002110 ASSERT_ON_STACK_GUARD();
2111
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002112 if (mAnimCompositionPending) {
2113 mAnimCompositionPending = false;
2114
Brian Anderson4e606e32017-03-16 15:34:57 -07002115 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002116 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002117 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002118
2119 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002120 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002121 // The HWC doesn't support present fences, so use the refresh
2122 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002123 const nsecs_t presentTime =
2124 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002125 DEFINE_STACK_GUARD(presentTime);
2126
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002127 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002128 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002129 }
2130 mAnimFrameTracker.advanceFrame();
2131 }
Dan Stozab90cf072015-03-05 11:05:59 -08002132
Ady Abraham8164d482019-01-11 14:47:59 -08002133 ASSERT_ON_STACK_GUARD();
2134
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002135 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002136 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002137 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002138 }
2139
Ady Abraham8164d482019-01-11 14:47:59 -08002140 ASSERT_ON_STACK_GUARD();
2141
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002142 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002143
Ady Abraham8164d482019-01-11 14:47:59 -08002144 ASSERT_ON_STACK_GUARD();
2145
Lloyd Pique32cbe282018-10-19 13:09:22 -07002146 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2147 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002148 return;
2149 }
2150
2151 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002152 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002153 if (mHasPoweredOff) {
2154 mHasPoweredOff = false;
2155 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002156 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002157 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002158 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002159 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002160 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2161 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002162 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002163 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002164 }
David Sodman4a36e932017-11-07 14:29:47 -08002165 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002166
2167 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002168 }
David Sodman4a36e932017-11-07 14:29:47 -08002169 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002170 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002171
2172 {
2173 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002174 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002175 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002176 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002177 if (refillCount > 0) {
2178 const size_t offset = mTexturePool.size();
2179 mTexturePool.resize(mTexturePoolSize);
2180 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2181 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2182 }
Ady Abraham8164d482019-01-11 14:47:59 -08002183 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002184 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002185
Marissa Wallfda30bb2018-10-12 11:34:28 -07002186 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002187 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002188
2189 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002190}
Ady Abraham8164d482019-01-11 14:47:59 -08002191#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002192
2193void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002194 ATRACE_CALL();
2195 ALOGV("rebuildLayerStacks");
2196
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002197 // We need to clear these out now as these may be holding on to a
2198 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2199 // also holds a reference. When the set of visible layers is recomputed,
2200 // some layers may be destroyed if the only thing keeping them alive was
2201 // that list of visible layers associated with each display. The layer
2202 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2203 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2204 for (const auto& [token, display] : mDisplays) {
2205 getBE().mCompositionInfo[token].clear();
2206 }
2207
Mathias Agopiancd60f992012-08-16 16:28:27 -07002208 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002209 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002210 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002211 mVisibleRegionsDirty = false;
2212 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002213
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002214 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002215 const auto& displayDevice = pair.second;
2216 auto display = displayDevice->getCompositionDisplay();
2217 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002218 Region opaqueRegion;
2219 Region dirtyRegion;
2220 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002221 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002222 const ui::Transform& tr = displayState.transform;
2223 const Rect bounds = displayState.bounds;
2224 if (displayState.isEnabled) {
2225 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002226
Jeff Sharkey76488112017-02-27 14:15:18 -07002227 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002228 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002229 const auto displayId = displayDevice->getId();
2230 if (display->belongsInOutput(layer->getLayerStack())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002231 Region drawRegion(tr.transform(
2232 layer->visibleNonTransparentRegion));
2233 drawRegion.andSelf(bounds);
2234 if (!drawRegion.isEmpty()) {
2235 layersSortedByZ.add(layer);
2236 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002237 // Clear out the HWC layer if this layer was
2238 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002239 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002240 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002241 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002242 // WM changes display->layerStack upon sleep/awake.
2243 // Here we make sure we delete the HWC layers even if
2244 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002245 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002246 }
2247
2248 // If a layer is not going to get a release fence because
2249 // it is invisible, but it is also going to release its
2250 // old buffer, add it to the list of layers needing
2251 // fences.
2252 if (hwcLayerDestroyed) {
2253 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2254 mLayersWithQueuedFrames.cend(), layer);
2255 if (found != mLayersWithQueuedFrames.cend()) {
2256 layersNeedingFences.add(layer);
2257 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002258 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002259 });
2260 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002261 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
2262 displayDevice->setLayersNeedingFences(layersNeedingFences);
2263
2264 Region undefinedRegion{bounds};
2265 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2266
2267 display->editState().undefinedRegion = undefinedRegion;
2268 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002269 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002270 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002271}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002272
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002273// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002274// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002275// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002276// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002277// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002278// The returned HDR data space is one of
2279// - Dataspace::UNKNOWN
2280// - Dataspace::BT2020_HLG
2281// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002282Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2283 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002284 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002285 *outHdrDataSpace = Dataspace::UNKNOWN;
2286
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002287 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002288 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002289 case Dataspace::V0_SCRGB:
2290 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002291 case Dataspace::BT2020:
2292 case Dataspace::BT2020_ITU:
2293 case Dataspace::BT2020_LINEAR:
2294 case Dataspace::DISPLAY_BT2020:
2295 bestDataSpace = Dataspace::DISPLAY_BT2020;
2296 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002297 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002298 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002299 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002300 case Dataspace::BT2020_PQ:
2301 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002302 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002303 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002304 case Dataspace::BT2020_HLG:
2305 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002306 // When there's mixed PQ content and HLG content, we set the HDR
2307 // data space to be BT2020_PQ and convert HLG to PQ.
2308 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2309 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002310 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002311 break;
2312 default:
2313 break;
2314 }
Romain Guy54f154a2017-10-24 21:40:32 +01002315 }
2316
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002317 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002318}
2319
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002320// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002321void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2322 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002323 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2324 *outMode = ColorMode::NATIVE;
2325 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002326 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002327 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002328 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002329
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002330 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002331 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002332
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002333 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2334
Peiyong Lindfde5112018-06-05 10:58:41 -07002335 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002336 const bool isHdr =
2337 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002338 if (isHdr) {
2339 bestDataSpace = hdrDataSpace;
2340 }
2341
Chia-I Wu0d711262018-05-21 15:19:35 -07002342 RenderIntent intent;
2343 switch (mDisplayColorSetting) {
2344 case DisplayColorSetting::MANAGED:
2345 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002346 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002347 break;
2348 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002349 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002350 break;
2351 default: // vendor display color setting
2352 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2353 break;
2354 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002355
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002356 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002357}
2358
Lloyd Pique32cbe282018-10-19 13:09:22 -07002359void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2360 auto display = displayDevice->getCompositionDisplay();
2361 const auto& displayState = display->getState();
2362
2363 bool dirty = !display->getPhysicalSpaceDirtyRegion(false).isEmpty();
2364 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2365 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002366
David Sodmanfa9b2af2017-12-24 13:28:59 -08002367 // If nothing has changed (!dirty), don't recompose.
2368 // If something changed, but we don't currently have any visible layers,
2369 // and didn't when we last did a composition, then skip it this time.
2370 // The second rule does two things:
2371 // - When all layers are removed from a display, we'll emit one black
2372 // frame, then nothing more until we get new layers.
2373 // - When a display is created with a private layer stack, we won't
2374 // emit any black frames until a layer is added to the layer stack.
2375 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002376
Dominik Laskowski075d3172018-05-24 15:50:06 -07002377 const char flagPrefix[] = {'-', '+'};
2378 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002379 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2380 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2381 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2382 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002383
Lloyd Pique31cb2942018-10-19 17:23:03 -07002384 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002385
David Sodmanfa9b2af2017-12-24 13:28:59 -08002386 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002387 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002388 }
2389}
2390
Lloyd Pique32cbe282018-10-19 13:09:22 -07002391void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2392 auto display = displayDevice->getCompositionDisplay();
2393 const auto& displayState = display->getState();
2394
2395 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002396 return;
David Sodman2b406362017-12-15 13:33:47 -08002397 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002398
Lloyd Pique31cb2942018-10-19 17:23:03 -07002399 status_t result = display->getRenderSurface()->prepareFrame(
2400 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002401 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002402 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002403}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002404
Lloyd Pique32cbe282018-10-19 13:09:22 -07002405void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002406 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002407 ALOGV("doComposition");
2408
Lloyd Pique32cbe282018-10-19 13:09:22 -07002409 auto display = displayDevice->getCompositionDisplay();
2410 const auto& displayState = display->getState();
2411
2412 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002413 // transform the dirty region into this screen's coordinate space
Lloyd Pique32cbe282018-10-19 13:09:22 -07002414 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002415
David Sodmanfa9b2af2017-12-24 13:28:59 -08002416 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002417 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002418
Lloyd Pique32cbe282018-10-19 13:09:22 -07002419 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002420 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002421 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002422 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002423}
2424
David Sodmanfa9b2af2017-12-24 13:28:59 -08002425void SurfaceFlinger::postFrame()
2426{
2427 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002428 const auto display = getDefaultDisplayDeviceLocked();
2429 if (display && getHwComposer().isConnected(*display->getId())) {
2430 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002431 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2432 logFrameStats();
2433 }
2434 }
2435}
2436
Lloyd Pique32cbe282018-10-19 13:09:22 -07002437void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002438 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002439 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002440
Lloyd Pique32cbe282018-10-19 13:09:22 -07002441 auto display = displayDevice->getCompositionDisplay();
2442 const auto& displayState = display->getState();
2443 const auto displayId = display->getId();
2444
David Sodmanfa9b2af2017-12-24 13:28:59 -08002445 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002446
Lloyd Pique32cbe282018-10-19 13:09:22 -07002447 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002448 if (displayId) {
2449 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002450 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002451 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002452 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002453 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002454
Chia-I Wu7b549592017-11-15 09:14:57 -08002455 // The layer buffer from the previous frame (if any) is released
2456 // by HWC only when the release fence from this frame (if any) is
2457 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002458 if (displayId && layer->hasHwcLayer(*displayId)) {
2459 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2460 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002461 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002462
2463 // If the layer was client composited in the previous frame, we
2464 // need to merge with the previous client target acquire fence.
2465 // Since we do not track that, always merge with the current
2466 // client target acquire fence when it is available, even though
2467 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002468 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002469 releaseFence =
2470 Fence::merge("LayerRelease", releaseFence,
2471 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002472 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002473
David Sodman15094112018-10-11 09:39:37 -07002474 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002475 }
Chia-I Wu83806892017-11-16 10:50:20 -08002476
2477 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002478 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002479 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002480 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002481 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002482 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002483 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002484 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002485 }
2486 }
2487
Dominik Laskowski075d3172018-05-24 15:50:06 -07002488 if (displayId) {
2489 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002490 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002491 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002492}
2493
Mathias Agopian87baae12012-07-31 12:38:26 -07002494void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002495{
Mathias Agopian841cde52012-03-01 15:44:37 -08002496 ATRACE_CALL();
2497
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002498 // here we keep a copy of the drawing state (that is the state that's
2499 // going to be overwritten by handleTransactionLocked()) outside of
2500 // mStateLock so that the side-effects of the State assignment
2501 // don't happen with mStateLock held (which can cause deadlocks).
2502 State drawingState(mDrawingState);
2503
Mathias Agopianca4d3602011-05-19 15:38:14 -07002504 Mutex::Autolock _l(mStateLock);
2505 const nsecs_t now = systemTime();
2506 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002507
Mathias Agopianca4d3602011-05-19 15:38:14 -07002508 // Here we're guaranteed that some transaction flags are set
2509 // so we can call handleTransactionLocked() unconditionally.
2510 // We call getTransactionFlags(), which will also clear the flags,
2511 // with mStateLock held to guarantee that mCurrentState won't change
2512 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002513
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002514 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002515 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002516 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002517
Mathias Agopianca4d3602011-05-19 15:38:14 -07002518 mLastTransactionTime = systemTime() - now;
2519 mDebugInTransaction = 0;
2520 invalidateHwcGeometry();
2521 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002522}
2523
Lloyd Piqueba04e622017-12-14 17:11:26 -08002524void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2525 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002526 const std::optional<DisplayIdentificationInfo> info =
2527 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002528
Dominik Laskowski075d3172018-05-24 15:50:06 -07002529 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002530 continue;
2531 }
2532
Lloyd Piqueba04e622017-12-14 17:11:26 -08002533 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002534 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002535 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002536 mPhysicalDisplayTokens[info->id] = new BBinder();
2537 DisplayDeviceState state;
2538 state.displayId = info->id;
2539 state.isSecure = true; // All physical displays are currently considered secure.
2540 state.displayName = info->name;
2541 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2542 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002543 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002544 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002545 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002546
Dominik Laskowski075d3172018-05-24 15:50:06 -07002547 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2548 if (index >= 0) {
2549 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2550 mInterceptor->saveDisplayDeletion(state.sequenceId);
2551 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002552 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002553 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002554 }
2555
2556 processDisplayChangesLocked();
2557 }
2558
2559 mPendingHotplugEvents.clear();
2560}
2561
Lloyd Pique99d3da52018-01-22 17:48:03 -08002562sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002563 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002564 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002565 const sp<IGraphicBufferProducer>& producer) {
2566 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002567 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002568 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002569 creationArgs.isSecure = state.isSecure;
2570 creationArgs.displaySurface = dispSurface;
2571 creationArgs.hasWideColorGamut = false;
2572 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002573
Dominik Laskowski075d3172018-05-24 15:50:06 -07002574 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2575 creationArgs.isPrimary = isInternalDisplay;
2576
2577 if (useColorManagement && displayId) {
2578 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002579 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002580 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002581 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002582 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002583
Dominik Laskowski7e045462018-05-30 13:02:02 -07002584 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002585 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002586 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002587 }
tangrobin6753a022018-08-10 10:58:54 +08002588 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002589
Dominik Laskowski075d3172018-05-24 15:50:06 -07002590 if (displayId) {
2591 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002592 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002593 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002594 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002595
Lloyd Pique90c115d2018-09-18 21:39:42 -07002596 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002597 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002598 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002599
Lloyd Pique99d3da52018-01-22 17:48:03 -08002600 // Make sure that composition can never be stalled by a virtual display
2601 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002602 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002603 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002604 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2605 }
2606
Dominik Laskowski075d3172018-05-24 15:50:06 -07002607 creationArgs.displayInstallOrientation =
2608 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002609
Lloyd Pique99d3da52018-01-22 17:48:03 -08002610 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002611 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002612
Lloyd Pique90c115d2018-09-18 21:39:42 -07002613 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002614
2615 if (maxFrameBufferAcquiredBuffers >= 3) {
2616 nativeWindowSurface->preallocateBuffers();
2617 }
2618
2619 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002620 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002621 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002622 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002623 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002624 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002625 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2626 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002627 if (!state.isVirtual()) {
2628 LOG_ALWAYS_FATAL_IF(!displayId);
2629 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002630 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002631
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002632 display->setLayerStack(state.layerStack);
2633 display->setProjection(state.orientation, state.viewport, state.frame);
2634 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002635
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002636 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002637}
2638
Lloyd Pique347200f2017-12-14 17:00:15 -08002639void SurfaceFlinger::processDisplayChangesLocked() {
2640 // here we take advantage of Vector's copy-on-write semantics to
2641 // improve performance by skipping the transaction entirely when
2642 // know that the lists are identical
2643 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2644 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2645 if (!curr.isIdenticalTo(draw)) {
2646 mVisibleRegionsDirty = true;
2647 const size_t cc = curr.size();
2648 size_t dc = draw.size();
2649
2650 // find the displays that were removed
2651 // (ie: in drawing state but not in current state)
2652 // also handle displays that changed
2653 // (ie: displays that are in both lists)
2654 for (size_t i = 0; i < dc;) {
2655 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2656 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002657 // Save display IDs before disconnecting.
2658 const auto internalDisplayId = getInternalDisplayId();
2659 const auto externalDisplayId = getExternalDisplayId();
2660
Lloyd Pique347200f2017-12-14 17:00:15 -08002661 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002662 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002663 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002664 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002665 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002666 if (mUseScheduler) {
2667 mScheduler->hotplugReceived(mAppConnectionHandle,
2668 EventThread::DisplayType::Primary, false);
2669 } else {
2670 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2671 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002672 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002673 if (mUseScheduler) {
2674 mScheduler->hotplugReceived(mAppConnectionHandle,
2675 EventThread::DisplayType::External, false);
2676 } else {
2677 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2678 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002679 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002680 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002681 } else {
2682 // this display is in both lists. see if something changed.
2683 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002684 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002685 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2686 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2687 if (state_binder != draw_binder) {
2688 // changing the surface is like destroying and
2689 // recreating the DisplayDevice, so we just remove it
2690 // from the drawing state, so that it get re-added
2691 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002692 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002693 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002694 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002695 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002696 mDrawingState.displays.removeItemsAt(i);
2697 dc--;
2698 // at this point we must loop to the next item
2699 continue;
2700 }
2701
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002702 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002703 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002704 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002705 }
2706 if ((state.orientation != draw[i].orientation) ||
2707 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002708 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002709 }
2710 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002711 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002712 }
2713 }
2714 }
2715 ++i;
2716 }
2717
2718 // find displays that were added
2719 // (ie: in current state but not in drawing state)
2720 for (size_t i = 0; i < cc; i++) {
2721 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2722 const DisplayDeviceState& state(curr[i]);
2723
Lloyd Pique542307f2018-10-19 13:24:08 -07002724 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002725 sp<IGraphicBufferProducer> producer;
2726 sp<IGraphicBufferProducer> bqProducer;
2727 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002728 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002729
Dominik Laskowski075d3172018-05-24 15:50:06 -07002730 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002731 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002732 // Virtual displays without a surface are dormant:
2733 // they have external state (layer stack, projection,
2734 // etc.) but no internal state (i.e. a DisplayDevice).
2735 if (state.surface != nullptr) {
2736 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002737 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002738 int width = 0;
2739 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2740 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2741 int height = 0;
2742 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2743 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2744 int intFormat = 0;
2745 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2746 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002747 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002748
Dominik Laskowski075d3172018-05-24 15:50:06 -07002749 displayId =
2750 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002751 }
2752
2753 // TODO: Plumb requested format back up to consumer
2754
2755 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002756 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002757 bqProducer, bqConsumer,
2758 state.displayName);
2759
2760 dispSurface = vds;
2761 producer = vds;
2762 }
2763 } else {
2764 ALOGE_IF(state.surface != nullptr,
2765 "adding a supported display, but rendering "
2766 "surface is provided (%p), ignoring it",
2767 state.surface.get());
2768
Dominik Laskowski075d3172018-05-24 15:50:06 -07002769 displayId = state.displayId;
2770 LOG_ALWAYS_FATAL_IF(!displayId);
2771 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002772 producer = bqProducer;
2773 }
2774
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002775 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002776 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002777 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002778 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002779 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002780 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002781 LOG_ALWAYS_FATAL_IF(!displayId);
2782
2783 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002784 if (mUseScheduler) {
2785 mScheduler->hotplugReceived(mAppConnectionHandle,
2786 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002787 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002788 } else {
2789 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2790 true);
2791 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002792 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002793 if (mUseScheduler) {
2794 mScheduler->hotplugReceived(mAppConnectionHandle,
2795 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002796 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002797 } else {
2798 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2799 true);
2800 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002801 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002802 }
2803 }
2804 }
2805 }
2806 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002807
2808 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002809}
2810
Mathias Agopian87baae12012-07-31 12:38:26 -07002811void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002812{
Dan Stoza7dde5992015-05-22 09:51:44 -07002813 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002814 mCurrentState.traverseInZOrder([](Layer* layer) {
2815 layer->notifyAvailableFrames();
2816 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002817
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002818 /*
2819 * Traversal of the children
2820 * (perform the transaction for each of them if needed)
2821 */
2822
Robert Carr720e5062018-07-30 17:45:14 -07002823 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002824 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002825 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002826 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002827 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002828
2829 const uint32_t flags = layer->doTransaction(0);
2830 if (flags & Layer::eVisibleRegion)
2831 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002832
2833 if (flags & Layer::eInputInfoChanged) {
2834 inputChanged = true;
2835 }
Robert Carr2047fae2016-11-28 14:09:09 -08002836 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002837 }
2838
2839 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002840 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002841 */
2842
Mathias Agopiane57f2922012-08-09 16:29:12 -07002843 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002844 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002845 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002846 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002847
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002848 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002849 // The transform hint might have changed for some layers
2850 // (either because a display has changed, or because a layer
2851 // as changed).
2852 //
2853 // Walk through all the layers in currentLayers,
2854 // and update their transform hint.
2855 //
2856 // If a layer is visible only on a single display, then that
2857 // display is used to calculate the hint, otherwise we use the
2858 // default display.
2859 //
2860 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2861 // the hint is set before we acquire a buffer from the surface texture.
2862 //
2863 // NOTE: layer transactions have taken place already, so we use their
2864 // drawing state. However, SurfaceFlinger's own transaction has not
2865 // happened yet, so we must use the current state layer list
2866 // (soon to become the drawing state list).
2867 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002868 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002869 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002870 bool first = true;
2871 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002872 // NOTE: we rely on the fact that layers are sorted by
2873 // layerStack first (so we don't have to traverse the list
2874 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002875 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002876 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002877 currentlayerStack = layerStack;
2878 // figure out if this layerstack is mirrored
2879 // (more than one display) if so, pick the default display,
2880 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002881 hintDisplay = nullptr;
2882 for (const auto& [token, display] : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002883 if (display->getCompositionDisplay()->belongsInOutput(layer->getLayerStack())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002884 if (hintDisplay) {
2885 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002886 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002887 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002888 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002889 }
2890 }
2891 }
2892 }
Chet Haase91d25932013-04-11 15:24:55 -07002893
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002894 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002895 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2896 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002897
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002898 // could be null when this layer is using a layerStack
2899 // that is not visible on any display. Also can occur at
2900 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002901 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002902 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002903
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002904 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002905 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002906 if (hintDisplay) {
2907 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002908 }
Robert Carr2047fae2016-11-28 14:09:09 -08002909
2910 first = false;
2911 });
Mathias Agopian84300952012-11-21 16:02:13 -08002912 }
2913
2914
Mathias Agopian3559b072012-08-15 13:46:03 -07002915 /*
2916 * Perform our own transaction if needed
2917 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002918
2919 if (mLayersAdded) {
2920 mLayersAdded = false;
2921 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002922 mVisibleRegionsDirty = true;
2923 }
2924
2925 // some layers might have been removed, so
2926 // we need to update the regions they're exposing.
2927 if (mLayersRemoved) {
2928 mLayersRemoved = false;
2929 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002930 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002931 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002932 // this layer is not visible anymore
2933 // TODO: we could traverse the tree from front to back and
2934 // compute the actual visible region
2935 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002936 Region visibleReg;
2937 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002938 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002939 }
Robert Carr2047fae2016-11-28 14:09:09 -08002940 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002941 }
2942
2943 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002944
Vishnu Nairde19f852018-12-18 16:11:53 -08002945 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002946 updateInputWindows();
2947 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002948 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002949
Riley Andrews03414a12014-07-01 14:22:59 -07002950 updateCursorAsync();
2951}
2952
Robert Carr720e5062018-07-30 17:45:14 -07002953void SurfaceFlinger::updateInputWindows() {
2954 ATRACE_CALL();
2955
Vishnu Nairde19f852018-12-18 16:11:53 -08002956 if (mInputFlinger == nullptr) {
2957 return;
2958 }
2959
Robert Carr720e5062018-07-30 17:45:14 -07002960 Vector<InputWindowInfo> inputHandles;
2961
2962 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2963 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002964 // When calculating the screen bounds we ignore the transparent region since it may
2965 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002966 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002967 }
2968 });
2969 mInputFlinger->setInputWindows(inputHandles);
2970}
2971
chaviwfbe5d9c2018-12-26 12:23:37 -08002972void SurfaceFlinger::executeInputWindowCommands() {
2973 if (!mInputFlinger) {
2974 return;
2975 }
2976
2977 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2978 if (transferTouchFocusCommand.fromToken != nullptr &&
2979 transferTouchFocusCommand.toToken != nullptr &&
2980 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2981 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2982 transferTouchFocusCommand.toToken);
2983 }
2984 }
2985
2986 mInputWindowCommands.clear();
2987}
2988
Riley Andrews03414a12014-07-01 14:22:59 -07002989void SurfaceFlinger::updateCursorAsync()
2990{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002991 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002992 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002993 continue;
2994 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002995
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002996 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2997 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002998 }
2999 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003000}
3001
chaviw61626f22018-11-15 16:26:27 -08003002void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3003 if (layer->hasReadyFrame()) {
3004 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3005 if (layer->shouldPresentNow(expectedPresentTime)) {
3006 bool ignored = false;
3007 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
3008 }
3009 }
3010 layer->releasePendingBuffer(systemTime());
3011}
3012
Mathias Agopian4fec8732012-06-29 14:12:52 -07003013void SurfaceFlinger::commitTransaction()
3014{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003015 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003016 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003017 for (const auto& l : mLayersPendingRemoval) {
3018 recordBufferingStats(l->getName().string(),
3019 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003020
3021 // We need to release the HWC layers when the Layer is removed
3022 // from the current state otherwise the HWC layer just continues
3023 // showing at its last configured state until we eventually
3024 // abandon the buffer queue.
3025 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003026 l->destroyHwcLayersForAllDisplays();
3027 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003028 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003029 }
3030 mLayersPendingRemoval.clear();
3031 }
3032
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003033 // If this transaction is part of a window animation then the next frame
3034 // we composite should be considered an animation as well.
3035 mAnimCompositionPending = mAnimTransactionPending;
3036
Mathias Agopian4fec8732012-06-29 14:12:52 -07003037 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003038 // clear the "changed" flags in current state
3039 mCurrentState.colorMatrixChanged = false;
3040
Robert Carr1f0a16a2016-10-24 16:27:39 -07003041 mDrawingState.traverseInZOrder([](Layer* layer) {
3042 layer->commitChildList();
3043 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003044 mTransactionPending = false;
3045 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003046 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003047}
3048
Lloyd Pique32cbe282018-10-19 13:09:22 -07003049void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003050 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003051 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003052 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003053
Lloyd Pique32cbe282018-10-19 13:09:22 -07003054 auto display = displayDevice->getCompositionDisplay();
3055
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003056 Region aboveOpaqueLayers;
3057 Region aboveCoveredLayers;
3058 Region dirty;
3059
Mathias Agopian87baae12012-07-31 12:38:26 -07003060 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003061
Robert Carr2047fae2016-11-28 14:09:09 -08003062 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003063 // start with the whole surface at its current location
3064 const Layer::State& s(layer->getDrawingState());
3065
Jesse Hall01e29052013-02-19 16:13:35 -08003066 // only consider the layers on the given layer stack
Lloyd Pique32cbe282018-10-19 13:09:22 -07003067 if (!display->belongsInOutput(layer->getLayerStack())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003068 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003069 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003070
Mathias Agopianab028732010-03-16 16:41:46 -07003071 /*
3072 * opaqueRegion: area of a surface that is fully opaque.
3073 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003074 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003075
3076 /*
3077 * visibleRegion: area of a surface that is visible on screen
3078 * and not fully transparent. This is essentially the layer's
3079 * footprint minus the opaque regions above it.
3080 * Areas covered by a translucent surface are considered visible.
3081 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003082 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003083
3084 /*
3085 * coveredRegion: area of a surface that is covered by all
3086 * visible regions above it (which includes the translucent areas).
3087 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003088 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003089
Jesse Halla8026d22012-09-25 13:25:04 -07003090 /*
3091 * transparentRegion: area of a surface that is hinted to be completely
3092 * transparent. This is only used to tell when the layer has no visible
3093 * non-transparent regions and can be removed from the layer list. It
3094 * does not affect the visibleRegion of this layer or any layers
3095 * beneath it. The hint may not be correct if apps don't respect the
3096 * SurfaceView restrictions (which, sadly, some don't).
3097 */
3098 Region transparentRegion;
3099
Mathias Agopianab028732010-03-16 16:41:46 -07003100
3101 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003102 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003103 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003104 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003105
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003106 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003107 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003108 if (!visibleRegion.isEmpty()) {
3109 // Remove the transparent area from the visible region
3110 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003111 if (tr.preserveRects()) {
3112 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003113 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003114 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003115 // transformation too complex, can't do the
3116 // transparent region optimization.
3117 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003118 }
Mathias Agopianab028732010-03-16 16:41:46 -07003119 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003120
Mathias Agopianab028732010-03-16 16:41:46 -07003121 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003122 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003123 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003124 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003125 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003126 // the opaque region is the layer's footprint
3127 opaqueRegion = visibleRegion;
3128 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003129 }
3130 }
3131
Robert Carre5f4f692018-01-12 13:12:28 -08003132 if (visibleRegion.isEmpty()) {
3133 layer->clearVisibilityRegions();
3134 return;
3135 }
3136
Mathias Agopianab028732010-03-16 16:41:46 -07003137 // Clip the covered region to the visible region
3138 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3139
3140 // Update aboveCoveredLayers for next (lower) layer
3141 aboveCoveredLayers.orSelf(visibleRegion);
3142
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003143 // subtract the opaque region covered by the layers above us
3144 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003145
3146 // compute this layer's dirty region
3147 if (layer->contentDirty) {
3148 // we need to invalidate the whole region
3149 dirty = visibleRegion;
3150 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003151 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003152 layer->contentDirty = false;
3153 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003154 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003155 * the exposed region consists of two components:
3156 * 1) what's VISIBLE now and was COVERED before
3157 * 2) what's EXPOSED now less what was EXPOSED before
3158 *
3159 * note that (1) is conservative, we start with the whole
3160 * visible region but only keep what used to be covered by
3161 * something -- which mean it may have been exposed.
3162 *
3163 * (2) handles areas that were not covered by anything but got
3164 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003165 */
Mathias Agopianab028732010-03-16 16:41:46 -07003166 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003167 const Region oldVisibleRegion = layer->visibleRegion;
3168 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003169 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3170 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003171 }
3172 dirty.subtractSelf(aboveOpaqueLayers);
3173
3174 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003175 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003176
Mathias Agopianab028732010-03-16 16:41:46 -07003177 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003178 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003179
Jesse Halla8026d22012-09-25 13:25:04 -07003180 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003181 layer->setVisibleRegion(visibleRegion);
3182 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003183 layer->setVisibleNonTransparentRegion(
3184 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003185 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003186
Mathias Agopian87baae12012-07-31 12:38:26 -07003187 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003188}
3189
Chia-I Wuab0c3192017-08-01 11:29:00 -07003190void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003191 for (const auto& [token, displayDevice] : mDisplays) {
3192 auto display = displayDevice->getCompositionDisplay();
3193 if (display->belongsInOutput(layer->getLayerStack())) {
3194 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003195 }
3196 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003197}
3198
Dan Stoza6b9454d2014-11-07 16:00:59 -08003199bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003200{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003201 ALOGV("handlePageFlip");
3202
Brian Andersond6927fb2016-07-23 23:37:30 -07003203 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003204
Mathias Agopian4fec8732012-06-29 14:12:52 -07003205 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003206 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003207 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003208
3209 // Store the set of layers that need updates. This set must not change as
3210 // buffers are being latched, as this could result in a deadlock.
3211 // Example: Two producers share the same command stream and:
3212 // 1.) Layer 0 is latched
3213 // 2.) Layer 0 gets a new frame
3214 // 2.) Layer 1 gets a new frame
3215 // 3.) Layer 1 is latched.
3216 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3217 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003218 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003219 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003220 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003221 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3222 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003223 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003224 } else {
3225 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003226 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003227 } else {
3228 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003229 }
Robert Carr2047fae2016-11-28 14:09:09 -08003230 });
3231
Lloyd Piquef2c79392018-12-20 16:23:33 -08003232 if (!mLayersWithQueuedFrames.empty()) {
3233 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3234 // writes to Layer current state. See also b/119481871
3235 Mutex::Autolock lock(mStateLock);
3236
3237 for (auto& layer : mLayersWithQueuedFrames) {
3238 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3239 layer->useSurfaceDamage();
3240 invalidateLayerStack(layer, dirty);
3241 if (layer->isBufferLatched()) {
3242 newDataLatched = true;
3243 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003244 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003245 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003246
Alec Mouri86770e52018-09-24 22:40:58 +00003247 // Clear the renderengine fence here...
3248 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3249 // clear instead of sp::clear.
3250 getBE().flushFence = Fence::NO_FENCE;
3251
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003252 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003253
Vishnu Nairde19f852018-12-18 16:11:53 -08003254 if (visibleRegions) {
3255 // Update input window info if the layer receives its first buffer.
3256 updateInputWindows();
3257 }
3258
Dan Stoza6b9454d2014-11-07 16:00:59 -08003259 // If we will need to wake up at some time in the future to deal with a
3260 // queued frame that shouldn't be displayed during this vsync period, wake
3261 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003262 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003263 signalLayerUpdate();
3264 }
3265
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003266 // enter boot animation on first buffer latch
3267 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3268 ALOGI("Enter boot animation");
3269 mBootStage = BootStage::BOOTANIMATION;
3270 }
3271
Dan Stoza6b9454d2014-11-07 16:00:59 -08003272 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003273 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003274}
3275
Mathias Agopianad456f92011-01-13 17:53:01 -08003276void SurfaceFlinger::invalidateHwcGeometry()
3277{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003278 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003279}
3280
Lloyd Pique32cbe282018-10-19 13:09:22 -07003281void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003282 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003283 auto display = displayDevice->getCompositionDisplay();
3284
Dan Stoza71433162014-02-04 16:22:36 -08003285 // We only need to actually compose the display if:
3286 // 1) It is being handled by hardware composer, which may need this to
3287 // keep its virtual display state machine in sync, or
3288 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003289 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003290 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003291 return;
3292 }
3293
Dan Stoza9e56aa02015-11-02 13:00:03 -08003294 ALOGV("doDisplayComposition");
Lloyd Pique32cbe282018-10-19 13:09:22 -07003295 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003296
3297 // swap buffers (presentation)
Lloyd Pique31cb2942018-10-19 17:23:03 -07003298 display->getRenderSurface()->queueBuffer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003299}
3300
Lloyd Pique32cbe282018-10-19 13:09:22 -07003301bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003302 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003303
Lloyd Pique32cbe282018-10-19 13:09:22 -07003304 auto display = displayDevice->getCompositionDisplay();
3305 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003306 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003307
3308 const Region bounds(displayState.bounds);
3309 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003310 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003311 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003312
Peiyong Lind3788632018-09-18 16:01:31 -07003313 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003314 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003315
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003316 // Framebuffer will live in this scope for GPU composition.
3317 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
3318
Dan Stoza9e56aa02015-11-02 13:00:03 -08003319 if (hasClientComposition) {
3320 ALOGV("hasClientComposition");
3321
Lloyd Pique31cb2942018-10-19 17:23:03 -07003322 sp<GraphicBuffer> buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003323
3324 if (buf == nullptr) {
3325 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3326 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003327 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003328 return false;
3329 }
3330
3331 // Bind the framebuffer in this scope.
3332 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3333 buf->getNativeBuffer());
3334
3335 if (fbo->getStatus() != NO_ERROR) {
3336 ALOGW("Binding buffer for display [%s] failed with status: %d",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003337 displayDevice->getDisplayName().c_str(), fbo->getStatus());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003338 return false;
3339 }
3340
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003341 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003342 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003343 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003344 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003345 }
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003346 getRenderEngine().setOutputDataSpace(outputDataspace);
3347 getRenderEngine().setDisplayMaxLuminance(
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003348 profile->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003349
Lloyd Pique441d5042018-10-18 16:49:51 -07003350 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003351 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003352 getHwComposer()
3353 .hasDisplayCapability(displayId,
3354 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003355
Peiyong Lind3788632018-09-18 16:01:31 -07003356 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003357 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3358 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003359 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003360 }
3361
Lloyd Pique31cb2942018-10-19 17:23:03 -07003362 display->getRenderSurface()->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003363
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003364 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003365 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003366 // when using overlays, we assume a fully transparent framebuffer
3367 // NOTE: we could reduce how much we need to clear, for instance
3368 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003369 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003370 // We'll revisit later if needed.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003371 getRenderEngine().clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003372 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003373 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003374 // we're left with the letterbox region
3375 // (common case is that letterbox ends-up being empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003376 const Region letterbox = bounds.subtract(displayState.scissor);
Mathias Agopian766dc492012-10-30 18:08:06 -07003377
3378 // compute the area to clear
Lloyd Pique32cbe282018-10-19 13:09:22 -07003379 const Region region = displayState.undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003380
Mathias Agopianb9494d52012-04-18 02:28:45 -07003381 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003382 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003383 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003384 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003385 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003386 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003387
Lloyd Pique32cbe282018-10-19 13:09:22 -07003388 const Rect& bounds = displayState.bounds;
3389 const Rect& scissor = displayState.scissor;
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003390 if (scissor != bounds) {
3391 // scissor doesn't match the screen's dimensions, so we
3392 // need to clear everything outside of it and enable
3393 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003394
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003395 // enable scissor for this frame
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003396 getRenderEngine().setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003397 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003398 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003399
Mathias Agopian85d751c2012-08-29 16:59:24 -07003400 /*
3401 * and then, render the layers targeted at the framebuffer
3402 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003403
Dan Stoza9e56aa02015-11-02 13:00:03 -08003404 ALOGV("Rendering client layers");
Lloyd Pique32cbe282018-10-19 13:09:22 -07003405 const ui::Transform& displayTransform = displayState.transform;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003406 bool firstLayer = true;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003407 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003408 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003409 displayTransform.transform(layer->visibleRegion)));
3410 ALOGV("Layer: %s", layer->getName().string());
3411 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003412 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003413 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003414 case HWC2::Composition::Cursor:
3415 case HWC2::Composition::Device:
3416 case HWC2::Composition::Sideband:
3417 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003418 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003419 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003420 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003421 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003422 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003423 // never clear the very first layer since we're
3424 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003425 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003426 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003427 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003428 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003429 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003430 if (layer->hasColorTransform()) {
3431 mat4 tmpMatrix;
3432 if (applyColorMatrix) {
3433 tmpMatrix = mDrawingState.colorMatrix;
3434 }
3435 tmpMatrix *= layer->getColorTransform();
Peiyong Lind3788632018-09-18 16:01:31 -07003436 getRenderEngine().setColorTransform(tmpMatrix);
3437 } else {
3438 getRenderEngine().setColorTransform(colorMatrix);
3439 }
David Sodmanc1498e62018-09-12 14:36:26 -07003440 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003441 break;
3442 }
3443 default:
3444 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003445 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003446 } else {
3447 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003448 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003449 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003450 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003451
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003452 // Perform some cleanup steps if we used client composition.
3453 if (hasClientComposition) {
3454 getRenderEngine().setColorTransform(mat4());
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003455 getRenderEngine().disableScissor();
Lloyd Pique31cb2942018-10-19 17:23:03 -07003456 display->getRenderSurface()->finishBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003457 // Clear out error flags here so that we don't wait until next
3458 // composition to log.
3459 getRenderEngine().checkErrors();
3460 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003461 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003462}
3463
Chia-I Wu28e3a252018-09-07 12:05:02 -07003464void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003465 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003466 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003467}
3468
Dan Stoza7d89d062015-04-30 13:29:25 -07003469status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003470 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003471 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003472 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003473 const sp<Layer>& parent,
3474 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003475{
Dan Stoza7d89d062015-04-30 13:29:25 -07003476 // add this layer to the current state list
3477 {
3478 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003479 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003480 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3481 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003482 return NO_MEMORY;
3483 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003484 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003485 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003486 } else if (parent == nullptr) {
3487 lbc->onRemovedFromCurrentState();
3488 } else if (parent->isRemovedFromCurrentState()) {
3489 parent->addChild(lbc);
3490 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003491 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003492 parent->addChild(lbc);
3493 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003494
Yiwei Zhang243b3782018-05-15 17:40:04 -07003495 if (gbc != nullptr) {
3496 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3497 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3498 mMaxGraphicBufferProducerListSize,
3499 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3500 mGraphicBufferProducerList.size(),
3501 mMaxGraphicBufferProducerListSize, mNumLayers);
3502 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003503 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003504 }
3505
Mathias Agopian96f08192010-06-02 23:28:45 -07003506 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003507 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003508
Dan Stoza7d89d062015-04-30 13:29:25 -07003509 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003510}
3511
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003512uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003513 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003514}
3515
Mathias Agopian3f844832013-08-07 21:24:32 -07003516uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003517 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003518}
3519
Mathias Agopian3f844832013-08-07 21:24:32 -07003520uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003521 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003522}
3523
3524uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003525 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003526 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003527 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003528 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003529 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003530 }
3531 return old;
3532}
3533
Marissa Wall713b63f2018-10-17 15:42:43 -07003534bool SurfaceFlinger::flushTransactionQueues() {
3535 Mutex::Autolock _l(mStateLock);
3536 auto it = mTransactionQueues.begin();
3537 while (it != mTransactionQueues.end()) {
3538 auto& [applyToken, transactionQueue] = *it;
3539
3540 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003541 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3542 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003543 break;
3544 }
chaviw273171b2018-12-26 11:46:30 -08003545 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003546 transactionQueue.pop();
3547 }
3548
3549 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3550 }
3551 return mTransactionQueues.empty();
3552}
3553
chaviwca27f252018-02-06 16:46:39 -08003554bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3555 for (const ComposerState& state : states) {
3556 // Here we need to check that the interface we're given is indeed
3557 // one of our own. A malicious client could give us a nullptr
3558 // IInterface, or one of its own or even one of our own but a
3559 // different type. All these situations would cause us to crash.
3560 if (state.client == nullptr) {
3561 return true;
3562 }
3563
3564 sp<IBinder> binder = IInterface::asBinder(state.client);
3565 if (binder == nullptr) {
3566 return true;
3567 }
3568
3569 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3570 return true;
3571 }
3572 }
3573 return false;
3574}
3575
Marissa Wall17b4e452018-12-26 16:32:34 -08003576bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3577 const Vector<ComposerState>& states) {
3578 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3579 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3580 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3581 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3582 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3583 return false;
3584 }
3585
Marissa Wall713b63f2018-10-17 15:42:43 -07003586 for (const ComposerState& state : states) {
3587 const layer_state_t& s = state.state;
3588 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3589 continue;
3590 }
3591 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003592 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003593 }
3594 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003595 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003596}
3597
3598void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3599 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003600 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003601 const InputWindowCommands& inputWindowCommands,
3602 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003603 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003604 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003605
chaviwca27f252018-02-06 16:46:39 -08003606 if (containsAnyInvalidClientState(states)) {
3607 return;
3608 }
3609
Marissa Wall713b63f2018-10-17 15:42:43 -07003610 // If its TransactionQueue already has a pending TransactionState or if it is pending
3611 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003612 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3613 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003614 setTransactionFlags(eTransactionNeeded);
3615 return;
3616 }
3617
chaviw273171b2018-12-26 11:46:30 -08003618 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003619}
3620
3621void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003622 const Vector<DisplayState>& displays, uint32_t flags,
3623 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003624 uint32_t transactionFlags = 0;
3625
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003626 if (flags & eAnimation) {
3627 // For window updates that are part of an animation we must wait for
3628 // previous animation "frames" to be handled.
3629 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003630 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003631 if (CC_UNLIKELY(err != NO_ERROR)) {
3632 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003633 // caller after a few seconds.
3634 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3635 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003636 mAnimTransactionPending = false;
3637 break;
3638 }
3639 }
3640 }
3641
chaviwca27f252018-02-06 16:46:39 -08003642 for (const DisplayState& display : displays) {
3643 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003644 }
3645
Marissa Walle2ffb422018-10-12 11:33:52 -07003646 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003647 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003648 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003649 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003650 // If the state doesn't require a traversal and there are callbacks, send them now
3651 if (!(clientStateFlags & eTraversalNeeded)) {
3652 mTransactionCompletedThread.sendCallbacks();
3653 }
3654 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003655
chaviw273171b2018-12-26 11:46:30 -08003656 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3657
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003658 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3659 // anyway. This can be used as a flush mechanism for previous async transactions.
3660 // Empty animation transaction can be used to simulate back-pressure, so also force a
3661 // transaction for empty animation transactions.
3662 if (transactionFlags == 0 &&
3663 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003664 transactionFlags = eTransactionNeeded;
3665 }
3666
Mathias Agopian386aa982011-11-07 21:58:03 -08003667 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003668 if (mInterceptor->isEnabled()) {
3669 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003670 }
Irvel468051e2016-06-13 16:44:44 -07003671
Mathias Agopian386aa982011-11-07 21:58:03 -08003672 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003673 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3674 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003675 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003676
3677 // if this is a synchronous transaction, wait for it to take effect
3678 // before returning.
3679 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003680 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003681 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003682 if (flags & eAnimation) {
3683 mAnimTransactionPending = true;
3684 }
3685 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003686 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3687 if (CC_UNLIKELY(err != NO_ERROR)) {
3688 // just in case something goes wrong in SF, return to the
3689 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003690 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3691 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003692 break;
3693 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003694 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003695 }
3696}
3697
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003698uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3699 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3700 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003701
Mathias Agopiane57f2922012-08-09 16:29:12 -07003702 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003703 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3704
3705 const uint32_t what = s.what;
3706 if (what & DisplayState::eSurfaceChanged) {
3707 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3708 state.surface = s.surface;
3709 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003710 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003711 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003712 if (what & DisplayState::eLayerStackChanged) {
3713 if (state.layerStack != s.layerStack) {
3714 state.layerStack = s.layerStack;
3715 flags |= eDisplayTransactionNeeded;
3716 }
3717 }
3718 if (what & DisplayState::eDisplayProjectionChanged) {
3719 if (state.orientation != s.orientation) {
3720 state.orientation = s.orientation;
3721 flags |= eDisplayTransactionNeeded;
3722 }
3723 if (state.frame != s.frame) {
3724 state.frame = s.frame;
3725 flags |= eDisplayTransactionNeeded;
3726 }
3727 if (state.viewport != s.viewport) {
3728 state.viewport = s.viewport;
3729 flags |= eDisplayTransactionNeeded;
3730 }
3731 }
3732 if (what & DisplayState::eDisplaySizeChanged) {
3733 if (state.width != s.width) {
3734 state.width = s.width;
3735 flags |= eDisplayTransactionNeeded;
3736 }
3737 if (state.height != s.height) {
3738 state.height = s.height;
3739 flags |= eDisplayTransactionNeeded;
3740 }
3741 }
3742
Mathias Agopiane57f2922012-08-09 16:29:12 -07003743 return flags;
3744}
3745
Robert Carrd4ae7f32018-06-07 16:10:57 -07003746bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3747 IPCThreadState* ipc = IPCThreadState::self();
3748 const int pid = ipc->getCallingPid();
3749 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003750 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003751 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003752 return false;
3753 }
3754 return true;
3755}
3756
chaviwca27f252018-02-06 16:46:39 -08003757uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3758 const layer_state_t& s = composerState.state;
3759 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3760
Mathias Agopian13127d82013-03-05 17:47:11 -08003761 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003762 if (layer == nullptr) {
3763 return 0;
3764 }
3765
chaviw8b3871a2017-11-01 17:41:01 -07003766 uint32_t flags = 0;
3767
Garfield Tan8a3083e2018-12-03 13:21:07 -08003768 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003769 bool geometryAppliesWithResize =
3770 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003771
3772 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3773 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003774 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003775 layer->pushPendingState();
3776 }
3777
chaviw8b3871a2017-11-01 17:41:01 -07003778 if (what & layer_state_t::ePositionChanged) {
3779 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3780 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003781 }
chaviw8b3871a2017-11-01 17:41:01 -07003782 }
3783 if (what & layer_state_t::eLayerChanged) {
3784 // NOTE: index needs to be calculated before we update the state
3785 const auto& p = layer->getParent();
3786 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003787 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003788 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003789 mCurrentState.layersSortedByZ.removeAt(idx);
3790 mCurrentState.layersSortedByZ.add(layer);
3791 // we need traversal (state changed)
3792 // AND transaction (list changed)
3793 flags |= eTransactionNeeded|eTraversalNeeded;
3794 }
chaviw8b3871a2017-11-01 17:41:01 -07003795 } else {
3796 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003797 flags |= eTransactionNeeded|eTraversalNeeded;
3798 }
3799 }
chaviw8b3871a2017-11-01 17:41:01 -07003800 }
3801 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003802 // NOTE: index needs to be calculated before we update the state
3803 const auto& p = layer->getParent();
3804 if (p == nullptr) {
3805 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3806 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3807 mCurrentState.layersSortedByZ.removeAt(idx);
3808 mCurrentState.layersSortedByZ.add(layer);
3809 // we need traversal (state changed)
3810 // AND transaction (list changed)
3811 flags |= eTransactionNeeded|eTraversalNeeded;
3812 }
3813 } else {
3814 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3815 flags |= eTransactionNeeded|eTraversalNeeded;
3816 }
chaviw8b3871a2017-11-01 17:41:01 -07003817 }
3818 }
3819 if (what & layer_state_t::eSizeChanged) {
3820 if (layer->setSize(s.w, s.h)) {
3821 flags |= eTraversalNeeded;
3822 }
3823 }
3824 if (what & layer_state_t::eAlphaChanged) {
3825 if (layer->setAlpha(s.alpha))
3826 flags |= eTraversalNeeded;
3827 }
3828 if (what & layer_state_t::eColorChanged) {
3829 if (layer->setColor(s.color))
3830 flags |= eTraversalNeeded;
3831 }
Peiyong Lind3788632018-09-18 16:01:31 -07003832 if (what & layer_state_t::eColorTransformChanged) {
3833 if (layer->setColorTransform(s.colorTransform)) {
3834 flags |= eTraversalNeeded;
3835 }
3836 }
chaviw8b3871a2017-11-01 17:41:01 -07003837 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003838 // TODO: b/109894387
3839 //
3840 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3841 // rotation. To see the problem observe that if we have a square parent, and a child
3842 // of the same size, then we rotate the child 45 degrees around it's center, the child
3843 // must now be cropped to a non rectangular 8 sided region.
3844 //
3845 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3846 // private API, and the WindowManager only uses rotation in one case, which is on a top
3847 // level layer in which cropping is not an issue.
3848 //
3849 // However given that abuse of rotation matrices could lead to surfaces extending outside
3850 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3851 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3852 // transformations.
3853 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003854 flags |= eTraversalNeeded;
3855 }
3856 if (what & layer_state_t::eTransparentRegionChanged) {
3857 if (layer->setTransparentRegionHint(s.transparentRegion))
3858 flags |= eTraversalNeeded;
3859 }
3860 if (what & layer_state_t::eFlagsChanged) {
3861 if (layer->setFlags(s.flags, s.mask))
3862 flags |= eTraversalNeeded;
3863 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003864 if (what & layer_state_t::eCropChanged_legacy) {
3865 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003866 flags |= eTraversalNeeded;
3867 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003868 if (what & layer_state_t::eCornerRadiusChanged) {
3869 if (layer->setCornerRadius(s.cornerRadius))
3870 flags |= eTraversalNeeded;
3871 }
chaviw8b3871a2017-11-01 17:41:01 -07003872 if (what & layer_state_t::eLayerStackChanged) {
3873 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3874 // We only allow setting layer stacks for top level layers,
3875 // everything else inherits layer stack from its parent.
3876 if (layer->hasParent()) {
3877 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3878 layer->getName().string());
3879 } else if (idx < 0) {
3880 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3881 "that also does not appear in the top level layer list. Something"
3882 " has gone wrong.", layer->getName().string());
3883 } else if (layer->setLayerStack(s.layerStack)) {
3884 mCurrentState.layersSortedByZ.removeAt(idx);
3885 mCurrentState.layersSortedByZ.add(layer);
3886 // we need traversal (state changed)
3887 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003888 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003889 }
3890 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003891 if (what & layer_state_t::eDeferTransaction_legacy) {
3892 if (s.barrierHandle_legacy != nullptr) {
3893 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3894 } else if (s.barrierGbp_legacy != nullptr) {
3895 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003896 if (authenticateSurfaceTextureLocked(gbp)) {
3897 const auto& otherLayer =
3898 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003899 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003900 } else {
3901 ALOGE("Attempt to defer transaction to to an"
3902 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003903 }
3904 }
chaviw8b3871a2017-11-01 17:41:01 -07003905 // We don't trigger a traversal here because if no other state is
3906 // changed, we don't want this to cause any more work
3907 }
3908 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003909 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003910 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003911 if (!hadParent) {
3912 mCurrentState.layersSortedByZ.remove(layer);
3913 }
chaviw8b3871a2017-11-01 17:41:01 -07003914 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003915 }
chaviw8b3871a2017-11-01 17:41:01 -07003916 }
3917 if (what & layer_state_t::eReparentChildren) {
3918 if (layer->reparentChildren(s.reparentHandle)) {
3919 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003920 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003921 }
chaviw8b3871a2017-11-01 17:41:01 -07003922 if (what & layer_state_t::eDetachChildren) {
3923 layer->detachChildren();
3924 }
3925 if (what & layer_state_t::eOverrideScalingModeChanged) {
3926 layer->setOverrideScalingMode(s.overrideScalingMode);
3927 // We don't trigger a traversal here because if no other state is
3928 // changed, we don't want this to cause any more work
3929 }
Marissa Wall61c58622018-07-18 10:12:20 -07003930 if (what & layer_state_t::eTransformChanged) {
3931 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3932 }
3933 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3934 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3935 flags |= eTraversalNeeded;
3936 }
3937 if (what & layer_state_t::eCropChanged) {
3938 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3939 }
Marissa Wall861616d2018-10-22 12:52:23 -07003940 if (what & layer_state_t::eFrameChanged) {
3941 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3942 }
Marissa Wall61c58622018-07-18 10:12:20 -07003943 if (what & layer_state_t::eBufferChanged) {
3944 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3945 }
3946 if (what & layer_state_t::eAcquireFenceChanged) {
3947 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3948 }
3949 if (what & layer_state_t::eDataspaceChanged) {
3950 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3951 }
3952 if (what & layer_state_t::eHdrMetadataChanged) {
3953 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3954 }
3955 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3956 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3957 }
3958 if (what & layer_state_t::eApiChanged) {
3959 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3960 }
3961 if (what & layer_state_t::eSidebandStreamChanged) {
3962 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3963 }
Robert Carr720e5062018-07-30 17:45:14 -07003964 if (what & layer_state_t::eInputInfoChanged) {
3965 layer->setInputInfo(s.inputInfo);
3966 flags |= eTraversalNeeded;
3967 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003968 std::vector<sp<CallbackHandle>> callbackHandles;
3969 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3970 mTransactionCompletedThread.run();
3971 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3972 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3973 }
3974 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003975 if (what & layer_state_t::eCachedBufferChanged) {
3976 sp<GraphicBuffer> buffer =
3977 mBufferStateLayerCache.get(s.cachedBuffer.token, s.cachedBuffer.bufferId);
3978 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
3979 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003980 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3981 // Do not put anything that updates layer state or modifies flags after
3982 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003983 return flags;
3984}
3985
chaviw273171b2018-12-26 11:46:30 -08003986uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3987 uint32_t flags = 0;
3988 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3989 flags |= eTraversalNeeded;
3990 }
3991
3992 mInputWindowCommands.merge(inputWindowCommands);
3993 return flags;
3994}
3995
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003996status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003997 const String8& name,
3998 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003999 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07004000 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05004001 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004002{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004003 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004004 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004005 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004006 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004007 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004008
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004009 status_t result = NO_ERROR;
4010
4011 sp<Layer> layer;
4012
Cody Northropbc755282017-03-31 12:00:08 -06004013 String8 uniqueName = getUniqueLayerName(name);
4014
Mathias Agopian3165cc22012-08-08 19:42:09 -07004015 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004016 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004017 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4018 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004019
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004020 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004021 case ISurfaceComposerClient::eFXSurfaceBufferState:
4022 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4023 break;
chaviw13fdc492017-06-27 12:40:18 -07004024 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004025 // check if buffer size is set for color layer.
4026 if (w > 0 || h > 0) {
4027 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4028 int(w), int(h));
4029 return BAD_VALUE;
4030 }
4031
chaviw13fdc492017-06-27 12:40:18 -07004032 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004033 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004034 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004035 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004036 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004037 // check if buffer size is set for container layer.
4038 if (w > 0 || h > 0) {
4039 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4040 int(w), int(h));
4041 return BAD_VALUE;
4042 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004043 result = createContainerLayer(client,
4044 uniqueName, w, h, flags,
4045 handle, &layer);
4046 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004047 default:
4048 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004049 break;
4050 }
4051
Dan Stoza7d89d062015-04-30 13:29:25 -07004052 if (result != NO_ERROR) {
4053 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004054 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004055
Chia-I Wuab0c3192017-08-01 11:29:00 -07004056 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4057 // TODO b/64227542
4058 if (windowType == 441731) {
4059 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
4060 layer->setPrimaryDisplayOnly();
4061 }
4062
Albert Chaulk479c60c2017-01-27 14:21:34 -05004063 layer->setInfo(windowType, ownerUid);
4064
Robert Carrb89ea9d2018-12-10 13:01:14 -08004065 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4066 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4067 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004068 if (result != NO_ERROR) {
4069 return result;
4070 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004071 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004072
4073 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004074 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004075}
4076
Cody Northropbc755282017-03-31 12:00:08 -06004077String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4078{
4079 bool matchFound = true;
4080 uint32_t dupeCounter = 0;
4081
4082 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4083 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4084
Dan Stoza436ccf32018-06-21 12:10:12 -07004085 // Grab the state lock since we're accessing mCurrentState
4086 Mutex::Autolock lock(mStateLock);
4087
Cody Northropbc755282017-03-31 12:00:08 -06004088 // Loop over layers until we're sure there is no matching name
4089 while (matchFound) {
4090 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004091 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004092 if (layer->getName() == uniqueName) {
4093 matchFound = true;
4094 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4095 }
4096 });
4097 }
4098
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004099 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4100 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004101
4102 return uniqueName;
4103}
4104
Marissa Wallfd668622018-05-10 10:21:13 -07004105status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4106 uint32_t w, uint32_t h, uint32_t flags,
4107 PixelFormat& format, sp<IBinder>* handle,
4108 sp<IGraphicBufferProducer>* gbp,
4109 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004110 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004111 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004112 case PIXEL_FORMAT_TRANSPARENT:
4113 case PIXEL_FORMAT_TRANSLUCENT:
4114 format = PIXEL_FORMAT_RGBA_8888;
4115 break;
4116 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004117 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004118 break;
4119 }
4120
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004121 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004122 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004123 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004124 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004125 *handle = layer->getHandle();
4126 *gbp = layer->getProducer();
4127 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004128 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004129
Marissa Wallfd668622018-05-10 10:21:13 -07004130 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004131 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004132}
4133
Marissa Wall61c58622018-07-18 10:12:20 -07004134status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4135 uint32_t w, uint32_t h, uint32_t flags,
4136 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004137 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004138 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004139 *handle = layer->getHandle();
4140 *outLayer = layer;
4141
4142 return NO_ERROR;
4143}
4144
chaviw13fdc492017-06-27 12:40:18 -07004145status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004146 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004147 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004148{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004149 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004150 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004151 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004152}
4153
Robert Carr6b3f6c52018-08-13 13:05:17 -07004154status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4155 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4156 sp<IBinder>* handle, sp<Layer>* outLayer)
4157{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004158 *outLayer =
4159 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004160 *handle = (*outLayer)->getHandle();
4161 return NO_ERROR;
4162}
4163
4164
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004165void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004166 mLayersPendingRemoval.add(layer);
4167 mLayersRemoved = true;
4168 setTransactionFlags(eTransactionNeeded);
4169}
4170
Robert Carr695d5282018-12-18 15:27:58 -08004171void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004172{
Robert Carr2e102c92018-10-23 12:11:15 -07004173 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004174 // If a layer has a parent, we allow it to out-live it's handle
4175 // with the idea that the parent holds a reference and will eventually
4176 // be cleaned up. However no one cleans up the top-level so we do so
4177 // here.
4178 if (layer->getParent() == nullptr) {
4179 mCurrentState.layersSortedByZ.remove(layer);
4180 }
4181 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004182 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004183}
4184
Mathias Agopianb60314a2012-04-10 22:09:54 -07004185// ---------------------------------------------------------------------------
4186
Andy McFadden13a082e2012-08-24 10:16:42 -07004187void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004188 const auto display = getDefaultDisplayDeviceLocked();
4189 if (!display) return;
4190
4191 const sp<IBinder> token = display->getDisplayToken().promote();
4192 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004193
Jesse Hall01e29052013-02-19 16:13:35 -08004194 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004195 Vector<ComposerState> state;
4196 Vector<DisplayState> displays;
4197 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004198 d.what = DisplayState::eDisplayProjectionChanged |
4199 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004200 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004201 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004202 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004203 d.frame.makeInvalid();
4204 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004205 d.width = 0;
4206 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004207 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004208 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004209
Dominik Laskowskie9774092018-12-11 10:04:24 -08004210 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004211
Dominik Laskowski83b88212018-12-11 13:34:06 -08004212 const nsecs_t vsyncPeriod = getVsyncPeriod();
4213 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004214
Brian Andersond0010582017-03-07 13:20:31 -08004215 // Use phase of 0 since phase is not known.
4216 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004217 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004218 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004219}
4220
4221void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004222 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004223 postMessageAsync(
4224 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004225}
4226
Dominik Laskowskie9774092018-12-11 10:04:24 -08004227void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004228 if (display->isVirtual()) {
4229 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004230 return;
4231 }
4232
Dominik Laskowski075d3172018-05-24 15:50:06 -07004233 const auto displayId = display->getId();
4234 LOG_ALWAYS_FATAL_IF(!displayId);
4235
Dominik Laskowski34157762018-10-31 13:07:19 -07004236 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004237
4238 int currentMode = display->getPowerMode();
4239 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004240 return;
4241 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004242
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004243 display->setPowerMode(mode);
4244
Lloyd Pique4dccc412018-01-22 17:21:36 -08004245 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004246 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004247 }
4248
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004249 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004250 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004251 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004252 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004253 if (mUseScheduler) {
4254 mScheduler->onScreenAcquired(mAppConnectionHandle);
4255 } else {
4256 mEventThread->onScreenAcquired();
4257 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004258 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004259 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004260
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004261 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004262 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004263 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004264
4265 struct sched_param param = {0};
4266 param.sched_priority = 1;
4267 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4268 ALOGW("Couldn't set SCHED_FIFO on display on");
4269 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004270 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004271 // Turn off the display
4272 struct sched_param param = {0};
4273 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4274 ALOGW("Couldn't set SCHED_OTHER on display off");
4275 }
4276
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004277 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004278 if (mUseScheduler) {
4279 mScheduler->disableHardwareVsync(true);
4280 } else {
4281 disableHardwareVsync(true); // also cancels any in-progress resync
4282 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004283 if (mUseScheduler) {
4284 mScheduler->onScreenReleased(mAppConnectionHandle);
4285 } else {
4286 mEventThread->onScreenReleased();
4287 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004288 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004289
Dominik Laskowski075d3172018-05-24 15:50:06 -07004290 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004291 mVisibleRegionsDirty = true;
4292 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004293 } else if (mode == HWC_POWER_MODE_DOZE ||
4294 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004295 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004296 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004297 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004298 if (mUseScheduler) {
4299 mScheduler->onScreenAcquired(mAppConnectionHandle);
4300 } else {
4301 mEventThread->onScreenAcquired();
4302 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004303 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004304 }
4305 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4306 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004307 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004308 if (mUseScheduler) {
4309 mScheduler->disableHardwareVsync(true);
4310 } else {
4311 disableHardwareVsync(true); // also cancels any in-progress resync
4312 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004313 if (mUseScheduler) {
4314 mScheduler->onScreenReleased(mAppConnectionHandle);
4315 } else {
4316 mEventThread->onScreenReleased();
4317 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004318 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004319 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004320 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004321 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004322 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004323 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004324
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004325 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004326 mTimeStats->setPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004327 }
4328
Dominik Laskowski34157762018-10-31 13:07:19 -07004329 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004330}
4331
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004332void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004333 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004334 const auto display = getDisplayDevice(displayToken);
4335 if (!display) {
4336 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4337 displayToken.get());
4338 } else if (display->isVirtual()) {
4339 ALOGW("Attempt to set power mode %d for virtual display", mode);
4340 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004341 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004342 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004343 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004344}
4345
4346// ---------------------------------------------------------------------------
4347
Dominik Laskowskic2867142019-01-21 11:33:38 -08004348status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4349 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004350 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004351
Mathias Agopianbd115332013-04-18 16:41:04 -07004352 IPCThreadState* ipc = IPCThreadState::self();
4353 const int pid = ipc->getCallingPid();
4354 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004355
Mathias Agopianbd115332013-04-18 16:41:04 -07004356 if ((uid != AID_SHELL) &&
4357 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004358 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4359 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004360 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004361 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004362 // (this would indicate SF is stuck, but we want to be able to
4363 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004364 status_t err = mStateLock.timedLock(s2ns(1));
4365 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004366 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004367 StringAppendF(&result,
4368 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4369 "(no locks held)\n",
4370 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004371 }
4372
Dominik Laskowskic2867142019-01-21 11:33:38 -08004373 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004374
Dominik Laskowskic2867142019-01-21 11:33:38 -08004375 static const std::unordered_map<std::string, Dumper> dumpers = {
4376 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4377 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4378 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
4379 {"--dispsync"s, dumper([this](std::string& s) { mPrimaryDispSync->dump(s); })},
4380 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4381 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
4382 {"--frame-composition"s, dumper(&SurfaceFlinger::dumpFrameCompositionInfo)},
4383 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4384 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4385 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4386 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4387 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4388 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004389 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004390 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4391 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004392
Dominik Laskowskic2867142019-01-21 11:33:38 -08004393 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004394
Dominik Laskowskic2867142019-01-21 11:33:38 -08004395 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4396 (it->second)(args, asProto, result);
4397 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004398 if (asProto) {
4399 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4400 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4401 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004402 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004403 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004404 }
4405
Mathias Agopian9795c422009-08-26 16:36:26 -07004406 if (locked) {
4407 mStateLock.unlock();
4408 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004409 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004410 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004411 return NO_ERROR;
4412}
4413
Dominik Laskowskic2867142019-01-21 11:33:38 -08004414void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004415 mCurrentState.traverseInZOrder(
4416 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004417}
4418
Dominik Laskowskic2867142019-01-21 11:33:38 -08004419void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004420 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004421
Dominik Laskowskic2867142019-01-21 11:33:38 -08004422 if (args.size() > 1) {
4423 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004424 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004425 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004426 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004427 }
Robert Carr2047fae2016-11-28 14:09:09 -08004428 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004429 } else {
4430 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004431 }
4432}
4433
Dominik Laskowskic2867142019-01-21 11:33:38 -08004434void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004435 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004436 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004437 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004438 }
Robert Carr2047fae2016-11-28 14:09:09 -08004439 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004440
Svetoslavd85084b2014-03-20 10:28:31 -07004441 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004442}
4443
Dominik Laskowskic2867142019-01-21 11:33:38 -08004444void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4445 mTimeStats->parseArgs(asProto, args, result);
4446}
4447
Jamie Gennis6547ff42013-07-16 20:12:42 -07004448// This should only be called from the main thread. Otherwise it would need
4449// the lock and should use mCurrentState rather than mDrawingState.
4450void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004451 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004452 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004453 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004454
4455 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4456}
4457
Yiwei Zhang5434a782018-12-05 18:06:32 -08004458void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004459 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004460
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004461 if (isLayerTripleBufferingDisabled())
4462 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004463
Yiwei Zhang5434a782018-12-05 18:06:32 -08004464 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4465 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4466 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4467 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4468 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4469 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004470 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004471}
4472
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004473void SurfaceFlinger::dumpVSync(std::string& result) const {
4474 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4475 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
4476 StringAppendF(&result,
4477 " app phase: %9" PRId64 " ns\t SF phase: %9" PRId64 " ns\n"
4478 " early app phase: %9" PRId64 " ns\t early SF phase: %9" PRId64 " ns\n"
4479 "GL early app phase: %9" PRId64 " ns\tGL early SF phase: %9" PRId64 " ns\n"
4480 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
4481 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, appEarlyOffset, sfEarlyOffset,
4482 appEarlyGlOffset, sfEarlyGlOffset, dispSyncPresentTimeOffset, getVsyncPeriod());
4483
4484 StringAppendF(&result, "Scheduler: %s\n\n", mUseScheduler ? "enabled" : "disabled");
4485
4486 if (mUseScheduler) {
4487 mScheduler->dump(mAppConnectionHandle, result);
4488 } else {
4489 mEventThread->dump(result);
4490 }
4491}
4492
Yiwei Zhang5434a782018-12-05 18:06:32 -08004493void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4494 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004495 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4496 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004497 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004498 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004499 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004500 }
David Sodman4a36e932017-11-07 14:29:47 -08004501 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004502 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004503 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004504 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4505 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004506}
4507
Dan Stozae77c7662016-05-13 11:37:28 -07004508void SurfaceFlinger::recordBufferingStats(const char* layerName,
4509 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004510 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4511 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004512 for (const auto& segment : history) {
4513 if (!segment.usedThirdBuffer) {
4514 stats.twoBufferTime += segment.totalTime;
4515 }
4516 if (segment.occupancyAverage < 1.0f) {
4517 stats.doubleBufferedTime += segment.totalTime;
4518 } else if (segment.occupancyAverage < 2.0f) {
4519 stats.tripleBufferedTime += segment.totalTime;
4520 }
4521 ++stats.numSegments;
4522 stats.totalTime += segment.totalTime;
4523 }
4524}
4525
Yiwei Zhang5434a782018-12-05 18:06:32 -08004526void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4527 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004528
4529 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4530 const size_t count = currentLayers.size();
4531 for (size_t i=0 ; i<count ; i++) {
4532 currentLayers[i]->dumpFrameEvents(result);
4533 }
4534}
4535
Yiwei Zhang5434a782018-12-05 18:06:32 -08004536void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004537 result.append("Buffering stats:\n");
4538 result.append(" [Layer name] <Active time> <Two buffer> "
4539 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004540 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004541 typedef std::tuple<std::string, float, float, float> BufferTuple;
4542 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004543 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004544 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004545 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004546 if (stats.numSegments == 0) {
4547 continue;
4548 }
4549 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4550 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4551 stats.totalTime;
4552 float doubleBufferRatio = static_cast<float>(
4553 stats.doubleBufferedTime) / stats.totalTime;
4554 float tripleBufferRatio = static_cast<float>(
4555 stats.tripleBufferedTime) / stats.totalTime;
4556 sorted.insert({activeTime, {name, twoBufferRatio,
4557 doubleBufferRatio, tripleBufferRatio}});
4558 }
4559 for (const auto& sortedPair : sorted) {
4560 float activeTime = sortedPair.first;
4561 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004562 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4563 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004564 }
4565 result.append("\n");
4566}
4567
Yiwei Zhang5434a782018-12-05 18:06:32 -08004568void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004569 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004570 const auto displayId = display->getId();
4571 if (!displayId) {
4572 continue;
4573 }
4574 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004575 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004576 continue;
4577 }
4578
Yiwei Zhang5434a782018-12-05 18:06:32 -08004579 StringAppendF(&result,
4580 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4581 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004582 uint8_t port;
4583 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004584 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004585 result.append("no identification data\n");
4586 continue;
4587 }
4588
4589 if (!isEdid(data)) {
4590 result.append("unknown identification data: ");
4591 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004592 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004593 }
4594 result.append("\n");
4595 continue;
4596 }
4597
4598 const auto edid = parseEdid(data);
4599 if (!edid) {
4600 result.append("invalid EDID: ");
4601 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004602 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004603 }
4604 result.append("\n");
4605 continue;
4606 }
4607
Yiwei Zhang5434a782018-12-05 18:06:32 -08004608 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004609 result.append(edid->displayName.data(), edid->displayName.length());
4610 result.append("\"\n");
4611 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004612}
4613
Yiwei Zhang5434a782018-12-05 18:06:32 -08004614void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4615 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4616 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4617 StringAppendF(&result, "DisplayColorSetting: %s\n",
4618 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004619
4620 // TODO: print out if wide-color mode is active or not
4621
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004622 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004623 const auto displayId = display->getId();
4624 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004625 continue;
4626 }
4627
Yiwei Zhang5434a782018-12-05 18:06:32 -08004628 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004629 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004630 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004631 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004632 }
4633
Lloyd Pique32cbe282018-10-19 13:09:22 -07004634 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004635 StringAppendF(&result, " Current color mode: %s (%d)\n",
4636 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004637 }
4638 result.append("\n");
4639}
4640
Yiwei Zhang5434a782018-12-05 18:06:32 -08004641void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004642 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004643 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4644 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004645 continue;
4646 }
4647
Dominik Laskowski05275f12018-11-01 15:03:24 -07004648 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004649 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4650 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004651 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004652 compositionInfo.dump(result, nullptr);
4653 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004654 }
4655 }
David Sodman7e4ae112018-02-09 15:02:28 -08004656}
4657
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004658LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004659 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004660 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4661 const State& state = useDrawing ? mDrawingState : mCurrentState;
4662 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004663 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004664 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004665 });
4666
4667 return layersProto;
4668}
4669
Lloyd Pique32cbe282018-10-19 13:09:22 -07004670LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004671 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004672
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004673 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004674 resolution->set_w(displayDevice.getWidth());
4675 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004676
Lloyd Pique32cbe282018-10-19 13:09:22 -07004677 auto display = displayDevice.getCompositionDisplay();
4678 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004679
Lloyd Pique32cbe282018-10-19 13:09:22 -07004680 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4681 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4682 layersProto.set_global_transform(displayState.orientation);
4683
4684 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004685 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004686 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004687 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004688 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004689 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004690 }
4691 });
4692
4693 return layersProto;
4694}
4695
Dominik Laskowskic2867142019-01-21 11:33:38 -08004696void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4697 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004698 Colorizer colorizer(colorize);
4699
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004700 // figure out if we're stuck somewhere
4701 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004702 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004703 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4704
4705 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004706 * Dump library configuration.
4707 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004708
4709 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004710 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004711 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004712 appendSfConfigString(result);
4713 appendUiConfigString(result);
4714 appendGuiConfigString(result);
4715 result.append("\n");
4716
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004717 result.append("\nDisplay identification data:\n");
4718 dumpDisplayIdentificationData(result);
4719
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004720 result.append("\nWide-Color information:\n");
4721 dumpWideColorInfo(result);
4722
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004723 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004724 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004725 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004726 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004727 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004728
Andy McFadden41d67d72014-04-25 16:58:34 -07004729 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004730 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004731 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004732 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004733 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004734
Dan Stozab90cf072015-03-05 11:05:59 -08004735 dumpStaticScreenStats(result);
4736 result.append("\n");
4737
Yiwei Zhang5434a782018-12-05 18:06:32 -08004738 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004739
Dan Stozae77c7662016-05-13 11:37:28 -07004740 dumpBufferingStats(result);
4741
Andy McFadden4803b742012-09-24 19:07:20 -07004742 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004743 * Dump the visible layer list
4744 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004745 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004746 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4747 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4748 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004749 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004750
Chia-I Wu2f884132018-09-13 15:17:58 -07004751 {
4752 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4753 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004754 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004755 result.append("\n");
4756 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004757
David Sodman7e4ae112018-02-09 15:02:28 -08004758 result.append("\nFrame-Composition information:\n");
4759 dumpFrameCompositionInfo(result);
4760 result.append("\n");
4761
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004762 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004763 * Dump Display state
4764 */
4765
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004766 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004767 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004768 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004769 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004770 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004771 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004772 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004773
4774 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004775 * Dump SurfaceFlinger global state
4776 */
4777
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004778 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004779 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004780 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004781
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004782 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004783
Dominik Laskowski075d3172018-05-24 15:50:06 -07004784 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004785 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4786 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004787 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4788 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004789 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004790 StringAppendF(&result,
4791 " transaction-flags : %08x\n"
4792 " gpu_to_cpu_unsupported : %d\n",
4793 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004794
Dominik Laskowski075d3172018-05-24 15:50:06 -07004795 if (const auto displayId = getInternalDisplayId();
4796 displayId && getHwComposer().isConnected(*displayId)) {
4797 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004798 StringAppendF(&result,
4799 " refresh-rate : %f fps\n"
4800 " x-dpi : %f\n"
4801 " y-dpi : %f\n",
4802 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4803 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004804 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004805
Yiwei Zhang5434a782018-12-05 18:06:32 -08004806 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004807
Dan Stozae22aec72016-08-01 13:20:59 -07004808 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004809 * Tracing state
4810 */
4811 mTracing.dump(result);
4812 result.append("\n");
4813
4814 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004815 * HWC layer minidump
4816 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004817 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004818 const auto displayId = display->getId();
4819 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004820 continue;
4821 }
4822
Yiwei Zhang5434a782018-12-05 18:06:32 -08004823 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004824 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004825 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004826 result.append("\n");
4827 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004828
4829 /*
4830 * Dump HWComposer state
4831 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004832 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004833 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004834 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004835 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004836 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004837 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004838
4839 /*
4840 * Dump gralloc state
4841 */
4842 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4843 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004844
4845 /*
4846 * Dump VrFlinger state if in use.
4847 */
4848 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4849 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004850 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004851 result.append("\n");
4852 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004853}
4854
Dominik Laskowski075d3172018-05-24 15:50:06 -07004855const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004856 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004857 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004858 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004859 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004860 }
4861 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004862
Dominik Laskowski34157762018-10-31 13:07:19 -07004863 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004864 static const Vector<sp<Layer>> empty;
4865 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004866}
4867
Keun young Park63f165f2012-08-31 10:53:36 -07004868bool SurfaceFlinger::startDdmConnection()
4869{
4870 void* libddmconnection_dso =
4871 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4872 if (!libddmconnection_dso) {
4873 return false;
4874 }
4875 void (*DdmConnection_start)(const char* name);
4876 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004877 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004878 if (!DdmConnection_start) {
4879 dlclose(libddmconnection_dso);
4880 return false;
4881 }
4882 (*DdmConnection_start)(getServiceName());
4883 return true;
4884}
4885
Chia-I Wu28f320b2018-05-03 11:02:56 -07004886void SurfaceFlinger::updateColorMatrixLocked() {
4887 mat4 colorMatrix;
4888 if (mGlobalSaturationFactor != 1.0f) {
4889 // Rec.709 luma coefficients
4890 float3 luminance{0.213f, 0.715f, 0.072f};
4891 luminance *= 1.0f - mGlobalSaturationFactor;
4892 mat4 saturationMatrix = mat4(
4893 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4894 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4895 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4896 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4897 );
4898 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4899 } else {
4900 colorMatrix = mClientColorMatrix * mDaltonizer();
4901 }
4902
4903 if (mCurrentState.colorMatrix != colorMatrix) {
4904 mCurrentState.colorMatrix = colorMatrix;
4905 mCurrentState.colorMatrixChanged = true;
4906 setTransactionFlags(eTransactionNeeded);
4907 }
4908}
4909
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004910status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004911#pragma clang diagnostic push
4912#pragma clang diagnostic error "-Wswitch-enum"
4913 switch (static_cast<ISurfaceComposerTag>(code)) {
4914 // These methods should at minimum make sure that the client requested
4915 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004916 case BOOT_FINISHED:
4917 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004918 case CREATE_DISPLAY:
4919 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004920 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004921 case GET_ACTIVE_COLOR_MODE:
4922 case GET_ANIMATION_FRAME_STATS:
4923 case GET_HDR_CAPABILITIES:
4924 case SET_ACTIVE_CONFIG:
4925 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004926 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004927 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004928 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004929 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4930 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004931 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4932 IPCThreadState* ipc = IPCThreadState::self();
4933 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4934 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004935 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004936 }
Robert Carr1db73f62016-12-21 12:58:51 -08004937 return OK;
4938 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004939 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004940 IPCThreadState* ipc = IPCThreadState::self();
4941 const int pid = ipc->getCallingPid();
4942 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004943 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4944 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004945 return PERMISSION_DENIED;
4946 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004947 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004948 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004949 // Used by apps to hook Choreographer to SurfaceFlinger.
4950 case CREATE_DISPLAY_EVENT_CONNECTION:
4951 // The following calls are currently used by clients that do not
4952 // request necessary permissions. However, they do not expose any secret
4953 // information, so it is OK to pass them.
4954 case AUTHENTICATE_SURFACE:
4955 case GET_ACTIVE_CONFIG:
4956 case GET_BUILT_IN_DISPLAY:
4957 case GET_DISPLAY_COLOR_MODES:
4958 case GET_DISPLAY_CONFIGS:
4959 case GET_DISPLAY_STATS:
4960 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4961 // Calling setTransactionState is safe, because you need to have been
4962 // granted a reference to Client* and Handle* to do anything with it.
4963 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004964 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004965 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004966 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004967 case GET_PROTECTED_CONTENT_SUPPORT:
4968 case CACHE_BUFFER:
4969 case UNCACHE_BUFFER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004970 return OK;
4971 }
4972 case CAPTURE_LAYERS:
4973 case CAPTURE_SCREEN: {
4974 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004975 IPCThreadState* ipc = IPCThreadState::self();
4976 const int pid = ipc->getCallingPid();
4977 const int uid = ipc->getCallingUid();
4978 if ((uid != AID_GRAPHICS) &&
4979 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4980 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4981 return PERMISSION_DENIED;
4982 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004983 return OK;
4984 }
4985 // The following codes are deprecated and should never be allowed to access SF.
4986 case CONNECT_DISPLAY_UNUSED:
4987 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4988 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4989 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004990 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004991 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004992
4993 // These codes are used for the IBinder protocol to either interrogate the recipient
4994 // side of the transaction for its canonical interface descriptor or to dump its state.
4995 // We let them pass by default.
4996 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4997 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4998 code == IBinder::SYSPROPS_TRANSACTION) {
4999 return OK;
5000 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005001 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005002 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005003 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005004 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5005 return OK;
5006 }
5007 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5008 return PERMISSION_DENIED;
5009#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005010}
5011
Ana Krulec13be8ad2018-08-21 02:43:56 +00005012status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5013 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005014 status_t credentialCheck = CheckTransactCodeCredentials(code);
5015 if (credentialCheck != OK) {
5016 return credentialCheck;
5017 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005018
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005019 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5020 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005021 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005022 IPCThreadState* ipc = IPCThreadState::self();
5023 const int uid = ipc->getCallingUid();
5024 if (CC_UNLIKELY(uid != AID_SYSTEM
5025 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005026 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005027 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005028 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005029 return PERMISSION_DENIED;
5030 }
5031 int n;
5032 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005033 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005034 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005035 return NO_ERROR;
5036 case 1002: // SHOW_UPDATES
5037 n = data.readInt32();
5038 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005039 invalidateHwcGeometry();
5040 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005041 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005042 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005043 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005044 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005045 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005046 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005047 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005048 setTransactionFlags(
5049 eTransactionNeeded|
5050 eDisplayTransactionNeeded|
5051 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005052 return NO_ERROR;
5053 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005054 case 1006:{ // send empty update
5055 signalRefresh();
5056 return NO_ERROR;
5057 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005058 case 1008: // toggle use of hw composer
5059 n = data.readInt32();
5060 mDebugDisableHWC = n ? 1 : 0;
5061 invalidateHwcGeometry();
5062 repaintEverything();
5063 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005064 case 1009: // toggle use of transform hint
5065 n = data.readInt32();
5066 mDebugDisableTransformHint = n ? 1 : 0;
5067 invalidateHwcGeometry();
5068 repaintEverything();
5069 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005070 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005071 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005072 reply->writeInt32(0);
5073 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005074 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005075 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005076 return NO_ERROR;
5077 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005078 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005079 if (!display) {
5080 return NAME_NOT_FOUND;
5081 }
5082
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005083 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005084 return NO_ERROR;
5085 }
5086 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005087 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005088 // daltonize
5089 n = data.readInt32();
5090 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005091 case 1:
5092 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5093 break;
5094 case 2:
5095 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5096 break;
5097 case 3:
5098 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5099 break;
5100 default:
5101 mDaltonizer.setType(ColorBlindnessType::None);
5102 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005103 }
5104 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005105 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005106 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005107 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005108 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005109
5110 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005111 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005112 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005113 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005114 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005115 // apply a color matrix
5116 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005117 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005118 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005119 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005120 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005121 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005122 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005123 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005124 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005125 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005126 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005127
5128 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5129 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005130 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005131 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5132 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5133 }
5134
Chia-I Wu28f320b2018-05-03 11:02:56 -07005135 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005136 return NO_ERROR;
5137 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005138 // This is an experimental interface
5139 // Needs to be shifted to proper binder interface when we productize
5140 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005141 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005142 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005143 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005144 return NO_ERROR;
5145 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005146 case 1017: {
5147 n = data.readInt32();
5148 mForceFullDamage = static_cast<bool>(n);
5149 return NO_ERROR;
5150 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005151 case 1018: { // Modify Choreographer's phase offset
5152 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005153 if (mUseScheduler) {
5154 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5155 } else {
5156 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5157 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005158 return NO_ERROR;
5159 }
5160 case 1019: { // Modify SurfaceFlinger's phase offset
5161 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005162 if (mUseScheduler) {
5163 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5164 } else {
5165 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5166 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005167 return NO_ERROR;
5168 }
Irvel468051e2016-06-13 16:44:44 -07005169 case 1020: { // Layer updates interceptor
5170 n = data.readInt32();
5171 if (n) {
5172 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005173 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005174 }
5175 else{
5176 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005177 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005178 }
5179 return NO_ERROR;
5180 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005181 case 1021: { // Disable HWC virtual displays
5182 n = data.readInt32();
5183 mUseHwcVirtualDisplays = !n;
5184 return NO_ERROR;
5185 }
Romain Guy0147a172017-06-01 13:53:56 -07005186 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005187 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005188 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005189
Chia-I Wu28f320b2018-05-03 11:02:56 -07005190 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005191 return NO_ERROR;
5192 }
Romain Guy54f154a2017-10-24 21:40:32 +01005193 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005194 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005195 invalidateHwcGeometry();
5196 repaintEverything();
5197 return NO_ERROR;
5198 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005199 // Deprecate, use 1030 to check whether the device is color managed.
5200 case 1024: {
5201 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005202 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005203 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005204 n = data.readInt32();
5205 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005206 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005207 mTracing.enable();
5208 doTracing("tracing.enable");
5209 reply->writeInt32(NO_ERROR);
5210 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005211 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005212 status_t err = mTracing.disable();
5213 reply->writeInt32(err);
5214 }
5215 return NO_ERROR;
5216 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005217 case 1026: { // Get layer tracing status
5218 reply->writeBool(mTracing.isEnabled());
5219 return NO_ERROR;
5220 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005221 // Is a DisplayColorSetting supported?
5222 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005223 const auto display = getDefaultDisplayDevice();
5224 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005225 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005226 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005227
5228 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5229 switch (setting) {
5230 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005231 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005232 break;
5233 case DisplayColorSetting::UNMANAGED:
5234 reply->writeBool(true);
5235 break;
5236 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005237 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005238 break;
5239 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005240 reply->writeBool(
5241 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005242 break;
5243 }
5244 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005245 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005246 // Is VrFlinger active?
5247 case 1028: {
5248 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005249 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005250 return NO_ERROR;
5251 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005252 // Is device color managed?
5253 case 1030: {
5254 reply->writeBool(useColorManagement);
5255 return NO_ERROR;
5256 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005257 // Override default composition data space
5258 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5259 // && adb shell stop zygote && adb shell start zygote
5260 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5261 // adb shell stop zygote && adb shell start zygote
5262 case 1031: {
5263 Mutex::Autolock _l(mStateLock);
5264 n = data.readInt32();
5265 if (n) {
5266 n = data.readInt32();
5267 if (n) {
5268 Dataspace dataspace = static_cast<Dataspace>(n);
5269 if (!validateCompositionDataspace(dataspace)) {
5270 return BAD_VALUE;
5271 }
5272 mDefaultCompositionDataspace = dataspace;
5273 }
5274 n = data.readInt32();
5275 if (n) {
5276 Dataspace dataspace = static_cast<Dataspace>(n);
5277 if (!validateCompositionDataspace(dataspace)) {
5278 return BAD_VALUE;
5279 }
5280 mWideColorGamutCompositionDataspace = dataspace;
5281 }
5282 } else {
5283 // restore composition data space.
5284 mDefaultCompositionDataspace = defaultCompositionDataspace;
5285 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5286 }
5287 return NO_ERROR;
5288 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005289 }
5290 }
5291 return err;
5292}
5293
Steven Thomas6d8110b2017-08-31 18:24:21 -07005294void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005295 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005296 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005297}
5298
Ana Krulec7d1d6832018-12-27 11:10:09 -08005299void SurfaceFlinger::repaintEverythingForHWC() {
5300 mRepaintEverything = true;
5301 mEventQueue->invalidateForHWC();
5302}
5303
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005304// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5305class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005306public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005307 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5308 ~WindowDisconnector() {
5309 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005310 }
5311
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005312private:
5313 ANativeWindow* mWindow;
5314 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005315};
5316
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005317status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005318 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5319 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005320 uint32_t reqWidth, uint32_t reqHeight,
5321 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005322 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005323 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005324
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005325 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005326
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005327 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5328
Chia-I Wu20261cb2018-08-23 12:55:44 -07005329 sp<DisplayDevice> display;
5330 {
5331 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005332
Chia-I Wu20261cb2018-08-23 12:55:44 -07005333 display = getDisplayDeviceLocked(displayToken);
5334 if (!display) return BAD_VALUE;
5335
Chia-I Wucb023152018-08-28 12:57:23 -07005336 // set the requested width/height to the logical display viewport size
5337 // by default
5338 if (reqWidth == 0 || reqHeight == 0) {
5339 reqWidth = uint32_t(display->getViewport().width());
5340 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005341 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005342 }
5343
Peiyong Lin0e003c92018-09-17 11:09:51 -07005344 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5345 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005346
5347 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005348 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005349 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5350 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005351}
5352
5353status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005354 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5355 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005356 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005357 ATRACE_CALL();
5358
5359 class LayerRenderArea : public RenderArea {
5360 public:
Robert Carr578038f2018-03-09 12:25:24 -08005361 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005362 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5363 bool childrenOnly)
5364 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005365 mLayer(layer),
5366 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005367 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005368 mFlinger(flinger),
5369 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005370 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005371 Rect getBounds() const override {
5372 const Layer::State& layerState(mLayer->getDrawingState());
5373 return mLayer->getBufferSize(layerState);
5374 }
Marissa Wall61c58622018-07-18 10:12:20 -07005375 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005376 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005377 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005378 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005379 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005380 }
chaviwa76b2712017-09-20 12:02:26 -07005381 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005382 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005383 Rect getSourceCrop() const override {
5384 if (mCrop.isEmpty()) {
5385 return getBounds();
5386 } else {
5387 return mCrop;
5388 }
5389 }
Robert Carr578038f2018-03-09 12:25:24 -08005390 class ReparentForDrawing {
5391 public:
5392 const sp<Layer>& oldParent;
5393 const sp<Layer>& newParent;
5394
5395 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5396 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005397 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005398 }
Robert Carr15eae092018-03-23 13:43:53 -07005399 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005400 };
5401
5402 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005403 const Rect sourceCrop = getSourceCrop();
5404 // no need to check rotation because there is none
5405 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5406 sourceCrop.height() != getReqHeight();
5407
Robert Carr578038f2018-03-09 12:25:24 -08005408 if (!mChildrenOnly) {
5409 mTransform = mLayer->getTransform().inverse();
5410 drawLayers();
5411 } else {
5412 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005413 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005414 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5415 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005416
5417 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5418 drawLayers();
5419 }
5420 }
chaviwa76b2712017-09-20 12:02:26 -07005421
chaviwa76b2712017-09-20 12:02:26 -07005422 private:
chaviw7206d492017-11-10 16:16:12 -08005423 const sp<Layer> mLayer;
5424 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005425
5426 // In the "childrenOnly" case we reparent the children to a screenshot
5427 // layer which has no properties set and which does not draw.
5428 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005429 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005430 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005431
5432 SurfaceFlinger* mFlinger;
5433 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005434 };
5435
5436 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5437 auto parent = layerHandle->owner.promote();
5438
Robert Carr2e102c92018-10-23 12:11:15 -07005439 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005440 ALOGE("captureLayers called with a removed parent");
5441 return NAME_NOT_FOUND;
5442 }
5443
Robert Carr578038f2018-03-09 12:25:24 -08005444 const int uid = IPCThreadState::self()->getCallingUid();
5445 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005446 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005447 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5448 return PERMISSION_DENIED;
5449 }
5450
chaviw7206d492017-11-10 16:16:12 -08005451 Rect crop(sourceCrop);
5452 if (sourceCrop.width() <= 0) {
5453 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005454 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005455 }
5456
5457 if (sourceCrop.height() <= 0) {
5458 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005459 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005460 }
5461
5462 int32_t reqWidth = crop.width() * frameScale;
5463 int32_t reqHeight = crop.height() * frameScale;
5464
Chia-I Wu20261cb2018-08-23 12:55:44 -07005465 // really small crop or frameScale
5466 if (reqWidth <= 0) {
5467 reqWidth = 1;
5468 }
5469 if (reqHeight <= 0) {
5470 reqHeight = 1;
5471 }
5472
Peiyong Lin0e003c92018-09-17 11:09:51 -07005473 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005474
Robert Carr578038f2018-03-09 12:25:24 -08005475 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005476 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5477 if (!layer->isVisible()) {
5478 return;
Robert Carr578038f2018-03-09 12:25:24 -08005479 } else if (childrenOnly && layer == parent.get()) {
5480 return;
chaviwa76b2712017-09-20 12:02:26 -07005481 }
5482 visitor(layer);
5483 });
5484 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005485 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005486}
5487
5488status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5489 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005490 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005491 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005492 bool useIdentityTransform) {
5493 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005494
Peiyong Lin0e003c92018-09-17 11:09:51 -07005495 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005496 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5497 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005498 *outBuffer =
5499 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5500 static_cast<android_pixel_format>(reqPixelFormat), 1,
5501 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005502
5503 // This mutex protects syncFd and captureResult for communication of the return values from the
5504 // main thread back to this Binder thread
5505 std::mutex captureMutex;
5506 std::condition_variable captureCondition;
5507 std::unique_lock<std::mutex> captureLock(captureMutex);
5508 int syncFd = -1;
5509 std::optional<status_t> captureResult;
5510
Robert Carr03480e22018-01-04 16:02:06 -08005511 const int uid = IPCThreadState::self()->getCallingUid();
5512 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5513
Dominik Laskowski8c001672018-05-30 16:52:06 -07005514 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005515 // If there is a refresh pending, bug out early and tell the binder thread to try again
5516 // after the refresh.
5517 if (mRefreshPending) {
5518 ATRACE_NAME("Skipping screenshot for now");
5519 std::unique_lock<std::mutex> captureLock(captureMutex);
5520 captureResult = std::make_optional<status_t>(EAGAIN);
5521 captureCondition.notify_one();
5522 return;
5523 }
5524
5525 status_t result = NO_ERROR;
5526 int fd = -1;
5527 {
5528 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005529 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005530 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5531 useIdentityTransform, forSystem, &fd);
5532 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005533 }
5534
5535 {
5536 std::unique_lock<std::mutex> captureLock(captureMutex);
5537 syncFd = fd;
5538 captureResult = std::make_optional<status_t>(result);
5539 captureCondition.notify_one();
5540 }
5541 });
5542
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005543 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005544 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005545 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005546 while (*captureResult == EAGAIN) {
5547 captureResult.reset();
5548 result = postMessageAsync(message);
5549 if (result != NO_ERROR) {
5550 return result;
5551 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005552 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005553 }
5554 result = *captureResult;
5555 }
5556
5557 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005558 sync_wait(syncFd, -1);
5559 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005560 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005561
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005562 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005563}
5564
chaviwa76b2712017-09-20 12:02:26 -07005565void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005566 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005567 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005568 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005569
Lloyd Pique144e1162017-12-20 16:44:52 -08005570 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005571
chaviwa76b2712017-09-20 12:02:26 -07005572 const auto reqWidth = renderArea.getReqWidth();
5573 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005574 const auto sourceCrop = renderArea.getSourceCrop();
5575 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005576
Peiyong Lin0e003c92018-09-17 11:09:51 -07005577 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005578 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005579
Mathias Agopian180f10d2013-04-10 22:55:41 -07005580 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005581 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005582
5583 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005584 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005585 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005586
chaviw50da5042018-04-09 13:49:37 -07005587 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005588 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005589 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005590
chaviwa76b2712017-09-20 12:02:26 -07005591 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005592 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005593 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005594 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005595 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005596}
5597
chaviwa76b2712017-09-20 12:02:26 -07005598status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5599 TraverseLayersFunction traverseLayers,
5600 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005601 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005602 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005603 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005604 ATRACE_CALL();
5605
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005606 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005607
5608 traverseLayers([&](Layer* layer) {
5609 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5610 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005611
Robert Carr03480e22018-01-04 16:02:06 -08005612 // We allow the system server to take screenshots of secure layers for
5613 // use in situations like the Screen-rotation animation and place
5614 // the impetus on WindowManager to not persist them.
5615 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005616 ALOGW("FB is protected: PERMISSION_DENIED");
5617 return PERMISSION_DENIED;
5618 }
Peiyong Linfb530cf2018-12-15 05:07:38 +00005619 auto& engine(getRenderEngine());
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005620
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005621 // this binds the given EGLImage as a framebuffer for the
5622 // duration of this scope.
Peiyong Linfb530cf2018-12-15 05:07:38 +00005623 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005624 if (bufferBond.getStatus() != NO_ERROR) {
5625 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005626 return INVALID_OPERATION;
5627 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005628
Dan Stozaabcda352017-06-01 14:37:39 -07005629 // this will in fact render into our dequeued buffer
5630 // via an FBO, which means we didn't have to create
5631 // an EGLSurface and therefore we're not
5632 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005633 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005634
Peiyong Linfb530cf2018-12-15 05:07:38 +00005635 base::unique_fd syncFd = engine.flush();
Alec Mouri492bc572018-09-11 21:40:04 +00005636 if (syncFd < 0) {
Peiyong Linfb530cf2018-12-15 05:07:38 +00005637 engine.finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005638 }
Alec Mouri492bc572018-09-11 21:40:04 +00005639 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005640
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005641 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005642}
5643
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005644// ---------------------------------------------------------------------------
5645
Dan Stoza412903f2017-04-27 13:42:17 -07005646void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5647 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005648}
5649
Dan Stoza412903f2017-04-27 13:42:17 -07005650void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5651 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005652}
5653
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005654void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005655 const LayerVector::Visitor& visitor) {
5656 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005657 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005658 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005659 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005660 continue;
5661 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005662 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005663 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005664 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005665 return;
5666 }
chaviwa76b2712017-09-20 12:02:26 -07005667 if (!layer->isVisible()) {
5668 return;
5669 }
5670 visitor(layer);
5671 });
5672 }
5673}
5674
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005675}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005676
Lloyd Pique074e8122018-07-26 12:57:23 -07005677
Mathias Agopian3f844832013-08-07 21:24:32 -07005678#if defined(__gl_h_)
5679#error "don't include gl/gl.h in this file"
5680#endif
5681
5682#if defined(__gl2_h_)
5683#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005684#endif