blob: 04c1ba0ade83ed5591c77e9b54aafa1666a09f64 [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
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001161status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001162 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001163 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001164
Chia-I Wu90f669f2017-10-05 14:24:41 -07001165 if (mInjectVSyncs == enable) {
1166 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001167 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001168
Dominik Laskowski83b88212018-12-11 13:34:06 -08001169 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001170
Ana Krulec98b5b242018-08-10 15:03:23 -07001171 // TODO(akrulec): Part of the Injector should be refactored, so that it
1172 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001173 if (enable) {
1174 ALOGV("VSync Injections enabled");
1175 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001176 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001177 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001178 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001179 impl::EventThread::InterceptVSyncsCallback(),
1180 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001181 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001182 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001183 } else {
1184 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001185 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001186 }
1187
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001188 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001189 }));
1190
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001191 return NO_ERROR;
1192}
1193
1194status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001195 Mutex::Autolock _l(mStateLock);
1196
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001197 if (!mInjectVSyncs) {
1198 ALOGE("VSync Injections not enabled");
1199 return BAD_VALUE;
1200 }
1201 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1202 ALOGV("Injecting VSync inside SurfaceFlinger");
1203 mVSyncInjector->onInjectSyncEvent(when);
1204 }
1205 return NO_ERROR;
1206}
1207
Lloyd Pique755e3192018-01-31 16:46:15 -08001208status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1209 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001210 // Try to acquire a lock for 1s, fail gracefully
1211 const status_t err = mStateLock.timedLock(s2ns(1));
1212 const bool locked = (err == NO_ERROR);
1213 if (!locked) {
1214 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1215 return TIMED_OUT;
1216 }
1217
1218 outLayers->clear();
1219 mCurrentState.traverseInZOrder([&](Layer* layer) {
1220 outLayers->push_back(layer->getLayerDebugInfo());
1221 });
1222
1223 mStateLock.unlock();
1224 return NO_ERROR;
1225}
1226
Peiyong Linc6780972018-10-28 15:24:08 -07001227status_t SurfaceFlinger::getCompositionPreference(
1228 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1229 Dataspace* outWideColorGamutDataspace,
1230 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001231 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001232 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001233 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001234 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001235 return NO_ERROR;
1236}
1237
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001238// ----------------------------------------------------------------------------
1239
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001240sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1241 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001242 auto resyncCallback = makeResyncCallback([this] {
1243 Mutex::Autolock lock(mStateLock);
1244 return getVsyncPeriod();
1245 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001246
Ana Krulec98b5b242018-08-10 15:03:23 -07001247 if (mUseScheduler) {
1248 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001249 return mScheduler->createDisplayEventConnection(mSfConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001250 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001251 return mScheduler->createDisplayEventConnection(mAppConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001252 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001253 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001254 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001255 return mSFEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001256 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001257 return mEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001258 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001259 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001260}
1261
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001262// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001263
1264void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001265 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001266}
1267
1268void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001269 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001270}
1271
1272void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001273 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001274}
1275
1276void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001277 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001278 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001279}
1280
1281status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001282 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001283 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001284}
1285
1286status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001287 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001288 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001289 if (res == NO_ERROR) {
1290 msg->wait();
1291 }
1292 return res;
1293}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001294
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001295void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001296 do {
1297 waitForEvent();
1298 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001299}
1300
Dominik Laskowski83b88212018-12-11 13:34:06 -08001301nsecs_t SurfaceFlinger::getVsyncPeriod() const {
1302 const auto displayId = getInternalDisplayId();
1303 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1304 return 0;
1305 }
1306
1307 const auto config = getHwComposer().getActiveConfig(*displayId);
1308 return config ? config->getVsyncPeriod() : 0;
1309}
1310
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001311void SurfaceFlinger::enableHardwareVsync() {
1312 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001313 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001314 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001315 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001316 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001317 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001318}
1319
Dominik Laskowski83b88212018-12-11 13:34:06 -08001320void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001321 Mutex::Autolock _l(mHWVsyncLock);
1322
Jesse Hall948fe0c2013-10-14 12:56:09 -07001323 if (makeAvailable) {
1324 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001325 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1326 if (mUseScheduler) {
1327 mScheduler->makeHWSyncAvailable(true);
1328 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001329 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001330 // Hardware vsync is not currently available, so abort the resync
1331 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001332 return;
1333 }
1334
Dominik Laskowski83b88212018-12-11 13:34:06 -08001335 if (period <= 0) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001336 return;
1337 }
1338
Ana Krulece588e312018-09-18 12:32:24 -07001339 if (mUseScheduler) {
1340 mScheduler->setVsyncPeriod(period);
1341 } else {
1342 mPrimaryDispSync->reset();
1343 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001344
Ana Krulece588e312018-09-18 12:32:24 -07001345 if (!mPrimaryHWVsyncEnabled) {
1346 mPrimaryDispSync->beginResync();
1347 mEventControlThread->setVsyncEnabled(true);
1348 mPrimaryHWVsyncEnabled = true;
1349 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001350 }
1351}
1352
Jesse Hall948fe0c2013-10-14 12:56:09 -07001353void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001354 Mutex::Autolock _l(mHWVsyncLock);
1355 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001356 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001357 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001358 mPrimaryHWVsyncEnabled = false;
1359 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001360 if (makeUnavailable) {
1361 mHWVsyncAvailable = false;
1362 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001363}
1364
Dominik Laskowski83b88212018-12-11 13:34:06 -08001365void SurfaceFlinger::VsyncState::resync(const GetVsyncPeriod& getVsyncPeriod) {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001366 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001367
Dan Stoza57164302017-05-08 14:03:54 -07001368 const nsecs_t now = systemTime();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001369 const nsecs_t last = lastResyncTime.exchange(now);
1370
1371 if (now - last > kIgnoreDelay) {
1372 flinger.resyncToHardwareVsync(false, getVsyncPeriod());
Tim Murray4a4e4a22016-04-19 16:29:23 +00001373 }
1374}
1375
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001376void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1377 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001378 ATRACE_NAME("SF onVsync");
1379
Steven Thomas3cfac282017-02-06 12:29:30 -08001380 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001381 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001382 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001383 return;
1384 }
1385
Dominik Laskowski075d3172018-05-24 15:50:06 -07001386 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001387 return;
1388 }
1389
Dominik Laskowski075d3172018-05-24 15:50:06 -07001390 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001391 // For now, we don't do anything with external display vsyncs.
1392 return;
1393 }
1394
Ana Krulece588e312018-09-18 12:32:24 -07001395 if (mUseScheduler) {
1396 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001397 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001398 bool needsHwVsync = false;
1399 { // Scope for the lock
1400 Mutex::Autolock _l(mHWVsyncLock);
1401 if (mPrimaryHWVsyncEnabled) {
1402 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1403 }
1404 }
1405
1406 if (needsHwVsync) {
1407 enableHardwareVsync();
1408 } else {
1409 disableHardwareVsync(false);
1410 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001411 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001412}
1413
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001414void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001415 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1416 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001417}
1418
Ana Krulec7d1d6832018-12-27 11:10:09 -08001419void SurfaceFlinger::setRefreshRateTo(float newFps) {
1420 const auto displayId = getInternalDisplayId();
1421 if (!displayId || mBootStage != BootStage::FINISHED) {
1422 return;
1423 }
1424 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1425 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1426 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1427 // refresh cycle.
1428
1429 // Don't do any updating if the current fps is the same as the new one.
1430 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
1431 const nsecs_t currentVsyncPeriod = activeConfig->getVsyncPeriod();
1432 if (currentVsyncPeriod == 0) {
1433 return;
1434 }
1435 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1436 // floating numbers.
1437 const float currentFps = 1e9 / currentVsyncPeriod;
1438 if (std::abs(currentFps - newFps) <= 1) {
1439 return;
1440 }
1441
1442 auto configs = getHwComposer().getConfigs(*displayId);
1443 for (int i = 0; i < configs.size(); i++) {
1444 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1445 if (vsyncPeriod == 0) {
1446 continue;
1447 }
1448 const float fps = 1e9 / vsyncPeriod;
1449 // TODO(b/113612090): There should be a better way at determining which config
1450 // has the right refresh rate.
1451 if (std::abs(fps - newFps) <= 1) {
1452 const auto display = getBuiltInDisplay(HWC_DISPLAY_PRIMARY);
1453 if (!display) return;
1454 // This is posted in async function to avoid deadlock when getDisplayDevice
1455 // requires mStateLock.
1456 setActiveConfigAsync(display, i);
1457 ATRACE_INT("FPS", newFps);
1458 }
1459 }
1460}
1461
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001462void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001463 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001464 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001465 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001466
Lloyd Piqueba04e622017-12-14 17:11:26 -08001467 // Ignore events that do not have the right sequenceId.
1468 if (sequenceId != getBE().mComposerSequenceId) {
1469 return;
1470 }
1471
Steven Thomasb02664d2017-07-26 18:48:28 -07001472 // Only lock if we're not on the main thread. This function is normally
1473 // called on a hwbinder thread, but for the primary display it's called on
1474 // the main thread with the state lock already held, so don't attempt to
1475 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001476 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001477
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001478 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001479
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001480 if (std::this_thread::get_id() == mMainThreadId) {
1481 // Process all pending hot plug events immediately if we are on the main thread.
1482 processDisplayHotplugEventsLocked();
1483 }
1484
Lloyd Piqueba04e622017-12-14 17:11:26 -08001485 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001486}
1487
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001488void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001489 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001490 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001491 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001492 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001493 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001494}
1495
Dominik Laskowski075d3172018-05-24 15:50:06 -07001496void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001497 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001498 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001499 if (const auto displayId = getInternalDisplayId()) {
1500 getHwComposer().setVsyncEnabled(*displayId,
1501 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1502 }
Mathias Agopian86303202012-07-24 22:46:10 -07001503}
1504
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001505// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001506void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001507 if (mUseScheduler) {
1508 mScheduler->disableHardwareVsync(true);
1509 } else {
1510 disableHardwareVsync(true);
1511 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001512 // Clear the drawing state so that the logic inside of
1513 // handleTransactionLocked will fire. It will determine the delta between
1514 // mCurrentState and mDrawingState and re-apply all changes when we make the
1515 // transition.
1516 mDrawingState.displays.clear();
1517 mDisplays.clear();
1518}
1519
Steven Thomas050b2c82017-03-06 11:45:16 -08001520void SurfaceFlinger::updateVrFlinger() {
1521 if (!mVrFlinger)
1522 return;
1523 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001524 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001525 return;
1526 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001527
Lloyd Pique441d5042018-10-18 16:49:51 -07001528 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001529 ALOGE("Vr flinger is only supported for remote hardware composer"
1530 " service connections. Ignoring request to transition to vr"
1531 " flinger.");
1532 mVrFlingerRequestsDisplay = false;
1533 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001534 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001535
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001536 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001537
Steven Thomas0123ac62018-07-12 11:32:34 -07001538 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001539 LOG_ALWAYS_FATAL_IF(!display);
1540 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001541 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1542 // called below. Clear the reference now so we don't accidentally use it
1543 // later.
1544 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001545
Steven Thomasb02664d2017-07-26 18:48:28 -07001546 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001547 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001548 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001549
Steven Thomasb02664d2017-07-26 18:48:28 -07001550 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001551 // Delete the current instance before creating the new one
1552 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1553 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1554 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1555 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001556
Lloyd Pique441d5042018-10-18 16:49:51 -07001557 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001558 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001559
1560 if (vrFlingerRequestsDisplay) {
1561 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001562 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001563
1564 mVisibleRegionsDirty = true;
1565 invalidateHwcGeometry();
1566
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001567 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001568 display = getDefaultDisplayDeviceLocked();
1569 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001570 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001571
Steven Thomasb02664d2017-07-26 18:48:28 -07001572 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001573 const nsecs_t vsyncPeriod = getVsyncPeriod();
1574 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001575
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001576 // The present fences returned from vr_hwc are not an accurate
1577 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001578 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001579 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1580 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001581 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001582 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001583 !hasSyncFramework);
1584 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001585
Steven Thomasb02664d2017-07-26 18:48:28 -07001586 // Use phase of 0 since phase is not known.
1587 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001588 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001589 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001590
Dominik Laskowski83b88212018-12-11 13:34:06 -08001591 resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001592
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001593 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001594 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001595}
1596
Mathias Agopian4fec8732012-06-29 14:12:52 -07001597void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001598 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001599 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001600 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001601 if (mUseScheduler) {
1602 // This call is made each time SF wakes up and creates a new frame.
1603 mScheduler->incrementFrameCounter();
1604 }
Dan Stoza50182882016-07-08 12:02:20 -07001605 bool frameMissed = !mHadClientComposition &&
1606 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001607 (mPreviousPresentFence->getSignalTime() ==
1608 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001609 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001610 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001611 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001612 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001613 if (mPropagateBackpressure) {
1614 signalLayerUpdate();
1615 break;
1616 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001617 }
Dan Stoza50182882016-07-08 12:02:20 -07001618
Steven Thomas050b2c82017-03-06 11:45:16 -08001619 // Now that we're going to make it to the handleMessageTransaction()
1620 // call below it's safe to call updateVrFlinger(), which will
1621 // potentially trigger a display handoff.
1622 updateVrFlinger();
1623
Dan Stoza6b9454d2014-11-07 16:00:59 -08001624 bool refreshNeeded = handleMessageTransaction();
1625 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001626 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001627 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001628 // Signal a refresh if a transaction modified the window state,
1629 // a new buffer was latched, or if HWC has requested a full
1630 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001631 signalRefresh();
1632 }
1633 break;
1634 }
1635 case MessageQueue::REFRESH: {
1636 handleMessageRefresh();
1637 break;
1638 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001639 }
1640}
1641
Dan Stoza6b9454d2014-11-07 16:00:59 -08001642bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001643 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001644
1645 // Apply any ready transactions in the queues if there are still transactions that have not been
1646 // applied, wake up during the next vsync period and check again
1647 bool transactionNeeded = false;
1648 if (!flushTransactionQueues()) {
1649 transactionNeeded = true;
1650 }
1651
Mathias Agopian4fec8732012-06-29 14:12:52 -07001652 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001653 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001654 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001655
1656 if (transactionNeeded) {
1657 setTransactionFlags(eTransactionNeeded);
1658 }
1659
1660 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001661}
1662
Mathias Agopian4fec8732012-06-29 14:12:52 -07001663void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001664 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001665
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001666 mRefreshPending = false;
1667
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001668 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001669 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001670 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001671 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001672 for (const auto& [token, display] : mDisplays) {
1673 beginFrame(display);
1674 prepareFrame(display);
1675 doDebugFlashRegions(display, repaintEverything);
1676 doComposition(display, repaintEverything);
1677 }
1678
Adrian Roos1e1a1282017-11-01 19:05:31 +01001679 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001680 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001681
1682 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001683 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001684
Dan Stozabfbffeb2016-07-21 14:49:33 -07001685 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001686 for (const auto& [token, displayDevice] : mDisplays) {
1687 auto display = displayDevice->getCompositionDisplay();
1688 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001689 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001690 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001691 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001692
Alec Mouri86770e52018-09-24 22:40:58 +00001693 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001694 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001695 if (mHadClientComposition) {
1696 base::unique_fd flushFence(getRenderEngine().flush());
1697 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1698 getBE().flushFence = new Fence(std::move(flushFence));
1699 } else {
1700 // Cleanup for hygiene.
1701 getBE().flushFence = Fence::NO_FENCE;
1702 }
1703 }
1704
Jorim Jaggi90535212018-05-23 23:44:06 +02001705 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001706
David Sodman7e4ae112018-02-09 15:02:28 -08001707 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001708 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001709 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001710 compositionInfo.hwc.hwcLayer = nullptr;
1711 }
David Sodmanba340492018-08-05 21:51:33 -07001712 }
David Sodman7e4ae112018-02-09 15:02:28 -08001713
1714 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001715}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001716
David Sodmanfa9b2af2017-12-24 13:28:59 -08001717
1718bool SurfaceFlinger::handleMessageInvalidate() {
1719 ATRACE_CALL();
1720 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001721}
1722
David Sodman79bba0e2018-08-05 18:07:49 -07001723void SurfaceFlinger::calculateWorkingSet() {
1724 ATRACE_CALL();
1725 ALOGV(__FUNCTION__);
1726
David Sodman79bba0e2018-08-05 18:07:49 -07001727 // build the h/w work list
1728 if (CC_UNLIKELY(mGeometryInvalid)) {
1729 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001730 for (const auto& [token, displayDevice] : mDisplays) {
1731 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001732 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001733 if (!displayId) {
1734 continue;
1735 }
David Sodman79bba0e2018-08-05 18:07:49 -07001736
Lloyd Pique32cbe282018-10-19 13:09:22 -07001737 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001738 for (size_t i = 0; i < currentLayers.size(); i++) {
1739 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001740
Dominik Laskowski075d3172018-05-24 15:50:06 -07001741 if (!layer->hasHwcLayer(*displayId)) {
1742 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1743 layer->forceClientComposition(*displayId);
1744 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001745 }
1746 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001747
Lloyd Pique32cbe282018-10-19 13:09:22 -07001748 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001749 if (mDebugDisableHWC || mDebugRegion) {
1750 layer->forceClientComposition(*displayId);
1751 }
David Sodman79bba0e2018-08-05 18:07:49 -07001752 }
1753 }
1754 }
1755
1756 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001757 for (const auto& [token, displayDevice] : mDisplays) {
1758 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001759 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001760 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001761 continue;
1762 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001763 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001764
1765 if (mDrawingState.colorMatrixChanged) {
1766 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001767 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001768 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001769 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001770 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001771 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1772 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001773 !profile->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001774 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001775 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1776 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001777 !profile->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001778 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001779 }
1780
Peiyong Lind3788632018-09-18 16:01:31 -07001781 // TODO(b/111562338) remove when composer 2.3 is shipped.
1782 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001783 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001784 }
1785
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001786 if (layer->getRoundedCornerState().radius > 0.0f) {
1787 layer->forceClientComposition(*displayId);
1788 }
1789
Dominik Laskowski075d3172018-05-24 15:50:06 -07001790 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001791 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001792 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001793 continue;
1794 }
1795
Lloyd Pique32cbe282018-10-19 13:09:22 -07001796 const auto& displayState = display->getState();
1797 layer->setPerFrameData(*displayId, displayState.transform, displayState.viewport,
1798 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001799 }
1800
Peiyong Lin13effd12018-07-24 17:01:47 -07001801 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001802 ColorMode colorMode;
1803 Dataspace dataSpace;
1804 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001805 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001806 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001807 }
1808 }
1809
1810 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001811
1812 for (const auto& [token, display] : mDisplays) {
1813 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001814 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001815 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001816
1817 if (displayId) {
1818 if (!layer->setHwcLayer(*displayId)) {
1819 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1820 }
1821 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001822 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001823
Dominik Laskowski05275f12018-11-01 15:03:24 -07001824 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001825 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1826 }
1827 }
David Sodman79bba0e2018-08-05 18:07:49 -07001828}
1829
Lloyd Pique32cbe282018-10-19 13:09:22 -07001830void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1831 bool repaintEverything) {
1832 auto display = displayDevice->getCompositionDisplay();
1833 const auto& displayState = display->getState();
1834
Mathias Agopiancd60f992012-08-16 16:28:27 -07001835 // is debugging enabled
1836 if (CC_LIKELY(!mDebugRegion))
1837 return;
1838
Lloyd Pique32cbe282018-10-19 13:09:22 -07001839 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001840 // transform the dirty region into this screen's coordinate space
Lloyd Pique32cbe282018-10-19 13:09:22 -07001841 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001842 if (!dirtyRegion.isEmpty()) {
1843 // redraw the whole screen
Lloyd Pique32cbe282018-10-19 13:09:22 -07001844 doComposeSurfaces(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001845
David Sodmanfa9b2af2017-12-24 13:28:59 -08001846 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001847 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001848 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001849
Lloyd Pique31cb2942018-10-19 17:23:03 -07001850 display->getRenderSurface()->queueBuffer();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001851 }
1852 }
1853
Lloyd Pique32cbe282018-10-19 13:09:22 -07001854 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001855
1856 if (mDebugRegion > 1) {
1857 usleep(mDebugRegion * 1000);
1858 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001859
Lloyd Pique32cbe282018-10-19 13:09:22 -07001860 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001861}
1862
Adrian Roos1e1a1282017-11-01 19:05:31 +01001863void SurfaceFlinger::doTracing(const char* where) {
1864 ATRACE_CALL();
1865 ATRACE_NAME(where);
1866 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001867 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001868 }
1869}
1870
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001871void SurfaceFlinger::logLayerStats() {
1872 ATRACE_CALL();
1873 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001874 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001875 if (display->isPrimary()) {
1876 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001877 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001878 }
1879 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001880
1881 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001882 }
1883}
1884
David Sodman2b406362017-12-15 13:33:47 -08001885void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001886{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001887 ATRACE_CALL();
1888 ALOGV("preComposition");
1889
David Sodman2b406362017-12-15 13:33:47 -08001890 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1891
Mathias Agopiancd60f992012-08-16 16:28:27 -07001892 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001893 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001894 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001895 needExtraInvalidate = true;
1896 }
Robert Carr2047fae2016-11-28 14:09:09 -08001897 });
1898
Mathias Agopiancd60f992012-08-16 16:28:27 -07001899 if (needExtraInvalidate) {
1900 signalLayerUpdate();
1901 }
1902}
1903
Ana Krulece588e312018-09-18 12:32:24 -07001904void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1905 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001906 // Update queue of past composite+present times and determine the
1907 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001908 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001909 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001910 while (!getBE().mCompositePresentTimes.empty()) {
1911 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001912 // Cached values should have been updated before calling this method,
1913 // which helps avoid duplicate syscalls.
1914 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1915 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1916 break;
1917 }
1918 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001919 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001920 }
1921
1922 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001923 while (getBE().mCompositePresentTimes.size() > 16) {
1924 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001925 }
1926
Ana Krulece588e312018-09-18 12:32:24 -07001927 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001928}
1929
Ana Krulece588e312018-09-18 12:32:24 -07001930void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1931 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001932 // Integer division and modulo round toward 0 not -inf, so we need to
1933 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001934 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1935 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1936 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001937
Brian Andersond0010582017-03-07 13:20:31 -08001938 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1939 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001940 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001941 }
1942
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001943 // Snap the latency to a value that removes scheduling jitter from the
1944 // composition and present times, which often have >1ms of jitter.
1945 // Reducing jitter is important if an app attempts to extrapolate
1946 // something (such as user input) to an accurate diasplay time.
1947 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1948 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001949 nsecs_t bias = stats.vsyncPeriod / 2;
1950 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1951 nsecs_t snappedCompositeToPresentLatency =
1952 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001953
David Sodman99974d22017-11-28 12:04:33 -08001954 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001955 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1956 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001957 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001958}
1959
Ady Abraham8164d482019-01-11 14:47:59 -08001960// debug patch for b/119477596 - add stack guards to catch stack
1961// corruptions and disable clang optimizations.
1962// The code below is temporary and planned to be removed once stack
1963// corruptions are found.
1964#pragma clang optimize off
1965class StackGuard {
1966public:
1967 StackGuard(const char* name, const char* func, int line) {
1968 guarders.reserve(MIN_CAPACITY);
1969 guarders.push_back({this, name, func, line});
1970 validate();
1971 }
1972 ~StackGuard() {
1973 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1974 if (i->guard == this) {
1975 guarders.erase(i);
1976 break;
1977 }
1978 }
1979 }
1980
1981 static void validate() {
1982 for (const auto& guard : guarders) {
1983 if (guard.guard->cookie != COOKIE_VALUE) {
1984 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1985 CallStack stack(LOG_TAG);
1986 abort();
1987 }
1988 }
1989 }
1990
1991private:
1992 uint64_t cookie = COOKIE_VALUE;
1993 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
1994 static constexpr size_t MIN_CAPACITY = 16;
1995
1996 struct GuarderElement {
1997 StackGuard* guard;
1998 const char* name;
1999 const char* func;
2000 int line;
2001 };
2002
2003 static std::vector<GuarderElement> guarders;
2004};
2005std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2006
2007#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2008
2009#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002010void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002011{
Ady Abraham8164d482019-01-11 14:47:59 -08002012 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002013 ATRACE_CALL();
2014 ALOGV("postComposition");
2015
Brian Anderson3546a3f2016-07-14 11:51:14 -07002016 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002017 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002018 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002019 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002020 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002021 }
Ady Abraham8164d482019-01-11 14:47:59 -08002022 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002023
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002024 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002025 const auto displayDevice = getDefaultDisplayDeviceLocked();
2026 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002027
David Sodman73beded2017-11-15 11:56:06 -08002028 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002029 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002030 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2031
Lloyd Pique32cbe282018-10-19 13:09:22 -07002032 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002033 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002034 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2035 ->getRenderSurface()
2036 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002037 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002038 } else {
2039 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2040 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002041
Ady Abraham8164d482019-01-11 14:47:59 -08002042 ASSERT_ON_STACK_GUARD();
2043
David Sodman73beded2017-11-15 11:56:06 -08002044 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002045 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2046 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002047 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002048 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002049 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002050
Ana Krulece588e312018-09-18 12:32:24 -07002051 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002052 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002053 if (mUseScheduler) {
2054 mScheduler->getDisplayStatInfo(&stats);
2055 } else {
2056 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2057 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2058 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002059
Ady Abraham8164d482019-01-11 14:47:59 -08002060 ASSERT_ON_STACK_GUARD();
2061
David Sodman2b406362017-12-15 13:33:47 -08002062 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002063 // when we started doing work for this frame, but that should be okay
2064 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002065 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002066 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002067 DEFINE_STACK_GUARD(compositorTiming);
2068
Brian Andersond0010582017-03-07 13:20:31 -08002069 {
David Sodman99974d22017-11-28 12:04:33 -08002070 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002071 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002072 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002073
2074 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002075 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002076
Robert Carr2047fae2016-11-28 14:09:09 -08002077 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002078 bool frameLatched =
2079 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2080 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002081 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002082 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002083 recordBufferingStats(layer->getName().string(),
2084 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002085 }
Ady Abraham8164d482019-01-11 14:47:59 -08002086 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002087 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002088
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002089 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002090 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002091 if (mUseScheduler) {
2092 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002093 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002094 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002095 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2096 enableHardwareVsync();
2097 } else {
2098 disableHardwareVsync(false);
2099 }
Ady Abraham8164d482019-01-11 14:47:59 -08002100 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002101 }
2102 }
2103
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002104 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002105 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2106 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002107 if (mUseScheduler) {
2108 mScheduler->enableHardwareVsync();
2109 } else {
2110 enableHardwareVsync();
2111 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002112 }
2113 }
2114
Ady Abraham8164d482019-01-11 14:47:59 -08002115 ASSERT_ON_STACK_GUARD();
2116
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002117 if (mAnimCompositionPending) {
2118 mAnimCompositionPending = false;
2119
Brian Anderson4e606e32017-03-16 15:34:57 -07002120 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002121 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002122 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002123
2124 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002125 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002126 // The HWC doesn't support present fences, so use the refresh
2127 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002128 const nsecs_t presentTime =
2129 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002130 DEFINE_STACK_GUARD(presentTime);
2131
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002132 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002133 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002134 }
2135 mAnimFrameTracker.advanceFrame();
2136 }
Dan Stozab90cf072015-03-05 11:05:59 -08002137
Ady Abraham8164d482019-01-11 14:47:59 -08002138 ASSERT_ON_STACK_GUARD();
2139
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002140 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002141 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002142 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002143 }
2144
Ady Abraham8164d482019-01-11 14:47:59 -08002145 ASSERT_ON_STACK_GUARD();
2146
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002147 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002148
Ady Abraham8164d482019-01-11 14:47:59 -08002149 ASSERT_ON_STACK_GUARD();
2150
Lloyd Pique32cbe282018-10-19 13:09:22 -07002151 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2152 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002153 return;
2154 }
2155
2156 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002157 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002158 if (mHasPoweredOff) {
2159 mHasPoweredOff = false;
2160 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002161 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002162 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002163 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002164 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002165 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2166 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002167 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002168 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002169 }
David Sodman4a36e932017-11-07 14:29:47 -08002170 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002171
2172 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002173 }
David Sodman4a36e932017-11-07 14:29:47 -08002174 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002175 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002176
2177 {
2178 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002179 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002180 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002181 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002182 if (refillCount > 0) {
2183 const size_t offset = mTexturePool.size();
2184 mTexturePool.resize(mTexturePoolSize);
2185 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2186 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2187 }
Ady Abraham8164d482019-01-11 14:47:59 -08002188 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002189 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002190
Marissa Wallfda30bb2018-10-12 11:34:28 -07002191 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002192 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002193
2194 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002195}
Ady Abraham8164d482019-01-11 14:47:59 -08002196#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002197
2198void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002199 ATRACE_CALL();
2200 ALOGV("rebuildLayerStacks");
2201
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002202 // We need to clear these out now as these may be holding on to a
2203 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2204 // also holds a reference. When the set of visible layers is recomputed,
2205 // some layers may be destroyed if the only thing keeping them alive was
2206 // that list of visible layers associated with each display. The layer
2207 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2208 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2209 for (const auto& [token, display] : mDisplays) {
2210 getBE().mCompositionInfo[token].clear();
2211 }
2212
Mathias Agopiancd60f992012-08-16 16:28:27 -07002213 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002214 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002215 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002216 mVisibleRegionsDirty = false;
2217 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002218
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002219 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002220 const auto& displayDevice = pair.second;
2221 auto display = displayDevice->getCompositionDisplay();
2222 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002223 Region opaqueRegion;
2224 Region dirtyRegion;
2225 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002226 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002227 const ui::Transform& tr = displayState.transform;
2228 const Rect bounds = displayState.bounds;
2229 if (displayState.isEnabled) {
2230 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002231
Jeff Sharkey76488112017-02-27 14:15:18 -07002232 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002233 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002234 const auto displayId = displayDevice->getId();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002235 if (display->belongsInOutput(layer->getLayerStack(),
2236 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002237 Region drawRegion(tr.transform(
2238 layer->visibleNonTransparentRegion));
2239 drawRegion.andSelf(bounds);
2240 if (!drawRegion.isEmpty()) {
2241 layersSortedByZ.add(layer);
2242 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002243 // Clear out the HWC layer if this layer was
2244 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002245 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002246 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002247 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002248 // WM changes display->layerStack upon sleep/awake.
2249 // Here we make sure we delete the HWC layers even if
2250 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002251 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002252 }
2253
2254 // If a layer is not going to get a release fence because
2255 // it is invisible, but it is also going to release its
2256 // old buffer, add it to the list of layers needing
2257 // fences.
2258 if (hwcLayerDestroyed) {
2259 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2260 mLayersWithQueuedFrames.cend(), layer);
2261 if (found != mLayersWithQueuedFrames.cend()) {
2262 layersNeedingFences.add(layer);
2263 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002264 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002265 });
2266 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002267 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
2268 displayDevice->setLayersNeedingFences(layersNeedingFences);
2269
2270 Region undefinedRegion{bounds};
2271 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2272
2273 display->editState().undefinedRegion = undefinedRegion;
2274 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002275 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002276 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002277}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002278
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002279// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002280// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002281// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002282// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002283// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002284// The returned HDR data space is one of
2285// - Dataspace::UNKNOWN
2286// - Dataspace::BT2020_HLG
2287// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002288Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2289 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002290 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002291 *outHdrDataSpace = Dataspace::UNKNOWN;
2292
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002293 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002294 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002295 case Dataspace::V0_SCRGB:
2296 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002297 case Dataspace::BT2020:
2298 case Dataspace::BT2020_ITU:
2299 case Dataspace::BT2020_LINEAR:
2300 case Dataspace::DISPLAY_BT2020:
2301 bestDataSpace = Dataspace::DISPLAY_BT2020;
2302 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002303 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002304 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002305 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002306 case Dataspace::BT2020_PQ:
2307 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002308 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002309 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002310 case Dataspace::BT2020_HLG:
2311 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002312 // When there's mixed PQ content and HLG content, we set the HDR
2313 // data space to be BT2020_PQ and convert HLG to PQ.
2314 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2315 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002316 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002317 break;
2318 default:
2319 break;
2320 }
Romain Guy54f154a2017-10-24 21:40:32 +01002321 }
2322
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002323 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002324}
2325
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002326// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002327void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2328 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002329 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2330 *outMode = ColorMode::NATIVE;
2331 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002332 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002333 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002334 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002335
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002336 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002337 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002338
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002339 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2340
Peiyong Lindfde5112018-06-05 10:58:41 -07002341 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002342 const bool isHdr =
2343 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002344 if (isHdr) {
2345 bestDataSpace = hdrDataSpace;
2346 }
2347
Chia-I Wu0d711262018-05-21 15:19:35 -07002348 RenderIntent intent;
2349 switch (mDisplayColorSetting) {
2350 case DisplayColorSetting::MANAGED:
2351 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002352 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002353 break;
2354 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002355 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002356 break;
2357 default: // vendor display color setting
2358 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2359 break;
2360 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002361
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002362 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002363}
2364
Lloyd Pique32cbe282018-10-19 13:09:22 -07002365void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2366 auto display = displayDevice->getCompositionDisplay();
2367 const auto& displayState = display->getState();
2368
2369 bool dirty = !display->getPhysicalSpaceDirtyRegion(false).isEmpty();
2370 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2371 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002372
David Sodmanfa9b2af2017-12-24 13:28:59 -08002373 // If nothing has changed (!dirty), don't recompose.
2374 // If something changed, but we don't currently have any visible layers,
2375 // and didn't when we last did a composition, then skip it this time.
2376 // The second rule does two things:
2377 // - When all layers are removed from a display, we'll emit one black
2378 // frame, then nothing more until we get new layers.
2379 // - When a display is created with a private layer stack, we won't
2380 // emit any black frames until a layer is added to the layer stack.
2381 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002382
Dominik Laskowski075d3172018-05-24 15:50:06 -07002383 const char flagPrefix[] = {'-', '+'};
2384 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002385 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2386 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2387 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2388 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002389
Lloyd Pique31cb2942018-10-19 17:23:03 -07002390 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002391
David Sodmanfa9b2af2017-12-24 13:28:59 -08002392 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002393 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002394 }
2395}
2396
Lloyd Pique32cbe282018-10-19 13:09:22 -07002397void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2398 auto display = displayDevice->getCompositionDisplay();
2399 const auto& displayState = display->getState();
2400
2401 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002402 return;
David Sodman2b406362017-12-15 13:33:47 -08002403 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002404
Lloyd Pique31cb2942018-10-19 17:23:03 -07002405 status_t result = display->getRenderSurface()->prepareFrame(
2406 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002407 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002408 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002409}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002410
Lloyd Pique32cbe282018-10-19 13:09:22 -07002411void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002412 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002413 ALOGV("doComposition");
2414
Lloyd Pique32cbe282018-10-19 13:09:22 -07002415 auto display = displayDevice->getCompositionDisplay();
2416 const auto& displayState = display->getState();
2417
2418 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002419 // transform the dirty region into this screen's coordinate space
Lloyd Pique32cbe282018-10-19 13:09:22 -07002420 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002421
David Sodmanfa9b2af2017-12-24 13:28:59 -08002422 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002423 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002424
Lloyd Pique32cbe282018-10-19 13:09:22 -07002425 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002426 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002427 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002428 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002429}
2430
David Sodmanfa9b2af2017-12-24 13:28:59 -08002431void SurfaceFlinger::postFrame()
2432{
2433 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002434 const auto display = getDefaultDisplayDeviceLocked();
2435 if (display && getHwComposer().isConnected(*display->getId())) {
2436 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002437 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2438 logFrameStats();
2439 }
2440 }
2441}
2442
Lloyd Pique32cbe282018-10-19 13:09:22 -07002443void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002444 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002445 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002446
Lloyd Pique32cbe282018-10-19 13:09:22 -07002447 auto display = displayDevice->getCompositionDisplay();
2448 const auto& displayState = display->getState();
2449 const auto displayId = display->getId();
2450
David Sodmanfa9b2af2017-12-24 13:28:59 -08002451 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002452
Lloyd Pique32cbe282018-10-19 13:09:22 -07002453 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002454 if (displayId) {
2455 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002456 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002457 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002458 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002459 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002460
Chia-I Wu7b549592017-11-15 09:14:57 -08002461 // The layer buffer from the previous frame (if any) is released
2462 // by HWC only when the release fence from this frame (if any) is
2463 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002464 if (displayId && layer->hasHwcLayer(*displayId)) {
2465 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2466 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002467 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002468
2469 // If the layer was client composited in the previous frame, we
2470 // need to merge with the previous client target acquire fence.
2471 // Since we do not track that, always merge with the current
2472 // client target acquire fence when it is available, even though
2473 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002474 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002475 releaseFence =
2476 Fence::merge("LayerRelease", releaseFence,
2477 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002478 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002479
David Sodman15094112018-10-11 09:39:37 -07002480 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002481 }
Chia-I Wu83806892017-11-16 10:50:20 -08002482
2483 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002484 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002485 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002486 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002487 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002488 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002489 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002490 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002491 }
2492 }
2493
Dominik Laskowski075d3172018-05-24 15:50:06 -07002494 if (displayId) {
2495 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002496 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002497 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002498}
2499
Mathias Agopian87baae12012-07-31 12:38:26 -07002500void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002501{
Mathias Agopian841cde52012-03-01 15:44:37 -08002502 ATRACE_CALL();
2503
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002504 // here we keep a copy of the drawing state (that is the state that's
2505 // going to be overwritten by handleTransactionLocked()) outside of
2506 // mStateLock so that the side-effects of the State assignment
2507 // don't happen with mStateLock held (which can cause deadlocks).
2508 State drawingState(mDrawingState);
2509
Mathias Agopianca4d3602011-05-19 15:38:14 -07002510 Mutex::Autolock _l(mStateLock);
2511 const nsecs_t now = systemTime();
2512 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002513
Mathias Agopianca4d3602011-05-19 15:38:14 -07002514 // Here we're guaranteed that some transaction flags are set
2515 // so we can call handleTransactionLocked() unconditionally.
2516 // We call getTransactionFlags(), which will also clear the flags,
2517 // with mStateLock held to guarantee that mCurrentState won't change
2518 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002519
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002520 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002521 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002522 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002523
Mathias Agopianca4d3602011-05-19 15:38:14 -07002524 mLastTransactionTime = systemTime() - now;
2525 mDebugInTransaction = 0;
2526 invalidateHwcGeometry();
2527 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002528}
2529
Lloyd Piqueba04e622017-12-14 17:11:26 -08002530void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2531 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002532 const std::optional<DisplayIdentificationInfo> info =
2533 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002534
Dominik Laskowski075d3172018-05-24 15:50:06 -07002535 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002536 continue;
2537 }
2538
Lloyd Piqueba04e622017-12-14 17:11:26 -08002539 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002540 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002541 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002542 mPhysicalDisplayTokens[info->id] = new BBinder();
2543 DisplayDeviceState state;
2544 state.displayId = info->id;
2545 state.isSecure = true; // All physical displays are currently considered secure.
2546 state.displayName = info->name;
2547 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2548 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002549 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002550 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002551 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002552
Dominik Laskowski075d3172018-05-24 15:50:06 -07002553 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2554 if (index >= 0) {
2555 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2556 mInterceptor->saveDisplayDeletion(state.sequenceId);
2557 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002558 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002559 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002560 }
2561
2562 processDisplayChangesLocked();
2563 }
2564
2565 mPendingHotplugEvents.clear();
2566}
2567
Lloyd Pique99d3da52018-01-22 17:48:03 -08002568sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002569 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002570 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002571 const sp<IGraphicBufferProducer>& producer) {
2572 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002573 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002574 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002575 creationArgs.isSecure = state.isSecure;
2576 creationArgs.displaySurface = dispSurface;
2577 creationArgs.hasWideColorGamut = false;
2578 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002579
Dominik Laskowski075d3172018-05-24 15:50:06 -07002580 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2581 creationArgs.isPrimary = isInternalDisplay;
2582
2583 if (useColorManagement && displayId) {
2584 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002585 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002586 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002587 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002588 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002589
Dominik Laskowski7e045462018-05-30 13:02:02 -07002590 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002591 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002592 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002593 }
tangrobin6753a022018-08-10 10:58:54 +08002594 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002595
Dominik Laskowski075d3172018-05-24 15:50:06 -07002596 if (displayId) {
2597 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002598 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002599 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002600 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002601
Lloyd Pique90c115d2018-09-18 21:39:42 -07002602 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002603 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002604 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002605
Lloyd Pique99d3da52018-01-22 17:48:03 -08002606 // Make sure that composition can never be stalled by a virtual display
2607 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002608 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002609 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002610 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2611 }
2612
Dominik Laskowski075d3172018-05-24 15:50:06 -07002613 creationArgs.displayInstallOrientation =
2614 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002615
Lloyd Pique99d3da52018-01-22 17:48:03 -08002616 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002617 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002618
Lloyd Pique90c115d2018-09-18 21:39:42 -07002619 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002620
2621 if (maxFrameBufferAcquiredBuffers >= 3) {
2622 nativeWindowSurface->preallocateBuffers();
2623 }
2624
2625 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002626 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002627 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002628 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002629 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002630 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002631 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2632 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002633 if (!state.isVirtual()) {
2634 LOG_ALWAYS_FATAL_IF(!displayId);
2635 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002636 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002637
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002638 display->setLayerStack(state.layerStack);
2639 display->setProjection(state.orientation, state.viewport, state.frame);
2640 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002641
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002642 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002643}
2644
Lloyd Pique347200f2017-12-14 17:00:15 -08002645void SurfaceFlinger::processDisplayChangesLocked() {
2646 // here we take advantage of Vector's copy-on-write semantics to
2647 // improve performance by skipping the transaction entirely when
2648 // know that the lists are identical
2649 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2650 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2651 if (!curr.isIdenticalTo(draw)) {
2652 mVisibleRegionsDirty = true;
2653 const size_t cc = curr.size();
2654 size_t dc = draw.size();
2655
2656 // find the displays that were removed
2657 // (ie: in drawing state but not in current state)
2658 // also handle displays that changed
2659 // (ie: displays that are in both lists)
2660 for (size_t i = 0; i < dc;) {
2661 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2662 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002663 // Save display IDs before disconnecting.
2664 const auto internalDisplayId = getInternalDisplayId();
2665 const auto externalDisplayId = getExternalDisplayId();
2666
Lloyd Pique347200f2017-12-14 17:00:15 -08002667 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002668 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002669 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002670 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002671 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002672 if (mUseScheduler) {
2673 mScheduler->hotplugReceived(mAppConnectionHandle,
2674 EventThread::DisplayType::Primary, false);
2675 } else {
2676 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2677 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002678 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002679 if (mUseScheduler) {
2680 mScheduler->hotplugReceived(mAppConnectionHandle,
2681 EventThread::DisplayType::External, false);
2682 } else {
2683 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2684 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002685 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002686 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002687 } else {
2688 // this display is in both lists. see if something changed.
2689 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002690 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002691 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2692 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2693 if (state_binder != draw_binder) {
2694 // changing the surface is like destroying and
2695 // recreating the DisplayDevice, so we just remove it
2696 // from the drawing state, so that it get re-added
2697 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002698 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002699 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002700 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002701 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002702 mDrawingState.displays.removeItemsAt(i);
2703 dc--;
2704 // at this point we must loop to the next item
2705 continue;
2706 }
2707
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002708 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002709 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002710 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002711 }
2712 if ((state.orientation != draw[i].orientation) ||
2713 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002714 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002715 }
2716 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002717 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002718 }
2719 }
2720 }
2721 ++i;
2722 }
2723
2724 // find displays that were added
2725 // (ie: in current state but not in drawing state)
2726 for (size_t i = 0; i < cc; i++) {
2727 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2728 const DisplayDeviceState& state(curr[i]);
2729
Lloyd Pique542307f2018-10-19 13:24:08 -07002730 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002731 sp<IGraphicBufferProducer> producer;
2732 sp<IGraphicBufferProducer> bqProducer;
2733 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002734 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002735
Dominik Laskowski075d3172018-05-24 15:50:06 -07002736 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002737 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002738 // Virtual displays without a surface are dormant:
2739 // they have external state (layer stack, projection,
2740 // etc.) but no internal state (i.e. a DisplayDevice).
2741 if (state.surface != nullptr) {
2742 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002743 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002744 int width = 0;
2745 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2746 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2747 int height = 0;
2748 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2749 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2750 int intFormat = 0;
2751 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2752 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002753 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002754
Dominik Laskowski075d3172018-05-24 15:50:06 -07002755 displayId =
2756 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002757 }
2758
2759 // TODO: Plumb requested format back up to consumer
2760
2761 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002762 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002763 bqProducer, bqConsumer,
2764 state.displayName);
2765
2766 dispSurface = vds;
2767 producer = vds;
2768 }
2769 } else {
2770 ALOGE_IF(state.surface != nullptr,
2771 "adding a supported display, but rendering "
2772 "surface is provided (%p), ignoring it",
2773 state.surface.get());
2774
Dominik Laskowski075d3172018-05-24 15:50:06 -07002775 displayId = state.displayId;
2776 LOG_ALWAYS_FATAL_IF(!displayId);
2777 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002778 producer = bqProducer;
2779 }
2780
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002781 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002782 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002783 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002784 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002785 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002786 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002787 LOG_ALWAYS_FATAL_IF(!displayId);
2788
2789 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002790 if (mUseScheduler) {
2791 mScheduler->hotplugReceived(mAppConnectionHandle,
2792 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002793 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002794 } else {
2795 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2796 true);
2797 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002798 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002799 if (mUseScheduler) {
2800 mScheduler->hotplugReceived(mAppConnectionHandle,
2801 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002802 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002803 } else {
2804 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2805 true);
2806 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002807 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002808 }
2809 }
2810 }
2811 }
2812 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002813
2814 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002815}
2816
Mathias Agopian87baae12012-07-31 12:38:26 -07002817void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002818{
Dan Stoza7dde5992015-05-22 09:51:44 -07002819 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002820 mCurrentState.traverseInZOrder([](Layer* layer) {
2821 layer->notifyAvailableFrames();
2822 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002823
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002824 /*
2825 * Traversal of the children
2826 * (perform the transaction for each of them if needed)
2827 */
2828
Robert Carr720e5062018-07-30 17:45:14 -07002829 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002830 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002831 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002832 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002833 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002834
2835 const uint32_t flags = layer->doTransaction(0);
2836 if (flags & Layer::eVisibleRegion)
2837 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002838
2839 if (flags & Layer::eInputInfoChanged) {
2840 inputChanged = true;
2841 }
Robert Carr2047fae2016-11-28 14:09:09 -08002842 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002843 }
2844
2845 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002846 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002847 */
2848
Mathias Agopiane57f2922012-08-09 16:29:12 -07002849 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002850 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002851 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002852 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002853
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002854 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002855 // The transform hint might have changed for some layers
2856 // (either because a display has changed, or because a layer
2857 // as changed).
2858 //
2859 // Walk through all the layers in currentLayers,
2860 // and update their transform hint.
2861 //
2862 // If a layer is visible only on a single display, then that
2863 // display is used to calculate the hint, otherwise we use the
2864 // default display.
2865 //
2866 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2867 // the hint is set before we acquire a buffer from the surface texture.
2868 //
2869 // NOTE: layer transactions have taken place already, so we use their
2870 // drawing state. However, SurfaceFlinger's own transaction has not
2871 // happened yet, so we must use the current state layer list
2872 // (soon to become the drawing state list).
2873 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002874 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002875 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002876 bool first = true;
2877 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002878 // NOTE: we rely on the fact that layers are sorted by
2879 // layerStack first (so we don't have to traverse the list
2880 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002881 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002882 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002883 currentlayerStack = layerStack;
2884 // figure out if this layerstack is mirrored
2885 // (more than one display) if so, pick the default display,
2886 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002887 hintDisplay = nullptr;
2888 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002889 if (display->getCompositionDisplay()
2890 ->belongsInOutput(layer->getLayerStack(),
2891 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002892 if (hintDisplay) {
2893 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002894 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002895 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002896 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002897 }
2898 }
2899 }
2900 }
Chet Haase91d25932013-04-11 15:24:55 -07002901
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002902 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002903 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2904 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002905
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002906 // could be null when this layer is using a layerStack
2907 // that is not visible on any display. Also can occur at
2908 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002909 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002910 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002911
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002912 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002913 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002914 if (hintDisplay) {
2915 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002916 }
Robert Carr2047fae2016-11-28 14:09:09 -08002917
2918 first = false;
2919 });
Mathias Agopian84300952012-11-21 16:02:13 -08002920 }
2921
2922
Mathias Agopian3559b072012-08-15 13:46:03 -07002923 /*
2924 * Perform our own transaction if needed
2925 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002926
2927 if (mLayersAdded) {
2928 mLayersAdded = false;
2929 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002930 mVisibleRegionsDirty = true;
2931 }
2932
2933 // some layers might have been removed, so
2934 // we need to update the regions they're exposing.
2935 if (mLayersRemoved) {
2936 mLayersRemoved = false;
2937 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002938 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002939 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002940 // this layer is not visible anymore
2941 // TODO: we could traverse the tree from front to back and
2942 // compute the actual visible region
2943 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002944 Region visibleReg;
2945 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002946 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002947 }
Robert Carr2047fae2016-11-28 14:09:09 -08002948 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002949 }
2950
2951 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002952
Vishnu Nairde19f852018-12-18 16:11:53 -08002953 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002954 updateInputWindows();
2955 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002956 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002957
Riley Andrews03414a12014-07-01 14:22:59 -07002958 updateCursorAsync();
2959}
2960
Robert Carr720e5062018-07-30 17:45:14 -07002961void SurfaceFlinger::updateInputWindows() {
2962 ATRACE_CALL();
2963
Vishnu Nairde19f852018-12-18 16:11:53 -08002964 if (mInputFlinger == nullptr) {
2965 return;
2966 }
2967
Robert Carr720e5062018-07-30 17:45:14 -07002968 Vector<InputWindowInfo> inputHandles;
2969
2970 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2971 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002972 // When calculating the screen bounds we ignore the transparent region since it may
2973 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002974 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002975 }
2976 });
2977 mInputFlinger->setInputWindows(inputHandles);
2978}
2979
chaviwfbe5d9c2018-12-26 12:23:37 -08002980void SurfaceFlinger::executeInputWindowCommands() {
2981 if (!mInputFlinger) {
2982 return;
2983 }
2984
2985 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2986 if (transferTouchFocusCommand.fromToken != nullptr &&
2987 transferTouchFocusCommand.toToken != nullptr &&
2988 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2989 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2990 transferTouchFocusCommand.toToken);
2991 }
2992 }
2993
2994 mInputWindowCommands.clear();
2995}
2996
Riley Andrews03414a12014-07-01 14:22:59 -07002997void SurfaceFlinger::updateCursorAsync()
2998{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002999 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003000 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003001 continue;
3002 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003003
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003004 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3005 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003006 }
3007 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003008}
3009
chaviw61626f22018-11-15 16:26:27 -08003010void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3011 if (layer->hasReadyFrame()) {
3012 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3013 if (layer->shouldPresentNow(expectedPresentTime)) {
3014 bool ignored = false;
3015 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
3016 }
3017 }
3018 layer->releasePendingBuffer(systemTime());
3019}
3020
Mathias Agopian4fec8732012-06-29 14:12:52 -07003021void SurfaceFlinger::commitTransaction()
3022{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003023 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003024 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003025 for (const auto& l : mLayersPendingRemoval) {
3026 recordBufferingStats(l->getName().string(),
3027 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003028
3029 // We need to release the HWC layers when the Layer is removed
3030 // from the current state otherwise the HWC layer just continues
3031 // showing at its last configured state until we eventually
3032 // abandon the buffer queue.
3033 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003034 l->destroyHwcLayersForAllDisplays();
3035 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003036 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003037 }
3038 mLayersPendingRemoval.clear();
3039 }
3040
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003041 // If this transaction is part of a window animation then the next frame
3042 // we composite should be considered an animation as well.
3043 mAnimCompositionPending = mAnimTransactionPending;
3044
Mathias Agopian4fec8732012-06-29 14:12:52 -07003045 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003046 // clear the "changed" flags in current state
3047 mCurrentState.colorMatrixChanged = false;
3048
Robert Carr1f0a16a2016-10-24 16:27:39 -07003049 mDrawingState.traverseInZOrder([](Layer* layer) {
3050 layer->commitChildList();
3051 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003052 mTransactionPending = false;
3053 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003054 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003055}
3056
Lloyd Pique32cbe282018-10-19 13:09:22 -07003057void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003058 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003059 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003060 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003061
Lloyd Pique32cbe282018-10-19 13:09:22 -07003062 auto display = displayDevice->getCompositionDisplay();
3063
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003064 Region aboveOpaqueLayers;
3065 Region aboveCoveredLayers;
3066 Region dirty;
3067
Mathias Agopian87baae12012-07-31 12:38:26 -07003068 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003069
Robert Carr2047fae2016-11-28 14:09:09 -08003070 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003071 // start with the whole surface at its current location
3072 const Layer::State& s(layer->getDrawingState());
3073
Jesse Hall01e29052013-02-19 16:13:35 -08003074 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003075 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003076 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003077 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003078
Mathias Agopianab028732010-03-16 16:41:46 -07003079 /*
3080 * opaqueRegion: area of a surface that is fully opaque.
3081 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003082 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003083
3084 /*
3085 * visibleRegion: area of a surface that is visible on screen
3086 * and not fully transparent. This is essentially the layer's
3087 * footprint minus the opaque regions above it.
3088 * Areas covered by a translucent surface are considered visible.
3089 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003090 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003091
3092 /*
3093 * coveredRegion: area of a surface that is covered by all
3094 * visible regions above it (which includes the translucent areas).
3095 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003096 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003097
Jesse Halla8026d22012-09-25 13:25:04 -07003098 /*
3099 * transparentRegion: area of a surface that is hinted to be completely
3100 * transparent. This is only used to tell when the layer has no visible
3101 * non-transparent regions and can be removed from the layer list. It
3102 * does not affect the visibleRegion of this layer or any layers
3103 * beneath it. The hint may not be correct if apps don't respect the
3104 * SurfaceView restrictions (which, sadly, some don't).
3105 */
3106 Region transparentRegion;
3107
Mathias Agopianab028732010-03-16 16:41:46 -07003108
3109 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003110 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003111 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003112 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003113
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003114 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003115 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003116 if (!visibleRegion.isEmpty()) {
3117 // Remove the transparent area from the visible region
3118 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003119 if (tr.preserveRects()) {
3120 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003121 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003122 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003123 // transformation too complex, can't do the
3124 // transparent region optimization.
3125 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003126 }
Mathias Agopianab028732010-03-16 16:41:46 -07003127 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003128
Mathias Agopianab028732010-03-16 16:41:46 -07003129 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003130 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003131 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003132 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003133 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003134 // the opaque region is the layer's footprint
3135 opaqueRegion = visibleRegion;
3136 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003137 }
3138 }
3139
Robert Carre5f4f692018-01-12 13:12:28 -08003140 if (visibleRegion.isEmpty()) {
3141 layer->clearVisibilityRegions();
3142 return;
3143 }
3144
Mathias Agopianab028732010-03-16 16:41:46 -07003145 // Clip the covered region to the visible region
3146 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3147
3148 // Update aboveCoveredLayers for next (lower) layer
3149 aboveCoveredLayers.orSelf(visibleRegion);
3150
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003151 // subtract the opaque region covered by the layers above us
3152 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003153
3154 // compute this layer's dirty region
3155 if (layer->contentDirty) {
3156 // we need to invalidate the whole region
3157 dirty = visibleRegion;
3158 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003159 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003160 layer->contentDirty = false;
3161 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003162 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003163 * the exposed region consists of two components:
3164 * 1) what's VISIBLE now and was COVERED before
3165 * 2) what's EXPOSED now less what was EXPOSED before
3166 *
3167 * note that (1) is conservative, we start with the whole
3168 * visible region but only keep what used to be covered by
3169 * something -- which mean it may have been exposed.
3170 *
3171 * (2) handles areas that were not covered by anything but got
3172 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003173 */
Mathias Agopianab028732010-03-16 16:41:46 -07003174 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003175 const Region oldVisibleRegion = layer->visibleRegion;
3176 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003177 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3178 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003179 }
3180 dirty.subtractSelf(aboveOpaqueLayers);
3181
3182 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003183 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003184
Mathias Agopianab028732010-03-16 16:41:46 -07003185 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003186 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003187
Jesse Halla8026d22012-09-25 13:25:04 -07003188 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003189 layer->setVisibleRegion(visibleRegion);
3190 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003191 layer->setVisibleNonTransparentRegion(
3192 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003193 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003194
Mathias Agopian87baae12012-07-31 12:38:26 -07003195 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003196}
3197
Chia-I Wuab0c3192017-08-01 11:29:00 -07003198void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003199 for (const auto& [token, displayDevice] : mDisplays) {
3200 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003201 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003202 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003203 }
3204 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003205}
3206
Dan Stoza6b9454d2014-11-07 16:00:59 -08003207bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003208{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003209 ALOGV("handlePageFlip");
3210
Brian Andersond6927fb2016-07-23 23:37:30 -07003211 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003212
Mathias Agopian4fec8732012-06-29 14:12:52 -07003213 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003214 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003215 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003216
3217 // Store the set of layers that need updates. This set must not change as
3218 // buffers are being latched, as this could result in a deadlock.
3219 // Example: Two producers share the same command stream and:
3220 // 1.) Layer 0 is latched
3221 // 2.) Layer 0 gets a new frame
3222 // 2.) Layer 1 gets a new frame
3223 // 3.) Layer 1 is latched.
3224 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3225 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003226 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003227 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003228 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003229 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3230 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003231 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003232 } else {
3233 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003234 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003235 } else {
3236 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003237 }
Robert Carr2047fae2016-11-28 14:09:09 -08003238 });
3239
Lloyd Piquef2c79392018-12-20 16:23:33 -08003240 if (!mLayersWithQueuedFrames.empty()) {
3241 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3242 // writes to Layer current state. See also b/119481871
3243 Mutex::Autolock lock(mStateLock);
3244
3245 for (auto& layer : mLayersWithQueuedFrames) {
3246 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3247 layer->useSurfaceDamage();
3248 invalidateLayerStack(layer, dirty);
3249 if (layer->isBufferLatched()) {
3250 newDataLatched = true;
3251 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003252 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003253 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003254
Alec Mouri86770e52018-09-24 22:40:58 +00003255 // Clear the renderengine fence here...
3256 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3257 // clear instead of sp::clear.
3258 getBE().flushFence = Fence::NO_FENCE;
3259
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003260 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003261
Vishnu Nairde19f852018-12-18 16:11:53 -08003262 if (visibleRegions) {
3263 // Update input window info if the layer receives its first buffer.
3264 updateInputWindows();
3265 }
3266
Dan Stoza6b9454d2014-11-07 16:00:59 -08003267 // If we will need to wake up at some time in the future to deal with a
3268 // queued frame that shouldn't be displayed during this vsync period, wake
3269 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003270 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003271 signalLayerUpdate();
3272 }
3273
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003274 // enter boot animation on first buffer latch
3275 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3276 ALOGI("Enter boot animation");
3277 mBootStage = BootStage::BOOTANIMATION;
3278 }
3279
Dan Stoza6b9454d2014-11-07 16:00:59 -08003280 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003281 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003282}
3283
Mathias Agopianad456f92011-01-13 17:53:01 -08003284void SurfaceFlinger::invalidateHwcGeometry()
3285{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003286 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003287}
3288
Lloyd Pique32cbe282018-10-19 13:09:22 -07003289void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003290 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003291 auto display = displayDevice->getCompositionDisplay();
3292
Dan Stoza71433162014-02-04 16:22:36 -08003293 // We only need to actually compose the display if:
3294 // 1) It is being handled by hardware composer, which may need this to
3295 // keep its virtual display state machine in sync, or
3296 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003297 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003298 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003299 return;
3300 }
3301
Dan Stoza9e56aa02015-11-02 13:00:03 -08003302 ALOGV("doDisplayComposition");
Lloyd Pique32cbe282018-10-19 13:09:22 -07003303 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003304
3305 // swap buffers (presentation)
Lloyd Pique31cb2942018-10-19 17:23:03 -07003306 display->getRenderSurface()->queueBuffer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003307}
3308
Lloyd Pique32cbe282018-10-19 13:09:22 -07003309bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003310 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003311
Lloyd Pique32cbe282018-10-19 13:09:22 -07003312 auto display = displayDevice->getCompositionDisplay();
3313 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003314 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003315
3316 const Region bounds(displayState.bounds);
3317 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003318 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003319 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003320
Peiyong Lind3788632018-09-18 16:01:31 -07003321 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003322 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003323
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003324 // Framebuffer will live in this scope for GPU composition.
3325 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
3326
Dan Stoza9e56aa02015-11-02 13:00:03 -08003327 if (hasClientComposition) {
3328 ALOGV("hasClientComposition");
3329
Lloyd Pique31cb2942018-10-19 17:23:03 -07003330 sp<GraphicBuffer> buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003331
3332 if (buf == nullptr) {
3333 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3334 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003335 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003336 return false;
3337 }
3338
3339 // Bind the framebuffer in this scope.
3340 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3341 buf->getNativeBuffer());
3342
3343 if (fbo->getStatus() != NO_ERROR) {
3344 ALOGW("Binding buffer for display [%s] failed with status: %d",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003345 displayDevice->getDisplayName().c_str(), fbo->getStatus());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003346 return false;
3347 }
3348
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003349 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003350 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003351 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003352 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003353 }
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003354 getRenderEngine().setOutputDataSpace(outputDataspace);
3355 getRenderEngine().setDisplayMaxLuminance(
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003356 profile->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003357
Lloyd Pique441d5042018-10-18 16:49:51 -07003358 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003359 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003360 getHwComposer()
3361 .hasDisplayCapability(displayId,
3362 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003363
Peiyong Lind3788632018-09-18 16:01:31 -07003364 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003365 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3366 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003367 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003368 }
3369
Lloyd Pique31cb2942018-10-19 17:23:03 -07003370 display->getRenderSurface()->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003371
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003372 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003373 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003374 // when using overlays, we assume a fully transparent framebuffer
3375 // NOTE: we could reduce how much we need to clear, for instance
3376 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003377 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003378 // We'll revisit later if needed.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003379 getRenderEngine().clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003380 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003381 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003382 // we're left with the letterbox region
3383 // (common case is that letterbox ends-up being empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003384 const Region letterbox = bounds.subtract(displayState.scissor);
Mathias Agopian766dc492012-10-30 18:08:06 -07003385
3386 // compute the area to clear
Lloyd Pique32cbe282018-10-19 13:09:22 -07003387 const Region region = displayState.undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003388
Mathias Agopianb9494d52012-04-18 02:28:45 -07003389 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003390 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003391 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003392 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003393 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003394 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003395
Lloyd Pique32cbe282018-10-19 13:09:22 -07003396 const Rect& bounds = displayState.bounds;
3397 const Rect& scissor = displayState.scissor;
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003398 if (scissor != bounds) {
3399 // scissor doesn't match the screen's dimensions, so we
3400 // need to clear everything outside of it and enable
3401 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003402
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003403 // enable scissor for this frame
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003404 getRenderEngine().setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003405 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003406 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003407
Mathias Agopian85d751c2012-08-29 16:59:24 -07003408 /*
3409 * and then, render the layers targeted at the framebuffer
3410 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003411
Dan Stoza9e56aa02015-11-02 13:00:03 -08003412 ALOGV("Rendering client layers");
Lloyd Pique32cbe282018-10-19 13:09:22 -07003413 const ui::Transform& displayTransform = displayState.transform;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003414 bool firstLayer = true;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003415 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003416 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003417 displayTransform.transform(layer->visibleRegion)));
3418 ALOGV("Layer: %s", layer->getName().string());
3419 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003420 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003421 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003422 case HWC2::Composition::Cursor:
3423 case HWC2::Composition::Device:
3424 case HWC2::Composition::Sideband:
3425 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003426 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003427 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003428 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003429 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003430 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003431 // never clear the very first layer since we're
3432 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003433 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003434 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003435 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003436 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003437 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003438 if (layer->hasColorTransform()) {
3439 mat4 tmpMatrix;
3440 if (applyColorMatrix) {
3441 tmpMatrix = mDrawingState.colorMatrix;
3442 }
3443 tmpMatrix *= layer->getColorTransform();
Peiyong Lind3788632018-09-18 16:01:31 -07003444 getRenderEngine().setColorTransform(tmpMatrix);
3445 } else {
3446 getRenderEngine().setColorTransform(colorMatrix);
3447 }
David Sodmanc1498e62018-09-12 14:36:26 -07003448 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003449 break;
3450 }
3451 default:
3452 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003453 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003454 } else {
3455 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003456 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003457 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003458 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003459
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003460 // Perform some cleanup steps if we used client composition.
3461 if (hasClientComposition) {
3462 getRenderEngine().setColorTransform(mat4());
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003463 getRenderEngine().disableScissor();
Lloyd Pique31cb2942018-10-19 17:23:03 -07003464 display->getRenderSurface()->finishBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003465 // Clear out error flags here so that we don't wait until next
3466 // composition to log.
3467 getRenderEngine().checkErrors();
3468 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003469 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003470}
3471
Chia-I Wu28e3a252018-09-07 12:05:02 -07003472void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003473 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003474 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003475}
3476
Dan Stoza7d89d062015-04-30 13:29:25 -07003477status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003478 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003479 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003480 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003481 const sp<Layer>& parent,
3482 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003483{
Dan Stoza7d89d062015-04-30 13:29:25 -07003484 // add this layer to the current state list
3485 {
3486 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003487 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003488 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3489 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003490 return NO_MEMORY;
3491 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003492 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003493 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003494 } else if (parent == nullptr) {
3495 lbc->onRemovedFromCurrentState();
3496 } else if (parent->isRemovedFromCurrentState()) {
3497 parent->addChild(lbc);
3498 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003499 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003500 parent->addChild(lbc);
3501 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003502
Yiwei Zhang243b3782018-05-15 17:40:04 -07003503 if (gbc != nullptr) {
3504 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3505 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3506 mMaxGraphicBufferProducerListSize,
3507 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3508 mGraphicBufferProducerList.size(),
3509 mMaxGraphicBufferProducerListSize, mNumLayers);
3510 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003511 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003512 }
3513
Mathias Agopian96f08192010-06-02 23:28:45 -07003514 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003515 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003516
Dan Stoza7d89d062015-04-30 13:29:25 -07003517 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003518}
3519
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003520uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003521 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003522}
3523
Mathias Agopian3f844832013-08-07 21:24:32 -07003524uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003525 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003526}
3527
Mathias Agopian3f844832013-08-07 21:24:32 -07003528uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003529 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003530}
3531
3532uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003533 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003534 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003535 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003536 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003537 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003538 }
3539 return old;
3540}
3541
Marissa Wall713b63f2018-10-17 15:42:43 -07003542bool SurfaceFlinger::flushTransactionQueues() {
3543 Mutex::Autolock _l(mStateLock);
3544 auto it = mTransactionQueues.begin();
3545 while (it != mTransactionQueues.end()) {
3546 auto& [applyToken, transactionQueue] = *it;
3547
3548 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003549 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3550 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003551 break;
3552 }
chaviw273171b2018-12-26 11:46:30 -08003553 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003554 transactionQueue.pop();
3555 }
3556
3557 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3558 }
3559 return mTransactionQueues.empty();
3560}
3561
chaviwca27f252018-02-06 16:46:39 -08003562bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3563 for (const ComposerState& state : states) {
3564 // Here we need to check that the interface we're given is indeed
3565 // one of our own. A malicious client could give us a nullptr
3566 // IInterface, or one of its own or even one of our own but a
3567 // different type. All these situations would cause us to crash.
3568 if (state.client == nullptr) {
3569 return true;
3570 }
3571
3572 sp<IBinder> binder = IInterface::asBinder(state.client);
3573 if (binder == nullptr) {
3574 return true;
3575 }
3576
3577 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3578 return true;
3579 }
3580 }
3581 return false;
3582}
3583
Marissa Wall17b4e452018-12-26 16:32:34 -08003584bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3585 const Vector<ComposerState>& states) {
3586 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3587 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3588 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3589 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3590 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3591 return false;
3592 }
3593
Marissa Wall713b63f2018-10-17 15:42:43 -07003594 for (const ComposerState& state : states) {
3595 const layer_state_t& s = state.state;
3596 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3597 continue;
3598 }
3599 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003600 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003601 }
3602 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003603 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003604}
3605
3606void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3607 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003608 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003609 const InputWindowCommands& inputWindowCommands,
3610 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003611 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003612 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003613
chaviwca27f252018-02-06 16:46:39 -08003614 if (containsAnyInvalidClientState(states)) {
3615 return;
3616 }
3617
Marissa Wall713b63f2018-10-17 15:42:43 -07003618 // If its TransactionQueue already has a pending TransactionState or if it is pending
3619 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003620 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3621 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003622 setTransactionFlags(eTransactionNeeded);
3623 return;
3624 }
3625
chaviw273171b2018-12-26 11:46:30 -08003626 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003627}
3628
3629void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003630 const Vector<DisplayState>& displays, uint32_t flags,
3631 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003632 uint32_t transactionFlags = 0;
3633
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003634 if (flags & eAnimation) {
3635 // For window updates that are part of an animation we must wait for
3636 // previous animation "frames" to be handled.
3637 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003638 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003639 if (CC_UNLIKELY(err != NO_ERROR)) {
3640 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003641 // caller after a few seconds.
3642 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3643 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003644 mAnimTransactionPending = false;
3645 break;
3646 }
3647 }
3648 }
3649
chaviwca27f252018-02-06 16:46:39 -08003650 for (const DisplayState& display : displays) {
3651 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003652 }
3653
Marissa Walle2ffb422018-10-12 11:33:52 -07003654 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003655 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003656 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003657 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003658 // If the state doesn't require a traversal and there are callbacks, send them now
3659 if (!(clientStateFlags & eTraversalNeeded)) {
3660 mTransactionCompletedThread.sendCallbacks();
3661 }
3662 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003663
chaviw273171b2018-12-26 11:46:30 -08003664 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3665
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003666 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3667 // anyway. This can be used as a flush mechanism for previous async transactions.
3668 // Empty animation transaction can be used to simulate back-pressure, so also force a
3669 // transaction for empty animation transactions.
3670 if (transactionFlags == 0 &&
3671 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003672 transactionFlags = eTransactionNeeded;
3673 }
3674
Mathias Agopian386aa982011-11-07 21:58:03 -08003675 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003676 if (mInterceptor->isEnabled()) {
3677 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003678 }
Irvel468051e2016-06-13 16:44:44 -07003679
Mathias Agopian386aa982011-11-07 21:58:03 -08003680 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003681 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3682 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003683 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003684
3685 // if this is a synchronous transaction, wait for it to take effect
3686 // before returning.
3687 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003688 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003689 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003690 if (flags & eAnimation) {
3691 mAnimTransactionPending = true;
3692 }
3693 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003694 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3695 if (CC_UNLIKELY(err != NO_ERROR)) {
3696 // just in case something goes wrong in SF, return to the
3697 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003698 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3699 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003700 break;
3701 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003702 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003703 }
3704}
3705
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003706uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3707 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3708 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003709
Mathias Agopiane57f2922012-08-09 16:29:12 -07003710 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003711 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3712
3713 const uint32_t what = s.what;
3714 if (what & DisplayState::eSurfaceChanged) {
3715 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3716 state.surface = s.surface;
3717 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003718 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003719 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003720 if (what & DisplayState::eLayerStackChanged) {
3721 if (state.layerStack != s.layerStack) {
3722 state.layerStack = s.layerStack;
3723 flags |= eDisplayTransactionNeeded;
3724 }
3725 }
3726 if (what & DisplayState::eDisplayProjectionChanged) {
3727 if (state.orientation != s.orientation) {
3728 state.orientation = s.orientation;
3729 flags |= eDisplayTransactionNeeded;
3730 }
3731 if (state.frame != s.frame) {
3732 state.frame = s.frame;
3733 flags |= eDisplayTransactionNeeded;
3734 }
3735 if (state.viewport != s.viewport) {
3736 state.viewport = s.viewport;
3737 flags |= eDisplayTransactionNeeded;
3738 }
3739 }
3740 if (what & DisplayState::eDisplaySizeChanged) {
3741 if (state.width != s.width) {
3742 state.width = s.width;
3743 flags |= eDisplayTransactionNeeded;
3744 }
3745 if (state.height != s.height) {
3746 state.height = s.height;
3747 flags |= eDisplayTransactionNeeded;
3748 }
3749 }
3750
Mathias Agopiane57f2922012-08-09 16:29:12 -07003751 return flags;
3752}
3753
Robert Carrd4ae7f32018-06-07 16:10:57 -07003754bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3755 IPCThreadState* ipc = IPCThreadState::self();
3756 const int pid = ipc->getCallingPid();
3757 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003758 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003759 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003760 return false;
3761 }
3762 return true;
3763}
3764
chaviwca27f252018-02-06 16:46:39 -08003765uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3766 const layer_state_t& s = composerState.state;
3767 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3768
Mathias Agopian13127d82013-03-05 17:47:11 -08003769 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003770 if (layer == nullptr) {
3771 return 0;
3772 }
3773
chaviw8b3871a2017-11-01 17:41:01 -07003774 uint32_t flags = 0;
3775
Garfield Tan8a3083e2018-12-03 13:21:07 -08003776 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003777 bool geometryAppliesWithResize =
3778 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003779
3780 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3781 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003782 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003783 layer->pushPendingState();
3784 }
3785
chaviw8b3871a2017-11-01 17:41:01 -07003786 if (what & layer_state_t::ePositionChanged) {
3787 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3788 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003789 }
chaviw8b3871a2017-11-01 17:41:01 -07003790 }
3791 if (what & layer_state_t::eLayerChanged) {
3792 // NOTE: index needs to be calculated before we update the state
3793 const auto& p = layer->getParent();
3794 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003795 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003796 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003797 mCurrentState.layersSortedByZ.removeAt(idx);
3798 mCurrentState.layersSortedByZ.add(layer);
3799 // we need traversal (state changed)
3800 // AND transaction (list changed)
3801 flags |= eTransactionNeeded|eTraversalNeeded;
3802 }
chaviw8b3871a2017-11-01 17:41:01 -07003803 } else {
3804 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003805 flags |= eTransactionNeeded|eTraversalNeeded;
3806 }
3807 }
chaviw8b3871a2017-11-01 17:41:01 -07003808 }
3809 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003810 // NOTE: index needs to be calculated before we update the state
3811 const auto& p = layer->getParent();
3812 if (p == nullptr) {
3813 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3814 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3815 mCurrentState.layersSortedByZ.removeAt(idx);
3816 mCurrentState.layersSortedByZ.add(layer);
3817 // we need traversal (state changed)
3818 // AND transaction (list changed)
3819 flags |= eTransactionNeeded|eTraversalNeeded;
3820 }
3821 } else {
3822 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3823 flags |= eTransactionNeeded|eTraversalNeeded;
3824 }
chaviw8b3871a2017-11-01 17:41:01 -07003825 }
3826 }
3827 if (what & layer_state_t::eSizeChanged) {
3828 if (layer->setSize(s.w, s.h)) {
3829 flags |= eTraversalNeeded;
3830 }
3831 }
3832 if (what & layer_state_t::eAlphaChanged) {
3833 if (layer->setAlpha(s.alpha))
3834 flags |= eTraversalNeeded;
3835 }
3836 if (what & layer_state_t::eColorChanged) {
3837 if (layer->setColor(s.color))
3838 flags |= eTraversalNeeded;
3839 }
Valerie Haued54efa2019-01-11 20:03:14 -08003840 if (what & layer_state_t::eColorAlphaChanged) {
3841 if (layer->setColorAlpha(s.colorAlpha)) flags |= eTraversalNeeded;
3842 }
3843 if (what & layer_state_t::eColorDataspaceChanged) {
3844 if (layer->setColorDataspace(s.colorDataspace)) flags |= eTraversalNeeded;
3845 }
Peiyong Lind3788632018-09-18 16:01:31 -07003846 if (what & layer_state_t::eColorTransformChanged) {
3847 if (layer->setColorTransform(s.colorTransform)) {
3848 flags |= eTraversalNeeded;
3849 }
3850 }
chaviw8b3871a2017-11-01 17:41:01 -07003851 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003852 // TODO: b/109894387
3853 //
3854 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3855 // rotation. To see the problem observe that if we have a square parent, and a child
3856 // of the same size, then we rotate the child 45 degrees around it's center, the child
3857 // must now be cropped to a non rectangular 8 sided region.
3858 //
3859 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3860 // private API, and the WindowManager only uses rotation in one case, which is on a top
3861 // level layer in which cropping is not an issue.
3862 //
3863 // However given that abuse of rotation matrices could lead to surfaces extending outside
3864 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3865 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3866 // transformations.
3867 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003868 flags |= eTraversalNeeded;
3869 }
3870 if (what & layer_state_t::eTransparentRegionChanged) {
3871 if (layer->setTransparentRegionHint(s.transparentRegion))
3872 flags |= eTraversalNeeded;
3873 }
3874 if (what & layer_state_t::eFlagsChanged) {
3875 if (layer->setFlags(s.flags, s.mask))
3876 flags |= eTraversalNeeded;
3877 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003878 if (what & layer_state_t::eCropChanged_legacy) {
3879 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003880 flags |= eTraversalNeeded;
3881 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003882 if (what & layer_state_t::eCornerRadiusChanged) {
3883 if (layer->setCornerRadius(s.cornerRadius))
3884 flags |= eTraversalNeeded;
3885 }
chaviw8b3871a2017-11-01 17:41:01 -07003886 if (what & layer_state_t::eLayerStackChanged) {
3887 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3888 // We only allow setting layer stacks for top level layers,
3889 // everything else inherits layer stack from its parent.
3890 if (layer->hasParent()) {
3891 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3892 layer->getName().string());
3893 } else if (idx < 0) {
3894 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3895 "that also does not appear in the top level layer list. Something"
3896 " has gone wrong.", layer->getName().string());
3897 } else if (layer->setLayerStack(s.layerStack)) {
3898 mCurrentState.layersSortedByZ.removeAt(idx);
3899 mCurrentState.layersSortedByZ.add(layer);
3900 // we need traversal (state changed)
3901 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003902 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003903 }
3904 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003905 if (what & layer_state_t::eDeferTransaction_legacy) {
3906 if (s.barrierHandle_legacy != nullptr) {
3907 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3908 } else if (s.barrierGbp_legacy != nullptr) {
3909 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003910 if (authenticateSurfaceTextureLocked(gbp)) {
3911 const auto& otherLayer =
3912 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003913 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003914 } else {
3915 ALOGE("Attempt to defer transaction to to an"
3916 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003917 }
3918 }
chaviw8b3871a2017-11-01 17:41:01 -07003919 // We don't trigger a traversal here because if no other state is
3920 // changed, we don't want this to cause any more work
3921 }
3922 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003923 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003924 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003925 if (!hadParent) {
3926 mCurrentState.layersSortedByZ.remove(layer);
3927 }
chaviw8b3871a2017-11-01 17:41:01 -07003928 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003929 }
chaviw8b3871a2017-11-01 17:41:01 -07003930 }
3931 if (what & layer_state_t::eReparentChildren) {
3932 if (layer->reparentChildren(s.reparentHandle)) {
3933 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003934 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003935 }
chaviw8b3871a2017-11-01 17:41:01 -07003936 if (what & layer_state_t::eDetachChildren) {
3937 layer->detachChildren();
3938 }
3939 if (what & layer_state_t::eOverrideScalingModeChanged) {
3940 layer->setOverrideScalingMode(s.overrideScalingMode);
3941 // We don't trigger a traversal here because if no other state is
3942 // changed, we don't want this to cause any more work
3943 }
Marissa Wall61c58622018-07-18 10:12:20 -07003944 if (what & layer_state_t::eTransformChanged) {
3945 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3946 }
3947 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3948 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3949 flags |= eTraversalNeeded;
3950 }
3951 if (what & layer_state_t::eCropChanged) {
3952 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3953 }
Marissa Wall861616d2018-10-22 12:52:23 -07003954 if (what & layer_state_t::eFrameChanged) {
3955 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3956 }
Marissa Wall61c58622018-07-18 10:12:20 -07003957 if (what & layer_state_t::eBufferChanged) {
3958 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3959 }
3960 if (what & layer_state_t::eAcquireFenceChanged) {
3961 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3962 }
3963 if (what & layer_state_t::eDataspaceChanged) {
3964 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3965 }
3966 if (what & layer_state_t::eHdrMetadataChanged) {
3967 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3968 }
3969 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3970 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3971 }
3972 if (what & layer_state_t::eApiChanged) {
3973 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3974 }
3975 if (what & layer_state_t::eSidebandStreamChanged) {
3976 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3977 }
Robert Carr720e5062018-07-30 17:45:14 -07003978 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003979 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
3980 layer->setInputInfo(s.inputInfo);
3981 flags |= eTraversalNeeded;
3982 } else {
3983 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3984 }
Robert Carr720e5062018-07-30 17:45:14 -07003985 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003986 if (what & layer_state_t::eMetadataChanged) {
3987 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3988 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003989 std::vector<sp<CallbackHandle>> callbackHandles;
3990 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3991 mTransactionCompletedThread.run();
3992 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3993 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3994 }
3995 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003996 if (what & layer_state_t::eCachedBufferChanged) {
3997 sp<GraphicBuffer> buffer =
3998 mBufferStateLayerCache.get(s.cachedBuffer.token, s.cachedBuffer.bufferId);
3999 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4000 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004001 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4002 // Do not put anything that updates layer state or modifies flags after
4003 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004004 return flags;
4005}
4006
chaviw273171b2018-12-26 11:46:30 -08004007uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4008 uint32_t flags = 0;
4009 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4010 flags |= eTraversalNeeded;
4011 }
4012
4013 mInputWindowCommands.merge(inputWindowCommands);
4014 return flags;
4015}
4016
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004017status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4018 uint32_t h, PixelFormat format, uint32_t flags,
4019 LayerMetadata metadata, sp<IBinder>* handle,
4020 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004021 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004022 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004023 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004024 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004025 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004026
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004027 status_t result = NO_ERROR;
4028
4029 sp<Layer> layer;
4030
Cody Northropbc755282017-03-31 12:00:08 -06004031 String8 uniqueName = getUniqueLayerName(name);
4032
Mathias Agopian3165cc22012-08-08 19:42:09 -07004033 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004034 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004035 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4036 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004037
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004038 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004039 case ISurfaceComposerClient::eFXSurfaceBufferState:
4040 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4041 break;
chaviw13fdc492017-06-27 12:40:18 -07004042 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004043 // check if buffer size is set for color layer.
4044 if (w > 0 || h > 0) {
4045 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4046 int(w), int(h));
4047 return BAD_VALUE;
4048 }
4049
chaviw13fdc492017-06-27 12:40:18 -07004050 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004051 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004052 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004053 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004054 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004055 // check if buffer size is set for container layer.
4056 if (w > 0 || h > 0) {
4057 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4058 int(w), int(h));
4059 return BAD_VALUE;
4060 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004061 result = createContainerLayer(client,
4062 uniqueName, w, h, flags,
4063 handle, &layer);
4064 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004065 default:
4066 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004067 break;
4068 }
4069
Dan Stoza7d89d062015-04-30 13:29:25 -07004070 if (result != NO_ERROR) {
4071 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004072 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004073
Chia-I Wuab0c3192017-08-01 11:29:00 -07004074 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4075 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004076 if (metadata.has(METADATA_WINDOW_TYPE)) {
4077 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4078 if (windowType == 441731) {
4079 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4080 layer->setPrimaryDisplayOnly();
4081 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004082 }
4083
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004084 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004085
Robert Carrb89ea9d2018-12-10 13:01:14 -08004086 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4087 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4088 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004089 if (result != NO_ERROR) {
4090 return result;
4091 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004092 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004093
4094 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004095 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004096}
4097
Cody Northropbc755282017-03-31 12:00:08 -06004098String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4099{
4100 bool matchFound = true;
4101 uint32_t dupeCounter = 0;
4102
4103 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4104 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4105
Dan Stoza436ccf32018-06-21 12:10:12 -07004106 // Grab the state lock since we're accessing mCurrentState
4107 Mutex::Autolock lock(mStateLock);
4108
Cody Northropbc755282017-03-31 12:00:08 -06004109 // Loop over layers until we're sure there is no matching name
4110 while (matchFound) {
4111 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004112 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004113 if (layer->getName() == uniqueName) {
4114 matchFound = true;
4115 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4116 }
4117 });
4118 }
4119
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004120 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4121 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004122
4123 return uniqueName;
4124}
4125
Marissa Wallfd668622018-05-10 10:21:13 -07004126status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4127 uint32_t w, uint32_t h, uint32_t flags,
4128 PixelFormat& format, sp<IBinder>* handle,
4129 sp<IGraphicBufferProducer>* gbp,
4130 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004131 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004132 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004133 case PIXEL_FORMAT_TRANSPARENT:
4134 case PIXEL_FORMAT_TRANSLUCENT:
4135 format = PIXEL_FORMAT_RGBA_8888;
4136 break;
4137 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004138 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004139 break;
4140 }
4141
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004142 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004143 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004144 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004145 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004146 *handle = layer->getHandle();
4147 *gbp = layer->getProducer();
4148 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004149 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004150
Marissa Wallfd668622018-05-10 10:21:13 -07004151 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004152 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004153}
4154
Marissa Wall61c58622018-07-18 10:12:20 -07004155status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4156 uint32_t w, uint32_t h, uint32_t flags,
4157 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004158 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004159 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004160 *handle = layer->getHandle();
4161 *outLayer = layer;
4162
4163 return NO_ERROR;
4164}
4165
chaviw13fdc492017-06-27 12:40:18 -07004166status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004167 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004168 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004169{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004170 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004171 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004172 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004173}
4174
Robert Carr6b3f6c52018-08-13 13:05:17 -07004175status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4176 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4177 sp<IBinder>* handle, sp<Layer>* outLayer)
4178{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004179 *outLayer =
4180 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004181 *handle = (*outLayer)->getHandle();
4182 return NO_ERROR;
4183}
4184
4185
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004186void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004187 mLayersPendingRemoval.add(layer);
4188 mLayersRemoved = true;
4189 setTransactionFlags(eTransactionNeeded);
4190}
4191
Robert Carr695d5282018-12-18 15:27:58 -08004192void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004193{
Robert Carr2e102c92018-10-23 12:11:15 -07004194 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004195 // If a layer has a parent, we allow it to out-live it's handle
4196 // with the idea that the parent holds a reference and will eventually
4197 // be cleaned up. However no one cleans up the top-level so we do so
4198 // here.
4199 if (layer->getParent() == nullptr) {
4200 mCurrentState.layersSortedByZ.remove(layer);
4201 }
4202 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004203 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004204}
4205
Mathias Agopianb60314a2012-04-10 22:09:54 -07004206// ---------------------------------------------------------------------------
4207
Andy McFadden13a082e2012-08-24 10:16:42 -07004208void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004209 const auto display = getDefaultDisplayDeviceLocked();
4210 if (!display) return;
4211
4212 const sp<IBinder> token = display->getDisplayToken().promote();
4213 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004214
Jesse Hall01e29052013-02-19 16:13:35 -08004215 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004216 Vector<ComposerState> state;
4217 Vector<DisplayState> displays;
4218 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004219 d.what = DisplayState::eDisplayProjectionChanged |
4220 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004221 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004222 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004223 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004224 d.frame.makeInvalid();
4225 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004226 d.width = 0;
4227 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004228 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004229 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004230
Dominik Laskowskie9774092018-12-11 10:04:24 -08004231 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004232
Dominik Laskowski83b88212018-12-11 13:34:06 -08004233 const nsecs_t vsyncPeriod = getVsyncPeriod();
4234 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004235
Brian Andersond0010582017-03-07 13:20:31 -08004236 // Use phase of 0 since phase is not known.
4237 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004238 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004239 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004240}
4241
4242void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004243 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004244 postMessageAsync(
4245 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004246}
4247
Dominik Laskowskie9774092018-12-11 10:04:24 -08004248void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004249 if (display->isVirtual()) {
4250 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004251 return;
4252 }
4253
Dominik Laskowski075d3172018-05-24 15:50:06 -07004254 const auto displayId = display->getId();
4255 LOG_ALWAYS_FATAL_IF(!displayId);
4256
Dominik Laskowski34157762018-10-31 13:07:19 -07004257 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004258
4259 int currentMode = display->getPowerMode();
4260 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004261 return;
4262 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004263
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004264 display->setPowerMode(mode);
4265
Lloyd Pique4dccc412018-01-22 17:21:36 -08004266 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004267 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004268 }
4269
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004270 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004271 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004272 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004273 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004274 if (mUseScheduler) {
4275 mScheduler->onScreenAcquired(mAppConnectionHandle);
4276 } else {
4277 mEventThread->onScreenAcquired();
4278 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004279 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004280 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004281
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004282 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004283 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004284 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004285
4286 struct sched_param param = {0};
4287 param.sched_priority = 1;
4288 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4289 ALOGW("Couldn't set SCHED_FIFO on display on");
4290 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004291 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004292 // Turn off the display
4293 struct sched_param param = {0};
4294 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4295 ALOGW("Couldn't set SCHED_OTHER on display off");
4296 }
4297
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004298 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004299 if (mUseScheduler) {
4300 mScheduler->disableHardwareVsync(true);
4301 } else {
4302 disableHardwareVsync(true); // also cancels any in-progress resync
4303 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004304 if (mUseScheduler) {
4305 mScheduler->onScreenReleased(mAppConnectionHandle);
4306 } else {
4307 mEventThread->onScreenReleased();
4308 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004309 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004310
Dominik Laskowski075d3172018-05-24 15:50:06 -07004311 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004312 mVisibleRegionsDirty = true;
4313 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004314 } else if (mode == HWC_POWER_MODE_DOZE ||
4315 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004316 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004317 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004318 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004319 if (mUseScheduler) {
4320 mScheduler->onScreenAcquired(mAppConnectionHandle);
4321 } else {
4322 mEventThread->onScreenAcquired();
4323 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004324 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004325 }
4326 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4327 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004328 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004329 if (mUseScheduler) {
4330 mScheduler->disableHardwareVsync(true);
4331 } else {
4332 disableHardwareVsync(true); // also cancels any in-progress resync
4333 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004334 if (mUseScheduler) {
4335 mScheduler->onScreenReleased(mAppConnectionHandle);
4336 } else {
4337 mEventThread->onScreenReleased();
4338 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004339 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004340 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004341 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004342 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004343 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004344 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004345
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004346 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004347 mTimeStats->setPowerMode(mode);
Ana Krulec4593b692019-01-11 22:07:25 -08004348 if (mUseScheduler && mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004349 // Update refresh rate stats.
4350 mRefreshRateStats->setPowerMode(mode);
4351 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004352 }
4353
Dominik Laskowski34157762018-10-31 13:07:19 -07004354 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004355}
4356
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004357void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004358 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004359 const auto display = getDisplayDevice(displayToken);
4360 if (!display) {
4361 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4362 displayToken.get());
4363 } else if (display->isVirtual()) {
4364 ALOGW("Attempt to set power mode %d for virtual display", mode);
4365 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004366 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004367 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004368 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004369}
4370
4371// ---------------------------------------------------------------------------
4372
Dominik Laskowskic2867142019-01-21 11:33:38 -08004373status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4374 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004375 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004376
Mathias Agopianbd115332013-04-18 16:41:04 -07004377 IPCThreadState* ipc = IPCThreadState::self();
4378 const int pid = ipc->getCallingPid();
4379 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004380
Mathias Agopianbd115332013-04-18 16:41:04 -07004381 if ((uid != AID_SHELL) &&
4382 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004383 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4384 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004385 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004386 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004387 // (this would indicate SF is stuck, but we want to be able to
4388 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004389 status_t err = mStateLock.timedLock(s2ns(1));
4390 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004391 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004392 StringAppendF(&result,
4393 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4394 "(no locks held)\n",
4395 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004396 }
4397
Dominik Laskowskic2867142019-01-21 11:33:38 -08004398 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004399
Dominik Laskowskic2867142019-01-21 11:33:38 -08004400 static const std::unordered_map<std::string, Dumper> dumpers = {
4401 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4402 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4403 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
4404 {"--dispsync"s, dumper([this](std::string& s) { mPrimaryDispSync->dump(s); })},
4405 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4406 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
4407 {"--frame-composition"s, dumper(&SurfaceFlinger::dumpFrameCompositionInfo)},
4408 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4409 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4410 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4411 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4412 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4413 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004414 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004415 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4416 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004417
Dominik Laskowskic2867142019-01-21 11:33:38 -08004418 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004419
Dominik Laskowskic2867142019-01-21 11:33:38 -08004420 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4421 (it->second)(args, asProto, result);
4422 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004423 if (asProto) {
4424 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4425 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4426 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004427 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004428 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004429 }
4430
Mathias Agopian9795c422009-08-26 16:36:26 -07004431 if (locked) {
4432 mStateLock.unlock();
4433 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004434 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004435 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004436 return NO_ERROR;
4437}
4438
Dominik Laskowskic2867142019-01-21 11:33:38 -08004439void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004440 mCurrentState.traverseInZOrder(
4441 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004442}
4443
Dominik Laskowskic2867142019-01-21 11:33:38 -08004444void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004445 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004446
Dominik Laskowskic2867142019-01-21 11:33:38 -08004447 if (args.size() > 1) {
4448 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004449 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004450 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004451 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004452 }
Robert Carr2047fae2016-11-28 14:09:09 -08004453 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004454 } else {
4455 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004456 }
4457}
4458
Dominik Laskowskic2867142019-01-21 11:33:38 -08004459void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004460 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004461 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004462 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004463 }
Robert Carr2047fae2016-11-28 14:09:09 -08004464 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004465
Svetoslavd85084b2014-03-20 10:28:31 -07004466 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004467}
4468
Dominik Laskowskic2867142019-01-21 11:33:38 -08004469void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4470 mTimeStats->parseArgs(asProto, args, result);
4471}
4472
Jamie Gennis6547ff42013-07-16 20:12:42 -07004473// This should only be called from the main thread. Otherwise it would need
4474// the lock and should use mCurrentState rather than mDrawingState.
4475void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004476 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004477 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004478 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004479
4480 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4481}
4482
Yiwei Zhang5434a782018-12-05 18:06:32 -08004483void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004484 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004485
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004486 if (isLayerTripleBufferingDisabled())
4487 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004488
Yiwei Zhang5434a782018-12-05 18:06:32 -08004489 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4490 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4491 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4492 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4493 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4494 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004495 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004496}
4497
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004498void SurfaceFlinger::dumpVSync(std::string& result) const {
4499 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4500 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
4501 StringAppendF(&result,
4502 " app phase: %9" PRId64 " ns\t SF phase: %9" PRId64 " ns\n"
4503 " early app phase: %9" PRId64 " ns\t early SF phase: %9" PRId64 " ns\n"
4504 "GL early app phase: %9" PRId64 " ns\tGL early SF phase: %9" PRId64 " ns\n"
4505 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
4506 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, appEarlyOffset, sfEarlyOffset,
4507 appEarlyGlOffset, sfEarlyGlOffset, dispSyncPresentTimeOffset, getVsyncPeriod());
4508
4509 StringAppendF(&result, "Scheduler: %s\n\n", mUseScheduler ? "enabled" : "disabled");
4510
4511 if (mUseScheduler) {
4512 mScheduler->dump(mAppConnectionHandle, result);
4513 } else {
4514 mEventThread->dump(result);
4515 }
4516}
4517
Yiwei Zhang5434a782018-12-05 18:06:32 -08004518void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4519 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004520 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4521 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004522 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004523 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004524 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004525 }
David Sodman4a36e932017-11-07 14:29:47 -08004526 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004527 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004528 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004529 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4530 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004531}
4532
Dan Stozae77c7662016-05-13 11:37:28 -07004533void SurfaceFlinger::recordBufferingStats(const char* layerName,
4534 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004535 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4536 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004537 for (const auto& segment : history) {
4538 if (!segment.usedThirdBuffer) {
4539 stats.twoBufferTime += segment.totalTime;
4540 }
4541 if (segment.occupancyAverage < 1.0f) {
4542 stats.doubleBufferedTime += segment.totalTime;
4543 } else if (segment.occupancyAverage < 2.0f) {
4544 stats.tripleBufferedTime += segment.totalTime;
4545 }
4546 ++stats.numSegments;
4547 stats.totalTime += segment.totalTime;
4548 }
4549}
4550
Yiwei Zhang5434a782018-12-05 18:06:32 -08004551void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4552 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004553
4554 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4555 const size_t count = currentLayers.size();
4556 for (size_t i=0 ; i<count ; i++) {
4557 currentLayers[i]->dumpFrameEvents(result);
4558 }
4559}
4560
Yiwei Zhang5434a782018-12-05 18:06:32 -08004561void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004562 result.append("Buffering stats:\n");
4563 result.append(" [Layer name] <Active time> <Two buffer> "
4564 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004565 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004566 typedef std::tuple<std::string, float, float, float> BufferTuple;
4567 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004568 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004569 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004570 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004571 if (stats.numSegments == 0) {
4572 continue;
4573 }
4574 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4575 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4576 stats.totalTime;
4577 float doubleBufferRatio = static_cast<float>(
4578 stats.doubleBufferedTime) / stats.totalTime;
4579 float tripleBufferRatio = static_cast<float>(
4580 stats.tripleBufferedTime) / stats.totalTime;
4581 sorted.insert({activeTime, {name, twoBufferRatio,
4582 doubleBufferRatio, tripleBufferRatio}});
4583 }
4584 for (const auto& sortedPair : sorted) {
4585 float activeTime = sortedPair.first;
4586 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004587 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4588 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004589 }
4590 result.append("\n");
4591}
4592
Yiwei Zhang5434a782018-12-05 18:06:32 -08004593void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004594 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004595 const auto displayId = display->getId();
4596 if (!displayId) {
4597 continue;
4598 }
4599 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004600 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004601 continue;
4602 }
4603
Yiwei Zhang5434a782018-12-05 18:06:32 -08004604 StringAppendF(&result,
4605 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4606 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004607 uint8_t port;
4608 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004609 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004610 result.append("no identification data\n");
4611 continue;
4612 }
4613
4614 if (!isEdid(data)) {
4615 result.append("unknown identification data: ");
4616 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004617 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004618 }
4619 result.append("\n");
4620 continue;
4621 }
4622
4623 const auto edid = parseEdid(data);
4624 if (!edid) {
4625 result.append("invalid EDID: ");
4626 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004627 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004628 }
4629 result.append("\n");
4630 continue;
4631 }
4632
Yiwei Zhang5434a782018-12-05 18:06:32 -08004633 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004634 result.append(edid->displayName.data(), edid->displayName.length());
4635 result.append("\"\n");
4636 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004637}
4638
Yiwei Zhang5434a782018-12-05 18:06:32 -08004639void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4640 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4641 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4642 StringAppendF(&result, "DisplayColorSetting: %s\n",
4643 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004644
4645 // TODO: print out if wide-color mode is active or not
4646
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004647 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004648 const auto displayId = display->getId();
4649 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004650 continue;
4651 }
4652
Yiwei Zhang5434a782018-12-05 18:06:32 -08004653 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004654 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004655 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004656 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004657 }
4658
Lloyd Pique32cbe282018-10-19 13:09:22 -07004659 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004660 StringAppendF(&result, " Current color mode: %s (%d)\n",
4661 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004662 }
4663 result.append("\n");
4664}
4665
Yiwei Zhang5434a782018-12-05 18:06:32 -08004666void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004667 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004668 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4669 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004670 continue;
4671 }
4672
Dominik Laskowski05275f12018-11-01 15:03:24 -07004673 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004674 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4675 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004676 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004677 compositionInfo.dump(result, nullptr);
4678 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004679 }
4680 }
David Sodman7e4ae112018-02-09 15:02:28 -08004681}
4682
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004683LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004684 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004685 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4686 const State& state = useDrawing ? mDrawingState : mCurrentState;
4687 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004688 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004689 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004690 });
4691
4692 return layersProto;
4693}
4694
Lloyd Pique32cbe282018-10-19 13:09:22 -07004695LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004696 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004697
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004698 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004699 resolution->set_w(displayDevice.getWidth());
4700 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004701
Lloyd Pique32cbe282018-10-19 13:09:22 -07004702 auto display = displayDevice.getCompositionDisplay();
4703 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004704
Lloyd Pique32cbe282018-10-19 13:09:22 -07004705 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4706 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4707 layersProto.set_global_transform(displayState.orientation);
4708
4709 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004710 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004711 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004712 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004713 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004714 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004715 }
4716 });
4717
4718 return layersProto;
4719}
4720
Dominik Laskowskic2867142019-01-21 11:33:38 -08004721void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4722 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004723 Colorizer colorizer(colorize);
4724
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004725 // figure out if we're stuck somewhere
4726 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004727 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004728 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4729
4730 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004731 * Dump library configuration.
4732 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004733
4734 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004735 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004736 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004737 appendSfConfigString(result);
4738 appendUiConfigString(result);
4739 appendGuiConfigString(result);
4740 result.append("\n");
4741
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004742 result.append("\nDisplay identification data:\n");
4743 dumpDisplayIdentificationData(result);
4744
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004745 result.append("\nWide-Color information:\n");
4746 dumpWideColorInfo(result);
4747
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004748 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004749 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004750 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004751 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004752 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004753
Andy McFadden41d67d72014-04-25 16:58:34 -07004754 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004755 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004756 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004757 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004758 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004759
Dan Stozab90cf072015-03-05 11:05:59 -08004760 dumpStaticScreenStats(result);
4761 result.append("\n");
4762
Yiwei Zhang5434a782018-12-05 18:06:32 -08004763 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004764
Dan Stozae77c7662016-05-13 11:37:28 -07004765 dumpBufferingStats(result);
4766
Andy McFadden4803b742012-09-24 19:07:20 -07004767 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004768 * Dump the visible layer list
4769 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004770 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004771 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4772 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4773 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004774 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004775
Chia-I Wu2f884132018-09-13 15:17:58 -07004776 {
4777 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4778 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004779 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004780 result.append("\n");
4781 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004782
David Sodman7e4ae112018-02-09 15:02:28 -08004783 result.append("\nFrame-Composition information:\n");
4784 dumpFrameCompositionInfo(result);
4785 result.append("\n");
4786
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004787 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004788 * Dump Display state
4789 */
4790
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004791 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004792 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004793 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004794 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004795 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004796 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004797 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004798
4799 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004800 * Dump SurfaceFlinger global state
4801 */
4802
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004803 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004804 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004805 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004806
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004807 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004808
Dominik Laskowski075d3172018-05-24 15:50:06 -07004809 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004810 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4811 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004812 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4813 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004814 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004815 StringAppendF(&result,
4816 " transaction-flags : %08x\n"
4817 " gpu_to_cpu_unsupported : %d\n",
4818 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004819
Dominik Laskowski075d3172018-05-24 15:50:06 -07004820 if (const auto displayId = getInternalDisplayId();
4821 displayId && getHwComposer().isConnected(*displayId)) {
4822 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004823 StringAppendF(&result,
4824 " refresh-rate : %f fps\n"
4825 " x-dpi : %f\n"
4826 " y-dpi : %f\n",
4827 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4828 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004829 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004830
Yiwei Zhang5434a782018-12-05 18:06:32 -08004831 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004832
Dan Stozae22aec72016-08-01 13:20:59 -07004833 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004834 * Tracing state
4835 */
4836 mTracing.dump(result);
4837 result.append("\n");
4838
4839 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004840 * HWC layer minidump
4841 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004842 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004843 const auto displayId = display->getId();
4844 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004845 continue;
4846 }
4847
Yiwei Zhang5434a782018-12-05 18:06:32 -08004848 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004849 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004850 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004851 result.append("\n");
4852 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004853
4854 /*
4855 * Dump HWComposer state
4856 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004857 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004858 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004859 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004860 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004861 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004862 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004863
4864 /*
4865 * Dump gralloc state
4866 */
4867 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4868 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004869
4870 /*
4871 * Dump VrFlinger state if in use.
4872 */
4873 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4874 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004875 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004876 result.append("\n");
4877 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004878
4879 /**
4880 * Scheduler dump state.
4881 */
4882 if (mUseScheduler) {
4883 result.append("\nScheduler state:\n");
4884 result.append(mScheduler->doDump() + "\n");
4885 result.append(mRefreshRateStats->doDump() + "\n");
4886 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004887}
4888
Dominik Laskowski075d3172018-05-24 15:50:06 -07004889const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004890 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004891 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004892 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004893 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004894 }
4895 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004896
Dominik Laskowski34157762018-10-31 13:07:19 -07004897 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004898 static const Vector<sp<Layer>> empty;
4899 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004900}
4901
Keun young Park63f165f2012-08-31 10:53:36 -07004902bool SurfaceFlinger::startDdmConnection()
4903{
4904 void* libddmconnection_dso =
4905 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4906 if (!libddmconnection_dso) {
4907 return false;
4908 }
4909 void (*DdmConnection_start)(const char* name);
4910 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004911 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004912 if (!DdmConnection_start) {
4913 dlclose(libddmconnection_dso);
4914 return false;
4915 }
4916 (*DdmConnection_start)(getServiceName());
4917 return true;
4918}
4919
Chia-I Wu28f320b2018-05-03 11:02:56 -07004920void SurfaceFlinger::updateColorMatrixLocked() {
4921 mat4 colorMatrix;
4922 if (mGlobalSaturationFactor != 1.0f) {
4923 // Rec.709 luma coefficients
4924 float3 luminance{0.213f, 0.715f, 0.072f};
4925 luminance *= 1.0f - mGlobalSaturationFactor;
4926 mat4 saturationMatrix = mat4(
4927 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4928 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4929 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4930 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4931 );
4932 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4933 } else {
4934 colorMatrix = mClientColorMatrix * mDaltonizer();
4935 }
4936
4937 if (mCurrentState.colorMatrix != colorMatrix) {
4938 mCurrentState.colorMatrix = colorMatrix;
4939 mCurrentState.colorMatrixChanged = true;
4940 setTransactionFlags(eTransactionNeeded);
4941 }
4942}
4943
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004944status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004945#pragma clang diagnostic push
4946#pragma clang diagnostic error "-Wswitch-enum"
4947 switch (static_cast<ISurfaceComposerTag>(code)) {
4948 // These methods should at minimum make sure that the client requested
4949 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004950 case BOOT_FINISHED:
4951 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004952 case CREATE_DISPLAY:
4953 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004954 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004955 case GET_ACTIVE_COLOR_MODE:
4956 case GET_ANIMATION_FRAME_STATS:
4957 case GET_HDR_CAPABILITIES:
4958 case SET_ACTIVE_CONFIG:
4959 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004960 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004961 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004962 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004963 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4964 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004965 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4966 IPCThreadState* ipc = IPCThreadState::self();
4967 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4968 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004969 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004970 }
Robert Carr1db73f62016-12-21 12:58:51 -08004971 return OK;
4972 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004973 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004974 IPCThreadState* ipc = IPCThreadState::self();
4975 const int pid = ipc->getCallingPid();
4976 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004977 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4978 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004979 return PERMISSION_DENIED;
4980 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004981 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004982 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004983 // Used by apps to hook Choreographer to SurfaceFlinger.
4984 case CREATE_DISPLAY_EVENT_CONNECTION:
4985 // The following calls are currently used by clients that do not
4986 // request necessary permissions. However, they do not expose any secret
4987 // information, so it is OK to pass them.
4988 case AUTHENTICATE_SURFACE:
4989 case GET_ACTIVE_CONFIG:
4990 case GET_BUILT_IN_DISPLAY:
4991 case GET_DISPLAY_COLOR_MODES:
4992 case GET_DISPLAY_CONFIGS:
4993 case GET_DISPLAY_STATS:
4994 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4995 // Calling setTransactionState is safe, because you need to have been
4996 // granted a reference to Client* and Handle* to do anything with it.
4997 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004998 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004999 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005000 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005001 case GET_PROTECTED_CONTENT_SUPPORT:
5002 case CACHE_BUFFER:
5003 case UNCACHE_BUFFER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005004 return OK;
5005 }
5006 case CAPTURE_LAYERS:
5007 case CAPTURE_SCREEN: {
5008 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005009 IPCThreadState* ipc = IPCThreadState::self();
5010 const int pid = ipc->getCallingPid();
5011 const int uid = ipc->getCallingUid();
5012 if ((uid != AID_GRAPHICS) &&
5013 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5014 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5015 return PERMISSION_DENIED;
5016 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005017 return OK;
5018 }
5019 // The following codes are deprecated and should never be allowed to access SF.
5020 case CONNECT_DISPLAY_UNUSED:
5021 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5022 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5023 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005024 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005025 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005026
5027 // These codes are used for the IBinder protocol to either interrogate the recipient
5028 // side of the transaction for its canonical interface descriptor or to dump its state.
5029 // We let them pass by default.
5030 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5031 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5032 code == IBinder::SYSPROPS_TRANSACTION) {
5033 return OK;
5034 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005035 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005036 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005037 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005038 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5039 return OK;
5040 }
5041 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5042 return PERMISSION_DENIED;
5043#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005044}
5045
Ana Krulec13be8ad2018-08-21 02:43:56 +00005046status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5047 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005048 status_t credentialCheck = CheckTransactCodeCredentials(code);
5049 if (credentialCheck != OK) {
5050 return credentialCheck;
5051 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005052
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005053 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5054 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005055 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005056 IPCThreadState* ipc = IPCThreadState::self();
5057 const int uid = ipc->getCallingUid();
5058 if (CC_UNLIKELY(uid != AID_SYSTEM
5059 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005060 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005061 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005062 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005063 return PERMISSION_DENIED;
5064 }
5065 int n;
5066 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005067 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005068 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005069 return NO_ERROR;
5070 case 1002: // SHOW_UPDATES
5071 n = data.readInt32();
5072 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005073 invalidateHwcGeometry();
5074 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005075 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005076 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005077 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005078 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005079 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005080 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005081 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005082 setTransactionFlags(
5083 eTransactionNeeded|
5084 eDisplayTransactionNeeded|
5085 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005086 return NO_ERROR;
5087 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005088 case 1006:{ // send empty update
5089 signalRefresh();
5090 return NO_ERROR;
5091 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005092 case 1008: // toggle use of hw composer
5093 n = data.readInt32();
5094 mDebugDisableHWC = n ? 1 : 0;
5095 invalidateHwcGeometry();
5096 repaintEverything();
5097 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005098 case 1009: // toggle use of transform hint
5099 n = data.readInt32();
5100 mDebugDisableTransformHint = n ? 1 : 0;
5101 invalidateHwcGeometry();
5102 repaintEverything();
5103 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005104 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005105 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005106 reply->writeInt32(0);
5107 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005108 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005109 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005110 return NO_ERROR;
5111 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005112 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005113 if (!display) {
5114 return NAME_NOT_FOUND;
5115 }
5116
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005117 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005118 return NO_ERROR;
5119 }
5120 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005121 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005122 // daltonize
5123 n = data.readInt32();
5124 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005125 case 1:
5126 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5127 break;
5128 case 2:
5129 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5130 break;
5131 case 3:
5132 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5133 break;
5134 default:
5135 mDaltonizer.setType(ColorBlindnessType::None);
5136 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005137 }
5138 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005139 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005140 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005141 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005142 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005143
5144 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005145 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005146 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005147 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005148 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005149 // apply a color matrix
5150 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005151 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005152 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005153 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005154 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005155 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005156 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005157 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005158 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005159 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005160 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005161
5162 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5163 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005164 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005165 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5166 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5167 }
5168
Chia-I Wu28f320b2018-05-03 11:02:56 -07005169 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005170 return NO_ERROR;
5171 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005172 // This is an experimental interface
5173 // Needs to be shifted to proper binder interface when we productize
5174 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005175 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005176 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005177 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005178 return NO_ERROR;
5179 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005180 case 1017: {
5181 n = data.readInt32();
5182 mForceFullDamage = static_cast<bool>(n);
5183 return NO_ERROR;
5184 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005185 case 1018: { // Modify Choreographer's phase offset
5186 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005187 if (mUseScheduler) {
5188 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5189 } else {
5190 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5191 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005192 return NO_ERROR;
5193 }
5194 case 1019: { // Modify SurfaceFlinger's phase offset
5195 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005196 if (mUseScheduler) {
5197 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5198 } else {
5199 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5200 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005201 return NO_ERROR;
5202 }
Irvel468051e2016-06-13 16:44:44 -07005203 case 1020: { // Layer updates interceptor
5204 n = data.readInt32();
5205 if (n) {
5206 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005207 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005208 }
5209 else{
5210 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005211 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005212 }
5213 return NO_ERROR;
5214 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005215 case 1021: { // Disable HWC virtual displays
5216 n = data.readInt32();
5217 mUseHwcVirtualDisplays = !n;
5218 return NO_ERROR;
5219 }
Romain Guy0147a172017-06-01 13:53:56 -07005220 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005221 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005222 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005223
Chia-I Wu28f320b2018-05-03 11:02:56 -07005224 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005225 return NO_ERROR;
5226 }
Romain Guy54f154a2017-10-24 21:40:32 +01005227 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005228 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005229 invalidateHwcGeometry();
5230 repaintEverything();
5231 return NO_ERROR;
5232 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005233 // Deprecate, use 1030 to check whether the device is color managed.
5234 case 1024: {
5235 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005236 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005237 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005238 n = data.readInt32();
5239 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005240 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005241 mTracing.enable();
5242 doTracing("tracing.enable");
5243 reply->writeInt32(NO_ERROR);
5244 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005245 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005246 status_t err = mTracing.disable();
5247 reply->writeInt32(err);
5248 }
5249 return NO_ERROR;
5250 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005251 case 1026: { // Get layer tracing status
5252 reply->writeBool(mTracing.isEnabled());
5253 return NO_ERROR;
5254 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005255 // Is a DisplayColorSetting supported?
5256 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005257 const auto display = getDefaultDisplayDevice();
5258 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005259 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005260 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005261
5262 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5263 switch (setting) {
5264 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005265 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005266 break;
5267 case DisplayColorSetting::UNMANAGED:
5268 reply->writeBool(true);
5269 break;
5270 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005271 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005272 break;
5273 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005274 reply->writeBool(
5275 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005276 break;
5277 }
5278 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005279 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005280 // Is VrFlinger active?
5281 case 1028: {
5282 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005283 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005284 return NO_ERROR;
5285 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005286 // Is device color managed?
5287 case 1030: {
5288 reply->writeBool(useColorManagement);
5289 return NO_ERROR;
5290 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005291 // Override default composition data space
5292 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5293 // && adb shell stop zygote && adb shell start zygote
5294 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5295 // adb shell stop zygote && adb shell start zygote
5296 case 1031: {
5297 Mutex::Autolock _l(mStateLock);
5298 n = data.readInt32();
5299 if (n) {
5300 n = data.readInt32();
5301 if (n) {
5302 Dataspace dataspace = static_cast<Dataspace>(n);
5303 if (!validateCompositionDataspace(dataspace)) {
5304 return BAD_VALUE;
5305 }
5306 mDefaultCompositionDataspace = dataspace;
5307 }
5308 n = data.readInt32();
5309 if (n) {
5310 Dataspace dataspace = static_cast<Dataspace>(n);
5311 if (!validateCompositionDataspace(dataspace)) {
5312 return BAD_VALUE;
5313 }
5314 mWideColorGamutCompositionDataspace = dataspace;
5315 }
5316 } else {
5317 // restore composition data space.
5318 mDefaultCompositionDataspace = defaultCompositionDataspace;
5319 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5320 }
5321 return NO_ERROR;
5322 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005323 }
5324 }
5325 return err;
5326}
5327
Steven Thomas6d8110b2017-08-31 18:24:21 -07005328void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005329 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005330 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005331}
5332
Ana Krulec7d1d6832018-12-27 11:10:09 -08005333void SurfaceFlinger::repaintEverythingForHWC() {
5334 mRepaintEverything = true;
5335 mEventQueue->invalidateForHWC();
5336}
5337
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005338// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5339class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005340public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005341 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5342 ~WindowDisconnector() {
5343 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005344 }
5345
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005346private:
5347 ANativeWindow* mWindow;
5348 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005349};
5350
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005351status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005352 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5353 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005354 uint32_t reqWidth, uint32_t reqHeight,
5355 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005356 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005357 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005358
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005359 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005360
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005361 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5362
Chia-I Wu20261cb2018-08-23 12:55:44 -07005363 sp<DisplayDevice> display;
5364 {
5365 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005366
Chia-I Wu20261cb2018-08-23 12:55:44 -07005367 display = getDisplayDeviceLocked(displayToken);
5368 if (!display) return BAD_VALUE;
5369
Chia-I Wucb023152018-08-28 12:57:23 -07005370 // set the requested width/height to the logical display viewport size
5371 // by default
5372 if (reqWidth == 0 || reqHeight == 0) {
5373 reqWidth = uint32_t(display->getViewport().width());
5374 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005375 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005376 }
5377
Peiyong Lin0e003c92018-09-17 11:09:51 -07005378 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5379 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005380
5381 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005382 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005383 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5384 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005385}
5386
5387status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005388 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5389 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005390 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005391 ATRACE_CALL();
5392
5393 class LayerRenderArea : public RenderArea {
5394 public:
Robert Carr578038f2018-03-09 12:25:24 -08005395 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005396 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5397 bool childrenOnly)
5398 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005399 mLayer(layer),
5400 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005401 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005402 mFlinger(flinger),
5403 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005404 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005405 Rect getBounds() const override {
5406 const Layer::State& layerState(mLayer->getDrawingState());
5407 return mLayer->getBufferSize(layerState);
5408 }
Marissa Wall61c58622018-07-18 10:12:20 -07005409 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005410 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005411 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005412 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005413 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005414 }
chaviwa76b2712017-09-20 12:02:26 -07005415 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005416 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005417 Rect getSourceCrop() const override {
5418 if (mCrop.isEmpty()) {
5419 return getBounds();
5420 } else {
5421 return mCrop;
5422 }
5423 }
Robert Carr578038f2018-03-09 12:25:24 -08005424 class ReparentForDrawing {
5425 public:
5426 const sp<Layer>& oldParent;
5427 const sp<Layer>& newParent;
5428
5429 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5430 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005431 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005432 }
Robert Carr15eae092018-03-23 13:43:53 -07005433 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005434 };
5435
5436 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005437 const Rect sourceCrop = getSourceCrop();
5438 // no need to check rotation because there is none
5439 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5440 sourceCrop.height() != getReqHeight();
5441
Robert Carr578038f2018-03-09 12:25:24 -08005442 if (!mChildrenOnly) {
5443 mTransform = mLayer->getTransform().inverse();
5444 drawLayers();
5445 } else {
5446 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005447 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005448 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5449 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005450
5451 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5452 drawLayers();
5453 }
5454 }
chaviwa76b2712017-09-20 12:02:26 -07005455
chaviwa76b2712017-09-20 12:02:26 -07005456 private:
chaviw7206d492017-11-10 16:16:12 -08005457 const sp<Layer> mLayer;
5458 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005459
5460 // In the "childrenOnly" case we reparent the children to a screenshot
5461 // layer which has no properties set and which does not draw.
5462 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005463 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005464 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005465
5466 SurfaceFlinger* mFlinger;
5467 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005468 };
5469
5470 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5471 auto parent = layerHandle->owner.promote();
5472
Robert Carr2e102c92018-10-23 12:11:15 -07005473 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005474 ALOGE("captureLayers called with a removed parent");
5475 return NAME_NOT_FOUND;
5476 }
5477
Robert Carr578038f2018-03-09 12:25:24 -08005478 const int uid = IPCThreadState::self()->getCallingUid();
5479 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005480 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005481 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5482 return PERMISSION_DENIED;
5483 }
5484
chaviw7206d492017-11-10 16:16:12 -08005485 Rect crop(sourceCrop);
5486 if (sourceCrop.width() <= 0) {
5487 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005488 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005489 }
5490
5491 if (sourceCrop.height() <= 0) {
5492 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005493 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005494 }
5495
5496 int32_t reqWidth = crop.width() * frameScale;
5497 int32_t reqHeight = crop.height() * frameScale;
5498
Chia-I Wu20261cb2018-08-23 12:55:44 -07005499 // really small crop or frameScale
5500 if (reqWidth <= 0) {
5501 reqWidth = 1;
5502 }
5503 if (reqHeight <= 0) {
5504 reqHeight = 1;
5505 }
5506
Peiyong Lin0e003c92018-09-17 11:09:51 -07005507 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005508
Robert Carr578038f2018-03-09 12:25:24 -08005509 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005510 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5511 if (!layer->isVisible()) {
5512 return;
Robert Carr578038f2018-03-09 12:25:24 -08005513 } else if (childrenOnly && layer == parent.get()) {
5514 return;
chaviwa76b2712017-09-20 12:02:26 -07005515 }
5516 visitor(layer);
5517 });
5518 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005519 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005520}
5521
5522status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5523 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005524 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005525 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005526 bool useIdentityTransform) {
5527 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005528
Peiyong Lin0e003c92018-09-17 11:09:51 -07005529 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005530 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5531 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005532 *outBuffer =
5533 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5534 static_cast<android_pixel_format>(reqPixelFormat), 1,
5535 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005536
5537 // This mutex protects syncFd and captureResult for communication of the return values from the
5538 // main thread back to this Binder thread
5539 std::mutex captureMutex;
5540 std::condition_variable captureCondition;
5541 std::unique_lock<std::mutex> captureLock(captureMutex);
5542 int syncFd = -1;
5543 std::optional<status_t> captureResult;
5544
Robert Carr03480e22018-01-04 16:02:06 -08005545 const int uid = IPCThreadState::self()->getCallingUid();
5546 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5547
Dominik Laskowski8c001672018-05-30 16:52:06 -07005548 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005549 // If there is a refresh pending, bug out early and tell the binder thread to try again
5550 // after the refresh.
5551 if (mRefreshPending) {
5552 ATRACE_NAME("Skipping screenshot for now");
5553 std::unique_lock<std::mutex> captureLock(captureMutex);
5554 captureResult = std::make_optional<status_t>(EAGAIN);
5555 captureCondition.notify_one();
5556 return;
5557 }
5558
5559 status_t result = NO_ERROR;
5560 int fd = -1;
5561 {
5562 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005563 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005564 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5565 useIdentityTransform, forSystem, &fd);
5566 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005567 }
5568
5569 {
5570 std::unique_lock<std::mutex> captureLock(captureMutex);
5571 syncFd = fd;
5572 captureResult = std::make_optional<status_t>(result);
5573 captureCondition.notify_one();
5574 }
5575 });
5576
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005577 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005578 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005579 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005580 while (*captureResult == EAGAIN) {
5581 captureResult.reset();
5582 result = postMessageAsync(message);
5583 if (result != NO_ERROR) {
5584 return result;
5585 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005586 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005587 }
5588 result = *captureResult;
5589 }
5590
5591 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005592 sync_wait(syncFd, -1);
5593 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005594 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005595
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005596 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005597}
5598
chaviwa76b2712017-09-20 12:02:26 -07005599void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005600 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005601 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005602 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005603
Lloyd Pique144e1162017-12-20 16:44:52 -08005604 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005605
chaviwa76b2712017-09-20 12:02:26 -07005606 const auto reqWidth = renderArea.getReqWidth();
5607 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005608 const auto sourceCrop = renderArea.getSourceCrop();
5609 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005610
Peiyong Lin0e003c92018-09-17 11:09:51 -07005611 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005612 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005613
Mathias Agopian180f10d2013-04-10 22:55:41 -07005614 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005615 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005616
5617 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005618 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005619 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005620
chaviw50da5042018-04-09 13:49:37 -07005621 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005622 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005623 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005624
chaviwa76b2712017-09-20 12:02:26 -07005625 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005626 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005627 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005628 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005629 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005630}
5631
chaviwa76b2712017-09-20 12:02:26 -07005632status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5633 TraverseLayersFunction traverseLayers,
5634 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005635 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005636 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005637 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005638 ATRACE_CALL();
5639
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005640 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005641
5642 traverseLayers([&](Layer* layer) {
5643 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5644 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005645
Robert Carr03480e22018-01-04 16:02:06 -08005646 // We allow the system server to take screenshots of secure layers for
5647 // use in situations like the Screen-rotation animation and place
5648 // the impetus on WindowManager to not persist them.
5649 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005650 ALOGW("FB is protected: PERMISSION_DENIED");
5651 return PERMISSION_DENIED;
5652 }
Peiyong Linfb530cf2018-12-15 05:07:38 +00005653 auto& engine(getRenderEngine());
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005654
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005655 // this binds the given EGLImage as a framebuffer for the
5656 // duration of this scope.
Peiyong Linfb530cf2018-12-15 05:07:38 +00005657 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005658 if (bufferBond.getStatus() != NO_ERROR) {
5659 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005660 return INVALID_OPERATION;
5661 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005662
Dan Stozaabcda352017-06-01 14:37:39 -07005663 // this will in fact render into our dequeued buffer
5664 // via an FBO, which means we didn't have to create
5665 // an EGLSurface and therefore we're not
5666 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005667 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005668
Peiyong Linfb530cf2018-12-15 05:07:38 +00005669 base::unique_fd syncFd = engine.flush();
Alec Mouri492bc572018-09-11 21:40:04 +00005670 if (syncFd < 0) {
Peiyong Linfb530cf2018-12-15 05:07:38 +00005671 engine.finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005672 }
Alec Mouri492bc572018-09-11 21:40:04 +00005673 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005674
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005675 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005676}
5677
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005678// ---------------------------------------------------------------------------
5679
Dan Stoza412903f2017-04-27 13:42:17 -07005680void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5681 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005682}
5683
Dan Stoza412903f2017-04-27 13:42:17 -07005684void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5685 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005686}
5687
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005688void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005689 const LayerVector::Visitor& visitor) {
5690 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005691 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005692 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005693 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005694 continue;
5695 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005696 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005697 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005698 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005699 return;
5700 }
chaviwa76b2712017-09-20 12:02:26 -07005701 if (!layer->isVisible()) {
5702 return;
5703 }
5704 visitor(layer);
5705 });
5706 }
5707}
5708
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005709}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005710
Lloyd Pique074e8122018-07-26 12:57:23 -07005711
Mathias Agopian3f844832013-08-07 21:24:32 -07005712#if defined(__gl_h_)
5713#error "don't include gl/gl.h in this file"
5714#endif
5715
5716#if defined(__gl2_h_)
5717#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005718#endif