blob: 61bf9090b479527dd91e9907e72f3a4c2d22c572 [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 */); });
Ana Krulecb43429d2019-01-09 14:28:51 -0800741 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(
742 getHwComposer().getConfigs(*display->getId()));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800743 }
744
Dan Stoza9e56aa02015-11-02 13:00:03 -0800745 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700746}
747
Romain Guy11d63f42017-07-20 12:47:14 -0700748void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700749 Mutex::Autolock _l(mStateLock);
750
Romain Guy11d63f42017-07-20 12:47:14 -0700751 char value[PROPERTY_VALUE_MAX];
752
753 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800754 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700755 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800756 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100757
758 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700759 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700760}
761
Mathias Agopiana67e4182012-06-19 17:26:12 -0700762void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800763 // Start boot animation service by setting a property mailbox
764 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700765 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800766 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700767 if (mStartPropertySetThread->join() != NO_ERROR) {
768 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800769 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700770}
771
Mathias Agopian875d8e12013-06-07 15:35:48 -0700772size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700773 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700774}
775
Mathias Agopian875d8e12013-06-07 15:35:48 -0700776size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700777 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700778}
779
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800780// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800781
Jamie Gennis582270d2011-08-17 18:19:00 -0700782bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800783 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800784 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800785 return authenticateSurfaceTextureLocked(bufferProducer);
786}
787
788bool SurfaceFlinger::authenticateSurfaceTextureLocked(
789 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800790 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800791 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800792}
793
Brian Anderson6b376712017-04-04 10:51:39 -0700794status_t SurfaceFlinger::getSupportedFrameTimestamps(
795 std::vector<FrameEvent>* outSupported) const {
796 *outSupported = {
797 FrameEvent::REQUESTED_PRESENT,
798 FrameEvent::ACQUIRE,
799 FrameEvent::LATCH,
800 FrameEvent::FIRST_REFRESH_START,
801 FrameEvent::LAST_REFRESH_START,
802 FrameEvent::GPU_COMPOSITION_DONE,
803 FrameEvent::DEQUEUE_READY,
804 FrameEvent::RELEASE,
805 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700806 ConditionalLock _l(mStateLock,
807 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700808 if (!getHwComposer().hasCapability(
809 HWC2::Capability::PresentFenceIsNotReliable)) {
810 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
811 }
812 return NO_ERROR;
813}
814
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700815status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
816 Vector<DisplayInfo>* configs) {
817 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700818 return BAD_VALUE;
819 }
820
Dominik Laskowski075d3172018-05-24 15:50:06 -0700821 const auto displayId = getPhysicalDisplayId(displayToken);
822 if (!displayId) {
823 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700824 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700825
Mathias Agopian8b736f12012-08-13 17:54:26 -0700826 // TODO: Not sure if display density should handled by SF any longer
827 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700828 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700829 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700830 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800831 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700832 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700833 }
834 return density;
835 }
836 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700837 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700838 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700839 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700840 return getDensityFromProperty("ro.sf.lcd_density"); }
841 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700842
Dan Stoza7f7da322014-05-02 15:26:25 -0700843 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700844
Steven Thomas6d8110b2017-08-31 18:24:21 -0700845 ConditionalLock _l(mStateLock,
846 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700847 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700848 DisplayInfo info = DisplayInfo();
849
Dan Stoza9e56aa02015-11-02 13:00:03 -0800850 float xdpi = hwConfig->getDpiX();
851 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700852
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700853 info.w = hwConfig->getWidth();
854 info.h = hwConfig->getHeight();
855 // Default display viewport to display width and height
856 info.viewportW = info.w;
857 info.viewportH = info.h;
858
Dominik Laskowski075d3172018-05-24 15:50:06 -0700859 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700860 // The density of the device is provided by a build property
861 float density = Density::getBuildDensity() / 160.0f;
862 if (density == 0) {
863 // the build doesn't provide a density -- this is wrong!
864 // use xdpi instead
865 ALOGE("ro.sf.lcd_density must be defined as a build property");
866 density = xdpi / 160.0f;
867 }
868 if (Density::getEmuDensity()) {
869 // if "qemu.sf.lcd_density" is specified, it overrides everything
870 xdpi = ydpi = density = Density::getEmuDensity();
871 density /= 160.0f;
872 }
873 info.density = density;
874
875 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700876 const auto display = getDefaultDisplayDeviceLocked();
877 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700878
879 // This is for screenrecord
880 const Rect viewport = display->getViewport();
881 if (viewport.isValid()) {
882 info.viewportW = uint32_t(viewport.getWidth());
883 info.viewportH = uint32_t(viewport.getHeight());
884 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700885 } else {
886 // TODO: where should this value come from?
887 static const int TV_DENSITY = 213;
888 info.density = TV_DENSITY / 160.0f;
889 info.orientation = 0;
890 }
891
Dan Stoza7f7da322014-05-02 15:26:25 -0700892 info.xdpi = xdpi;
893 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800894 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900895 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800896
Andy McFadden91b2ca82014-06-13 14:04:23 -0700897 // This is how far in advance a buffer must be queued for
898 // presentation at a given time. If you want a buffer to appear
899 // on the screen at time N, you must submit the buffer before
900 // (N - presentationDeadline).
901 //
902 // Normally it's one full refresh period (to give SF a chance to
903 // latch the buffer), but this can be reduced by configuring a
904 // DispSync offset. Any additional delays introduced by the hardware
905 // composer or panel must be accounted for here.
906 //
907 // We add an additional 1ms to allow for processing time and
908 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800909 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800910 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700911
912 // All non-virtual displays are currently considered secure.
913 info.secure = true;
914
Dominik Laskowski075d3172018-05-24 15:50:06 -0700915 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700916 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800917 std::swap(info.w, info.h);
918 }
919
Michael Wright28f24d02016-07-12 13:30:53 -0700920 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700921 }
922
Dan Stoza7f7da322014-05-02 15:26:25 -0700923 return NO_ERROR;
924}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700925
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700926status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
927 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700928 return BAD_VALUE;
929 }
930
Ana Krulece588e312018-09-18 12:32:24 -0700931 if (mUseScheduler) {
932 mScheduler->getDisplayStatInfo(stats);
933 } else {
934 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
935 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
936 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700937 return NO_ERROR;
938}
939
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700940int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
941 const auto display = getDisplayDevice(displayToken);
942 if (!display) {
943 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800944 return BAD_VALUE;
945 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700946
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700947 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700948}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700949
Ana Krulec7d1d6832018-12-27 11:10:09 -0800950status_t SurfaceFlinger::setActiveConfigAsync(const sp<IBinder>& displayToken, int mode) {
951 ATRACE_NAME("setActiveConfigAsync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800952 postMessageAsync(new LambdaMessage(
953 [=]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800954 return NO_ERROR;
955}
956
957status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
958 ATRACE_NAME("setActiveConfigSync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800959 postMessageSync(new LambdaMessage(
960 [&]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800961 return NO_ERROR;
962}
963
964void SurfaceFlinger::setActiveConfigInternal(const sp<IBinder>& displayToken, int mode) {
965 Vector<DisplayInfo> configs;
966 getDisplayConfigs(displayToken, &configs);
967 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
968 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
969 return;
970 }
971
972 const auto display = getDisplayDevice(displayToken);
973 if (!display) {
974 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
975 displayToken.get());
976 return;
977 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700978 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800979 ALOGW("Attempt to set active config %d for virtual display", mode);
980 return;
981 }
982 int currentDisplayPowerMode = display->getPowerMode();
983 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
984 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700985 return;
986 }
987
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700988 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700989 if (mode == currentMode) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800990 // Don't update config if we are already running in the desired mode.
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700991 return;
992 }
Ana Krulecb43429d2019-01-09 14:28:51 -0800993 if (mUseScheduler) {
994 mRefreshRateStats->setConfigMode(mode);
995 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700996
Dominik Laskowski075d3172018-05-24 15:50:06 -0700997 const auto displayId = display->getId();
998 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700999
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001000 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001001 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001002
Ana Krulec7d1d6832018-12-27 11:10:09 -08001003 ATRACE_INT("ActiveConfigMode", mode);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001004 resyncToHardwareVsync(true, getVsyncPeriod());
Mathias Agopianc666cae2012-07-25 18:56:13 -07001005}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001006
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001007status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1008 Vector<ColorMode>* outColorModes) {
1009 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001010 return BAD_VALUE;
1011 }
1012
Dominik Laskowski075d3172018-05-24 15:50:06 -07001013 const auto displayId = getPhysicalDisplayId(displayToken);
1014 if (!displayId) {
1015 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -07001016 }
1017
Peiyong Lina52f0292018-03-14 17:26:31 -07001018 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001019 {
1020 ConditionalLock _l(mStateLock,
1021 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001022 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001023 }
Michael Wright28f24d02016-07-12 13:30:53 -07001024 outColorModes->clear();
1025 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1026
1027 return NO_ERROR;
1028}
1029
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001030ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1031 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001032 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001033 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001034 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001035}
1036
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001037status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001038 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001039 Vector<ColorMode> modes;
1040 getDisplayColorModes(displayToken, &modes);
1041 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1042 if (mode < ColorMode::NATIVE || !exists) {
1043 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1044 decodeColorMode(mode).c_str(), mode, displayToken.get());
1045 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001046 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001047 const auto display = getDisplayDevice(displayToken);
1048 if (!display) {
1049 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1050 decodeColorMode(mode).c_str(), mode, displayToken.get());
1051 } else if (display->isVirtual()) {
1052 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1053 decodeColorMode(mode).c_str(), mode);
1054 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001055 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1056 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001057 }
1058 }));
1059
Michael Wright28f24d02016-07-12 13:30:53 -07001060 return NO_ERROR;
1061}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001062
Svetoslavd85084b2014-03-20 10:28:31 -07001063status_t SurfaceFlinger::clearAnimationFrameStats() {
1064 Mutex::Autolock _l(mStateLock);
1065 mAnimFrameTracker.clearStats();
1066 return NO_ERROR;
1067}
1068
1069status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1070 Mutex::Autolock _l(mStateLock);
1071 mAnimFrameTracker.getStats(outStats);
1072 return NO_ERROR;
1073}
1074
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001075status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1076 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001077 Mutex::Autolock _l(mStateLock);
1078
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001079 const auto display = getDisplayDeviceLocked(displayToken);
1080 if (!display) {
1081 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001082 return BAD_VALUE;
1083 }
1084
Peiyong Linfb069302018-04-25 14:34:31 -07001085 // At this point the DisplayDeivce should already be set up,
1086 // meaning the luminance information is already queried from
1087 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001088 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001089 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1090 capabilities.getDesiredMaxLuminance(),
1091 capabilities.getDesiredMaxAverageLuminance(),
1092 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001093
1094 return NO_ERROR;
1095}
1096
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001097status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1098 ui::PixelFormat* outFormat,
1099 ui::Dataspace* outDataspace,
1100 uint8_t* outComponentMask) const {
1101 if (!outFormat || !outDataspace || !outComponentMask) {
1102 return BAD_VALUE;
1103 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001104 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001105 if (!display || !display->getId()) {
1106 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1107 return BAD_VALUE;
1108 }
1109 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1110 outDataspace, outComponentMask);
1111}
1112
Kevin DuBois74e53772018-11-19 10:52:38 -08001113status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1114 bool enable, uint8_t componentMask,
1115 uint64_t maxFrames) const {
1116 const auto display = getDisplayDevice(displayToken);
1117 if (!display || !display->getId()) {
1118 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1119 return BAD_VALUE;
1120 }
1121
1122 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1123 componentMask, maxFrames);
1124}
1125
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001126status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1127 uint64_t maxFrames, uint64_t timestamp,
1128 DisplayedFrameStats* outStats) const {
1129 const auto display = getDisplayDevice(displayToken);
1130 if (!display || !display->getId()) {
1131 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1132 return BAD_VALUE;
1133 }
1134
1135 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1136 outStats);
1137}
1138
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001139status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1140 if (!outSupported) {
1141 return BAD_VALUE;
1142 }
1143 *outSupported = getRenderEngine().supportsProtectedContent();
1144 return NO_ERROR;
1145}
1146
Marissa Wallebc2c052019-01-16 19:16:55 -08001147status_t SurfaceFlinger::cacheBuffer(const sp<IBinder>& token, const sp<GraphicBuffer>& buffer,
1148 int32_t* outBufferId) {
1149 if (!outBufferId) {
1150 return BAD_VALUE;
1151 }
1152 *outBufferId = mBufferStateLayerCache.add(token, buffer);
1153 return NO_ERROR;
1154}
1155
1156status_t SurfaceFlinger::uncacheBuffer(const sp<IBinder>& token, int32_t bufferId) {
1157 mBufferStateLayerCache.release(token, bufferId);
1158 return NO_ERROR;
1159}
1160
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001161status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1162 bool* outIsWideColorDisplay) const {
1163 if (!displayToken || !outIsWideColorDisplay) {
1164 return BAD_VALUE;
1165 }
1166 Mutex::Autolock _l(mStateLock);
1167 const auto display = getDisplayDeviceLocked(displayToken);
1168 if (!display) {
1169 return BAD_VALUE;
1170 }
1171 *outIsWideColorDisplay = display->hasWideColorGamut();
1172 return NO_ERROR;
1173}
1174
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001175status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001176 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001177 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001178
Chia-I Wu90f669f2017-10-05 14:24:41 -07001179 if (mInjectVSyncs == enable) {
1180 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001181 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001182
Dominik Laskowski83b88212018-12-11 13:34:06 -08001183 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001184
Ana Krulec98b5b242018-08-10 15:03:23 -07001185 // TODO(akrulec): Part of the Injector should be refactored, so that it
1186 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001187 if (enable) {
1188 ALOGV("VSync Injections enabled");
1189 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001190 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001191 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001192 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001193 impl::EventThread::InterceptVSyncsCallback(),
1194 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001195 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001196 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001197 } else {
1198 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001199 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001200 }
1201
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001202 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001203 }));
1204
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001205 return NO_ERROR;
1206}
1207
1208status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001209 Mutex::Autolock _l(mStateLock);
1210
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001211 if (!mInjectVSyncs) {
1212 ALOGE("VSync Injections not enabled");
1213 return BAD_VALUE;
1214 }
1215 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1216 ALOGV("Injecting VSync inside SurfaceFlinger");
1217 mVSyncInjector->onInjectSyncEvent(when);
1218 }
1219 return NO_ERROR;
1220}
1221
Lloyd Pique755e3192018-01-31 16:46:15 -08001222status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1223 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001224 // Try to acquire a lock for 1s, fail gracefully
1225 const status_t err = mStateLock.timedLock(s2ns(1));
1226 const bool locked = (err == NO_ERROR);
1227 if (!locked) {
1228 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1229 return TIMED_OUT;
1230 }
1231
1232 outLayers->clear();
1233 mCurrentState.traverseInZOrder([&](Layer* layer) {
1234 outLayers->push_back(layer->getLayerDebugInfo());
1235 });
1236
1237 mStateLock.unlock();
1238 return NO_ERROR;
1239}
1240
Peiyong Linc6780972018-10-28 15:24:08 -07001241status_t SurfaceFlinger::getCompositionPreference(
1242 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1243 Dataspace* outWideColorGamutDataspace,
1244 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001245 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001246 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001247 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001248 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001249 return NO_ERROR;
1250}
1251
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001252// ----------------------------------------------------------------------------
1253
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001254sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1255 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001256 auto resyncCallback = makeResyncCallback([this] {
1257 Mutex::Autolock lock(mStateLock);
1258 return getVsyncPeriod();
1259 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001260
Ana Krulec98b5b242018-08-10 15:03:23 -07001261 if (mUseScheduler) {
1262 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001263 return mScheduler->createDisplayEventConnection(mSfConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001264 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001265 return mScheduler->createDisplayEventConnection(mAppConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001266 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001267 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001268 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001269 return mSFEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001270 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001271 return mEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001272 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001273 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001274}
1275
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001276// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001277
1278void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001279 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001280}
1281
1282void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001283 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001284}
1285
1286void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001287 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001288}
1289
1290void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001291 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001292 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001293}
1294
1295status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001296 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001297 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001298}
1299
1300status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001301 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001302 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001303 if (res == NO_ERROR) {
1304 msg->wait();
1305 }
1306 return res;
1307}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001308
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001309void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001310 do {
1311 waitForEvent();
1312 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001313}
1314
Dominik Laskowski83b88212018-12-11 13:34:06 -08001315nsecs_t SurfaceFlinger::getVsyncPeriod() const {
1316 const auto displayId = getInternalDisplayId();
1317 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1318 return 0;
1319 }
1320
1321 const auto config = getHwComposer().getActiveConfig(*displayId);
1322 return config ? config->getVsyncPeriod() : 0;
1323}
1324
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001325void SurfaceFlinger::enableHardwareVsync() {
1326 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001327 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001328 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001329 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001330 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001331 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001332}
1333
Dominik Laskowski83b88212018-12-11 13:34:06 -08001334void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001335 Mutex::Autolock _l(mHWVsyncLock);
1336
Jesse Hall948fe0c2013-10-14 12:56:09 -07001337 if (makeAvailable) {
1338 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001339 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1340 if (mUseScheduler) {
1341 mScheduler->makeHWSyncAvailable(true);
1342 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001343 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001344 // Hardware vsync is not currently available, so abort the resync
1345 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001346 return;
1347 }
1348
Dominik Laskowski83b88212018-12-11 13:34:06 -08001349 if (period <= 0) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001350 return;
1351 }
1352
Ana Krulece588e312018-09-18 12:32:24 -07001353 if (mUseScheduler) {
1354 mScheduler->setVsyncPeriod(period);
1355 } else {
1356 mPrimaryDispSync->reset();
1357 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001358
Ana Krulece588e312018-09-18 12:32:24 -07001359 if (!mPrimaryHWVsyncEnabled) {
1360 mPrimaryDispSync->beginResync();
1361 mEventControlThread->setVsyncEnabled(true);
1362 mPrimaryHWVsyncEnabled = true;
1363 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001364 }
1365}
1366
Jesse Hall948fe0c2013-10-14 12:56:09 -07001367void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001368 Mutex::Autolock _l(mHWVsyncLock);
1369 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001370 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001371 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001372 mPrimaryHWVsyncEnabled = false;
1373 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001374 if (makeUnavailable) {
1375 mHWVsyncAvailable = false;
1376 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001377}
1378
Dominik Laskowski83b88212018-12-11 13:34:06 -08001379void SurfaceFlinger::VsyncState::resync(const GetVsyncPeriod& getVsyncPeriod) {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001380 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001381
Dan Stoza57164302017-05-08 14:03:54 -07001382 const nsecs_t now = systemTime();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001383 const nsecs_t last = lastResyncTime.exchange(now);
1384
1385 if (now - last > kIgnoreDelay) {
1386 flinger.resyncToHardwareVsync(false, getVsyncPeriod());
Tim Murray4a4e4a22016-04-19 16:29:23 +00001387 }
1388}
1389
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001390void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1391 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001392 ATRACE_NAME("SF onVsync");
1393
Steven Thomas3cfac282017-02-06 12:29:30 -08001394 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001395 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001396 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001397 return;
1398 }
1399
Dominik Laskowski075d3172018-05-24 15:50:06 -07001400 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001401 return;
1402 }
1403
Dominik Laskowski075d3172018-05-24 15:50:06 -07001404 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001405 // For now, we don't do anything with external display vsyncs.
1406 return;
1407 }
1408
Ana Krulece588e312018-09-18 12:32:24 -07001409 if (mUseScheduler) {
1410 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001411 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001412 bool needsHwVsync = false;
1413 { // Scope for the lock
1414 Mutex::Autolock _l(mHWVsyncLock);
1415 if (mPrimaryHWVsyncEnabled) {
1416 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1417 }
1418 }
1419
1420 if (needsHwVsync) {
1421 enableHardwareVsync();
1422 } else {
1423 disableHardwareVsync(false);
1424 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001425 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001426}
1427
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001428void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001429 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1430 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001431}
1432
Ana Krulec7d1d6832018-12-27 11:10:09 -08001433void SurfaceFlinger::setRefreshRateTo(float newFps) {
1434 const auto displayId = getInternalDisplayId();
1435 if (!displayId || mBootStage != BootStage::FINISHED) {
1436 return;
1437 }
1438 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1439 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1440 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1441 // refresh cycle.
1442
1443 // Don't do any updating if the current fps is the same as the new one.
1444 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
1445 const nsecs_t currentVsyncPeriod = activeConfig->getVsyncPeriod();
1446 if (currentVsyncPeriod == 0) {
1447 return;
1448 }
1449 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1450 // floating numbers.
1451 const float currentFps = 1e9 / currentVsyncPeriod;
1452 if (std::abs(currentFps - newFps) <= 1) {
1453 return;
1454 }
1455
1456 auto configs = getHwComposer().getConfigs(*displayId);
1457 for (int i = 0; i < configs.size(); i++) {
1458 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1459 if (vsyncPeriod == 0) {
1460 continue;
1461 }
1462 const float fps = 1e9 / vsyncPeriod;
1463 // TODO(b/113612090): There should be a better way at determining which config
1464 // has the right refresh rate.
1465 if (std::abs(fps - newFps) <= 1) {
1466 const auto display = getBuiltInDisplay(HWC_DISPLAY_PRIMARY);
1467 if (!display) return;
1468 // This is posted in async function to avoid deadlock when getDisplayDevice
1469 // requires mStateLock.
1470 setActiveConfigAsync(display, i);
1471 ATRACE_INT("FPS", newFps);
1472 }
1473 }
1474}
1475
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001476void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001477 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001478 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001479 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001480
Lloyd Piqueba04e622017-12-14 17:11:26 -08001481 // Ignore events that do not have the right sequenceId.
1482 if (sequenceId != getBE().mComposerSequenceId) {
1483 return;
1484 }
1485
Steven Thomasb02664d2017-07-26 18:48:28 -07001486 // Only lock if we're not on the main thread. This function is normally
1487 // called on a hwbinder thread, but for the primary display it's called on
1488 // the main thread with the state lock already held, so don't attempt to
1489 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001490 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001491
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001492 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001493
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001494 if (std::this_thread::get_id() == mMainThreadId) {
1495 // Process all pending hot plug events immediately if we are on the main thread.
1496 processDisplayHotplugEventsLocked();
1497 }
1498
Lloyd Piqueba04e622017-12-14 17:11:26 -08001499 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001500}
1501
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001502void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001503 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001504 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001505 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001506 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001507 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001508}
1509
Dominik Laskowski075d3172018-05-24 15:50:06 -07001510void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001511 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001512 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001513 if (const auto displayId = getInternalDisplayId()) {
1514 getHwComposer().setVsyncEnabled(*displayId,
1515 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1516 }
Mathias Agopian86303202012-07-24 22:46:10 -07001517}
1518
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001519// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001520void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001521 if (mUseScheduler) {
1522 mScheduler->disableHardwareVsync(true);
1523 } else {
1524 disableHardwareVsync(true);
1525 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001526 // Clear the drawing state so that the logic inside of
1527 // handleTransactionLocked will fire. It will determine the delta between
1528 // mCurrentState and mDrawingState and re-apply all changes when we make the
1529 // transition.
1530 mDrawingState.displays.clear();
1531 mDisplays.clear();
1532}
1533
Steven Thomas050b2c82017-03-06 11:45:16 -08001534void SurfaceFlinger::updateVrFlinger() {
1535 if (!mVrFlinger)
1536 return;
1537 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001538 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001539 return;
1540 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001541
Lloyd Pique441d5042018-10-18 16:49:51 -07001542 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001543 ALOGE("Vr flinger is only supported for remote hardware composer"
1544 " service connections. Ignoring request to transition to vr"
1545 " flinger.");
1546 mVrFlingerRequestsDisplay = false;
1547 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001548 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001549
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001550 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001551
Steven Thomas0123ac62018-07-12 11:32:34 -07001552 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001553 LOG_ALWAYS_FATAL_IF(!display);
1554 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001555 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1556 // called below. Clear the reference now so we don't accidentally use it
1557 // later.
1558 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001559
Steven Thomasb02664d2017-07-26 18:48:28 -07001560 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001561 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001562 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001563
Steven Thomasb02664d2017-07-26 18:48:28 -07001564 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001565 // Delete the current instance before creating the new one
1566 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1567 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1568 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1569 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001570
Lloyd Pique441d5042018-10-18 16:49:51 -07001571 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001572 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001573
1574 if (vrFlingerRequestsDisplay) {
1575 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001576 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001577
1578 mVisibleRegionsDirty = true;
1579 invalidateHwcGeometry();
1580
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001581 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001582 display = getDefaultDisplayDeviceLocked();
1583 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001584 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001585
Steven Thomasb02664d2017-07-26 18:48:28 -07001586 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001587 const nsecs_t vsyncPeriod = getVsyncPeriod();
1588 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001589
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001590 // The present fences returned from vr_hwc are not an accurate
1591 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001592 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001593 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1594 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001595 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001596 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001597 !hasSyncFramework);
1598 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001599
Steven Thomasb02664d2017-07-26 18:48:28 -07001600 // Use phase of 0 since phase is not known.
1601 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001602 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001603 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001604
Dominik Laskowski83b88212018-12-11 13:34:06 -08001605 resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001606
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001607 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001608 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001609}
1610
Mathias Agopian4fec8732012-06-29 14:12:52 -07001611void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001612 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001613 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001614 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001615 if (mUseScheduler) {
1616 // This call is made each time SF wakes up and creates a new frame.
1617 mScheduler->incrementFrameCounter();
1618 }
Dan Stoza50182882016-07-08 12:02:20 -07001619 bool frameMissed = !mHadClientComposition &&
1620 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001621 (mPreviousPresentFence->getSignalTime() ==
1622 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001623 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001624 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001625 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001626 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001627 if (mPropagateBackpressure) {
1628 signalLayerUpdate();
1629 break;
1630 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001631 }
Dan Stoza50182882016-07-08 12:02:20 -07001632
Steven Thomas050b2c82017-03-06 11:45:16 -08001633 // Now that we're going to make it to the handleMessageTransaction()
1634 // call below it's safe to call updateVrFlinger(), which will
1635 // potentially trigger a display handoff.
1636 updateVrFlinger();
1637
Dan Stoza6b9454d2014-11-07 16:00:59 -08001638 bool refreshNeeded = handleMessageTransaction();
1639 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001640 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001641 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001642 // Signal a refresh if a transaction modified the window state,
1643 // a new buffer was latched, or if HWC has requested a full
1644 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001645 signalRefresh();
1646 }
1647 break;
1648 }
1649 case MessageQueue::REFRESH: {
1650 handleMessageRefresh();
1651 break;
1652 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001653 }
1654}
1655
Dan Stoza6b9454d2014-11-07 16:00:59 -08001656bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001657 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001658
1659 // Apply any ready transactions in the queues if there are still transactions that have not been
1660 // applied, wake up during the next vsync period and check again
1661 bool transactionNeeded = false;
1662 if (!flushTransactionQueues()) {
1663 transactionNeeded = true;
1664 }
1665
Mathias Agopian4fec8732012-06-29 14:12:52 -07001666 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001667 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001668 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001669
1670 if (transactionNeeded) {
1671 setTransactionFlags(eTransactionNeeded);
1672 }
1673
1674 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001675}
1676
Mathias Agopian4fec8732012-06-29 14:12:52 -07001677void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001678 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001679
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001680 mRefreshPending = false;
1681
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001682 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001683 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001684 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001685 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001686 for (const auto& [token, display] : mDisplays) {
1687 beginFrame(display);
1688 prepareFrame(display);
1689 doDebugFlashRegions(display, repaintEverything);
1690 doComposition(display, repaintEverything);
1691 }
1692
Adrian Roos1e1a1282017-11-01 19:05:31 +01001693 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001694 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001695
1696 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001697 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001698
Dan Stozabfbffeb2016-07-21 14:49:33 -07001699 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001700 for (const auto& [token, displayDevice] : mDisplays) {
1701 auto display = displayDevice->getCompositionDisplay();
1702 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001703 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001704 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001705 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001706
Alec Mouri86770e52018-09-24 22:40:58 +00001707 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001708 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001709 if (mHadClientComposition) {
1710 base::unique_fd flushFence(getRenderEngine().flush());
1711 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1712 getBE().flushFence = new Fence(std::move(flushFence));
1713 } else {
1714 // Cleanup for hygiene.
1715 getBE().flushFence = Fence::NO_FENCE;
1716 }
1717 }
1718
Jorim Jaggi90535212018-05-23 23:44:06 +02001719 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001720
David Sodman7e4ae112018-02-09 15:02:28 -08001721 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001722 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001723 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001724 compositionInfo.hwc.hwcLayer = nullptr;
1725 }
David Sodmanba340492018-08-05 21:51:33 -07001726 }
David Sodman7e4ae112018-02-09 15:02:28 -08001727
1728 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001729}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001730
David Sodmanfa9b2af2017-12-24 13:28:59 -08001731
1732bool SurfaceFlinger::handleMessageInvalidate() {
1733 ATRACE_CALL();
1734 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001735}
1736
David Sodman79bba0e2018-08-05 18:07:49 -07001737void SurfaceFlinger::calculateWorkingSet() {
1738 ATRACE_CALL();
1739 ALOGV(__FUNCTION__);
1740
David Sodman79bba0e2018-08-05 18:07:49 -07001741 // build the h/w work list
1742 if (CC_UNLIKELY(mGeometryInvalid)) {
1743 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001744 for (const auto& [token, displayDevice] : mDisplays) {
1745 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001746 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001747 if (!displayId) {
1748 continue;
1749 }
David Sodman79bba0e2018-08-05 18:07:49 -07001750
Lloyd Pique32cbe282018-10-19 13:09:22 -07001751 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001752 for (size_t i = 0; i < currentLayers.size(); i++) {
1753 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001754
Dominik Laskowski075d3172018-05-24 15:50:06 -07001755 if (!layer->hasHwcLayer(*displayId)) {
1756 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1757 layer->forceClientComposition(*displayId);
1758 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001759 }
1760 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001761
Lloyd Pique32cbe282018-10-19 13:09:22 -07001762 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001763 if (mDebugDisableHWC || mDebugRegion) {
1764 layer->forceClientComposition(*displayId);
1765 }
David Sodman79bba0e2018-08-05 18:07:49 -07001766 }
1767 }
1768 }
1769
1770 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001771 for (const auto& [token, displayDevice] : mDisplays) {
1772 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001773 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001774 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001775 continue;
1776 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001777 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001778
1779 if (mDrawingState.colorMatrixChanged) {
1780 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001781 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001782 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001783 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001784 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001785 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1786 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001787 !profile->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001788 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001789 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1790 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001791 !profile->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001792 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001793 }
1794
Peiyong Lind3788632018-09-18 16:01:31 -07001795 // TODO(b/111562338) remove when composer 2.3 is shipped.
1796 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001797 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001798 }
1799
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001800 if (layer->getRoundedCornerState().radius > 0.0f) {
1801 layer->forceClientComposition(*displayId);
1802 }
1803
Dominik Laskowski075d3172018-05-24 15:50:06 -07001804 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001805 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001806 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001807 continue;
1808 }
1809
Lloyd Pique32cbe282018-10-19 13:09:22 -07001810 const auto& displayState = display->getState();
1811 layer->setPerFrameData(*displayId, displayState.transform, displayState.viewport,
1812 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001813 }
1814
Peiyong Lin13effd12018-07-24 17:01:47 -07001815 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001816 ColorMode colorMode;
1817 Dataspace dataSpace;
1818 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001819 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001820 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001821 }
1822 }
1823
1824 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001825
1826 for (const auto& [token, display] : mDisplays) {
1827 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001828 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001829 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001830
1831 if (displayId) {
1832 if (!layer->setHwcLayer(*displayId)) {
1833 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1834 }
1835 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001836 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001837
Dominik Laskowski05275f12018-11-01 15:03:24 -07001838 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001839 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1840 }
1841 }
David Sodman79bba0e2018-08-05 18:07:49 -07001842}
1843
Lloyd Pique32cbe282018-10-19 13:09:22 -07001844void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1845 bool repaintEverything) {
1846 auto display = displayDevice->getCompositionDisplay();
1847 const auto& displayState = display->getState();
1848
Mathias Agopiancd60f992012-08-16 16:28:27 -07001849 // is debugging enabled
1850 if (CC_LIKELY(!mDebugRegion))
1851 return;
1852
Lloyd Pique32cbe282018-10-19 13:09:22 -07001853 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001854 // transform the dirty region into this screen's coordinate space
Lloyd Pique32cbe282018-10-19 13:09:22 -07001855 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001856 if (!dirtyRegion.isEmpty()) {
1857 // redraw the whole screen
Lloyd Pique32cbe282018-10-19 13:09:22 -07001858 doComposeSurfaces(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001859
David Sodmanfa9b2af2017-12-24 13:28:59 -08001860 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001861 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001862 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001863
Lloyd Pique31cb2942018-10-19 17:23:03 -07001864 display->getRenderSurface()->queueBuffer();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001865 }
1866 }
1867
Lloyd Pique32cbe282018-10-19 13:09:22 -07001868 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001869
1870 if (mDebugRegion > 1) {
1871 usleep(mDebugRegion * 1000);
1872 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001873
Lloyd Pique32cbe282018-10-19 13:09:22 -07001874 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001875}
1876
Adrian Roos1e1a1282017-11-01 19:05:31 +01001877void SurfaceFlinger::doTracing(const char* where) {
1878 ATRACE_CALL();
1879 ATRACE_NAME(where);
1880 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001881 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001882 }
1883}
1884
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001885void SurfaceFlinger::logLayerStats() {
1886 ATRACE_CALL();
1887 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001888 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001889 if (display->isPrimary()) {
1890 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001891 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001892 }
1893 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001894
1895 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001896 }
1897}
1898
David Sodman2b406362017-12-15 13:33:47 -08001899void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001900{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001901 ATRACE_CALL();
1902 ALOGV("preComposition");
1903
David Sodman2b406362017-12-15 13:33:47 -08001904 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1905
Mathias Agopiancd60f992012-08-16 16:28:27 -07001906 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001907 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001908 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001909 needExtraInvalidate = true;
1910 }
Robert Carr2047fae2016-11-28 14:09:09 -08001911 });
1912
Mathias Agopiancd60f992012-08-16 16:28:27 -07001913 if (needExtraInvalidate) {
1914 signalLayerUpdate();
1915 }
1916}
1917
Ana Krulece588e312018-09-18 12:32:24 -07001918void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1919 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001920 // Update queue of past composite+present times and determine the
1921 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001922 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001923 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001924 while (!getBE().mCompositePresentTimes.empty()) {
1925 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001926 // Cached values should have been updated before calling this method,
1927 // which helps avoid duplicate syscalls.
1928 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1929 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1930 break;
1931 }
1932 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001933 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001934 }
1935
1936 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001937 while (getBE().mCompositePresentTimes.size() > 16) {
1938 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001939 }
1940
Ana Krulece588e312018-09-18 12:32:24 -07001941 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001942}
1943
Ana Krulece588e312018-09-18 12:32:24 -07001944void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1945 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001946 // Integer division and modulo round toward 0 not -inf, so we need to
1947 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001948 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1949 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1950 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001951
Brian Andersond0010582017-03-07 13:20:31 -08001952 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1953 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001954 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001955 }
1956
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001957 // Snap the latency to a value that removes scheduling jitter from the
1958 // composition and present times, which often have >1ms of jitter.
1959 // Reducing jitter is important if an app attempts to extrapolate
1960 // something (such as user input) to an accurate diasplay time.
1961 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1962 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001963 nsecs_t bias = stats.vsyncPeriod / 2;
1964 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1965 nsecs_t snappedCompositeToPresentLatency =
1966 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001967
David Sodman99974d22017-11-28 12:04:33 -08001968 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001969 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1970 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001971 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001972}
1973
Ady Abraham8164d482019-01-11 14:47:59 -08001974// debug patch for b/119477596 - add stack guards to catch stack
1975// corruptions and disable clang optimizations.
1976// The code below is temporary and planned to be removed once stack
1977// corruptions are found.
1978#pragma clang optimize off
1979class StackGuard {
1980public:
1981 StackGuard(const char* name, const char* func, int line) {
1982 guarders.reserve(MIN_CAPACITY);
1983 guarders.push_back({this, name, func, line});
1984 validate();
1985 }
1986 ~StackGuard() {
1987 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1988 if (i->guard == this) {
1989 guarders.erase(i);
1990 break;
1991 }
1992 }
1993 }
1994
1995 static void validate() {
1996 for (const auto& guard : guarders) {
1997 if (guard.guard->cookie != COOKIE_VALUE) {
1998 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1999 CallStack stack(LOG_TAG);
2000 abort();
2001 }
2002 }
2003 }
2004
2005private:
2006 uint64_t cookie = COOKIE_VALUE;
2007 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
2008 static constexpr size_t MIN_CAPACITY = 16;
2009
2010 struct GuarderElement {
2011 StackGuard* guard;
2012 const char* name;
2013 const char* func;
2014 int line;
2015 };
2016
2017 static std::vector<GuarderElement> guarders;
2018};
2019std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2020
2021#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2022
2023#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002024void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002025{
Ady Abraham8164d482019-01-11 14:47:59 -08002026 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002027 ATRACE_CALL();
2028 ALOGV("postComposition");
2029
Brian Anderson3546a3f2016-07-14 11:51:14 -07002030 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002031 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002032 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002033 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002034 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002035 }
Ady Abraham8164d482019-01-11 14:47:59 -08002036 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002037
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002038 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002039 const auto displayDevice = getDefaultDisplayDeviceLocked();
2040 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002041
David Sodman73beded2017-11-15 11:56:06 -08002042 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002043 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002044 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2045
Lloyd Pique32cbe282018-10-19 13:09:22 -07002046 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002047 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002048 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2049 ->getRenderSurface()
2050 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002051 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002052 } else {
2053 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2054 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002055
Ady Abraham8164d482019-01-11 14:47:59 -08002056 ASSERT_ON_STACK_GUARD();
2057
David Sodman73beded2017-11-15 11:56:06 -08002058 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002059 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2060 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002061 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002062 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002063 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002064
Ana Krulece588e312018-09-18 12:32:24 -07002065 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002066 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002067 if (mUseScheduler) {
2068 mScheduler->getDisplayStatInfo(&stats);
2069 } else {
2070 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2071 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2072 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002073
Ady Abraham8164d482019-01-11 14:47:59 -08002074 ASSERT_ON_STACK_GUARD();
2075
David Sodman2b406362017-12-15 13:33:47 -08002076 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002077 // when we started doing work for this frame, but that should be okay
2078 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002079 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002080 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002081 DEFINE_STACK_GUARD(compositorTiming);
2082
Brian Andersond0010582017-03-07 13:20:31 -08002083 {
David Sodman99974d22017-11-28 12:04:33 -08002084 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002085 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002086 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002087
2088 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002089 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002090
Robert Carr2047fae2016-11-28 14:09:09 -08002091 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002092 bool frameLatched =
2093 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2094 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002095 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002096 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002097 recordBufferingStats(layer->getName().string(),
2098 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002099 }
Ady Abraham8164d482019-01-11 14:47:59 -08002100 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002101 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002102
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002103 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002104 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002105 if (mUseScheduler) {
2106 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002107 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002108 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002109 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2110 enableHardwareVsync();
2111 } else {
2112 disableHardwareVsync(false);
2113 }
Ady Abraham8164d482019-01-11 14:47:59 -08002114 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002115 }
2116 }
2117
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002118 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002119 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2120 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002121 if (mUseScheduler) {
2122 mScheduler->enableHardwareVsync();
2123 } else {
2124 enableHardwareVsync();
2125 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002126 }
2127 }
2128
Ady Abraham8164d482019-01-11 14:47:59 -08002129 ASSERT_ON_STACK_GUARD();
2130
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002131 if (mAnimCompositionPending) {
2132 mAnimCompositionPending = false;
2133
Brian Anderson4e606e32017-03-16 15:34:57 -07002134 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002135 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002136 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002137
2138 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002139 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002140 // The HWC doesn't support present fences, so use the refresh
2141 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002142 const nsecs_t presentTime =
2143 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002144 DEFINE_STACK_GUARD(presentTime);
2145
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002146 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002147 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002148 }
2149 mAnimFrameTracker.advanceFrame();
2150 }
Dan Stozab90cf072015-03-05 11:05:59 -08002151
Ady Abraham8164d482019-01-11 14:47:59 -08002152 ASSERT_ON_STACK_GUARD();
2153
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002154 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002155 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002156 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002157 }
2158
Ady Abraham8164d482019-01-11 14:47:59 -08002159 ASSERT_ON_STACK_GUARD();
2160
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002161 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002162
Ady Abraham8164d482019-01-11 14:47:59 -08002163 ASSERT_ON_STACK_GUARD();
2164
Lloyd Pique32cbe282018-10-19 13:09:22 -07002165 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2166 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002167 return;
2168 }
2169
2170 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002171 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002172 if (mHasPoweredOff) {
2173 mHasPoweredOff = false;
2174 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002175 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002176 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002177 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002178 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002179 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2180 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002181 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002182 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002183 }
David Sodman4a36e932017-11-07 14:29:47 -08002184 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002185
2186 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002187 }
David Sodman4a36e932017-11-07 14:29:47 -08002188 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002189 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002190
2191 {
2192 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002193 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002194 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002195 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002196 if (refillCount > 0) {
2197 const size_t offset = mTexturePool.size();
2198 mTexturePool.resize(mTexturePoolSize);
2199 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2200 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2201 }
Ady Abraham8164d482019-01-11 14:47:59 -08002202 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002203 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002204
Marissa Wallfda30bb2018-10-12 11:34:28 -07002205 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002206 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002207
2208 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002209}
Ady Abraham8164d482019-01-11 14:47:59 -08002210#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002211
2212void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002213 ATRACE_CALL();
2214 ALOGV("rebuildLayerStacks");
2215
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002216 // We need to clear these out now as these may be holding on to a
2217 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2218 // also holds a reference. When the set of visible layers is recomputed,
2219 // some layers may be destroyed if the only thing keeping them alive was
2220 // that list of visible layers associated with each display. The layer
2221 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2222 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2223 for (const auto& [token, display] : mDisplays) {
2224 getBE().mCompositionInfo[token].clear();
2225 }
2226
Mathias Agopiancd60f992012-08-16 16:28:27 -07002227 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002228 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002229 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002230 mVisibleRegionsDirty = false;
2231 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002232
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002233 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002234 const auto& displayDevice = pair.second;
2235 auto display = displayDevice->getCompositionDisplay();
2236 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002237 Region opaqueRegion;
2238 Region dirtyRegion;
2239 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002240 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002241 const ui::Transform& tr = displayState.transform;
2242 const Rect bounds = displayState.bounds;
2243 if (displayState.isEnabled) {
2244 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002245
Jeff Sharkey76488112017-02-27 14:15:18 -07002246 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002247 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002248 const auto displayId = displayDevice->getId();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002249 if (display->belongsInOutput(layer->getLayerStack(),
2250 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002251 Region drawRegion(tr.transform(
2252 layer->visibleNonTransparentRegion));
2253 drawRegion.andSelf(bounds);
2254 if (!drawRegion.isEmpty()) {
2255 layersSortedByZ.add(layer);
2256 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002257 // Clear out the HWC layer if this layer was
2258 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002259 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002260 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002261 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002262 // WM changes display->layerStack upon sleep/awake.
2263 // Here we make sure we delete the HWC layers even if
2264 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002265 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002266 }
2267
2268 // If a layer is not going to get a release fence because
2269 // it is invisible, but it is also going to release its
2270 // old buffer, add it to the list of layers needing
2271 // fences.
2272 if (hwcLayerDestroyed) {
2273 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2274 mLayersWithQueuedFrames.cend(), layer);
2275 if (found != mLayersWithQueuedFrames.cend()) {
2276 layersNeedingFences.add(layer);
2277 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002278 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002279 });
2280 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002281 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
2282 displayDevice->setLayersNeedingFences(layersNeedingFences);
2283
2284 Region undefinedRegion{bounds};
2285 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2286
2287 display->editState().undefinedRegion = undefinedRegion;
2288 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002289 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002290 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002291}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002292
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002293// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002294// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002295// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002296// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002297// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002298// The returned HDR data space is one of
2299// - Dataspace::UNKNOWN
2300// - Dataspace::BT2020_HLG
2301// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002302Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2303 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002304 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002305 *outHdrDataSpace = Dataspace::UNKNOWN;
2306
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002307 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002308 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002309 case Dataspace::V0_SCRGB:
2310 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002311 case Dataspace::BT2020:
2312 case Dataspace::BT2020_ITU:
2313 case Dataspace::BT2020_LINEAR:
2314 case Dataspace::DISPLAY_BT2020:
2315 bestDataSpace = Dataspace::DISPLAY_BT2020;
2316 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002317 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002318 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002319 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002320 case Dataspace::BT2020_PQ:
2321 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002322 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002323 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002324 case Dataspace::BT2020_HLG:
2325 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002326 // When there's mixed PQ content and HLG content, we set the HDR
2327 // data space to be BT2020_PQ and convert HLG to PQ.
2328 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2329 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002330 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002331 break;
2332 default:
2333 break;
2334 }
Romain Guy54f154a2017-10-24 21:40:32 +01002335 }
2336
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002337 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002338}
2339
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002340// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002341void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2342 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002343 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2344 *outMode = ColorMode::NATIVE;
2345 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002346 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002347 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002348 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002349
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002350 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002351 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002352
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002353 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2354
Peiyong Lindfde5112018-06-05 10:58:41 -07002355 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002356 const bool isHdr =
2357 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002358 if (isHdr) {
2359 bestDataSpace = hdrDataSpace;
2360 }
2361
Chia-I Wu0d711262018-05-21 15:19:35 -07002362 RenderIntent intent;
2363 switch (mDisplayColorSetting) {
2364 case DisplayColorSetting::MANAGED:
2365 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002366 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002367 break;
2368 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002369 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002370 break;
2371 default: // vendor display color setting
2372 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2373 break;
2374 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002375
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002376 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002377}
2378
Lloyd Pique32cbe282018-10-19 13:09:22 -07002379void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2380 auto display = displayDevice->getCompositionDisplay();
2381 const auto& displayState = display->getState();
2382
2383 bool dirty = !display->getPhysicalSpaceDirtyRegion(false).isEmpty();
2384 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2385 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002386
David Sodmanfa9b2af2017-12-24 13:28:59 -08002387 // If nothing has changed (!dirty), don't recompose.
2388 // If something changed, but we don't currently have any visible layers,
2389 // and didn't when we last did a composition, then skip it this time.
2390 // The second rule does two things:
2391 // - When all layers are removed from a display, we'll emit one black
2392 // frame, then nothing more until we get new layers.
2393 // - When a display is created with a private layer stack, we won't
2394 // emit any black frames until a layer is added to the layer stack.
2395 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002396
Dominik Laskowski075d3172018-05-24 15:50:06 -07002397 const char flagPrefix[] = {'-', '+'};
2398 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002399 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2400 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2401 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2402 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002403
Lloyd Pique31cb2942018-10-19 17:23:03 -07002404 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002405
David Sodmanfa9b2af2017-12-24 13:28:59 -08002406 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002407 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002408 }
2409}
2410
Lloyd Pique32cbe282018-10-19 13:09:22 -07002411void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2412 auto display = displayDevice->getCompositionDisplay();
2413 const auto& displayState = display->getState();
2414
2415 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002416 return;
David Sodman2b406362017-12-15 13:33:47 -08002417 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002418
Lloyd Pique31cb2942018-10-19 17:23:03 -07002419 status_t result = display->getRenderSurface()->prepareFrame(
2420 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002421 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002422 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002423}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002424
Lloyd Pique32cbe282018-10-19 13:09:22 -07002425void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002426 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002427 ALOGV("doComposition");
2428
Lloyd Pique32cbe282018-10-19 13:09:22 -07002429 auto display = displayDevice->getCompositionDisplay();
2430 const auto& displayState = display->getState();
2431
2432 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002433 // transform the dirty region into this screen's coordinate space
Lloyd Pique32cbe282018-10-19 13:09:22 -07002434 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002435
David Sodmanfa9b2af2017-12-24 13:28:59 -08002436 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002437 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002438
Lloyd Pique32cbe282018-10-19 13:09:22 -07002439 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002440 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002441 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002442 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002443}
2444
David Sodmanfa9b2af2017-12-24 13:28:59 -08002445void SurfaceFlinger::postFrame()
2446{
2447 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002448 const auto display = getDefaultDisplayDeviceLocked();
2449 if (display && getHwComposer().isConnected(*display->getId())) {
2450 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002451 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2452 logFrameStats();
2453 }
2454 }
2455}
2456
Lloyd Pique32cbe282018-10-19 13:09:22 -07002457void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002458 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002459 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002460
Lloyd Pique32cbe282018-10-19 13:09:22 -07002461 auto display = displayDevice->getCompositionDisplay();
2462 const auto& displayState = display->getState();
2463 const auto displayId = display->getId();
2464
David Sodmanfa9b2af2017-12-24 13:28:59 -08002465 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002466
Lloyd Pique32cbe282018-10-19 13:09:22 -07002467 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002468 if (displayId) {
2469 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002470 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002471 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002472 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002473 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002474
Chia-I Wu7b549592017-11-15 09:14:57 -08002475 // The layer buffer from the previous frame (if any) is released
2476 // by HWC only when the release fence from this frame (if any) is
2477 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002478 if (displayId && layer->hasHwcLayer(*displayId)) {
2479 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2480 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002481 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002482
2483 // If the layer was client composited in the previous frame, we
2484 // need to merge with the previous client target acquire fence.
2485 // Since we do not track that, always merge with the current
2486 // client target acquire fence when it is available, even though
2487 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002488 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002489 releaseFence =
2490 Fence::merge("LayerRelease", releaseFence,
2491 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002492 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002493
David Sodman15094112018-10-11 09:39:37 -07002494 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002495 }
Chia-I Wu83806892017-11-16 10:50:20 -08002496
2497 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002498 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002499 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002500 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002501 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002502 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002503 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002504 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002505 }
2506 }
2507
Dominik Laskowski075d3172018-05-24 15:50:06 -07002508 if (displayId) {
2509 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002510 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002511 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002512}
2513
Mathias Agopian87baae12012-07-31 12:38:26 -07002514void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002515{
Mathias Agopian841cde52012-03-01 15:44:37 -08002516 ATRACE_CALL();
2517
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002518 // here we keep a copy of the drawing state (that is the state that's
2519 // going to be overwritten by handleTransactionLocked()) outside of
2520 // mStateLock so that the side-effects of the State assignment
2521 // don't happen with mStateLock held (which can cause deadlocks).
2522 State drawingState(mDrawingState);
2523
Mathias Agopianca4d3602011-05-19 15:38:14 -07002524 Mutex::Autolock _l(mStateLock);
2525 const nsecs_t now = systemTime();
2526 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002527
Mathias Agopianca4d3602011-05-19 15:38:14 -07002528 // Here we're guaranteed that some transaction flags are set
2529 // so we can call handleTransactionLocked() unconditionally.
2530 // We call getTransactionFlags(), which will also clear the flags,
2531 // with mStateLock held to guarantee that mCurrentState won't change
2532 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002533
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002534 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002535 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002536 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002537
Mathias Agopianca4d3602011-05-19 15:38:14 -07002538 mLastTransactionTime = systemTime() - now;
2539 mDebugInTransaction = 0;
2540 invalidateHwcGeometry();
2541 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002542}
2543
Lloyd Piqueba04e622017-12-14 17:11:26 -08002544void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2545 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002546 const std::optional<DisplayIdentificationInfo> info =
2547 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002548
Dominik Laskowski075d3172018-05-24 15:50:06 -07002549 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002550 continue;
2551 }
2552
Lloyd Piqueba04e622017-12-14 17:11:26 -08002553 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002554 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002555 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002556 mPhysicalDisplayTokens[info->id] = new BBinder();
2557 DisplayDeviceState state;
2558 state.displayId = info->id;
2559 state.isSecure = true; // All physical displays are currently considered secure.
2560 state.displayName = info->name;
2561 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2562 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002563 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002564 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002565 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002566
Dominik Laskowski075d3172018-05-24 15:50:06 -07002567 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2568 if (index >= 0) {
2569 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2570 mInterceptor->saveDisplayDeletion(state.sequenceId);
2571 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002572 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002573 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002574 }
2575
2576 processDisplayChangesLocked();
2577 }
2578
2579 mPendingHotplugEvents.clear();
2580}
2581
Lloyd Pique99d3da52018-01-22 17:48:03 -08002582sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002583 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002584 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002585 const sp<IGraphicBufferProducer>& producer) {
2586 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002587 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002588 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002589 creationArgs.isSecure = state.isSecure;
2590 creationArgs.displaySurface = dispSurface;
2591 creationArgs.hasWideColorGamut = false;
2592 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002593
Dominik Laskowski075d3172018-05-24 15:50:06 -07002594 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2595 creationArgs.isPrimary = isInternalDisplay;
2596
2597 if (useColorManagement && displayId) {
2598 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002599 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002600 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002601 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002602 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002603
Dominik Laskowski7e045462018-05-30 13:02:02 -07002604 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002605 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002606 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002607 }
tangrobin6753a022018-08-10 10:58:54 +08002608 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002609
Dominik Laskowski075d3172018-05-24 15:50:06 -07002610 if (displayId) {
2611 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002612 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002613 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002614 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002615
Lloyd Pique90c115d2018-09-18 21:39:42 -07002616 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002617 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002618 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002619
Lloyd Pique99d3da52018-01-22 17:48:03 -08002620 // Make sure that composition can never be stalled by a virtual display
2621 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002622 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002623 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002624 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2625 }
2626
Dominik Laskowski075d3172018-05-24 15:50:06 -07002627 creationArgs.displayInstallOrientation =
2628 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002629
Lloyd Pique99d3da52018-01-22 17:48:03 -08002630 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002631 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002632
Lloyd Pique90c115d2018-09-18 21:39:42 -07002633 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002634
2635 if (maxFrameBufferAcquiredBuffers >= 3) {
2636 nativeWindowSurface->preallocateBuffers();
2637 }
2638
2639 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002640 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002641 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002642 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002643 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002644 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002645 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2646 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002647 if (!state.isVirtual()) {
2648 LOG_ALWAYS_FATAL_IF(!displayId);
2649 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002650 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002651
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002652 display->setLayerStack(state.layerStack);
2653 display->setProjection(state.orientation, state.viewport, state.frame);
2654 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002655
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002656 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002657}
2658
Lloyd Pique347200f2017-12-14 17:00:15 -08002659void SurfaceFlinger::processDisplayChangesLocked() {
2660 // here we take advantage of Vector's copy-on-write semantics to
2661 // improve performance by skipping the transaction entirely when
2662 // know that the lists are identical
2663 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2664 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2665 if (!curr.isIdenticalTo(draw)) {
2666 mVisibleRegionsDirty = true;
2667 const size_t cc = curr.size();
2668 size_t dc = draw.size();
2669
2670 // find the displays that were removed
2671 // (ie: in drawing state but not in current state)
2672 // also handle displays that changed
2673 // (ie: displays that are in both lists)
2674 for (size_t i = 0; i < dc;) {
2675 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2676 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002677 // Save display IDs before disconnecting.
2678 const auto internalDisplayId = getInternalDisplayId();
2679 const auto externalDisplayId = getExternalDisplayId();
2680
Lloyd Pique347200f2017-12-14 17:00:15 -08002681 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002682 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002683 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002684 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002685 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002686 if (mUseScheduler) {
2687 mScheduler->hotplugReceived(mAppConnectionHandle,
2688 EventThread::DisplayType::Primary, false);
2689 } else {
2690 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2691 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002692 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002693 if (mUseScheduler) {
2694 mScheduler->hotplugReceived(mAppConnectionHandle,
2695 EventThread::DisplayType::External, false);
2696 } else {
2697 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2698 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002699 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002700 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002701 } else {
2702 // this display is in both lists. see if something changed.
2703 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002704 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002705 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2706 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2707 if (state_binder != draw_binder) {
2708 // changing the surface is like destroying and
2709 // recreating the DisplayDevice, so we just remove it
2710 // from the drawing state, so that it get re-added
2711 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002712 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002713 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002714 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002715 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002716 mDrawingState.displays.removeItemsAt(i);
2717 dc--;
2718 // at this point we must loop to the next item
2719 continue;
2720 }
2721
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002722 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002723 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002724 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002725 }
2726 if ((state.orientation != draw[i].orientation) ||
2727 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002728 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002729 }
2730 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002731 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002732 }
2733 }
2734 }
2735 ++i;
2736 }
2737
2738 // find displays that were added
2739 // (ie: in current state but not in drawing state)
2740 for (size_t i = 0; i < cc; i++) {
2741 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2742 const DisplayDeviceState& state(curr[i]);
2743
Lloyd Pique542307f2018-10-19 13:24:08 -07002744 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002745 sp<IGraphicBufferProducer> producer;
2746 sp<IGraphicBufferProducer> bqProducer;
2747 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002748 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002749
Dominik Laskowski075d3172018-05-24 15:50:06 -07002750 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002751 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002752 // Virtual displays without a surface are dormant:
2753 // they have external state (layer stack, projection,
2754 // etc.) but no internal state (i.e. a DisplayDevice).
2755 if (state.surface != nullptr) {
2756 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002757 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002758 int width = 0;
2759 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2760 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2761 int height = 0;
2762 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2763 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2764 int intFormat = 0;
2765 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2766 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002767 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002768
Dominik Laskowski075d3172018-05-24 15:50:06 -07002769 displayId =
2770 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002771 }
2772
2773 // TODO: Plumb requested format back up to consumer
2774
2775 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002776 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002777 bqProducer, bqConsumer,
2778 state.displayName);
2779
2780 dispSurface = vds;
2781 producer = vds;
2782 }
2783 } else {
2784 ALOGE_IF(state.surface != nullptr,
2785 "adding a supported display, but rendering "
2786 "surface is provided (%p), ignoring it",
2787 state.surface.get());
2788
Dominik Laskowski075d3172018-05-24 15:50:06 -07002789 displayId = state.displayId;
2790 LOG_ALWAYS_FATAL_IF(!displayId);
2791 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002792 producer = bqProducer;
2793 }
2794
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002795 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002796 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002797 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002798 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002799 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002800 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002801 LOG_ALWAYS_FATAL_IF(!displayId);
2802
2803 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002804 if (mUseScheduler) {
2805 mScheduler->hotplugReceived(mAppConnectionHandle,
2806 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002807 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002808 } else {
2809 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2810 true);
2811 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002812 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002813 if (mUseScheduler) {
2814 mScheduler->hotplugReceived(mAppConnectionHandle,
2815 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002816 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002817 } else {
2818 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2819 true);
2820 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002821 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002822 }
2823 }
2824 }
2825 }
2826 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002827
2828 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002829}
2830
Mathias Agopian87baae12012-07-31 12:38:26 -07002831void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002832{
Dan Stoza7dde5992015-05-22 09:51:44 -07002833 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002834 mCurrentState.traverseInZOrder([](Layer* layer) {
2835 layer->notifyAvailableFrames();
2836 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002837
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002838 /*
2839 * Traversal of the children
2840 * (perform the transaction for each of them if needed)
2841 */
2842
Robert Carr720e5062018-07-30 17:45:14 -07002843 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002844 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002845 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002846 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002847 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002848
2849 const uint32_t flags = layer->doTransaction(0);
2850 if (flags & Layer::eVisibleRegion)
2851 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002852
2853 if (flags & Layer::eInputInfoChanged) {
2854 inputChanged = true;
2855 }
Robert Carr2047fae2016-11-28 14:09:09 -08002856 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002857 }
2858
2859 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002860 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002861 */
2862
Mathias Agopiane57f2922012-08-09 16:29:12 -07002863 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002864 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002865 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002866 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002867
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002868 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002869 // The transform hint might have changed for some layers
2870 // (either because a display has changed, or because a layer
2871 // as changed).
2872 //
2873 // Walk through all the layers in currentLayers,
2874 // and update their transform hint.
2875 //
2876 // If a layer is visible only on a single display, then that
2877 // display is used to calculate the hint, otherwise we use the
2878 // default display.
2879 //
2880 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2881 // the hint is set before we acquire a buffer from the surface texture.
2882 //
2883 // NOTE: layer transactions have taken place already, so we use their
2884 // drawing state. However, SurfaceFlinger's own transaction has not
2885 // happened yet, so we must use the current state layer list
2886 // (soon to become the drawing state list).
2887 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002888 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002889 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002890 bool first = true;
2891 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002892 // NOTE: we rely on the fact that layers are sorted by
2893 // layerStack first (so we don't have to traverse the list
2894 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002895 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002896 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002897 currentlayerStack = layerStack;
2898 // figure out if this layerstack is mirrored
2899 // (more than one display) if so, pick the default display,
2900 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002901 hintDisplay = nullptr;
2902 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002903 if (display->getCompositionDisplay()
2904 ->belongsInOutput(layer->getLayerStack(),
2905 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002906 if (hintDisplay) {
2907 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002908 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002909 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002910 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002911 }
2912 }
2913 }
2914 }
Chet Haase91d25932013-04-11 15:24:55 -07002915
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002916 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002917 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2918 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002919
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002920 // could be null when this layer is using a layerStack
2921 // that is not visible on any display. Also can occur at
2922 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002923 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002924 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002925
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002926 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002927 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002928 if (hintDisplay) {
2929 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002930 }
Robert Carr2047fae2016-11-28 14:09:09 -08002931
2932 first = false;
2933 });
Mathias Agopian84300952012-11-21 16:02:13 -08002934 }
2935
2936
Mathias Agopian3559b072012-08-15 13:46:03 -07002937 /*
2938 * Perform our own transaction if needed
2939 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002940
2941 if (mLayersAdded) {
2942 mLayersAdded = false;
2943 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002944 mVisibleRegionsDirty = true;
2945 }
2946
2947 // some layers might have been removed, so
2948 // we need to update the regions they're exposing.
2949 if (mLayersRemoved) {
2950 mLayersRemoved = false;
2951 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002952 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002953 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002954 // this layer is not visible anymore
2955 // TODO: we could traverse the tree from front to back and
2956 // compute the actual visible region
2957 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002958 Region visibleReg;
2959 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002960 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002961 }
Robert Carr2047fae2016-11-28 14:09:09 -08002962 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002963 }
2964
2965 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002966
Vishnu Nairde19f852018-12-18 16:11:53 -08002967 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002968 updateInputWindows();
2969 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002970 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002971
Riley Andrews03414a12014-07-01 14:22:59 -07002972 updateCursorAsync();
2973}
2974
Robert Carr720e5062018-07-30 17:45:14 -07002975void SurfaceFlinger::updateInputWindows() {
2976 ATRACE_CALL();
2977
Vishnu Nairde19f852018-12-18 16:11:53 -08002978 if (mInputFlinger == nullptr) {
2979 return;
2980 }
2981
Robert Carr720e5062018-07-30 17:45:14 -07002982 Vector<InputWindowInfo> inputHandles;
2983
2984 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2985 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002986 // When calculating the screen bounds we ignore the transparent region since it may
2987 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002988 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002989 }
2990 });
2991 mInputFlinger->setInputWindows(inputHandles);
2992}
2993
chaviwfbe5d9c2018-12-26 12:23:37 -08002994void SurfaceFlinger::executeInputWindowCommands() {
2995 if (!mInputFlinger) {
2996 return;
2997 }
2998
2999 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3000 if (transferTouchFocusCommand.fromToken != nullptr &&
3001 transferTouchFocusCommand.toToken != nullptr &&
3002 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3003 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3004 transferTouchFocusCommand.toToken);
3005 }
3006 }
3007
3008 mInputWindowCommands.clear();
3009}
3010
Riley Andrews03414a12014-07-01 14:22:59 -07003011void SurfaceFlinger::updateCursorAsync()
3012{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003013 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003014 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003015 continue;
3016 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003017
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003018 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3019 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003020 }
3021 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003022}
3023
chaviw61626f22018-11-15 16:26:27 -08003024void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3025 if (layer->hasReadyFrame()) {
3026 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3027 if (layer->shouldPresentNow(expectedPresentTime)) {
3028 bool ignored = false;
3029 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
3030 }
3031 }
3032 layer->releasePendingBuffer(systemTime());
3033}
3034
Mathias Agopian4fec8732012-06-29 14:12:52 -07003035void SurfaceFlinger::commitTransaction()
3036{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003037 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003038 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003039 for (const auto& l : mLayersPendingRemoval) {
3040 recordBufferingStats(l->getName().string(),
3041 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003042
3043 // We need to release the HWC layers when the Layer is removed
3044 // from the current state otherwise the HWC layer just continues
3045 // showing at its last configured state until we eventually
3046 // abandon the buffer queue.
3047 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003048 l->destroyHwcLayersForAllDisplays();
3049 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003050 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003051 }
3052 mLayersPendingRemoval.clear();
3053 }
3054
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003055 // If this transaction is part of a window animation then the next frame
3056 // we composite should be considered an animation as well.
3057 mAnimCompositionPending = mAnimTransactionPending;
3058
Mathias Agopian4fec8732012-06-29 14:12:52 -07003059 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003060 // clear the "changed" flags in current state
3061 mCurrentState.colorMatrixChanged = false;
3062
Robert Carr1f0a16a2016-10-24 16:27:39 -07003063 mDrawingState.traverseInZOrder([](Layer* layer) {
3064 layer->commitChildList();
3065 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003066 mTransactionPending = false;
3067 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003068 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003069}
3070
Lloyd Pique32cbe282018-10-19 13:09:22 -07003071void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003072 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003073 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003074 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003075
Lloyd Pique32cbe282018-10-19 13:09:22 -07003076 auto display = displayDevice->getCompositionDisplay();
3077
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003078 Region aboveOpaqueLayers;
3079 Region aboveCoveredLayers;
3080 Region dirty;
3081
Mathias Agopian87baae12012-07-31 12:38:26 -07003082 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003083
Robert Carr2047fae2016-11-28 14:09:09 -08003084 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003085 // start with the whole surface at its current location
3086 const Layer::State& s(layer->getDrawingState());
3087
Jesse Hall01e29052013-02-19 16:13:35 -08003088 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003089 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003090 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003091 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003092
Mathias Agopianab028732010-03-16 16:41:46 -07003093 /*
3094 * opaqueRegion: area of a surface that is fully opaque.
3095 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003096 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003097
3098 /*
3099 * visibleRegion: area of a surface that is visible on screen
3100 * and not fully transparent. This is essentially the layer's
3101 * footprint minus the opaque regions above it.
3102 * Areas covered by a translucent surface are considered visible.
3103 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003104 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003105
3106 /*
3107 * coveredRegion: area of a surface that is covered by all
3108 * visible regions above it (which includes the translucent areas).
3109 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003110 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003111
Jesse Halla8026d22012-09-25 13:25:04 -07003112 /*
3113 * transparentRegion: area of a surface that is hinted to be completely
3114 * transparent. This is only used to tell when the layer has no visible
3115 * non-transparent regions and can be removed from the layer list. It
3116 * does not affect the visibleRegion of this layer or any layers
3117 * beneath it. The hint may not be correct if apps don't respect the
3118 * SurfaceView restrictions (which, sadly, some don't).
3119 */
3120 Region transparentRegion;
3121
Mathias Agopianab028732010-03-16 16:41:46 -07003122
3123 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003124 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003125 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003126 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003127
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003128 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003129 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003130 if (!visibleRegion.isEmpty()) {
3131 // Remove the transparent area from the visible region
3132 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003133 if (tr.preserveRects()) {
3134 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003135 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003136 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003137 // transformation too complex, can't do the
3138 // transparent region optimization.
3139 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003140 }
Mathias Agopianab028732010-03-16 16:41:46 -07003141 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003142
Mathias Agopianab028732010-03-16 16:41:46 -07003143 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003144 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003145 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003146 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003147 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003148 // the opaque region is the layer's footprint
3149 opaqueRegion = visibleRegion;
3150 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003151 }
3152 }
3153
Robert Carre5f4f692018-01-12 13:12:28 -08003154 if (visibleRegion.isEmpty()) {
3155 layer->clearVisibilityRegions();
3156 return;
3157 }
3158
Mathias Agopianab028732010-03-16 16:41:46 -07003159 // Clip the covered region to the visible region
3160 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3161
3162 // Update aboveCoveredLayers for next (lower) layer
3163 aboveCoveredLayers.orSelf(visibleRegion);
3164
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003165 // subtract the opaque region covered by the layers above us
3166 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003167
3168 // compute this layer's dirty region
3169 if (layer->contentDirty) {
3170 // we need to invalidate the whole region
3171 dirty = visibleRegion;
3172 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003173 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003174 layer->contentDirty = false;
3175 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003176 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003177 * the exposed region consists of two components:
3178 * 1) what's VISIBLE now and was COVERED before
3179 * 2) what's EXPOSED now less what was EXPOSED before
3180 *
3181 * note that (1) is conservative, we start with the whole
3182 * visible region but only keep what used to be covered by
3183 * something -- which mean it may have been exposed.
3184 *
3185 * (2) handles areas that were not covered by anything but got
3186 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003187 */
Mathias Agopianab028732010-03-16 16:41:46 -07003188 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003189 const Region oldVisibleRegion = layer->visibleRegion;
3190 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003191 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3192 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003193 }
3194 dirty.subtractSelf(aboveOpaqueLayers);
3195
3196 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003197 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003198
Mathias Agopianab028732010-03-16 16:41:46 -07003199 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003200 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003201
Jesse Halla8026d22012-09-25 13:25:04 -07003202 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003203 layer->setVisibleRegion(visibleRegion);
3204 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003205 layer->setVisibleNonTransparentRegion(
3206 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003207 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003208
Mathias Agopian87baae12012-07-31 12:38:26 -07003209 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003210}
3211
Chia-I Wuab0c3192017-08-01 11:29:00 -07003212void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003213 for (const auto& [token, displayDevice] : mDisplays) {
3214 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003215 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003216 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003217 }
3218 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003219}
3220
Dan Stoza6b9454d2014-11-07 16:00:59 -08003221bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003222{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003223 ALOGV("handlePageFlip");
3224
Brian Andersond6927fb2016-07-23 23:37:30 -07003225 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003226
Mathias Agopian4fec8732012-06-29 14:12:52 -07003227 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003228 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003229 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003230
3231 // Store the set of layers that need updates. This set must not change as
3232 // buffers are being latched, as this could result in a deadlock.
3233 // Example: Two producers share the same command stream and:
3234 // 1.) Layer 0 is latched
3235 // 2.) Layer 0 gets a new frame
3236 // 2.) Layer 1 gets a new frame
3237 // 3.) Layer 1 is latched.
3238 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3239 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003240 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003241 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003242 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003243 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3244 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003245 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003246 } else {
3247 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003248 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003249 } else {
3250 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003251 }
Robert Carr2047fae2016-11-28 14:09:09 -08003252 });
3253
Lloyd Piquef2c79392018-12-20 16:23:33 -08003254 if (!mLayersWithQueuedFrames.empty()) {
3255 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3256 // writes to Layer current state. See also b/119481871
3257 Mutex::Autolock lock(mStateLock);
3258
3259 for (auto& layer : mLayersWithQueuedFrames) {
3260 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3261 layer->useSurfaceDamage();
3262 invalidateLayerStack(layer, dirty);
3263 if (layer->isBufferLatched()) {
3264 newDataLatched = true;
3265 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003266 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003267 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003268
Alec Mouri86770e52018-09-24 22:40:58 +00003269 // Clear the renderengine fence here...
3270 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3271 // clear instead of sp::clear.
3272 getBE().flushFence = Fence::NO_FENCE;
3273
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003274 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003275
Vishnu Nairde19f852018-12-18 16:11:53 -08003276 if (visibleRegions) {
3277 // Update input window info if the layer receives its first buffer.
3278 updateInputWindows();
3279 }
3280
Dan Stoza6b9454d2014-11-07 16:00:59 -08003281 // If we will need to wake up at some time in the future to deal with a
3282 // queued frame that shouldn't be displayed during this vsync period, wake
3283 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003284 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003285 signalLayerUpdate();
3286 }
3287
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003288 // enter boot animation on first buffer latch
3289 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3290 ALOGI("Enter boot animation");
3291 mBootStage = BootStage::BOOTANIMATION;
3292 }
3293
Dan Stoza6b9454d2014-11-07 16:00:59 -08003294 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003295 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003296}
3297
Mathias Agopianad456f92011-01-13 17:53:01 -08003298void SurfaceFlinger::invalidateHwcGeometry()
3299{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003300 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003301}
3302
Lloyd Pique32cbe282018-10-19 13:09:22 -07003303void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003304 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003305 auto display = displayDevice->getCompositionDisplay();
3306
Dan Stoza71433162014-02-04 16:22:36 -08003307 // We only need to actually compose the display if:
3308 // 1) It is being handled by hardware composer, which may need this to
3309 // keep its virtual display state machine in sync, or
3310 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003311 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003312 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003313 return;
3314 }
3315
Dan Stoza9e56aa02015-11-02 13:00:03 -08003316 ALOGV("doDisplayComposition");
Lloyd Pique32cbe282018-10-19 13:09:22 -07003317 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003318
3319 // swap buffers (presentation)
Lloyd Pique31cb2942018-10-19 17:23:03 -07003320 display->getRenderSurface()->queueBuffer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003321}
3322
Lloyd Pique32cbe282018-10-19 13:09:22 -07003323bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003324 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003325
Lloyd Pique32cbe282018-10-19 13:09:22 -07003326 auto display = displayDevice->getCompositionDisplay();
3327 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003328 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003329
3330 const Region bounds(displayState.bounds);
3331 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003332 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003333 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003334
Peiyong Lind3788632018-09-18 16:01:31 -07003335 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003336 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003337
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003338 // Framebuffer will live in this scope for GPU composition.
3339 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
3340
Dan Stoza9e56aa02015-11-02 13:00:03 -08003341 if (hasClientComposition) {
3342 ALOGV("hasClientComposition");
3343
Lloyd Pique31cb2942018-10-19 17:23:03 -07003344 sp<GraphicBuffer> buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003345
3346 if (buf == nullptr) {
3347 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3348 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003349 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003350 return false;
3351 }
3352
3353 // Bind the framebuffer in this scope.
3354 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3355 buf->getNativeBuffer());
3356
3357 if (fbo->getStatus() != NO_ERROR) {
3358 ALOGW("Binding buffer for display [%s] failed with status: %d",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003359 displayDevice->getDisplayName().c_str(), fbo->getStatus());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003360 return false;
3361 }
3362
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003363 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003364 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003365 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003366 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003367 }
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003368 getRenderEngine().setOutputDataSpace(outputDataspace);
3369 getRenderEngine().setDisplayMaxLuminance(
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003370 profile->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003371
Lloyd Pique441d5042018-10-18 16:49:51 -07003372 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003373 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003374 getHwComposer()
3375 .hasDisplayCapability(displayId,
3376 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003377
Peiyong Lind3788632018-09-18 16:01:31 -07003378 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003379 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3380 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003381 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003382 }
3383
Lloyd Pique31cb2942018-10-19 17:23:03 -07003384 display->getRenderSurface()->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003385
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003386 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003387 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003388 // when using overlays, we assume a fully transparent framebuffer
3389 // NOTE: we could reduce how much we need to clear, for instance
3390 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003391 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003392 // We'll revisit later if needed.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003393 getRenderEngine().clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003394 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003395 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003396 // we're left with the letterbox region
3397 // (common case is that letterbox ends-up being empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003398 const Region letterbox = bounds.subtract(displayState.scissor);
Mathias Agopian766dc492012-10-30 18:08:06 -07003399
3400 // compute the area to clear
Lloyd Pique32cbe282018-10-19 13:09:22 -07003401 const Region region = displayState.undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003402
Mathias Agopianb9494d52012-04-18 02:28:45 -07003403 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003404 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003405 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003406 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003407 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003408 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003409
Lloyd Pique32cbe282018-10-19 13:09:22 -07003410 const Rect& bounds = displayState.bounds;
3411 const Rect& scissor = displayState.scissor;
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003412 if (scissor != bounds) {
3413 // scissor doesn't match the screen's dimensions, so we
3414 // need to clear everything outside of it and enable
3415 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003416
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003417 // enable scissor for this frame
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003418 getRenderEngine().setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003419 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003420 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003421
Mathias Agopian85d751c2012-08-29 16:59:24 -07003422 /*
3423 * and then, render the layers targeted at the framebuffer
3424 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003425
Dan Stoza9e56aa02015-11-02 13:00:03 -08003426 ALOGV("Rendering client layers");
Lloyd Pique32cbe282018-10-19 13:09:22 -07003427 const ui::Transform& displayTransform = displayState.transform;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003428 bool firstLayer = true;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003429 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003430 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003431 displayTransform.transform(layer->visibleRegion)));
3432 ALOGV("Layer: %s", layer->getName().string());
3433 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003434 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003435 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003436 case HWC2::Composition::Cursor:
3437 case HWC2::Composition::Device:
3438 case HWC2::Composition::Sideband:
3439 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003440 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003441 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003442 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003443 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003444 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003445 // never clear the very first layer since we're
3446 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003447 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003448 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003449 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003450 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003451 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003452 if (layer->hasColorTransform()) {
3453 mat4 tmpMatrix;
3454 if (applyColorMatrix) {
3455 tmpMatrix = mDrawingState.colorMatrix;
3456 }
3457 tmpMatrix *= layer->getColorTransform();
Peiyong Lind3788632018-09-18 16:01:31 -07003458 getRenderEngine().setColorTransform(tmpMatrix);
3459 } else {
3460 getRenderEngine().setColorTransform(colorMatrix);
3461 }
David Sodmanc1498e62018-09-12 14:36:26 -07003462 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003463 break;
3464 }
3465 default:
3466 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003467 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003468 } else {
3469 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003470 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003471 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003472 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003473
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003474 // Perform some cleanup steps if we used client composition.
3475 if (hasClientComposition) {
3476 getRenderEngine().setColorTransform(mat4());
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003477 getRenderEngine().disableScissor();
Lloyd Pique31cb2942018-10-19 17:23:03 -07003478 display->getRenderSurface()->finishBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003479 // Clear out error flags here so that we don't wait until next
3480 // composition to log.
3481 getRenderEngine().checkErrors();
3482 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003483 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003484}
3485
Chia-I Wu28e3a252018-09-07 12:05:02 -07003486void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003487 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003488 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003489}
3490
Dan Stoza7d89d062015-04-30 13:29:25 -07003491status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003492 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003493 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003494 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003495 const sp<Layer>& parent,
3496 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003497{
Dan Stoza7d89d062015-04-30 13:29:25 -07003498 // add this layer to the current state list
3499 {
3500 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003501 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003502 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3503 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003504 return NO_MEMORY;
3505 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003506 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003507 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003508 } else if (parent == nullptr) {
3509 lbc->onRemovedFromCurrentState();
3510 } else if (parent->isRemovedFromCurrentState()) {
3511 parent->addChild(lbc);
3512 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003513 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003514 parent->addChild(lbc);
3515 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003516
Yiwei Zhang243b3782018-05-15 17:40:04 -07003517 if (gbc != nullptr) {
3518 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3519 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3520 mMaxGraphicBufferProducerListSize,
3521 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3522 mGraphicBufferProducerList.size(),
3523 mMaxGraphicBufferProducerListSize, mNumLayers);
3524 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003525 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003526 }
3527
Mathias Agopian96f08192010-06-02 23:28:45 -07003528 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003529 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003530
Dan Stoza7d89d062015-04-30 13:29:25 -07003531 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003532}
3533
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003534uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003535 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003536}
3537
Mathias Agopian3f844832013-08-07 21:24:32 -07003538uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003539 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003540}
3541
Mathias Agopian3f844832013-08-07 21:24:32 -07003542uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003543 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003544}
3545
3546uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003547 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003548 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003549 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003550 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003551 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003552 }
3553 return old;
3554}
3555
Marissa Wall713b63f2018-10-17 15:42:43 -07003556bool SurfaceFlinger::flushTransactionQueues() {
3557 Mutex::Autolock _l(mStateLock);
3558 auto it = mTransactionQueues.begin();
3559 while (it != mTransactionQueues.end()) {
3560 auto& [applyToken, transactionQueue] = *it;
3561
3562 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003563 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3564 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003565 break;
3566 }
chaviw273171b2018-12-26 11:46:30 -08003567 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003568 transactionQueue.pop();
3569 }
3570
3571 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3572 }
3573 return mTransactionQueues.empty();
3574}
3575
chaviwca27f252018-02-06 16:46:39 -08003576bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3577 for (const ComposerState& state : states) {
3578 // Here we need to check that the interface we're given is indeed
3579 // one of our own. A malicious client could give us a nullptr
3580 // IInterface, or one of its own or even one of our own but a
3581 // different type. All these situations would cause us to crash.
3582 if (state.client == nullptr) {
3583 return true;
3584 }
3585
3586 sp<IBinder> binder = IInterface::asBinder(state.client);
3587 if (binder == nullptr) {
3588 return true;
3589 }
3590
3591 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3592 return true;
3593 }
3594 }
3595 return false;
3596}
3597
Marissa Wall17b4e452018-12-26 16:32:34 -08003598bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3599 const Vector<ComposerState>& states) {
3600 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3601 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3602 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3603 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3604 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3605 return false;
3606 }
3607
Marissa Wall713b63f2018-10-17 15:42:43 -07003608 for (const ComposerState& state : states) {
3609 const layer_state_t& s = state.state;
3610 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3611 continue;
3612 }
3613 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003614 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003615 }
3616 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003617 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003618}
3619
3620void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3621 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003622 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003623 const InputWindowCommands& inputWindowCommands,
3624 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003625 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003626 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003627
chaviwca27f252018-02-06 16:46:39 -08003628 if (containsAnyInvalidClientState(states)) {
3629 return;
3630 }
3631
Marissa Wall713b63f2018-10-17 15:42:43 -07003632 // If its TransactionQueue already has a pending TransactionState or if it is pending
3633 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003634 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3635 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003636 setTransactionFlags(eTransactionNeeded);
3637 return;
3638 }
3639
chaviw273171b2018-12-26 11:46:30 -08003640 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003641}
3642
3643void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003644 const Vector<DisplayState>& displays, uint32_t flags,
3645 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003646 uint32_t transactionFlags = 0;
3647
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003648 if (flags & eAnimation) {
3649 // For window updates that are part of an animation we must wait for
3650 // previous animation "frames" to be handled.
3651 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003652 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003653 if (CC_UNLIKELY(err != NO_ERROR)) {
3654 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003655 // caller after a few seconds.
3656 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3657 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003658 mAnimTransactionPending = false;
3659 break;
3660 }
3661 }
3662 }
3663
chaviwca27f252018-02-06 16:46:39 -08003664 for (const DisplayState& display : displays) {
3665 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003666 }
3667
Marissa Walle2ffb422018-10-12 11:33:52 -07003668 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003669 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003670 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003671 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003672 // If the state doesn't require a traversal and there are callbacks, send them now
3673 if (!(clientStateFlags & eTraversalNeeded)) {
3674 mTransactionCompletedThread.sendCallbacks();
3675 }
3676 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003677
chaviw273171b2018-12-26 11:46:30 -08003678 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3679
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003680 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3681 // anyway. This can be used as a flush mechanism for previous async transactions.
3682 // Empty animation transaction can be used to simulate back-pressure, so also force a
3683 // transaction for empty animation transactions.
3684 if (transactionFlags == 0 &&
3685 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003686 transactionFlags = eTransactionNeeded;
3687 }
3688
Mathias Agopian386aa982011-11-07 21:58:03 -08003689 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003690 if (mInterceptor->isEnabled()) {
3691 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003692 }
Irvel468051e2016-06-13 16:44:44 -07003693
Mathias Agopian386aa982011-11-07 21:58:03 -08003694 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003695 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3696 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003697 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003698
3699 // if this is a synchronous transaction, wait for it to take effect
3700 // before returning.
3701 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003702 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003703 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003704 if (flags & eAnimation) {
3705 mAnimTransactionPending = true;
3706 }
3707 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003708 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3709 if (CC_UNLIKELY(err != NO_ERROR)) {
3710 // just in case something goes wrong in SF, return to the
3711 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003712 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3713 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003714 break;
3715 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003716 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003717 }
3718}
3719
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003720uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3721 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3722 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003723
Mathias Agopiane57f2922012-08-09 16:29:12 -07003724 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003725 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3726
3727 const uint32_t what = s.what;
3728 if (what & DisplayState::eSurfaceChanged) {
3729 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3730 state.surface = s.surface;
3731 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003732 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003733 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003734 if (what & DisplayState::eLayerStackChanged) {
3735 if (state.layerStack != s.layerStack) {
3736 state.layerStack = s.layerStack;
3737 flags |= eDisplayTransactionNeeded;
3738 }
3739 }
3740 if (what & DisplayState::eDisplayProjectionChanged) {
3741 if (state.orientation != s.orientation) {
3742 state.orientation = s.orientation;
3743 flags |= eDisplayTransactionNeeded;
3744 }
3745 if (state.frame != s.frame) {
3746 state.frame = s.frame;
3747 flags |= eDisplayTransactionNeeded;
3748 }
3749 if (state.viewport != s.viewport) {
3750 state.viewport = s.viewport;
3751 flags |= eDisplayTransactionNeeded;
3752 }
3753 }
3754 if (what & DisplayState::eDisplaySizeChanged) {
3755 if (state.width != s.width) {
3756 state.width = s.width;
3757 flags |= eDisplayTransactionNeeded;
3758 }
3759 if (state.height != s.height) {
3760 state.height = s.height;
3761 flags |= eDisplayTransactionNeeded;
3762 }
3763 }
3764
Mathias Agopiane57f2922012-08-09 16:29:12 -07003765 return flags;
3766}
3767
Robert Carrd4ae7f32018-06-07 16:10:57 -07003768bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3769 IPCThreadState* ipc = IPCThreadState::self();
3770 const int pid = ipc->getCallingPid();
3771 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003772 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003773 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003774 return false;
3775 }
3776 return true;
3777}
3778
chaviwca27f252018-02-06 16:46:39 -08003779uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3780 const layer_state_t& s = composerState.state;
3781 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3782
Mathias Agopian13127d82013-03-05 17:47:11 -08003783 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003784 if (layer == nullptr) {
3785 return 0;
3786 }
3787
chaviw8b3871a2017-11-01 17:41:01 -07003788 uint32_t flags = 0;
3789
Garfield Tan8a3083e2018-12-03 13:21:07 -08003790 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003791 bool geometryAppliesWithResize =
3792 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003793
3794 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3795 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003796 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003797 layer->pushPendingState();
3798 }
3799
chaviw8b3871a2017-11-01 17:41:01 -07003800 if (what & layer_state_t::ePositionChanged) {
3801 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3802 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003803 }
chaviw8b3871a2017-11-01 17:41:01 -07003804 }
3805 if (what & layer_state_t::eLayerChanged) {
3806 // NOTE: index needs to be calculated before we update the state
3807 const auto& p = layer->getParent();
3808 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003809 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003810 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003811 mCurrentState.layersSortedByZ.removeAt(idx);
3812 mCurrentState.layersSortedByZ.add(layer);
3813 // we need traversal (state changed)
3814 // AND transaction (list changed)
3815 flags |= eTransactionNeeded|eTraversalNeeded;
3816 }
chaviw8b3871a2017-11-01 17:41:01 -07003817 } else {
3818 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003819 flags |= eTransactionNeeded|eTraversalNeeded;
3820 }
3821 }
chaviw8b3871a2017-11-01 17:41:01 -07003822 }
3823 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003824 // NOTE: index needs to be calculated before we update the state
3825 const auto& p = layer->getParent();
3826 if (p == nullptr) {
3827 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3828 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3829 mCurrentState.layersSortedByZ.removeAt(idx);
3830 mCurrentState.layersSortedByZ.add(layer);
3831 // we need traversal (state changed)
3832 // AND transaction (list changed)
3833 flags |= eTransactionNeeded|eTraversalNeeded;
3834 }
3835 } else {
3836 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3837 flags |= eTransactionNeeded|eTraversalNeeded;
3838 }
chaviw8b3871a2017-11-01 17:41:01 -07003839 }
3840 }
3841 if (what & layer_state_t::eSizeChanged) {
3842 if (layer->setSize(s.w, s.h)) {
3843 flags |= eTraversalNeeded;
3844 }
3845 }
3846 if (what & layer_state_t::eAlphaChanged) {
3847 if (layer->setAlpha(s.alpha))
3848 flags |= eTraversalNeeded;
3849 }
3850 if (what & layer_state_t::eColorChanged) {
3851 if (layer->setColor(s.color))
3852 flags |= eTraversalNeeded;
3853 }
Valerie Haued54efa2019-01-11 20:03:14 -08003854 if (what & layer_state_t::eColorAlphaChanged) {
3855 if (layer->setColorAlpha(s.colorAlpha)) flags |= eTraversalNeeded;
3856 }
3857 if (what & layer_state_t::eColorDataspaceChanged) {
3858 if (layer->setColorDataspace(s.colorDataspace)) flags |= eTraversalNeeded;
3859 }
Peiyong Lind3788632018-09-18 16:01:31 -07003860 if (what & layer_state_t::eColorTransformChanged) {
3861 if (layer->setColorTransform(s.colorTransform)) {
3862 flags |= eTraversalNeeded;
3863 }
3864 }
chaviw8b3871a2017-11-01 17:41:01 -07003865 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003866 // TODO: b/109894387
3867 //
3868 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3869 // rotation. To see the problem observe that if we have a square parent, and a child
3870 // of the same size, then we rotate the child 45 degrees around it's center, the child
3871 // must now be cropped to a non rectangular 8 sided region.
3872 //
3873 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3874 // private API, and the WindowManager only uses rotation in one case, which is on a top
3875 // level layer in which cropping is not an issue.
3876 //
3877 // However given that abuse of rotation matrices could lead to surfaces extending outside
3878 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3879 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3880 // transformations.
3881 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003882 flags |= eTraversalNeeded;
3883 }
3884 if (what & layer_state_t::eTransparentRegionChanged) {
3885 if (layer->setTransparentRegionHint(s.transparentRegion))
3886 flags |= eTraversalNeeded;
3887 }
3888 if (what & layer_state_t::eFlagsChanged) {
3889 if (layer->setFlags(s.flags, s.mask))
3890 flags |= eTraversalNeeded;
3891 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003892 if (what & layer_state_t::eCropChanged_legacy) {
3893 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003894 flags |= eTraversalNeeded;
3895 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003896 if (what & layer_state_t::eCornerRadiusChanged) {
3897 if (layer->setCornerRadius(s.cornerRadius))
3898 flags |= eTraversalNeeded;
3899 }
chaviw8b3871a2017-11-01 17:41:01 -07003900 if (what & layer_state_t::eLayerStackChanged) {
3901 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3902 // We only allow setting layer stacks for top level layers,
3903 // everything else inherits layer stack from its parent.
3904 if (layer->hasParent()) {
3905 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3906 layer->getName().string());
3907 } else if (idx < 0) {
3908 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3909 "that also does not appear in the top level layer list. Something"
3910 " has gone wrong.", layer->getName().string());
3911 } else if (layer->setLayerStack(s.layerStack)) {
3912 mCurrentState.layersSortedByZ.removeAt(idx);
3913 mCurrentState.layersSortedByZ.add(layer);
3914 // we need traversal (state changed)
3915 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003916 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003917 }
3918 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003919 if (what & layer_state_t::eDeferTransaction_legacy) {
3920 if (s.barrierHandle_legacy != nullptr) {
3921 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3922 } else if (s.barrierGbp_legacy != nullptr) {
3923 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003924 if (authenticateSurfaceTextureLocked(gbp)) {
3925 const auto& otherLayer =
3926 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003927 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003928 } else {
3929 ALOGE("Attempt to defer transaction to to an"
3930 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003931 }
3932 }
chaviw8b3871a2017-11-01 17:41:01 -07003933 // We don't trigger a traversal here because if no other state is
3934 // changed, we don't want this to cause any more work
3935 }
3936 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003937 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003938 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003939 if (!hadParent) {
3940 mCurrentState.layersSortedByZ.remove(layer);
3941 }
chaviw8b3871a2017-11-01 17:41:01 -07003942 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003943 }
chaviw8b3871a2017-11-01 17:41:01 -07003944 }
3945 if (what & layer_state_t::eReparentChildren) {
3946 if (layer->reparentChildren(s.reparentHandle)) {
3947 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003948 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003949 }
chaviw8b3871a2017-11-01 17:41:01 -07003950 if (what & layer_state_t::eDetachChildren) {
3951 layer->detachChildren();
3952 }
3953 if (what & layer_state_t::eOverrideScalingModeChanged) {
3954 layer->setOverrideScalingMode(s.overrideScalingMode);
3955 // We don't trigger a traversal here because if no other state is
3956 // changed, we don't want this to cause any more work
3957 }
Marissa Wall61c58622018-07-18 10:12:20 -07003958 if (what & layer_state_t::eTransformChanged) {
3959 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3960 }
3961 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3962 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3963 flags |= eTraversalNeeded;
3964 }
3965 if (what & layer_state_t::eCropChanged) {
3966 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3967 }
Marissa Wall861616d2018-10-22 12:52:23 -07003968 if (what & layer_state_t::eFrameChanged) {
3969 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3970 }
Marissa Wall61c58622018-07-18 10:12:20 -07003971 if (what & layer_state_t::eBufferChanged) {
3972 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3973 }
3974 if (what & layer_state_t::eAcquireFenceChanged) {
3975 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3976 }
3977 if (what & layer_state_t::eDataspaceChanged) {
3978 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3979 }
3980 if (what & layer_state_t::eHdrMetadataChanged) {
3981 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3982 }
3983 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3984 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3985 }
3986 if (what & layer_state_t::eApiChanged) {
3987 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3988 }
3989 if (what & layer_state_t::eSidebandStreamChanged) {
3990 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3991 }
Robert Carr720e5062018-07-30 17:45:14 -07003992 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003993 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
3994 layer->setInputInfo(s.inputInfo);
3995 flags |= eTraversalNeeded;
3996 } else {
3997 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3998 }
Robert Carr720e5062018-07-30 17:45:14 -07003999 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004000 std::vector<sp<CallbackHandle>> callbackHandles;
4001 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
4002 mTransactionCompletedThread.run();
4003 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
4004 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4005 }
4006 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004007 if (what & layer_state_t::eCachedBufferChanged) {
4008 sp<GraphicBuffer> buffer =
4009 mBufferStateLayerCache.get(s.cachedBuffer.token, s.cachedBuffer.bufferId);
4010 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4011 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004012 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4013 // Do not put anything that updates layer state or modifies flags after
4014 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004015 return flags;
4016}
4017
chaviw273171b2018-12-26 11:46:30 -08004018uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4019 uint32_t flags = 0;
4020 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4021 flags |= eTraversalNeeded;
4022 }
4023
4024 mInputWindowCommands.merge(inputWindowCommands);
4025 return flags;
4026}
4027
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004028status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07004029 const String8& name,
4030 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004031 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07004032 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05004033 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004034{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004035 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004036 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004037 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004038 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004039 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004040
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004041 status_t result = NO_ERROR;
4042
4043 sp<Layer> layer;
4044
Cody Northropbc755282017-03-31 12:00:08 -06004045 String8 uniqueName = getUniqueLayerName(name);
4046
Mathias Agopian3165cc22012-08-08 19:42:09 -07004047 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004048 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004049 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4050 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004051
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004052 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004053 case ISurfaceComposerClient::eFXSurfaceBufferState:
4054 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4055 break;
chaviw13fdc492017-06-27 12:40:18 -07004056 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004057 // check if buffer size is set for color layer.
4058 if (w > 0 || h > 0) {
4059 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4060 int(w), int(h));
4061 return BAD_VALUE;
4062 }
4063
chaviw13fdc492017-06-27 12:40:18 -07004064 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004065 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004066 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004067 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004068 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004069 // check if buffer size is set for container layer.
4070 if (w > 0 || h > 0) {
4071 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4072 int(w), int(h));
4073 return BAD_VALUE;
4074 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004075 result = createContainerLayer(client,
4076 uniqueName, w, h, flags,
4077 handle, &layer);
4078 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004079 default:
4080 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004081 break;
4082 }
4083
Dan Stoza7d89d062015-04-30 13:29:25 -07004084 if (result != NO_ERROR) {
4085 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004086 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004087
Chia-I Wuab0c3192017-08-01 11:29:00 -07004088 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4089 // TODO b/64227542
4090 if (windowType == 441731) {
4091 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
4092 layer->setPrimaryDisplayOnly();
4093 }
4094
Albert Chaulk479c60c2017-01-27 14:21:34 -05004095 layer->setInfo(windowType, ownerUid);
4096
Robert Carrb89ea9d2018-12-10 13:01:14 -08004097 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4098 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4099 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004100 if (result != NO_ERROR) {
4101 return result;
4102 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004103 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004104
4105 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004106 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004107}
4108
Cody Northropbc755282017-03-31 12:00:08 -06004109String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4110{
4111 bool matchFound = true;
4112 uint32_t dupeCounter = 0;
4113
4114 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4115 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4116
Dan Stoza436ccf32018-06-21 12:10:12 -07004117 // Grab the state lock since we're accessing mCurrentState
4118 Mutex::Autolock lock(mStateLock);
4119
Cody Northropbc755282017-03-31 12:00:08 -06004120 // Loop over layers until we're sure there is no matching name
4121 while (matchFound) {
4122 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004123 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004124 if (layer->getName() == uniqueName) {
4125 matchFound = true;
4126 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4127 }
4128 });
4129 }
4130
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004131 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4132 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004133
4134 return uniqueName;
4135}
4136
Marissa Wallfd668622018-05-10 10:21:13 -07004137status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4138 uint32_t w, uint32_t h, uint32_t flags,
4139 PixelFormat& format, sp<IBinder>* handle,
4140 sp<IGraphicBufferProducer>* gbp,
4141 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004142 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004143 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004144 case PIXEL_FORMAT_TRANSPARENT:
4145 case PIXEL_FORMAT_TRANSLUCENT:
4146 format = PIXEL_FORMAT_RGBA_8888;
4147 break;
4148 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004149 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004150 break;
4151 }
4152
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004153 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004154 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004155 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004156 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004157 *handle = layer->getHandle();
4158 *gbp = layer->getProducer();
4159 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004160 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004161
Marissa Wallfd668622018-05-10 10:21:13 -07004162 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004163 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004164}
4165
Marissa Wall61c58622018-07-18 10:12:20 -07004166status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4167 uint32_t w, uint32_t h, uint32_t flags,
4168 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004169 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004170 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004171 *handle = layer->getHandle();
4172 *outLayer = layer;
4173
4174 return NO_ERROR;
4175}
4176
chaviw13fdc492017-06-27 12:40:18 -07004177status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004178 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004179 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004180{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004181 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004182 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004183 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004184}
4185
Robert Carr6b3f6c52018-08-13 13:05:17 -07004186status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4187 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4188 sp<IBinder>* handle, sp<Layer>* outLayer)
4189{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004190 *outLayer =
4191 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004192 *handle = (*outLayer)->getHandle();
4193 return NO_ERROR;
4194}
4195
4196
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004197void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004198 mLayersPendingRemoval.add(layer);
4199 mLayersRemoved = true;
4200 setTransactionFlags(eTransactionNeeded);
4201}
4202
Robert Carr695d5282018-12-18 15:27:58 -08004203void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004204{
Robert Carr2e102c92018-10-23 12:11:15 -07004205 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004206 // If a layer has a parent, we allow it to out-live it's handle
4207 // with the idea that the parent holds a reference and will eventually
4208 // be cleaned up. However no one cleans up the top-level so we do so
4209 // here.
4210 if (layer->getParent() == nullptr) {
4211 mCurrentState.layersSortedByZ.remove(layer);
4212 }
4213 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004214 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004215}
4216
Mathias Agopianb60314a2012-04-10 22:09:54 -07004217// ---------------------------------------------------------------------------
4218
Andy McFadden13a082e2012-08-24 10:16:42 -07004219void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004220 const auto display = getDefaultDisplayDeviceLocked();
4221 if (!display) return;
4222
4223 const sp<IBinder> token = display->getDisplayToken().promote();
4224 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004225
Jesse Hall01e29052013-02-19 16:13:35 -08004226 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004227 Vector<ComposerState> state;
4228 Vector<DisplayState> displays;
4229 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004230 d.what = DisplayState::eDisplayProjectionChanged |
4231 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004232 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004233 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004234 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004235 d.frame.makeInvalid();
4236 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004237 d.width = 0;
4238 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004239 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004240 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004241
Dominik Laskowskie9774092018-12-11 10:04:24 -08004242 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004243
Dominik Laskowski83b88212018-12-11 13:34:06 -08004244 const nsecs_t vsyncPeriod = getVsyncPeriod();
4245 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004246
Brian Andersond0010582017-03-07 13:20:31 -08004247 // Use phase of 0 since phase is not known.
4248 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004249 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004250 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004251}
4252
4253void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004254 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004255 postMessageAsync(
4256 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004257}
4258
Dominik Laskowskie9774092018-12-11 10:04:24 -08004259void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004260 if (display->isVirtual()) {
4261 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004262 return;
4263 }
4264
Dominik Laskowski075d3172018-05-24 15:50:06 -07004265 const auto displayId = display->getId();
4266 LOG_ALWAYS_FATAL_IF(!displayId);
4267
Dominik Laskowski34157762018-10-31 13:07:19 -07004268 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004269
4270 int currentMode = display->getPowerMode();
4271 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004272 return;
4273 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004274
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004275 display->setPowerMode(mode);
4276
Lloyd Pique4dccc412018-01-22 17:21:36 -08004277 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004278 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004279 }
4280
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004281 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004282 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004283 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004284 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004285 if (mUseScheduler) {
4286 mScheduler->onScreenAcquired(mAppConnectionHandle);
4287 } else {
4288 mEventThread->onScreenAcquired();
4289 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004290 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004291 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004292
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004293 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004294 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004295 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004296
4297 struct sched_param param = {0};
4298 param.sched_priority = 1;
4299 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4300 ALOGW("Couldn't set SCHED_FIFO on display on");
4301 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004302 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004303 // Turn off the display
4304 struct sched_param param = {0};
4305 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4306 ALOGW("Couldn't set SCHED_OTHER on display off");
4307 }
4308
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004309 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004310 if (mUseScheduler) {
4311 mScheduler->disableHardwareVsync(true);
4312 } else {
4313 disableHardwareVsync(true); // also cancels any in-progress resync
4314 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004315 if (mUseScheduler) {
4316 mScheduler->onScreenReleased(mAppConnectionHandle);
4317 } else {
4318 mEventThread->onScreenReleased();
4319 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004320 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004321
Dominik Laskowski075d3172018-05-24 15:50:06 -07004322 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004323 mVisibleRegionsDirty = true;
4324 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004325 } else if (mode == HWC_POWER_MODE_DOZE ||
4326 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004327 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004328 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004329 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004330 if (mUseScheduler) {
4331 mScheduler->onScreenAcquired(mAppConnectionHandle);
4332 } else {
4333 mEventThread->onScreenAcquired();
4334 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004335 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004336 }
4337 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4338 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004339 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004340 if (mUseScheduler) {
4341 mScheduler->disableHardwareVsync(true);
4342 } else {
4343 disableHardwareVsync(true); // also cancels any in-progress resync
4344 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004345 if (mUseScheduler) {
4346 mScheduler->onScreenReleased(mAppConnectionHandle);
4347 } else {
4348 mEventThread->onScreenReleased();
4349 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004350 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004351 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004352 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004353 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004354 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004355 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004356
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004357 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004358 mTimeStats->setPowerMode(mode);
Ana Krulec4593b692019-01-11 22:07:25 -08004359 if (mUseScheduler && mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004360 // Update refresh rate stats.
4361 mRefreshRateStats->setPowerMode(mode);
4362 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004363 }
4364
Dominik Laskowski34157762018-10-31 13:07:19 -07004365 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004366}
4367
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004368void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004369 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004370 const auto display = getDisplayDevice(displayToken);
4371 if (!display) {
4372 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4373 displayToken.get());
4374 } else if (display->isVirtual()) {
4375 ALOGW("Attempt to set power mode %d for virtual display", mode);
4376 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004377 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004378 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004379 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004380}
4381
4382// ---------------------------------------------------------------------------
4383
Dominik Laskowskic2867142019-01-21 11:33:38 -08004384status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4385 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004386 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004387
Mathias Agopianbd115332013-04-18 16:41:04 -07004388 IPCThreadState* ipc = IPCThreadState::self();
4389 const int pid = ipc->getCallingPid();
4390 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004391
Mathias Agopianbd115332013-04-18 16:41:04 -07004392 if ((uid != AID_SHELL) &&
4393 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004394 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4395 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004396 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004397 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004398 // (this would indicate SF is stuck, but we want to be able to
4399 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004400 status_t err = mStateLock.timedLock(s2ns(1));
4401 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004402 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004403 StringAppendF(&result,
4404 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4405 "(no locks held)\n",
4406 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004407 }
4408
Dominik Laskowskic2867142019-01-21 11:33:38 -08004409 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004410
Dominik Laskowskic2867142019-01-21 11:33:38 -08004411 static const std::unordered_map<std::string, Dumper> dumpers = {
4412 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4413 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4414 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
4415 {"--dispsync"s, dumper([this](std::string& s) { mPrimaryDispSync->dump(s); })},
4416 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4417 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
4418 {"--frame-composition"s, dumper(&SurfaceFlinger::dumpFrameCompositionInfo)},
4419 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4420 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4421 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4422 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4423 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4424 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004425 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004426 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4427 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004428
Dominik Laskowskic2867142019-01-21 11:33:38 -08004429 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004430
Dominik Laskowskic2867142019-01-21 11:33:38 -08004431 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4432 (it->second)(args, asProto, result);
4433 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004434 if (asProto) {
4435 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4436 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4437 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004438 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004439 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004440 }
4441
Mathias Agopian9795c422009-08-26 16:36:26 -07004442 if (locked) {
4443 mStateLock.unlock();
4444 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004445 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004446 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004447 return NO_ERROR;
4448}
4449
Dominik Laskowskic2867142019-01-21 11:33:38 -08004450void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004451 mCurrentState.traverseInZOrder(
4452 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004453}
4454
Dominik Laskowskic2867142019-01-21 11:33:38 -08004455void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004456 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004457
Dominik Laskowskic2867142019-01-21 11:33:38 -08004458 if (args.size() > 1) {
4459 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004460 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004461 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004462 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004463 }
Robert Carr2047fae2016-11-28 14:09:09 -08004464 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004465 } else {
4466 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004467 }
4468}
4469
Dominik Laskowskic2867142019-01-21 11:33:38 -08004470void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004471 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004472 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004473 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004474 }
Robert Carr2047fae2016-11-28 14:09:09 -08004475 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004476
Svetoslavd85084b2014-03-20 10:28:31 -07004477 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004478}
4479
Dominik Laskowskic2867142019-01-21 11:33:38 -08004480void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4481 mTimeStats->parseArgs(asProto, args, result);
4482}
4483
Jamie Gennis6547ff42013-07-16 20:12:42 -07004484// This should only be called from the main thread. Otherwise it would need
4485// the lock and should use mCurrentState rather than mDrawingState.
4486void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004487 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004488 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004489 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004490
4491 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4492}
4493
Yiwei Zhang5434a782018-12-05 18:06:32 -08004494void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004495 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004496
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004497 if (isLayerTripleBufferingDisabled())
4498 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004499
Yiwei Zhang5434a782018-12-05 18:06:32 -08004500 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4501 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4502 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4503 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4504 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4505 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004506 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004507}
4508
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004509void SurfaceFlinger::dumpVSync(std::string& result) const {
4510 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4511 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
4512 StringAppendF(&result,
4513 " app phase: %9" PRId64 " ns\t SF phase: %9" PRId64 " ns\n"
4514 " early app phase: %9" PRId64 " ns\t early SF phase: %9" PRId64 " ns\n"
4515 "GL early app phase: %9" PRId64 " ns\tGL early SF phase: %9" PRId64 " ns\n"
4516 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
4517 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, appEarlyOffset, sfEarlyOffset,
4518 appEarlyGlOffset, sfEarlyGlOffset, dispSyncPresentTimeOffset, getVsyncPeriod());
4519
4520 StringAppendF(&result, "Scheduler: %s\n\n", mUseScheduler ? "enabled" : "disabled");
4521
4522 if (mUseScheduler) {
4523 mScheduler->dump(mAppConnectionHandle, result);
4524 } else {
4525 mEventThread->dump(result);
4526 }
4527}
4528
Yiwei Zhang5434a782018-12-05 18:06:32 -08004529void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4530 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004531 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4532 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004533 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004534 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004535 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004536 }
David Sodman4a36e932017-11-07 14:29:47 -08004537 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004538 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004539 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004540 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4541 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004542}
4543
Dan Stozae77c7662016-05-13 11:37:28 -07004544void SurfaceFlinger::recordBufferingStats(const char* layerName,
4545 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004546 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4547 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004548 for (const auto& segment : history) {
4549 if (!segment.usedThirdBuffer) {
4550 stats.twoBufferTime += segment.totalTime;
4551 }
4552 if (segment.occupancyAverage < 1.0f) {
4553 stats.doubleBufferedTime += segment.totalTime;
4554 } else if (segment.occupancyAverage < 2.0f) {
4555 stats.tripleBufferedTime += segment.totalTime;
4556 }
4557 ++stats.numSegments;
4558 stats.totalTime += segment.totalTime;
4559 }
4560}
4561
Yiwei Zhang5434a782018-12-05 18:06:32 -08004562void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4563 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004564
4565 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4566 const size_t count = currentLayers.size();
4567 for (size_t i=0 ; i<count ; i++) {
4568 currentLayers[i]->dumpFrameEvents(result);
4569 }
4570}
4571
Yiwei Zhang5434a782018-12-05 18:06:32 -08004572void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004573 result.append("Buffering stats:\n");
4574 result.append(" [Layer name] <Active time> <Two buffer> "
4575 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004576 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004577 typedef std::tuple<std::string, float, float, float> BufferTuple;
4578 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004579 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004580 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004581 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004582 if (stats.numSegments == 0) {
4583 continue;
4584 }
4585 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4586 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4587 stats.totalTime;
4588 float doubleBufferRatio = static_cast<float>(
4589 stats.doubleBufferedTime) / stats.totalTime;
4590 float tripleBufferRatio = static_cast<float>(
4591 stats.tripleBufferedTime) / stats.totalTime;
4592 sorted.insert({activeTime, {name, twoBufferRatio,
4593 doubleBufferRatio, tripleBufferRatio}});
4594 }
4595 for (const auto& sortedPair : sorted) {
4596 float activeTime = sortedPair.first;
4597 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004598 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4599 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004600 }
4601 result.append("\n");
4602}
4603
Yiwei Zhang5434a782018-12-05 18:06:32 -08004604void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004605 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004606 const auto displayId = display->getId();
4607 if (!displayId) {
4608 continue;
4609 }
4610 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004611 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004612 continue;
4613 }
4614
Yiwei Zhang5434a782018-12-05 18:06:32 -08004615 StringAppendF(&result,
4616 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4617 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004618 uint8_t port;
4619 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004620 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004621 result.append("no identification data\n");
4622 continue;
4623 }
4624
4625 if (!isEdid(data)) {
4626 result.append("unknown identification data: ");
4627 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004628 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004629 }
4630 result.append("\n");
4631 continue;
4632 }
4633
4634 const auto edid = parseEdid(data);
4635 if (!edid) {
4636 result.append("invalid EDID: ");
4637 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004638 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004639 }
4640 result.append("\n");
4641 continue;
4642 }
4643
Yiwei Zhang5434a782018-12-05 18:06:32 -08004644 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004645 result.append(edid->displayName.data(), edid->displayName.length());
4646 result.append("\"\n");
4647 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004648}
4649
Yiwei Zhang5434a782018-12-05 18:06:32 -08004650void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4651 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4652 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4653 StringAppendF(&result, "DisplayColorSetting: %s\n",
4654 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004655
4656 // TODO: print out if wide-color mode is active or not
4657
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004658 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004659 const auto displayId = display->getId();
4660 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004661 continue;
4662 }
4663
Yiwei Zhang5434a782018-12-05 18:06:32 -08004664 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004665 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004666 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004667 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004668 }
4669
Lloyd Pique32cbe282018-10-19 13:09:22 -07004670 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004671 StringAppendF(&result, " Current color mode: %s (%d)\n",
4672 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004673 }
4674 result.append("\n");
4675}
4676
Yiwei Zhang5434a782018-12-05 18:06:32 -08004677void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004678 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004679 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4680 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004681 continue;
4682 }
4683
Dominik Laskowski05275f12018-11-01 15:03:24 -07004684 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004685 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4686 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004687 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004688 compositionInfo.dump(result, nullptr);
4689 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004690 }
4691 }
David Sodman7e4ae112018-02-09 15:02:28 -08004692}
4693
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004694LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004695 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004696 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4697 const State& state = useDrawing ? mDrawingState : mCurrentState;
4698 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004699 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004700 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004701 });
4702
4703 return layersProto;
4704}
4705
Lloyd Pique32cbe282018-10-19 13:09:22 -07004706LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004707 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004708
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004709 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004710 resolution->set_w(displayDevice.getWidth());
4711 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004712
Lloyd Pique32cbe282018-10-19 13:09:22 -07004713 auto display = displayDevice.getCompositionDisplay();
4714 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004715
Lloyd Pique32cbe282018-10-19 13:09:22 -07004716 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4717 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4718 layersProto.set_global_transform(displayState.orientation);
4719
4720 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004721 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004722 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004723 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004724 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004725 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004726 }
4727 });
4728
4729 return layersProto;
4730}
4731
Dominik Laskowskic2867142019-01-21 11:33:38 -08004732void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4733 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004734 Colorizer colorizer(colorize);
4735
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004736 // figure out if we're stuck somewhere
4737 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004738 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004739 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4740
4741 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004742 * Dump library configuration.
4743 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004744
4745 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004746 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004747 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004748 appendSfConfigString(result);
4749 appendUiConfigString(result);
4750 appendGuiConfigString(result);
4751 result.append("\n");
4752
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004753 result.append("\nDisplay identification data:\n");
4754 dumpDisplayIdentificationData(result);
4755
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004756 result.append("\nWide-Color information:\n");
4757 dumpWideColorInfo(result);
4758
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004759 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004760 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004761 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004762 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004763 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004764
Andy McFadden41d67d72014-04-25 16:58:34 -07004765 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004766 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004767 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004768 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004769 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004770
Dan Stozab90cf072015-03-05 11:05:59 -08004771 dumpStaticScreenStats(result);
4772 result.append("\n");
4773
Yiwei Zhang5434a782018-12-05 18:06:32 -08004774 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004775
Dan Stozae77c7662016-05-13 11:37:28 -07004776 dumpBufferingStats(result);
4777
Andy McFadden4803b742012-09-24 19:07:20 -07004778 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004779 * Dump the visible layer list
4780 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004781 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004782 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4783 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4784 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004785 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004786
Chia-I Wu2f884132018-09-13 15:17:58 -07004787 {
4788 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4789 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004790 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004791 result.append("\n");
4792 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004793
David Sodman7e4ae112018-02-09 15:02:28 -08004794 result.append("\nFrame-Composition information:\n");
4795 dumpFrameCompositionInfo(result);
4796 result.append("\n");
4797
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004798 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004799 * Dump Display state
4800 */
4801
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004802 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004803 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004804 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004805 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004806 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004807 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004808 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004809
4810 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004811 * Dump SurfaceFlinger global state
4812 */
4813
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004814 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004815 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004816 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004817
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004818 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004819
Dominik Laskowski075d3172018-05-24 15:50:06 -07004820 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004821 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4822 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004823 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4824 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004825 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004826 StringAppendF(&result,
4827 " transaction-flags : %08x\n"
4828 " gpu_to_cpu_unsupported : %d\n",
4829 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004830
Dominik Laskowski075d3172018-05-24 15:50:06 -07004831 if (const auto displayId = getInternalDisplayId();
4832 displayId && getHwComposer().isConnected(*displayId)) {
4833 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004834 StringAppendF(&result,
4835 " refresh-rate : %f fps\n"
4836 " x-dpi : %f\n"
4837 " y-dpi : %f\n",
4838 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4839 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004840 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004841
Yiwei Zhang5434a782018-12-05 18:06:32 -08004842 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004843
Dan Stozae22aec72016-08-01 13:20:59 -07004844 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004845 * Tracing state
4846 */
4847 mTracing.dump(result);
4848 result.append("\n");
4849
4850 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004851 * HWC layer minidump
4852 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004853 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004854 const auto displayId = display->getId();
4855 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004856 continue;
4857 }
4858
Yiwei Zhang5434a782018-12-05 18:06:32 -08004859 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004860 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004861 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004862 result.append("\n");
4863 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004864
4865 /*
4866 * Dump HWComposer state
4867 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004868 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004869 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004870 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004871 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004872 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004873 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004874
4875 /*
4876 * Dump gralloc state
4877 */
4878 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4879 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004880
4881 /*
4882 * Dump VrFlinger state if in use.
4883 */
4884 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4885 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004886 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004887 result.append("\n");
4888 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004889
4890 /**
4891 * Scheduler dump state.
4892 */
4893 if (mUseScheduler) {
4894 result.append("\nScheduler state:\n");
4895 result.append(mScheduler->doDump() + "\n");
4896 result.append(mRefreshRateStats->doDump() + "\n");
4897 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004898}
4899
Dominik Laskowski075d3172018-05-24 15:50:06 -07004900const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004901 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004902 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004903 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004904 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004905 }
4906 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004907
Dominik Laskowski34157762018-10-31 13:07:19 -07004908 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004909 static const Vector<sp<Layer>> empty;
4910 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004911}
4912
Keun young Park63f165f2012-08-31 10:53:36 -07004913bool SurfaceFlinger::startDdmConnection()
4914{
4915 void* libddmconnection_dso =
4916 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4917 if (!libddmconnection_dso) {
4918 return false;
4919 }
4920 void (*DdmConnection_start)(const char* name);
4921 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004922 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004923 if (!DdmConnection_start) {
4924 dlclose(libddmconnection_dso);
4925 return false;
4926 }
4927 (*DdmConnection_start)(getServiceName());
4928 return true;
4929}
4930
Chia-I Wu28f320b2018-05-03 11:02:56 -07004931void SurfaceFlinger::updateColorMatrixLocked() {
4932 mat4 colorMatrix;
4933 if (mGlobalSaturationFactor != 1.0f) {
4934 // Rec.709 luma coefficients
4935 float3 luminance{0.213f, 0.715f, 0.072f};
4936 luminance *= 1.0f - mGlobalSaturationFactor;
4937 mat4 saturationMatrix = mat4(
4938 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4939 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4940 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4941 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4942 );
4943 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4944 } else {
4945 colorMatrix = mClientColorMatrix * mDaltonizer();
4946 }
4947
4948 if (mCurrentState.colorMatrix != colorMatrix) {
4949 mCurrentState.colorMatrix = colorMatrix;
4950 mCurrentState.colorMatrixChanged = true;
4951 setTransactionFlags(eTransactionNeeded);
4952 }
4953}
4954
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004955status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004956#pragma clang diagnostic push
4957#pragma clang diagnostic error "-Wswitch-enum"
4958 switch (static_cast<ISurfaceComposerTag>(code)) {
4959 // These methods should at minimum make sure that the client requested
4960 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004961 case BOOT_FINISHED:
4962 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004963 case CREATE_DISPLAY:
4964 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004965 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004966 case GET_ACTIVE_COLOR_MODE:
4967 case GET_ANIMATION_FRAME_STATS:
4968 case GET_HDR_CAPABILITIES:
4969 case SET_ACTIVE_CONFIG:
4970 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004971 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004972 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004973 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004974 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4975 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004976 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4977 IPCThreadState* ipc = IPCThreadState::self();
4978 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4979 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004980 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004981 }
Robert Carr1db73f62016-12-21 12:58:51 -08004982 return OK;
4983 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004984 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004985 IPCThreadState* ipc = IPCThreadState::self();
4986 const int pid = ipc->getCallingPid();
4987 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004988 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4989 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004990 return PERMISSION_DENIED;
4991 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004992 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004993 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004994 // Used by apps to hook Choreographer to SurfaceFlinger.
4995 case CREATE_DISPLAY_EVENT_CONNECTION:
4996 // The following calls are currently used by clients that do not
4997 // request necessary permissions. However, they do not expose any secret
4998 // information, so it is OK to pass them.
4999 case AUTHENTICATE_SURFACE:
5000 case GET_ACTIVE_CONFIG:
5001 case GET_BUILT_IN_DISPLAY:
5002 case GET_DISPLAY_COLOR_MODES:
5003 case GET_DISPLAY_CONFIGS:
5004 case GET_DISPLAY_STATS:
5005 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5006 // Calling setTransactionState is safe, because you need to have been
5007 // granted a reference to Client* and Handle* to do anything with it.
5008 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005009 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005010 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005011 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005012 case GET_PROTECTED_CONTENT_SUPPORT:
5013 case CACHE_BUFFER:
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08005014 case UNCACHE_BUFFER:
5015 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005016 return OK;
5017 }
5018 case CAPTURE_LAYERS:
5019 case CAPTURE_SCREEN: {
5020 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005021 IPCThreadState* ipc = IPCThreadState::self();
5022 const int pid = ipc->getCallingPid();
5023 const int uid = ipc->getCallingUid();
5024 if ((uid != AID_GRAPHICS) &&
5025 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5026 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5027 return PERMISSION_DENIED;
5028 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005029 return OK;
5030 }
5031 // The following codes are deprecated and should never be allowed to access SF.
5032 case CONNECT_DISPLAY_UNUSED:
5033 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5034 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5035 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005036 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005037 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005038
5039 // These codes are used for the IBinder protocol to either interrogate the recipient
5040 // side of the transaction for its canonical interface descriptor or to dump its state.
5041 // We let them pass by default.
5042 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5043 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5044 code == IBinder::SYSPROPS_TRANSACTION) {
5045 return OK;
5046 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005047 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005048 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005049 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005050 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5051 return OK;
5052 }
5053 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5054 return PERMISSION_DENIED;
5055#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005056}
5057
Ana Krulec13be8ad2018-08-21 02:43:56 +00005058status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5059 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005060 status_t credentialCheck = CheckTransactCodeCredentials(code);
5061 if (credentialCheck != OK) {
5062 return credentialCheck;
5063 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005064
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005065 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5066 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005067 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005068 IPCThreadState* ipc = IPCThreadState::self();
5069 const int uid = ipc->getCallingUid();
5070 if (CC_UNLIKELY(uid != AID_SYSTEM
5071 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005072 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005073 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005074 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005075 return PERMISSION_DENIED;
5076 }
5077 int n;
5078 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005079 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005080 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005081 return NO_ERROR;
5082 case 1002: // SHOW_UPDATES
5083 n = data.readInt32();
5084 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005085 invalidateHwcGeometry();
5086 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005087 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005088 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005089 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005090 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005091 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005092 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005093 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005094 setTransactionFlags(
5095 eTransactionNeeded|
5096 eDisplayTransactionNeeded|
5097 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005098 return NO_ERROR;
5099 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005100 case 1006:{ // send empty update
5101 signalRefresh();
5102 return NO_ERROR;
5103 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005104 case 1008: // toggle use of hw composer
5105 n = data.readInt32();
5106 mDebugDisableHWC = n ? 1 : 0;
5107 invalidateHwcGeometry();
5108 repaintEverything();
5109 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005110 case 1009: // toggle use of transform hint
5111 n = data.readInt32();
5112 mDebugDisableTransformHint = n ? 1 : 0;
5113 invalidateHwcGeometry();
5114 repaintEverything();
5115 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005116 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005117 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005118 reply->writeInt32(0);
5119 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005120 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005121 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005122 return NO_ERROR;
5123 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005124 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005125 if (!display) {
5126 return NAME_NOT_FOUND;
5127 }
5128
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005129 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005130 return NO_ERROR;
5131 }
5132 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005133 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005134 // daltonize
5135 n = data.readInt32();
5136 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005137 case 1:
5138 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5139 break;
5140 case 2:
5141 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5142 break;
5143 case 3:
5144 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5145 break;
5146 default:
5147 mDaltonizer.setType(ColorBlindnessType::None);
5148 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005149 }
5150 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005151 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005152 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005153 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005154 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005155
5156 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005157 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005158 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005159 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005160 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005161 // apply a color matrix
5162 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005163 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005164 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005165 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005166 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005167 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005168 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005169 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005170 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005171 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005172 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005173
5174 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5175 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005176 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005177 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5178 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5179 }
5180
Chia-I Wu28f320b2018-05-03 11:02:56 -07005181 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005182 return NO_ERROR;
5183 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005184 // This is an experimental interface
5185 // Needs to be shifted to proper binder interface when we productize
5186 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005187 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005188 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005189 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005190 return NO_ERROR;
5191 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005192 case 1017: {
5193 n = data.readInt32();
5194 mForceFullDamage = static_cast<bool>(n);
5195 return NO_ERROR;
5196 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005197 case 1018: { // Modify Choreographer's phase offset
5198 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005199 if (mUseScheduler) {
5200 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5201 } else {
5202 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5203 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005204 return NO_ERROR;
5205 }
5206 case 1019: { // Modify SurfaceFlinger's phase offset
5207 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005208 if (mUseScheduler) {
5209 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5210 } else {
5211 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5212 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005213 return NO_ERROR;
5214 }
Irvel468051e2016-06-13 16:44:44 -07005215 case 1020: { // Layer updates interceptor
5216 n = data.readInt32();
5217 if (n) {
5218 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005219 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005220 }
5221 else{
5222 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005223 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005224 }
5225 return NO_ERROR;
5226 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005227 case 1021: { // Disable HWC virtual displays
5228 n = data.readInt32();
5229 mUseHwcVirtualDisplays = !n;
5230 return NO_ERROR;
5231 }
Romain Guy0147a172017-06-01 13:53:56 -07005232 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005233 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005234 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005235
Chia-I Wu28f320b2018-05-03 11:02:56 -07005236 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005237 return NO_ERROR;
5238 }
Romain Guy54f154a2017-10-24 21:40:32 +01005239 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005240 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005241 invalidateHwcGeometry();
5242 repaintEverything();
5243 return NO_ERROR;
5244 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005245 // Deprecate, use 1030 to check whether the device is color managed.
5246 case 1024: {
5247 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005248 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005249 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005250 n = data.readInt32();
5251 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005252 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005253 mTracing.enable();
5254 doTracing("tracing.enable");
5255 reply->writeInt32(NO_ERROR);
5256 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005257 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005258 status_t err = mTracing.disable();
5259 reply->writeInt32(err);
5260 }
5261 return NO_ERROR;
5262 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005263 case 1026: { // Get layer tracing status
5264 reply->writeBool(mTracing.isEnabled());
5265 return NO_ERROR;
5266 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005267 // Is a DisplayColorSetting supported?
5268 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005269 const auto display = getDefaultDisplayDevice();
5270 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005271 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005272 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005273
5274 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5275 switch (setting) {
5276 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005277 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005278 break;
5279 case DisplayColorSetting::UNMANAGED:
5280 reply->writeBool(true);
5281 break;
5282 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005283 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005284 break;
5285 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005286 reply->writeBool(
5287 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005288 break;
5289 }
5290 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005291 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005292 // Is VrFlinger active?
5293 case 1028: {
5294 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005295 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005296 return NO_ERROR;
5297 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005298 // Is device color managed?
5299 case 1030: {
5300 reply->writeBool(useColorManagement);
5301 return NO_ERROR;
5302 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005303 // Override default composition data space
5304 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5305 // && adb shell stop zygote && adb shell start zygote
5306 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5307 // adb shell stop zygote && adb shell start zygote
5308 case 1031: {
5309 Mutex::Autolock _l(mStateLock);
5310 n = data.readInt32();
5311 if (n) {
5312 n = data.readInt32();
5313 if (n) {
5314 Dataspace dataspace = static_cast<Dataspace>(n);
5315 if (!validateCompositionDataspace(dataspace)) {
5316 return BAD_VALUE;
5317 }
5318 mDefaultCompositionDataspace = dataspace;
5319 }
5320 n = data.readInt32();
5321 if (n) {
5322 Dataspace dataspace = static_cast<Dataspace>(n);
5323 if (!validateCompositionDataspace(dataspace)) {
5324 return BAD_VALUE;
5325 }
5326 mWideColorGamutCompositionDataspace = dataspace;
5327 }
5328 } else {
5329 // restore composition data space.
5330 mDefaultCompositionDataspace = defaultCompositionDataspace;
5331 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5332 }
5333 return NO_ERROR;
5334 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005335 }
5336 }
5337 return err;
5338}
5339
Steven Thomas6d8110b2017-08-31 18:24:21 -07005340void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005341 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005342 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005343}
5344
Ana Krulec7d1d6832018-12-27 11:10:09 -08005345void SurfaceFlinger::repaintEverythingForHWC() {
5346 mRepaintEverything = true;
5347 mEventQueue->invalidateForHWC();
5348}
5349
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005350// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5351class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005352public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005353 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5354 ~WindowDisconnector() {
5355 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005356 }
5357
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005358private:
5359 ANativeWindow* mWindow;
5360 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005361};
5362
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005363status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005364 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5365 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005366 uint32_t reqWidth, uint32_t reqHeight,
5367 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005368 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005369 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005370
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005371 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005372
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005373 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5374
Chia-I Wu20261cb2018-08-23 12:55:44 -07005375 sp<DisplayDevice> display;
5376 {
5377 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005378
Chia-I Wu20261cb2018-08-23 12:55:44 -07005379 display = getDisplayDeviceLocked(displayToken);
5380 if (!display) return BAD_VALUE;
5381
Chia-I Wucb023152018-08-28 12:57:23 -07005382 // set the requested width/height to the logical display viewport size
5383 // by default
5384 if (reqWidth == 0 || reqHeight == 0) {
5385 reqWidth = uint32_t(display->getViewport().width());
5386 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005387 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005388 }
5389
Peiyong Lin0e003c92018-09-17 11:09:51 -07005390 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5391 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005392
5393 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005394 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005395 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5396 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005397}
5398
5399status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005400 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5401 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005402 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005403 ATRACE_CALL();
5404
5405 class LayerRenderArea : public RenderArea {
5406 public:
Robert Carr578038f2018-03-09 12:25:24 -08005407 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005408 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5409 bool childrenOnly)
5410 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005411 mLayer(layer),
5412 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005413 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005414 mFlinger(flinger),
5415 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005416 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005417 Rect getBounds() const override {
5418 const Layer::State& layerState(mLayer->getDrawingState());
5419 return mLayer->getBufferSize(layerState);
5420 }
Marissa Wall61c58622018-07-18 10:12:20 -07005421 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005422 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005423 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005424 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005425 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005426 }
chaviwa76b2712017-09-20 12:02:26 -07005427 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005428 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005429 Rect getSourceCrop() const override {
5430 if (mCrop.isEmpty()) {
5431 return getBounds();
5432 } else {
5433 return mCrop;
5434 }
5435 }
Robert Carr578038f2018-03-09 12:25:24 -08005436 class ReparentForDrawing {
5437 public:
5438 const sp<Layer>& oldParent;
5439 const sp<Layer>& newParent;
5440
5441 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5442 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005443 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005444 }
Robert Carr15eae092018-03-23 13:43:53 -07005445 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005446 };
5447
5448 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005449 const Rect sourceCrop = getSourceCrop();
5450 // no need to check rotation because there is none
5451 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5452 sourceCrop.height() != getReqHeight();
5453
Robert Carr578038f2018-03-09 12:25:24 -08005454 if (!mChildrenOnly) {
5455 mTransform = mLayer->getTransform().inverse();
5456 drawLayers();
5457 } else {
5458 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005459 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005460 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5461 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005462
5463 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5464 drawLayers();
5465 }
5466 }
chaviwa76b2712017-09-20 12:02:26 -07005467
chaviwa76b2712017-09-20 12:02:26 -07005468 private:
chaviw7206d492017-11-10 16:16:12 -08005469 const sp<Layer> mLayer;
5470 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005471
5472 // In the "childrenOnly" case we reparent the children to a screenshot
5473 // layer which has no properties set and which does not draw.
5474 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005475 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005476 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005477
5478 SurfaceFlinger* mFlinger;
5479 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005480 };
5481
5482 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5483 auto parent = layerHandle->owner.promote();
5484
Robert Carr2e102c92018-10-23 12:11:15 -07005485 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005486 ALOGE("captureLayers called with a removed parent");
5487 return NAME_NOT_FOUND;
5488 }
5489
Robert Carr578038f2018-03-09 12:25:24 -08005490 const int uid = IPCThreadState::self()->getCallingUid();
5491 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005492 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005493 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5494 return PERMISSION_DENIED;
5495 }
5496
chaviw7206d492017-11-10 16:16:12 -08005497 Rect crop(sourceCrop);
5498 if (sourceCrop.width() <= 0) {
5499 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005500 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005501 }
5502
5503 if (sourceCrop.height() <= 0) {
5504 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005505 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005506 }
5507
5508 int32_t reqWidth = crop.width() * frameScale;
5509 int32_t reqHeight = crop.height() * frameScale;
5510
Chia-I Wu20261cb2018-08-23 12:55:44 -07005511 // really small crop or frameScale
5512 if (reqWidth <= 0) {
5513 reqWidth = 1;
5514 }
5515 if (reqHeight <= 0) {
5516 reqHeight = 1;
5517 }
5518
Peiyong Lin0e003c92018-09-17 11:09:51 -07005519 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005520
Robert Carr578038f2018-03-09 12:25:24 -08005521 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005522 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5523 if (!layer->isVisible()) {
5524 return;
Robert Carr578038f2018-03-09 12:25:24 -08005525 } else if (childrenOnly && layer == parent.get()) {
5526 return;
chaviwa76b2712017-09-20 12:02:26 -07005527 }
5528 visitor(layer);
5529 });
5530 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005531 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005532}
5533
5534status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5535 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005536 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005537 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005538 bool useIdentityTransform) {
5539 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005540
Peiyong Lin0e003c92018-09-17 11:09:51 -07005541 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005542 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5543 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005544 *outBuffer =
5545 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5546 static_cast<android_pixel_format>(reqPixelFormat), 1,
5547 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005548
5549 // This mutex protects syncFd and captureResult for communication of the return values from the
5550 // main thread back to this Binder thread
5551 std::mutex captureMutex;
5552 std::condition_variable captureCondition;
5553 std::unique_lock<std::mutex> captureLock(captureMutex);
5554 int syncFd = -1;
5555 std::optional<status_t> captureResult;
5556
Robert Carr03480e22018-01-04 16:02:06 -08005557 const int uid = IPCThreadState::self()->getCallingUid();
5558 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5559
Dominik Laskowski8c001672018-05-30 16:52:06 -07005560 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005561 // If there is a refresh pending, bug out early and tell the binder thread to try again
5562 // after the refresh.
5563 if (mRefreshPending) {
5564 ATRACE_NAME("Skipping screenshot for now");
5565 std::unique_lock<std::mutex> captureLock(captureMutex);
5566 captureResult = std::make_optional<status_t>(EAGAIN);
5567 captureCondition.notify_one();
5568 return;
5569 }
5570
5571 status_t result = NO_ERROR;
5572 int fd = -1;
5573 {
5574 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005575 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005576 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5577 useIdentityTransform, forSystem, &fd);
5578 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005579 }
5580
5581 {
5582 std::unique_lock<std::mutex> captureLock(captureMutex);
5583 syncFd = fd;
5584 captureResult = std::make_optional<status_t>(result);
5585 captureCondition.notify_one();
5586 }
5587 });
5588
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005589 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005590 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005591 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005592 while (*captureResult == EAGAIN) {
5593 captureResult.reset();
5594 result = postMessageAsync(message);
5595 if (result != NO_ERROR) {
5596 return result;
5597 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005598 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005599 }
5600 result = *captureResult;
5601 }
5602
5603 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005604 sync_wait(syncFd, -1);
5605 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005606 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005607
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005608 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005609}
5610
chaviwa76b2712017-09-20 12:02:26 -07005611void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005612 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005613 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005614 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005615
Lloyd Pique144e1162017-12-20 16:44:52 -08005616 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005617
chaviwa76b2712017-09-20 12:02:26 -07005618 const auto reqWidth = renderArea.getReqWidth();
5619 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005620 const auto sourceCrop = renderArea.getSourceCrop();
5621 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005622
Peiyong Lin0e003c92018-09-17 11:09:51 -07005623 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005624 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005625
Mathias Agopian180f10d2013-04-10 22:55:41 -07005626 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005627 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005628
5629 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005630 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005631 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005632
chaviw50da5042018-04-09 13:49:37 -07005633 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005634 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005635 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005636
chaviwa76b2712017-09-20 12:02:26 -07005637 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005638 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005639 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005640 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005641 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005642}
5643
chaviwa76b2712017-09-20 12:02:26 -07005644status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5645 TraverseLayersFunction traverseLayers,
5646 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005647 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005648 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005649 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005650 ATRACE_CALL();
5651
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005652 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005653
5654 traverseLayers([&](Layer* layer) {
5655 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5656 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005657
Robert Carr03480e22018-01-04 16:02:06 -08005658 // We allow the system server to take screenshots of secure layers for
5659 // use in situations like the Screen-rotation animation and place
5660 // the impetus on WindowManager to not persist them.
5661 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005662 ALOGW("FB is protected: PERMISSION_DENIED");
5663 return PERMISSION_DENIED;
5664 }
Peiyong Linfb530cf2018-12-15 05:07:38 +00005665 auto& engine(getRenderEngine());
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005666
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005667 // this binds the given EGLImage as a framebuffer for the
5668 // duration of this scope.
Peiyong Linfb530cf2018-12-15 05:07:38 +00005669 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005670 if (bufferBond.getStatus() != NO_ERROR) {
5671 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005672 return INVALID_OPERATION;
5673 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005674
Dan Stozaabcda352017-06-01 14:37:39 -07005675 // this will in fact render into our dequeued buffer
5676 // via an FBO, which means we didn't have to create
5677 // an EGLSurface and therefore we're not
5678 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005679 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005680
Peiyong Linfb530cf2018-12-15 05:07:38 +00005681 base::unique_fd syncFd = engine.flush();
Alec Mouri492bc572018-09-11 21:40:04 +00005682 if (syncFd < 0) {
Peiyong Linfb530cf2018-12-15 05:07:38 +00005683 engine.finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005684 }
Alec Mouri492bc572018-09-11 21:40:04 +00005685 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005686
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005687 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005688}
5689
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005690// ---------------------------------------------------------------------------
5691
Dan Stoza412903f2017-04-27 13:42:17 -07005692void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5693 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005694}
5695
Dan Stoza412903f2017-04-27 13:42:17 -07005696void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5697 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005698}
5699
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005700void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005701 const LayerVector::Visitor& visitor) {
5702 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005703 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005704 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005705 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005706 continue;
5707 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005708 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005709 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005710 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005711 return;
5712 }
chaviwa76b2712017-09-20 12:02:26 -07005713 if (!layer->isVisible()) {
5714 return;
5715 }
5716 visitor(layer);
5717 });
5718 }
5719}
5720
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005721}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005722
Lloyd Pique074e8122018-07-26 12:57:23 -07005723
Mathias Agopian3f844832013-08-07 21:24:32 -07005724#if defined(__gl_h_)
5725#error "don't include gl/gl.h in this file"
5726#endif
5727
5728#if defined(__gl2_h_)
5729#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005730#endif