blob: 0bbaf5c41209d0abc617b8ade381821c4673e630 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Lloyd Pique70d91362018-10-18 16:02:55 -070038#include <compositionengine/CompositionEngine.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070039#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070040#include <compositionengine/DisplayColorProfile.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070041#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070042#include <compositionengine/impl/OutputCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080043#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080047#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070050#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070051#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070052#include <ui/ColorSpace.h>
53#include <ui/DebugUtils.h>
54#include <ui/DisplayInfo.h>
55#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070056#include <ui/GraphicBufferAllocator.h>
57#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070058#include <ui/UiConfig.h>
Ady Abraham8164d482019-01-11 14:47:59 -080059#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070061#include <utils/String16.h>
62#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070063#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080064#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070065#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080066
Mathias Agopian921e6ac2012-07-23 23:11:29 -070067#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070068#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080069
Robert Carr578038f2018-03-09 12:25:24 -080070#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070071#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070072#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020073#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080074#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020075#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080076#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080077#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070080#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080081#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070082#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070083#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070085#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080086
Steven Thomasb02664d2017-07-26 18:48:28 -070087#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070088#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070089#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070090#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070091#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070092#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070093#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070094#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070095#include "Scheduler/EventControlThread.h"
96#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070097#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070098#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070099#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800100#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700101
Mathias Agopianff2ed702013-09-01 21:36:12 -0700102#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700103
David Sodman7e4ae112018-02-09 15:02:28 -0800104#include "android-base/stringprintf.h"
105
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900106#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800107#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700108#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800109#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900110#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900111
chaviw1d044282017-09-27 12:19:28 -0700112#include <layerproto/LayerProtoParser.h>
113
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800114namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700115
Jaesoo Lee43518572017-01-23 19:03:16 +0900116using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900117using namespace android::hardware::configstore::V1_0;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800118using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700119using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700120using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700121using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700122using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900123
Steven Thomasb02664d2017-07-26 18:48:28 -0700124namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700125
126#pragma clang diagnostic push
127#pragma clang diagnostic error "-Wswitch-enum"
128
129bool isWideColorMode(const ColorMode colorMode) {
130 switch (colorMode) {
131 case ColorMode::DISPLAY_P3:
132 case ColorMode::ADOBE_RGB:
133 case ColorMode::DCI_P3:
134 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700135 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700136 case ColorMode::BT2100_PQ:
137 case ColorMode::BT2100_HLG:
138 return true;
139 case ColorMode::NATIVE:
140 case ColorMode::STANDARD_BT601_625:
141 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
142 case ColorMode::STANDARD_BT601_525:
143 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
144 case ColorMode::STANDARD_BT709:
145 case ColorMode::SRGB:
146 return false;
147 }
148 return false;
149}
150
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700151ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
152 switch (rotation) {
153 case ISurfaceComposer::eRotateNone:
154 return ui::Transform::ROT_0;
155 case ISurfaceComposer::eRotate90:
156 return ui::Transform::ROT_90;
157 case ISurfaceComposer::eRotate180:
158 return ui::Transform::ROT_180;
159 case ISurfaceComposer::eRotate270:
160 return ui::Transform::ROT_270;
161 }
162 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
163 return ui::Transform::ROT_0;
164}
165
Peiyong Linfca547f2018-07-09 13:03:33 -0700166#pragma clang diagnostic pop
167
Steven Thomasb02664d2017-07-26 18:48:28 -0700168class ConditionalLock {
169public:
170 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
171 if (lock) {
172 mMutex.lock();
173 }
174 }
175 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
176private:
177 Mutex& mMutex;
178 bool mLocked;
179};
Peiyong Linfca547f2018-07-09 13:03:33 -0700180
Peiyong Lin9d846a52018-11-05 13:18:20 -0800181// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
182bool validateCompositionDataspace(Dataspace dataspace) {
183 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
184}
185
Steven Thomasb02664d2017-07-26 18:48:28 -0700186} // namespace anonymous
187
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800188// ---------------------------------------------------------------------------
189
Mathias Agopian99b49842011-06-27 16:05:52 -0700190const String16 sHardwareTest("android.permission.HARDWARE_TEST");
191const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
192const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
193const String16 sDump("android.permission.DUMP");
194
195// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800196int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
197int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700198int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700199bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800200uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800201bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800202bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800203int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600204bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700205int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700206bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700207bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700208Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
209ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
210Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
211ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700212
Kalle Raitaa099a242017-01-11 11:17:29 -0800213std::string getHwcServiceName() {
214 char value[PROPERTY_VALUE_MAX] = {};
215 property_get("debug.sf.hwc_service_name", value, "default");
216 ALOGI("Using HWComposer service: '%s'", value);
217 return std::string(value);
218}
219
220bool useTrebleTestingOverride() {
221 char value[PROPERTY_VALUE_MAX] = {};
222 property_get("debug.sf.treble_testing_override", value, "false");
223 ALOGI("Treble testing override: '%s'", value);
224 return std::string(value) == "true";
225}
226
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800227std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
228 switch(displayColorSetting) {
229 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700230 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800231 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700232 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800233 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700234 return std::string("Enhanced");
235 default:
236 return std::string("Unknown ") +
237 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800238 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800239}
240
David Sodmanbc815282017-11-05 18:57:52 -0800241SurfaceFlingerBE::SurfaceFlingerBE()
242 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800243 mFrameBuckets(),
244 mTotalTime(0),
245 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800246 mComposerSequenceId(0) {
247}
248
Lloyd Pique90c115d2018-09-18 21:39:42 -0700249SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
250 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800251 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700252 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700253 mTransactionPending(false),
254 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700255 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700256 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257 mBootTime(systemTime()),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800258 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800259 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800260 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800261 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800262 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700263 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700264 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700265 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700266 mDebugInTransaction(0),
267 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700268 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800269 mTimeStats(factory.createTimeStats()),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700270 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700271 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800272 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800273 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800274 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700275 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700276 mMainThreadId(std::this_thread::get_id()),
277 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800278
Lloyd Pique90c115d2018-09-18 21:39:42 -0700279SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
280 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800281 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800282
283 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
284 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
285
286 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
287 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
288
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800289 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
290 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800291
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700292 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
293 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
294
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700295 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
296 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
297
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800298 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
299 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
300
Steven Thomas050b2c82017-03-06 11:45:16 -0800301 // Vr flinger is only enabled on Daydream ready devices.
302 useVrFlinger = getBool< ISurfaceFlingerConfigs,
303 &ISurfaceFlingerConfigs::useVrFlinger>(false);
304
Fabien Sanglard1971b632017-03-10 14:50:03 -0800305 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
306 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
307
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600308 hasWideColorDisplay =
309 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700310 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700311 getBool<V1_2::ISurfaceFlingerConfigs,
312 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
313
314 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
315 if (surfaceFlingerConfigsServiceV1_2) {
316 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
Peiyong Linc6780972018-10-28 15:24:08 -0700317 [&](auto tmpDefaultDataspace, auto tmpDefaultPixelFormat,
318 auto tmpWideColorGamutDataspace, auto tmpWideColorGamutPixelFormat) {
319 defaultCompositionDataspace = tmpDefaultDataspace;
320 defaultCompositionPixelFormat = tmpDefaultPixelFormat;
321 wideColorGamutCompositionDataspace = tmpWideColorGamutDataspace;
322 wideColorGamutCompositionPixelFormat = tmpWideColorGamutPixelFormat;
323 });
Peiyong Lin0256f722018-08-31 15:45:10 -0700324 }
Peiyong Lin9d846a52018-11-05 13:18:20 -0800325 mDefaultCompositionDataspace = defaultCompositionDataspace;
326 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600327
Peiyong Linb3839ad2018-09-05 15:37:19 -0700328 useContextPriority = getBool<ISurfaceFlingerConfigs,
329 &ISurfaceFlingerConfigs::useContextPriority>(true);
330
Iris Chang7501ed62018-04-30 14:45:42 +0800331 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700332 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
333 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800334 V1_1::DisplayOrientation::ORIENTATION_0);
335
336 switch (primaryDisplayOrientation) {
337 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700338 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800339 break;
340 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700341 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800342 break;
343 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700344 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800345 break;
346 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700347 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800348 break;
349 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700350 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800351
Lloyd Pique90c115d2018-09-18 21:39:42 -0700352 mPrimaryDispSync =
353 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
354 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700355
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800356 // debugging stuff...
357 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700358
Mathias Agopianb4b17302013-03-20 18:36:41 -0700359 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700360 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700361
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800362 property_get("debug.sf.showupdates", value, "0");
363 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700364
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700365 property_get("debug.sf.ddms", value, "0");
366 mDebugDDMS = atoi(value);
367 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700368 if (!startDdmConnection()) {
369 // start failed, and DDMS debugging not enabled
370 mDebugDDMS = 0;
371 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700372 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700373 ALOGI_IF(mDebugRegion, "showupdates enabled");
374 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700375
376 property_get("debug.sf.disable_backpressure", value, "0");
377 mPropagateBackpressure = !atoi(value);
378 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700379
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800380 property_get("debug.sf.enable_hwc_vds", value, "0");
381 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800382 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800383
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800384 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800385 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800386 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700387
Yiwei Zhang243b3782018-05-15 17:40:04 -0700388 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700389 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
390 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
391
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200392 property_get("debug.sf.early_phase_offset_ns", value, "-1");
393 const int earlySfOffsetNs = atoi(value);
394
395 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
396 const int earlyGlSfOffsetNs = atoi(value);
397
398 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
399 const int earlyAppOffsetNs = atoi(value);
400
401 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
402 const int earlyGlAppOffsetNs = atoi(value);
403
Ana Krulec98b5b242018-08-10 15:03:23 -0700404 property_get("debug.sf.use_scheduler", value, "0");
405 mUseScheduler = atoi(value);
406
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200407 const VSyncModulator::Offsets earlyOffsets =
408 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
409 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
410 const VSyncModulator::Offsets earlyGlOffsets =
411 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
412 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
413 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
414 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700415
Romain Guy11d63f42017-07-20 12:47:14 -0700416 // We should be reading 'persist.sys.sf.color_saturation' here
417 // but since /data may be encrypted, we need to wait until after vold
418 // comes online to attempt to read the property. The property is
419 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800420
421 if (useTrebleTestingOverride()) {
422 // Without the override SurfaceFlinger cannot connect to HIDL
423 // services that are not listed in the manifests. Considered
424 // deriving the setting from the set service name, but it
425 // would be brittle if the name that's not 'default' is used
426 // for production purposes later on.
427 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
428 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800429}
430
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800431void SurfaceFlinger::onFirstRef()
432{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800433 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800434}
435
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800436SurfaceFlinger::~SurfaceFlinger()
437{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800438}
439
Dan Stozac7014012014-02-14 15:03:43 -0800440void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800441{
442 // the window manager died on us. prepare its eulogy.
443
Andy McFadden13a082e2012-08-24 10:16:42 -0700444 // restore initial conditions (default device unblank, etc)
445 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800446
447 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700448 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800449}
450
Robert Carr1db73f62016-12-21 12:58:51 -0800451static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700452 status_t err = client->initCheck();
453 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800454 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800455 }
Robert Carr1db73f62016-12-21 12:58:51 -0800456 return nullptr;
457}
458
459sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
460 return initClient(new Client(this));
461}
462
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700463sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
464 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700465{
466 class DisplayToken : public BBinder {
467 sp<SurfaceFlinger> flinger;
468 virtual ~DisplayToken() {
469 // no more references, this display must be terminated
470 Mutex::Autolock _l(flinger->mStateLock);
471 flinger->mCurrentState.displays.removeItem(this);
472 flinger->setTransactionFlags(eDisplayTransactionNeeded);
473 }
474 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700475 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700476 : flinger(flinger) {
477 }
478 };
479
480 sp<BBinder> token = new DisplayToken(this);
481
482 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700483 // Display ID is assigned when virtual display is allocated by HWC.
484 DisplayDeviceState state;
485 state.isSecure = secure;
486 state.displayName = displayName;
487 mCurrentState.displays.add(token, state);
488 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700489 return token;
490}
491
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700492void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700493 Mutex::Autolock _l(mStateLock);
494
Dominik Laskowski075d3172018-05-24 15:50:06 -0700495 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
496 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700497 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700498 return;
499 }
500
Dominik Laskowski075d3172018-05-24 15:50:06 -0700501 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
502 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700503 ALOGE("destroyDisplay called for non-virtual display");
504 return;
505 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700506 mInterceptor->saveDisplayDeletion(state.sequenceId);
507 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700508 setTransactionFlags(eDisplayTransactionNeeded);
509}
510
Mathias Agopiane57f2922012-08-09 16:29:12 -0700511sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700512 std::optional<DisplayId> displayId;
513
514 if (id == HWC_DISPLAY_PRIMARY) {
515 displayId = getInternalDisplayId();
516 } else if (id == HWC_DISPLAY_EXTERNAL) {
517 displayId = getExternalDisplayId();
518 }
519
520 if (!displayId) {
521 ALOGE("%s: Invalid display %d", __FUNCTION__, id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800522 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700523 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700524
525 return getPhysicalDisplayToken(*displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700526}
527
Ady Abraham37965d42018-11-01 13:43:32 -0700528status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
529 if (!outGetColorManagement) {
530 return BAD_VALUE;
531 }
532 *outGetColorManagement = useColorManagement;
533 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700534}
535
Lloyd Pique441d5042018-10-18 16:49:51 -0700536HWComposer& SurfaceFlinger::getHwComposer() const {
537 return mCompositionEngine->getHwComposer();
538}
539
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700540renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
541 return mCompositionEngine->getRenderEngine();
542}
543
Lloyd Pique70d91362018-10-18 16:02:55 -0700544compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
545 return *mCompositionEngine.get();
546}
547
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800548void SurfaceFlinger::bootFinished()
549{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700550 if (mStartPropertySetThread->join() != NO_ERROR) {
551 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800552 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800553 const nsecs_t now = systemTime();
554 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000555 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700556
557 // wait patiently for the window manager death
558 const String16 name("window");
559 sp<IBinder> window(defaultServiceManager()->getService(name));
560 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700561 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700562 }
Robert Carr720e5062018-07-30 17:45:14 -0700563 sp<IBinder> input(defaultServiceManager()->getService(
564 String16("inputflinger")));
565 if (input == nullptr) {
566 ALOGE("Failed to link to input service");
567 } else {
568 mInputFlinger = interface_cast<IInputFlinger>(input);
569 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700570
Steven Thomas050b2c82017-03-06 11:45:16 -0800571 if (mVrFlinger) {
572 mVrFlinger->OnBootFinished();
573 }
574
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700575 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700576 // formerly we would just kill the process, but we now ask it to exit so it
577 // can choose where to stop the animation.
578 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700579
580 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
581 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
582 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700583
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800584 postMessageAsync(new LambdaMessage([this] {
585 readPersistentProperties();
586 mBootStage = BootStage::FINISHED;
587 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800588}
589
Dan Stoza436ccf32018-06-21 12:10:12 -0700590uint32_t SurfaceFlinger::getNewTexture() {
591 {
592 std::lock_guard lock(mTexturePoolMutex);
593 if (!mTexturePool.empty()) {
594 uint32_t name = mTexturePool.back();
595 mTexturePool.pop_back();
596 ATRACE_INT("TexturePoolSize", mTexturePool.size());
597 return name;
598 }
599
600 // The pool was too small, so increase it for the future
601 ++mTexturePoolSize;
602 }
603
604 // The pool was empty, so we need to get a new texture name directly using a
605 // blocking call to the main thread
606 uint32_t name = 0;
607 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
608 return name;
609}
610
Mathias Agopian3f844832013-08-07 21:24:32 -0700611void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700612 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700613}
614
Wei Wangf9b05ee2017-07-19 20:59:39 -0700615// Do not call property_set on main thread which will be blocked by init
616// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700617void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700618 ALOGI( "SurfaceFlinger's main thread ready to run. "
619 "Initializing graphics H/W...");
620
Thierry Strudel2924d012017-08-14 15:19:37 -0700621 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900622
Steven Thomasb02664d2017-07-26 18:48:28 -0700623 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800624
Steven Thomasb02664d2017-07-26 18:48:28 -0700625 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700626 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700627 mScheduler = getFactory().createScheduler([this](bool enabled) {
628 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
629 });
630
Ana Krulec98b5b242018-08-10 15:03:23 -0700631 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700632 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700633 [this] { resyncWithRateLimit(); },
634 impl::EventThread::InterceptVSyncsCallback());
635 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700636 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700637 [this] { resyncWithRateLimit(); },
638 [this](nsecs_t timestamp) {
639 mInterceptor->saveVSyncEvent(timestamp);
640 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800641
Ana Krulec98b5b242018-08-10 15:03:23 -0700642 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700643 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
644 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700645 } else {
646 mEventThreadSource =
647 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
648 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
649 mEventThread =
650 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
651 [this] { resyncWithRateLimit(); },
652 impl::EventThread::InterceptVSyncsCallback(),
653 "appEventThread");
654 mSfEventThreadSource =
655 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
656 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
657
658 mSFEventThread =
659 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
660 [this] { resyncWithRateLimit(); },
661 [this](nsecs_t timestamp) {
662 mInterceptor->saveVSyncEvent(timestamp);
663 },
664 "sfEventThread");
665 mEventQueue->setEventThread(mSFEventThread.get());
666 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
667 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800668
Steven Thomasb02664d2017-07-26 18:48:28 -0700669 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700670 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700671 renderEngineFeature |= (useColorManagement ?
672 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700673 renderEngineFeature |= (useContextPriority ?
674 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700675
676 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700677 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700678 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700679 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700680
681 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
682 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700683 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
684 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800685 // Process any initial hotplug and resulting display changes.
686 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700687 const auto display = getDefaultDisplayDeviceLocked();
688 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700689 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700690 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800691
Steven Thomas050b2c82017-03-06 11:45:16 -0800692 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700693 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700694 // This callback is called from the vr flinger dispatch thread. We
695 // need to call signalTransaction(), which requires holding
696 // mStateLock when we're not on the main thread. Acquiring
697 // mStateLock from the vr flinger dispatch thread might trigger a
698 // deadlock in surface flinger (see b/66916578), so post a message
699 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700700 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700701 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
702 mVrFlingerRequestsDisplay = requestDisplay;
703 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700704 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800705 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700706 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
707 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700708 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700709 .value_or(0),
710 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800711 if (!mVrFlinger) {
712 ALOGE("Failed to start vrflinger");
713 }
714 }
715
Lloyd Pique90c115d2018-09-18 21:39:42 -0700716 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700717 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700718
Mathias Agopian92a979a2012-08-02 18:32:23 -0700719 // initialize our drawing state
720 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700721
Andy McFadden13a082e2012-08-24 10:16:42 -0700722 // set initial conditions (e.g. unblank default device)
723 initializeDisplays();
724
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700725 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700726
Wei Wangf9b05ee2017-07-19 20:59:39 -0700727 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700728
729 const bool presentFenceReliable =
730 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
731 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700732
733 if (mStartPropertySetThread->Start() != NO_ERROR) {
734 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800735 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800736
Ana Krulec7d1d6832018-12-27 11:10:09 -0800737 if (mUseScheduler) {
738 mScheduler->setExpiredIdleTimerCallback([this]() { setRefreshRateTo(60.f /* fps */); });
739 mScheduler->setResetIdleTimerCallback([this]() { setRefreshRateTo(90.f /* fps */); });
740 }
741
Dan Stoza9e56aa02015-11-02 13:00:03 -0800742 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700743}
744
Romain Guy11d63f42017-07-20 12:47:14 -0700745void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700746 Mutex::Autolock _l(mStateLock);
747
Romain Guy11d63f42017-07-20 12:47:14 -0700748 char value[PROPERTY_VALUE_MAX];
749
750 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800751 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700752 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800753 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100754
755 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700756 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700757}
758
Mathias Agopiana67e4182012-06-19 17:26:12 -0700759void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800760 // Start boot animation service by setting a property mailbox
761 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700762 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800763 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700764 if (mStartPropertySetThread->join() != NO_ERROR) {
765 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800766 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700767}
768
Mathias Agopian875d8e12013-06-07 15:35:48 -0700769size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700770 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700771}
772
Mathias Agopian875d8e12013-06-07 15:35:48 -0700773size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700774 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700775}
776
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800777// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800778
Jamie Gennis582270d2011-08-17 18:19:00 -0700779bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800780 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800781 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800782 return authenticateSurfaceTextureLocked(bufferProducer);
783}
784
785bool SurfaceFlinger::authenticateSurfaceTextureLocked(
786 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800787 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800788 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800789}
790
Brian Anderson6b376712017-04-04 10:51:39 -0700791status_t SurfaceFlinger::getSupportedFrameTimestamps(
792 std::vector<FrameEvent>* outSupported) const {
793 *outSupported = {
794 FrameEvent::REQUESTED_PRESENT,
795 FrameEvent::ACQUIRE,
796 FrameEvent::LATCH,
797 FrameEvent::FIRST_REFRESH_START,
798 FrameEvent::LAST_REFRESH_START,
799 FrameEvent::GPU_COMPOSITION_DONE,
800 FrameEvent::DEQUEUE_READY,
801 FrameEvent::RELEASE,
802 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700803 ConditionalLock _l(mStateLock,
804 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700805 if (!getHwComposer().hasCapability(
806 HWC2::Capability::PresentFenceIsNotReliable)) {
807 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
808 }
809 return NO_ERROR;
810}
811
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700812status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
813 Vector<DisplayInfo>* configs) {
814 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700815 return BAD_VALUE;
816 }
817
Dominik Laskowski075d3172018-05-24 15:50:06 -0700818 const auto displayId = getPhysicalDisplayId(displayToken);
819 if (!displayId) {
820 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700821 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700822
Mathias Agopian8b736f12012-08-13 17:54:26 -0700823 // TODO: Not sure if display density should handled by SF any longer
824 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700825 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700826 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700827 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800828 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700829 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700830 }
831 return density;
832 }
833 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700834 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700835 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700836 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700837 return getDensityFromProperty("ro.sf.lcd_density"); }
838 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700839
Dan Stoza7f7da322014-05-02 15:26:25 -0700840 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700841
Steven Thomas6d8110b2017-08-31 18:24:21 -0700842 ConditionalLock _l(mStateLock,
843 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700844 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700845 DisplayInfo info = DisplayInfo();
846
Dan Stoza9e56aa02015-11-02 13:00:03 -0800847 float xdpi = hwConfig->getDpiX();
848 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700849
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700850 info.w = hwConfig->getWidth();
851 info.h = hwConfig->getHeight();
852 // Default display viewport to display width and height
853 info.viewportW = info.w;
854 info.viewportH = info.h;
855
Dominik Laskowski075d3172018-05-24 15:50:06 -0700856 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700857 // The density of the device is provided by a build property
858 float density = Density::getBuildDensity() / 160.0f;
859 if (density == 0) {
860 // the build doesn't provide a density -- this is wrong!
861 // use xdpi instead
862 ALOGE("ro.sf.lcd_density must be defined as a build property");
863 density = xdpi / 160.0f;
864 }
865 if (Density::getEmuDensity()) {
866 // if "qemu.sf.lcd_density" is specified, it overrides everything
867 xdpi = ydpi = density = Density::getEmuDensity();
868 density /= 160.0f;
869 }
870 info.density = density;
871
872 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700873 const auto display = getDefaultDisplayDeviceLocked();
874 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700875
876 // This is for screenrecord
877 const Rect viewport = display->getViewport();
878 if (viewport.isValid()) {
879 info.viewportW = uint32_t(viewport.getWidth());
880 info.viewportH = uint32_t(viewport.getHeight());
881 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700882 } else {
883 // TODO: where should this value come from?
884 static const int TV_DENSITY = 213;
885 info.density = TV_DENSITY / 160.0f;
886 info.orientation = 0;
887 }
888
Dan Stoza7f7da322014-05-02 15:26:25 -0700889 info.xdpi = xdpi;
890 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800891 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900892 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800893
Andy McFadden91b2ca82014-06-13 14:04:23 -0700894 // This is how far in advance a buffer must be queued for
895 // presentation at a given time. If you want a buffer to appear
896 // on the screen at time N, you must submit the buffer before
897 // (N - presentationDeadline).
898 //
899 // Normally it's one full refresh period (to give SF a chance to
900 // latch the buffer), but this can be reduced by configuring a
901 // DispSync offset. Any additional delays introduced by the hardware
902 // composer or panel must be accounted for here.
903 //
904 // We add an additional 1ms to allow for processing time and
905 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800906 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800907 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700908
909 // All non-virtual displays are currently considered secure.
910 info.secure = true;
911
Dominik Laskowski075d3172018-05-24 15:50:06 -0700912 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700913 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800914 std::swap(info.w, info.h);
915 }
916
Michael Wright28f24d02016-07-12 13:30:53 -0700917 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700918 }
919
Dan Stoza7f7da322014-05-02 15:26:25 -0700920 return NO_ERROR;
921}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700922
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700923status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
924 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700925 return BAD_VALUE;
926 }
927
Ana Krulece588e312018-09-18 12:32:24 -0700928 if (mUseScheduler) {
929 mScheduler->getDisplayStatInfo(stats);
930 } else {
931 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
932 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
933 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700934 return NO_ERROR;
935}
936
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700937int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
938 const auto display = getDisplayDevice(displayToken);
939 if (!display) {
940 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800941 return BAD_VALUE;
942 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700943
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700944 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700945}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700946
Ana Krulec7d1d6832018-12-27 11:10:09 -0800947status_t SurfaceFlinger::setActiveConfigAsync(const sp<IBinder>& displayToken, int mode) {
948 ATRACE_NAME("setActiveConfigAsync");
949 postMessageAsync(new LambdaMessage([=] { setActiveConfigInternal(displayToken, mode); }));
950 return NO_ERROR;
951}
952
953status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
954 ATRACE_NAME("setActiveConfigSync");
955 postMessageSync(new LambdaMessage([&] { setActiveConfigInternal(displayToken, mode); }));
956 return NO_ERROR;
957}
958
959void SurfaceFlinger::setActiveConfigInternal(const sp<IBinder>& displayToken, int mode) {
960 Vector<DisplayInfo> configs;
961 getDisplayConfigs(displayToken, &configs);
962 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
963 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
964 return;
965 }
966
967 const auto display = getDisplayDevice(displayToken);
968 if (!display) {
969 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
970 displayToken.get());
971 return;
972 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700973 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800974 ALOGW("Attempt to set active config %d for virtual display", mode);
975 return;
976 }
977 int currentDisplayPowerMode = display->getPowerMode();
978 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
979 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700980 return;
981 }
982
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700983 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700984 if (mode == currentMode) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800985 // Don't update config if we are already running in the desired mode.
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700986 return;
987 }
988
Dominik Laskowski075d3172018-05-24 15:50:06 -0700989 const auto displayId = display->getId();
990 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700991
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700992 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700993 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700994
Ana Krulec7d1d6832018-12-27 11:10:09 -0800995 ATRACE_INT("ActiveConfigMode", mode);
996 resyncToHardwareVsync(true);
Mathias Agopianc666cae2012-07-25 18:56:13 -0700997}
Dominik Laskowski075d3172018-05-24 15:50:06 -0700998
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700999status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1000 Vector<ColorMode>* outColorModes) {
1001 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001002 return BAD_VALUE;
1003 }
1004
Dominik Laskowski075d3172018-05-24 15:50:06 -07001005 const auto displayId = getPhysicalDisplayId(displayToken);
1006 if (!displayId) {
1007 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -07001008 }
1009
Peiyong Lina52f0292018-03-14 17:26:31 -07001010 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001011 {
1012 ConditionalLock _l(mStateLock,
1013 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001014 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001015 }
Michael Wright28f24d02016-07-12 13:30:53 -07001016 outColorModes->clear();
1017 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1018
1019 return NO_ERROR;
1020}
1021
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001022ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1023 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001024 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001025 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001026 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001027}
1028
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001029status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001030 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001031 Vector<ColorMode> modes;
1032 getDisplayColorModes(displayToken, &modes);
1033 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1034 if (mode < ColorMode::NATIVE || !exists) {
1035 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1036 decodeColorMode(mode).c_str(), mode, displayToken.get());
1037 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001038 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001039 const auto display = getDisplayDevice(displayToken);
1040 if (!display) {
1041 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1042 decodeColorMode(mode).c_str(), mode, displayToken.get());
1043 } else if (display->isVirtual()) {
1044 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1045 decodeColorMode(mode).c_str(), mode);
1046 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001047 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1048 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001049 }
1050 }));
1051
Michael Wright28f24d02016-07-12 13:30:53 -07001052 return NO_ERROR;
1053}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001054
Svetoslavd85084b2014-03-20 10:28:31 -07001055status_t SurfaceFlinger::clearAnimationFrameStats() {
1056 Mutex::Autolock _l(mStateLock);
1057 mAnimFrameTracker.clearStats();
1058 return NO_ERROR;
1059}
1060
1061status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1062 Mutex::Autolock _l(mStateLock);
1063 mAnimFrameTracker.getStats(outStats);
1064 return NO_ERROR;
1065}
1066
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001067status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1068 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001069 Mutex::Autolock _l(mStateLock);
1070
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001071 const auto display = getDisplayDeviceLocked(displayToken);
1072 if (!display) {
1073 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001074 return BAD_VALUE;
1075 }
1076
Peiyong Linfb069302018-04-25 14:34:31 -07001077 // At this point the DisplayDeivce should already be set up,
1078 // meaning the luminance information is already queried from
1079 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001080 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001081 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1082 capabilities.getDesiredMaxLuminance(),
1083 capabilities.getDesiredMaxAverageLuminance(),
1084 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001085
1086 return NO_ERROR;
1087}
1088
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001089status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1090 ui::PixelFormat* outFormat,
1091 ui::Dataspace* outDataspace,
1092 uint8_t* outComponentMask) const {
1093 if (!outFormat || !outDataspace || !outComponentMask) {
1094 return BAD_VALUE;
1095 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001096 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001097 if (!display || !display->getId()) {
1098 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1099 return BAD_VALUE;
1100 }
1101 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1102 outDataspace, outComponentMask);
1103}
1104
Kevin DuBois74e53772018-11-19 10:52:38 -08001105status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1106 bool enable, uint8_t componentMask,
1107 uint64_t maxFrames) const {
1108 const auto display = getDisplayDevice(displayToken);
1109 if (!display || !display->getId()) {
1110 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1111 return BAD_VALUE;
1112 }
1113
1114 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1115 componentMask, maxFrames);
1116}
1117
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001118status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1119 uint64_t maxFrames, uint64_t timestamp,
1120 DisplayedFrameStats* outStats) const {
1121 const auto display = getDisplayDevice(displayToken);
1122 if (!display || !display->getId()) {
1123 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1124 return BAD_VALUE;
1125 }
1126
1127 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1128 outStats);
1129}
1130
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001131status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001132 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001133 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001134
Chia-I Wu90f669f2017-10-05 14:24:41 -07001135 if (mInjectVSyncs == enable) {
1136 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001137 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001138
Ana Krulec98b5b242018-08-10 15:03:23 -07001139 // TODO(akrulec): Part of the Injector should be refactored, so that it
1140 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001141 if (enable) {
1142 ALOGV("VSync Injections enabled");
1143 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001144 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001145 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001146 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001147 impl::EventThread::InterceptVSyncsCallback(),
1148 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001149 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001150 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001151 } else {
1152 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001153 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001154 }
1155
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001156 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001157 }));
1158
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001159 return NO_ERROR;
1160}
1161
1162status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001163 Mutex::Autolock _l(mStateLock);
1164
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001165 if (!mInjectVSyncs) {
1166 ALOGE("VSync Injections not enabled");
1167 return BAD_VALUE;
1168 }
1169 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1170 ALOGV("Injecting VSync inside SurfaceFlinger");
1171 mVSyncInjector->onInjectSyncEvent(when);
1172 }
1173 return NO_ERROR;
1174}
1175
Lloyd Pique755e3192018-01-31 16:46:15 -08001176status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1177 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001178 // Try to acquire a lock for 1s, fail gracefully
1179 const status_t err = mStateLock.timedLock(s2ns(1));
1180 const bool locked = (err == NO_ERROR);
1181 if (!locked) {
1182 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1183 return TIMED_OUT;
1184 }
1185
1186 outLayers->clear();
1187 mCurrentState.traverseInZOrder([&](Layer* layer) {
1188 outLayers->push_back(layer->getLayerDebugInfo());
1189 });
1190
1191 mStateLock.unlock();
1192 return NO_ERROR;
1193}
1194
Peiyong Linc6780972018-10-28 15:24:08 -07001195status_t SurfaceFlinger::getCompositionPreference(
1196 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1197 Dataspace* outWideColorGamutDataspace,
1198 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001199 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001200 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001201 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001202 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001203 return NO_ERROR;
1204}
1205
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001206// ----------------------------------------------------------------------------
1207
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001208sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1209 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001210 if (mUseScheduler) {
1211 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1212 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1213 } else {
1214 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1215 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001216 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001217 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1218 return mSFEventThread->createEventConnection();
1219 } else {
1220 return mEventThread->createEventConnection();
1221 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001222 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001223}
1224
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001225// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001226
1227void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001228 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001229}
1230
1231void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001232 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001233}
1234
1235void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001236 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001237}
1238
1239void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001240 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001241 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001242}
1243
1244status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001245 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001246 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001247}
1248
1249status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001250 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001251 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001252 if (res == NO_ERROR) {
1253 msg->wait();
1254 }
1255 return res;
1256}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001257
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001258void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001259 do {
1260 waitForEvent();
1261 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001262}
1263
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001264void SurfaceFlinger::enableHardwareVsync() {
1265 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001266 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001267 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001268 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001269 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001270 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001271}
1272
Jesse Hall948fe0c2013-10-14 12:56:09 -07001273void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001274 Mutex::Autolock _l(mHWVsyncLock);
1275
Jesse Hall948fe0c2013-10-14 12:56:09 -07001276 if (makeAvailable) {
1277 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001278 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1279 if (mUseScheduler) {
1280 mScheduler->makeHWSyncAvailable(true);
1281 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001282 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001283 // Hardware vsync is not currently available, so abort the resync
1284 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001285 return;
1286 }
1287
Dominik Laskowski075d3172018-05-24 15:50:06 -07001288 const auto displayId = getInternalDisplayId();
1289 if (!displayId || !getHwComposer().isConnected(*displayId)) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001290 return;
1291 }
1292
Dominik Laskowski075d3172018-05-24 15:50:06 -07001293 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001294 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001295
Ana Krulece588e312018-09-18 12:32:24 -07001296 if (mUseScheduler) {
1297 mScheduler->setVsyncPeriod(period);
1298 } else {
1299 mPrimaryDispSync->reset();
1300 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001301
Ana Krulece588e312018-09-18 12:32:24 -07001302 if (!mPrimaryHWVsyncEnabled) {
1303 mPrimaryDispSync->beginResync();
1304 mEventControlThread->setVsyncEnabled(true);
1305 mPrimaryHWVsyncEnabled = true;
1306 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001307 }
1308}
1309
Jesse Hall948fe0c2013-10-14 12:56:09 -07001310void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001311 Mutex::Autolock _l(mHWVsyncLock);
1312 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001313 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001314 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001315 mPrimaryHWVsyncEnabled = false;
1316 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001317 if (makeUnavailable) {
1318 mHWVsyncAvailable = false;
1319 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001320}
1321
Tim Murray4a4e4a22016-04-19 16:29:23 +00001322void SurfaceFlinger::resyncWithRateLimit() {
1323 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001324
1325 // No explicit locking is needed here since EventThread holds a lock while calling this method
1326 static nsecs_t sLastResyncAttempted = 0;
1327 const nsecs_t now = systemTime();
1328 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001329 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001330 }
Dan Stoza57164302017-05-08 14:03:54 -07001331 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001332}
1333
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001334void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1335 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001336 ATRACE_NAME("SF onVsync");
1337
Steven Thomas3cfac282017-02-06 12:29:30 -08001338 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001339 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001340 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001341 return;
1342 }
1343
Dominik Laskowski075d3172018-05-24 15:50:06 -07001344 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001345 return;
1346 }
1347
Dominik Laskowski075d3172018-05-24 15:50:06 -07001348 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001349 // For now, we don't do anything with external display vsyncs.
1350 return;
1351 }
1352
Ana Krulece588e312018-09-18 12:32:24 -07001353 if (mUseScheduler) {
1354 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001355 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001356 bool needsHwVsync = false;
1357 { // Scope for the lock
1358 Mutex::Autolock _l(mHWVsyncLock);
1359 if (mPrimaryHWVsyncEnabled) {
1360 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1361 }
1362 }
1363
1364 if (needsHwVsync) {
1365 enableHardwareVsync();
1366 } else {
1367 disableHardwareVsync(false);
1368 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001369 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001370}
1371
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001372void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001373 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1374 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001375}
1376
Ana Krulec7d1d6832018-12-27 11:10:09 -08001377void SurfaceFlinger::setRefreshRateTo(float newFps) {
1378 const auto displayId = getInternalDisplayId();
1379 if (!displayId || mBootStage != BootStage::FINISHED) {
1380 return;
1381 }
1382 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1383 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1384 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1385 // refresh cycle.
1386
1387 // Don't do any updating if the current fps is the same as the new one.
1388 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
1389 const nsecs_t currentVsyncPeriod = activeConfig->getVsyncPeriod();
1390 if (currentVsyncPeriod == 0) {
1391 return;
1392 }
1393 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1394 // floating numbers.
1395 const float currentFps = 1e9 / currentVsyncPeriod;
1396 if (std::abs(currentFps - newFps) <= 1) {
1397 return;
1398 }
1399
1400 auto configs = getHwComposer().getConfigs(*displayId);
1401 for (int i = 0; i < configs.size(); i++) {
1402 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1403 if (vsyncPeriod == 0) {
1404 continue;
1405 }
1406 const float fps = 1e9 / vsyncPeriod;
1407 // TODO(b/113612090): There should be a better way at determining which config
1408 // has the right refresh rate.
1409 if (std::abs(fps - newFps) <= 1) {
1410 const auto display = getBuiltInDisplay(HWC_DISPLAY_PRIMARY);
1411 if (!display) return;
1412 // This is posted in async function to avoid deadlock when getDisplayDevice
1413 // requires mStateLock.
1414 setActiveConfigAsync(display, i);
1415 ATRACE_INT("FPS", newFps);
1416 }
1417 }
1418}
1419
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001420void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001421 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001422 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001423 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001424
Lloyd Piqueba04e622017-12-14 17:11:26 -08001425 // Ignore events that do not have the right sequenceId.
1426 if (sequenceId != getBE().mComposerSequenceId) {
1427 return;
1428 }
1429
Steven Thomasb02664d2017-07-26 18:48:28 -07001430 // Only lock if we're not on the main thread. This function is normally
1431 // called on a hwbinder thread, but for the primary display it's called on
1432 // the main thread with the state lock already held, so don't attempt to
1433 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001434 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001435
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001436 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001437
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001438 if (std::this_thread::get_id() == mMainThreadId) {
1439 // Process all pending hot plug events immediately if we are on the main thread.
1440 processDisplayHotplugEventsLocked();
1441 }
1442
Lloyd Piqueba04e622017-12-14 17:11:26 -08001443 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001444}
1445
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001446void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001447 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001448 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001449 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001450 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001451 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001452}
1453
Dominik Laskowski075d3172018-05-24 15:50:06 -07001454void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001455 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001456 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001457 if (const auto displayId = getInternalDisplayId()) {
1458 getHwComposer().setVsyncEnabled(*displayId,
1459 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1460 }
Mathias Agopian86303202012-07-24 22:46:10 -07001461}
1462
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001463// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001464void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001465 if (mUseScheduler) {
1466 mScheduler->disableHardwareVsync(true);
1467 } else {
1468 disableHardwareVsync(true);
1469 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001470 // Clear the drawing state so that the logic inside of
1471 // handleTransactionLocked will fire. It will determine the delta between
1472 // mCurrentState and mDrawingState and re-apply all changes when we make the
1473 // transition.
1474 mDrawingState.displays.clear();
1475 mDisplays.clear();
1476}
1477
Steven Thomas050b2c82017-03-06 11:45:16 -08001478void SurfaceFlinger::updateVrFlinger() {
1479 if (!mVrFlinger)
1480 return;
1481 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001482 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001483 return;
1484 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001485
Lloyd Pique441d5042018-10-18 16:49:51 -07001486 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001487 ALOGE("Vr flinger is only supported for remote hardware composer"
1488 " service connections. Ignoring request to transition to vr"
1489 " flinger.");
1490 mVrFlingerRequestsDisplay = false;
1491 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001492 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001493
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001494 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001495
Steven Thomas0123ac62018-07-12 11:32:34 -07001496 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001497 LOG_ALWAYS_FATAL_IF(!display);
1498 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001499 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1500 // called below. Clear the reference now so we don't accidentally use it
1501 // later.
1502 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001503
Steven Thomasb02664d2017-07-26 18:48:28 -07001504 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001505 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001506 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001507
Steven Thomasb02664d2017-07-26 18:48:28 -07001508 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001509 // Delete the current instance before creating the new one
1510 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1511 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1512 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1513 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001514
Lloyd Pique441d5042018-10-18 16:49:51 -07001515 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001516 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001517
1518 if (vrFlingerRequestsDisplay) {
1519 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001520 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001521
1522 mVisibleRegionsDirty = true;
1523 invalidateHwcGeometry();
1524
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001525 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001526 display = getDefaultDisplayDeviceLocked();
1527 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001528 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001529
Steven Thomasb02664d2017-07-26 18:48:28 -07001530 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski075d3172018-05-24 15:50:06 -07001531 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001532 const nsecs_t period = activeConfig->getVsyncPeriod();
1533 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001534
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001535 // The present fences returned from vr_hwc are not an accurate
1536 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001537 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001538 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1539 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001540 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001541 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001542 !hasSyncFramework);
1543 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001544
Steven Thomasb02664d2017-07-26 18:48:28 -07001545 // Use phase of 0 since phase is not known.
1546 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001547 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1548 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001549
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001550 resyncToHardwareVsync(false);
1551
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001552 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001553 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001554}
1555
Mathias Agopian4fec8732012-06-29 14:12:52 -07001556void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001557 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001558 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001559 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001560 if (mUseScheduler) {
1561 // This call is made each time SF wakes up and creates a new frame.
1562 mScheduler->incrementFrameCounter();
1563 }
Dan Stoza50182882016-07-08 12:02:20 -07001564 bool frameMissed = !mHadClientComposition &&
1565 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001566 (mPreviousPresentFence->getSignalTime() ==
1567 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001568 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001569 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001570 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001571 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001572 if (mPropagateBackpressure) {
1573 signalLayerUpdate();
1574 break;
1575 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001576 }
Dan Stoza50182882016-07-08 12:02:20 -07001577
Steven Thomas050b2c82017-03-06 11:45:16 -08001578 // Now that we're going to make it to the handleMessageTransaction()
1579 // call below it's safe to call updateVrFlinger(), which will
1580 // potentially trigger a display handoff.
1581 updateVrFlinger();
1582
Dan Stoza6b9454d2014-11-07 16:00:59 -08001583 bool refreshNeeded = handleMessageTransaction();
1584 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001585 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001586 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001587 // Signal a refresh if a transaction modified the window state,
1588 // a new buffer was latched, or if HWC has requested a full
1589 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001590 signalRefresh();
1591 }
1592 break;
1593 }
1594 case MessageQueue::REFRESH: {
1595 handleMessageRefresh();
1596 break;
1597 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001598 }
1599}
1600
Dan Stoza6b9454d2014-11-07 16:00:59 -08001601bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001602 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001603
1604 // Apply any ready transactions in the queues if there are still transactions that have not been
1605 // applied, wake up during the next vsync period and check again
1606 bool transactionNeeded = false;
1607 if (!flushTransactionQueues()) {
1608 transactionNeeded = true;
1609 }
1610
Mathias Agopian4fec8732012-06-29 14:12:52 -07001611 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001612 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001613 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001614
1615 if (transactionNeeded) {
1616 setTransactionFlags(eTransactionNeeded);
1617 }
1618
1619 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001620}
1621
Mathias Agopian4fec8732012-06-29 14:12:52 -07001622void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001623 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001624
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001625 mRefreshPending = false;
1626
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001627 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001628 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001629 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001630 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001631 for (const auto& [token, display] : mDisplays) {
1632 beginFrame(display);
1633 prepareFrame(display);
1634 doDebugFlashRegions(display, repaintEverything);
1635 doComposition(display, repaintEverything);
1636 }
1637
Adrian Roos1e1a1282017-11-01 19:05:31 +01001638 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001639 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001640
1641 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001642 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001643
Dan Stozabfbffeb2016-07-21 14:49:33 -07001644 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001645 for (const auto& [token, displayDevice] : mDisplays) {
1646 auto display = displayDevice->getCompositionDisplay();
1647 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001648 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001649 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001650 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001651
Alec Mouri86770e52018-09-24 22:40:58 +00001652 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001653 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001654 if (mHadClientComposition) {
1655 base::unique_fd flushFence(getRenderEngine().flush());
1656 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1657 getBE().flushFence = new Fence(std::move(flushFence));
1658 } else {
1659 // Cleanup for hygiene.
1660 getBE().flushFence = Fence::NO_FENCE;
1661 }
1662 }
1663
Jorim Jaggi90535212018-05-23 23:44:06 +02001664 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001665
David Sodman7e4ae112018-02-09 15:02:28 -08001666 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001667 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001668 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001669 compositionInfo.hwc.hwcLayer = nullptr;
1670 }
David Sodmanba340492018-08-05 21:51:33 -07001671 }
David Sodman7e4ae112018-02-09 15:02:28 -08001672
1673 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001674}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001675
David Sodmanfa9b2af2017-12-24 13:28:59 -08001676
1677bool SurfaceFlinger::handleMessageInvalidate() {
1678 ATRACE_CALL();
1679 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001680}
1681
David Sodman79bba0e2018-08-05 18:07:49 -07001682void SurfaceFlinger::calculateWorkingSet() {
1683 ATRACE_CALL();
1684 ALOGV(__FUNCTION__);
1685
David Sodman79bba0e2018-08-05 18:07:49 -07001686 // build the h/w work list
1687 if (CC_UNLIKELY(mGeometryInvalid)) {
1688 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001689 for (const auto& [token, displayDevice] : mDisplays) {
1690 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001691 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001692 if (!displayId) {
1693 continue;
1694 }
David Sodman79bba0e2018-08-05 18:07:49 -07001695
Lloyd Pique32cbe282018-10-19 13:09:22 -07001696 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001697 for (size_t i = 0; i < currentLayers.size(); i++) {
1698 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001699
Dominik Laskowski075d3172018-05-24 15:50:06 -07001700 if (!layer->hasHwcLayer(*displayId)) {
1701 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1702 layer->forceClientComposition(*displayId);
1703 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001704 }
1705 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001706
Lloyd Pique32cbe282018-10-19 13:09:22 -07001707 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001708 if (mDebugDisableHWC || mDebugRegion) {
1709 layer->forceClientComposition(*displayId);
1710 }
David Sodman79bba0e2018-08-05 18:07:49 -07001711 }
1712 }
1713 }
1714
1715 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001716 for (const auto& [token, displayDevice] : mDisplays) {
1717 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001718 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001719 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001720 continue;
1721 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001722 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001723
1724 if (mDrawingState.colorMatrixChanged) {
1725 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001726 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001727 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001728 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001729 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001730 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1731 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001732 !profile->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001733 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001734 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1735 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001736 !profile->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001737 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001738 }
1739
Peiyong Lind3788632018-09-18 16:01:31 -07001740 // TODO(b/111562338) remove when composer 2.3 is shipped.
1741 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001742 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001743 }
1744
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001745 if (layer->getRoundedCornerState().radius > 0.0f) {
1746 layer->forceClientComposition(*displayId);
1747 }
1748
Dominik Laskowski075d3172018-05-24 15:50:06 -07001749 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001750 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001751 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001752 continue;
1753 }
1754
Lloyd Pique32cbe282018-10-19 13:09:22 -07001755 const auto& displayState = display->getState();
1756 layer->setPerFrameData(*displayId, displayState.transform, displayState.viewport,
1757 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001758 }
1759
Peiyong Lin13effd12018-07-24 17:01:47 -07001760 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001761 ColorMode colorMode;
1762 Dataspace dataSpace;
1763 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001764 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001765 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001766 }
1767 }
1768
1769 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001770
1771 for (const auto& [token, display] : mDisplays) {
1772 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001773 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001774 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001775
1776 if (displayId) {
1777 if (!layer->setHwcLayer(*displayId)) {
1778 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1779 }
1780 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001781 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001782
Dominik Laskowski05275f12018-11-01 15:03:24 -07001783 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001784 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1785 }
1786 }
David Sodman79bba0e2018-08-05 18:07:49 -07001787}
1788
Lloyd Pique32cbe282018-10-19 13:09:22 -07001789void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1790 bool repaintEverything) {
1791 auto display = displayDevice->getCompositionDisplay();
1792 const auto& displayState = display->getState();
1793
Mathias Agopiancd60f992012-08-16 16:28:27 -07001794 // is debugging enabled
1795 if (CC_LIKELY(!mDebugRegion))
1796 return;
1797
Lloyd Pique32cbe282018-10-19 13:09:22 -07001798 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001799 // transform the dirty region into this screen's coordinate space
Lloyd Pique32cbe282018-10-19 13:09:22 -07001800 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001801 if (!dirtyRegion.isEmpty()) {
1802 // redraw the whole screen
Lloyd Pique32cbe282018-10-19 13:09:22 -07001803 doComposeSurfaces(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001804
David Sodmanfa9b2af2017-12-24 13:28:59 -08001805 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001806 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001807 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001808
Lloyd Pique31cb2942018-10-19 17:23:03 -07001809 display->getRenderSurface()->queueBuffer();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001810 }
1811 }
1812
Lloyd Pique32cbe282018-10-19 13:09:22 -07001813 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001814
1815 if (mDebugRegion > 1) {
1816 usleep(mDebugRegion * 1000);
1817 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001818
Lloyd Pique32cbe282018-10-19 13:09:22 -07001819 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001820}
1821
Adrian Roos1e1a1282017-11-01 19:05:31 +01001822void SurfaceFlinger::doTracing(const char* where) {
1823 ATRACE_CALL();
1824 ATRACE_NAME(where);
1825 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001826 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001827 }
1828}
1829
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001830void SurfaceFlinger::logLayerStats() {
1831 ATRACE_CALL();
1832 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001833 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001834 if (display->isPrimary()) {
1835 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001836 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001837 }
1838 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001839
1840 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001841 }
1842}
1843
David Sodman2b406362017-12-15 13:33:47 -08001844void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001845{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001846 ATRACE_CALL();
1847 ALOGV("preComposition");
1848
David Sodman2b406362017-12-15 13:33:47 -08001849 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1850
Mathias Agopiancd60f992012-08-16 16:28:27 -07001851 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001852 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001853 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001854 needExtraInvalidate = true;
1855 }
Robert Carr2047fae2016-11-28 14:09:09 -08001856 });
1857
Mathias Agopiancd60f992012-08-16 16:28:27 -07001858 if (needExtraInvalidate) {
1859 signalLayerUpdate();
1860 }
1861}
1862
Ana Krulece588e312018-09-18 12:32:24 -07001863void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1864 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001865 // Update queue of past composite+present times and determine the
1866 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001867 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001868 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001869 while (!getBE().mCompositePresentTimes.empty()) {
1870 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001871 // Cached values should have been updated before calling this method,
1872 // which helps avoid duplicate syscalls.
1873 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1874 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1875 break;
1876 }
1877 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001878 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001879 }
1880
1881 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001882 while (getBE().mCompositePresentTimes.size() > 16) {
1883 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001884 }
1885
Ana Krulece588e312018-09-18 12:32:24 -07001886 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001887}
1888
Ana Krulece588e312018-09-18 12:32:24 -07001889void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1890 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001891 // Integer division and modulo round toward 0 not -inf, so we need to
1892 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001893 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1894 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1895 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001896
Brian Andersond0010582017-03-07 13:20:31 -08001897 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1898 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001899 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001900 }
1901
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001902 // Snap the latency to a value that removes scheduling jitter from the
1903 // composition and present times, which often have >1ms of jitter.
1904 // Reducing jitter is important if an app attempts to extrapolate
1905 // something (such as user input) to an accurate diasplay time.
1906 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1907 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001908 nsecs_t bias = stats.vsyncPeriod / 2;
1909 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1910 nsecs_t snappedCompositeToPresentLatency =
1911 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001912
David Sodman99974d22017-11-28 12:04:33 -08001913 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001914 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1915 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001916 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001917}
1918
Ady Abraham8164d482019-01-11 14:47:59 -08001919// debug patch for b/119477596 - add stack guards to catch stack
1920// corruptions and disable clang optimizations.
1921// The code below is temporary and planned to be removed once stack
1922// corruptions are found.
1923#pragma clang optimize off
1924class StackGuard {
1925public:
1926 StackGuard(const char* name, const char* func, int line) {
1927 guarders.reserve(MIN_CAPACITY);
1928 guarders.push_back({this, name, func, line});
1929 validate();
1930 }
1931 ~StackGuard() {
1932 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1933 if (i->guard == this) {
1934 guarders.erase(i);
1935 break;
1936 }
1937 }
1938 }
1939
1940 static void validate() {
1941 for (const auto& guard : guarders) {
1942 if (guard.guard->cookie != COOKIE_VALUE) {
1943 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1944 CallStack stack(LOG_TAG);
1945 abort();
1946 }
1947 }
1948 }
1949
1950private:
1951 uint64_t cookie = COOKIE_VALUE;
1952 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
1953 static constexpr size_t MIN_CAPACITY = 16;
1954
1955 struct GuarderElement {
1956 StackGuard* guard;
1957 const char* name;
1958 const char* func;
1959 int line;
1960 };
1961
1962 static std::vector<GuarderElement> guarders;
1963};
1964std::vector<StackGuard::GuarderElement> StackGuard::guarders;
1965
1966#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
1967
1968#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08001969void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001970{
Ady Abraham8164d482019-01-11 14:47:59 -08001971 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001972 ATRACE_CALL();
1973 ALOGV("postComposition");
1974
Brian Anderson3546a3f2016-07-14 11:51:14 -07001975 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001976 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08001977 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001978 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001979 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001980 }
Ady Abraham8164d482019-01-11 14:47:59 -08001981 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001982
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001983 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07001984 const auto displayDevice = getDefaultDisplayDeviceLocked();
1985 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001986
David Sodman73beded2017-11-15 11:56:06 -08001987 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001988 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08001989 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
1990
Lloyd Pique32cbe282018-10-19 13:09:22 -07001991 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001992 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07001993 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
1994 ->getRenderSurface()
1995 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001996 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001997 } else {
1998 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1999 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002000
Ady Abraham8164d482019-01-11 14:47:59 -08002001 ASSERT_ON_STACK_GUARD();
2002
David Sodman73beded2017-11-15 11:56:06 -08002003 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002004 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2005 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002006 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002007 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002008 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002009
Ana Krulece588e312018-09-18 12:32:24 -07002010 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002011 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002012 if (mUseScheduler) {
2013 mScheduler->getDisplayStatInfo(&stats);
2014 } else {
2015 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2016 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2017 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002018
Ady Abraham8164d482019-01-11 14:47:59 -08002019 ASSERT_ON_STACK_GUARD();
2020
David Sodman2b406362017-12-15 13:33:47 -08002021 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002022 // when we started doing work for this frame, but that should be okay
2023 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002024 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002025 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002026 DEFINE_STACK_GUARD(compositorTiming);
2027
Brian Andersond0010582017-03-07 13:20:31 -08002028 {
David Sodman99974d22017-11-28 12:04:33 -08002029 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002030 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002031 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002032
2033 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002034 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002035
Robert Carr2047fae2016-11-28 14:09:09 -08002036 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002037 bool frameLatched =
2038 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2039 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002040 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002041 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002042 recordBufferingStats(layer->getName().string(),
2043 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002044 }
Ady Abraham8164d482019-01-11 14:47:59 -08002045 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002046 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002047
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002048 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002049 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002050 if (mUseScheduler) {
2051 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002052 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002053 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002054 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2055 enableHardwareVsync();
2056 } else {
2057 disableHardwareVsync(false);
2058 }
Ady Abraham8164d482019-01-11 14:47:59 -08002059 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002060 }
2061 }
2062
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002063 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002064 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2065 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002066 if (mUseScheduler) {
2067 mScheduler->enableHardwareVsync();
2068 } else {
2069 enableHardwareVsync();
2070 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002071 }
2072 }
2073
Ady Abraham8164d482019-01-11 14:47:59 -08002074 ASSERT_ON_STACK_GUARD();
2075
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002076 if (mAnimCompositionPending) {
2077 mAnimCompositionPending = false;
2078
Brian Anderson4e606e32017-03-16 15:34:57 -07002079 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002080 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002081 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002082
2083 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002084 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002085 // The HWC doesn't support present fences, so use the refresh
2086 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002087 const nsecs_t presentTime =
2088 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002089 DEFINE_STACK_GUARD(presentTime);
2090
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002091 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002092 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002093 }
2094 mAnimFrameTracker.advanceFrame();
2095 }
Dan Stozab90cf072015-03-05 11:05:59 -08002096
Ady Abraham8164d482019-01-11 14:47:59 -08002097 ASSERT_ON_STACK_GUARD();
2098
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002099 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002100 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002101 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002102 }
2103
Ady Abraham8164d482019-01-11 14:47:59 -08002104 ASSERT_ON_STACK_GUARD();
2105
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002106 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002107
Ady Abraham8164d482019-01-11 14:47:59 -08002108 ASSERT_ON_STACK_GUARD();
2109
Lloyd Pique32cbe282018-10-19 13:09:22 -07002110 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2111 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002112 return;
2113 }
2114
2115 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002116 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002117 if (mHasPoweredOff) {
2118 mHasPoweredOff = false;
2119 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002120 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002121 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002122 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002123 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002124 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2125 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002126 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002127 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002128 }
David Sodman4a36e932017-11-07 14:29:47 -08002129 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002130
2131 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002132 }
David Sodman4a36e932017-11-07 14:29:47 -08002133 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002134 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002135
2136 {
2137 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002138 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002139 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002140 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002141 if (refillCount > 0) {
2142 const size_t offset = mTexturePool.size();
2143 mTexturePool.resize(mTexturePoolSize);
2144 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2145 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2146 }
Ady Abraham8164d482019-01-11 14:47:59 -08002147 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002148 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002149
Marissa Wallfda30bb2018-10-12 11:34:28 -07002150 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002151 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002152
2153 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002154}
Ady Abraham8164d482019-01-11 14:47:59 -08002155#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002156
2157void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002158 ATRACE_CALL();
2159 ALOGV("rebuildLayerStacks");
2160
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002161 // We need to clear these out now as these may be holding on to a
2162 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2163 // also holds a reference. When the set of visible layers is recomputed,
2164 // some layers may be destroyed if the only thing keeping them alive was
2165 // that list of visible layers associated with each display. The layer
2166 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2167 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2168 for (const auto& [token, display] : mDisplays) {
2169 getBE().mCompositionInfo[token].clear();
2170 }
2171
Mathias Agopiancd60f992012-08-16 16:28:27 -07002172 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002173 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002174 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002175 mVisibleRegionsDirty = false;
2176 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002177
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002178 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002179 const auto& displayDevice = pair.second;
2180 auto display = displayDevice->getCompositionDisplay();
2181 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002182 Region opaqueRegion;
2183 Region dirtyRegion;
2184 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002185 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002186 const ui::Transform& tr = displayState.transform;
2187 const Rect bounds = displayState.bounds;
2188 if (displayState.isEnabled) {
2189 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002190
Jeff Sharkey76488112017-02-27 14:15:18 -07002191 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002192 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002193 const auto displayId = displayDevice->getId();
2194 if (display->belongsInOutput(layer->getLayerStack())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002195 Region drawRegion(tr.transform(
2196 layer->visibleNonTransparentRegion));
2197 drawRegion.andSelf(bounds);
2198 if (!drawRegion.isEmpty()) {
2199 layersSortedByZ.add(layer);
2200 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002201 // Clear out the HWC layer if this layer was
2202 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002203 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002204 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002205 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002206 // WM changes display->layerStack upon sleep/awake.
2207 // Here we make sure we delete the HWC layers even if
2208 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002209 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002210 }
2211
2212 // If a layer is not going to get a release fence because
2213 // it is invisible, but it is also going to release its
2214 // old buffer, add it to the list of layers needing
2215 // fences.
2216 if (hwcLayerDestroyed) {
2217 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2218 mLayersWithQueuedFrames.cend(), layer);
2219 if (found != mLayersWithQueuedFrames.cend()) {
2220 layersNeedingFences.add(layer);
2221 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002222 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002223 });
2224 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002225 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
2226 displayDevice->setLayersNeedingFences(layersNeedingFences);
2227
2228 Region undefinedRegion{bounds};
2229 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2230
2231 display->editState().undefinedRegion = undefinedRegion;
2232 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002233 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002234 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002235}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002236
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002237// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002238// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002239// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002240// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002241// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002242// The returned HDR data space is one of
2243// - Dataspace::UNKNOWN
2244// - Dataspace::BT2020_HLG
2245// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002246Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2247 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002248 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002249 *outHdrDataSpace = Dataspace::UNKNOWN;
2250
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002251 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002252 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002253 case Dataspace::V0_SCRGB:
2254 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002255 case Dataspace::BT2020:
2256 case Dataspace::BT2020_ITU:
2257 case Dataspace::BT2020_LINEAR:
2258 case Dataspace::DISPLAY_BT2020:
2259 bestDataSpace = Dataspace::DISPLAY_BT2020;
2260 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002261 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002262 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002263 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002264 case Dataspace::BT2020_PQ:
2265 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002266 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002267 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002268 case Dataspace::BT2020_HLG:
2269 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002270 // When there's mixed PQ content and HLG content, we set the HDR
2271 // data space to be BT2020_PQ and convert HLG to PQ.
2272 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2273 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002274 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002275 break;
2276 default:
2277 break;
2278 }
Romain Guy54f154a2017-10-24 21:40:32 +01002279 }
2280
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002281 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002282}
2283
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002284// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002285void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2286 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002287 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2288 *outMode = ColorMode::NATIVE;
2289 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002290 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002291 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002292 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002293
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002294 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002295 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002296
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002297 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2298
Peiyong Lindfde5112018-06-05 10:58:41 -07002299 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002300 const bool isHdr =
2301 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002302 if (isHdr) {
2303 bestDataSpace = hdrDataSpace;
2304 }
2305
Chia-I Wu0d711262018-05-21 15:19:35 -07002306 RenderIntent intent;
2307 switch (mDisplayColorSetting) {
2308 case DisplayColorSetting::MANAGED:
2309 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002310 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002311 break;
2312 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002313 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002314 break;
2315 default: // vendor display color setting
2316 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2317 break;
2318 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002319
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002320 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002321}
2322
Lloyd Pique32cbe282018-10-19 13:09:22 -07002323void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2324 auto display = displayDevice->getCompositionDisplay();
2325 const auto& displayState = display->getState();
2326
2327 bool dirty = !display->getPhysicalSpaceDirtyRegion(false).isEmpty();
2328 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2329 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002330
David Sodmanfa9b2af2017-12-24 13:28:59 -08002331 // If nothing has changed (!dirty), don't recompose.
2332 // If something changed, but we don't currently have any visible layers,
2333 // and didn't when we last did a composition, then skip it this time.
2334 // The second rule does two things:
2335 // - When all layers are removed from a display, we'll emit one black
2336 // frame, then nothing more until we get new layers.
2337 // - When a display is created with a private layer stack, we won't
2338 // emit any black frames until a layer is added to the layer stack.
2339 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002340
Dominik Laskowski075d3172018-05-24 15:50:06 -07002341 const char flagPrefix[] = {'-', '+'};
2342 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002343 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2344 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2345 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2346 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002347
Lloyd Pique31cb2942018-10-19 17:23:03 -07002348 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002349
David Sodmanfa9b2af2017-12-24 13:28:59 -08002350 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002351 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002352 }
2353}
2354
Lloyd Pique32cbe282018-10-19 13:09:22 -07002355void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2356 auto display = displayDevice->getCompositionDisplay();
2357 const auto& displayState = display->getState();
2358
2359 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002360 return;
David Sodman2b406362017-12-15 13:33:47 -08002361 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002362
Lloyd Pique31cb2942018-10-19 17:23:03 -07002363 status_t result = display->getRenderSurface()->prepareFrame(
2364 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002365 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002366 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002367}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002368
Lloyd Pique32cbe282018-10-19 13:09:22 -07002369void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002370 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002371 ALOGV("doComposition");
2372
Lloyd Pique32cbe282018-10-19 13:09:22 -07002373 auto display = displayDevice->getCompositionDisplay();
2374 const auto& displayState = display->getState();
2375
2376 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002377 // transform the dirty region into this screen's coordinate space
Lloyd Pique32cbe282018-10-19 13:09:22 -07002378 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002379
David Sodmanfa9b2af2017-12-24 13:28:59 -08002380 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002381 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002382
Lloyd Pique32cbe282018-10-19 13:09:22 -07002383 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002384 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002385 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002386 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002387}
2388
David Sodmanfa9b2af2017-12-24 13:28:59 -08002389void SurfaceFlinger::postFrame()
2390{
2391 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002392 const auto display = getDefaultDisplayDeviceLocked();
2393 if (display && getHwComposer().isConnected(*display->getId())) {
2394 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002395 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2396 logFrameStats();
2397 }
2398 }
2399}
2400
Lloyd Pique32cbe282018-10-19 13:09:22 -07002401void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002402 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002403 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002404
Lloyd Pique32cbe282018-10-19 13:09:22 -07002405 auto display = displayDevice->getCompositionDisplay();
2406 const auto& displayState = display->getState();
2407 const auto displayId = display->getId();
2408
David Sodmanfa9b2af2017-12-24 13:28:59 -08002409 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002410
Lloyd Pique32cbe282018-10-19 13:09:22 -07002411 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002412 if (displayId) {
2413 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002414 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002415 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002416 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002417 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002418
Chia-I Wu7b549592017-11-15 09:14:57 -08002419 // The layer buffer from the previous frame (if any) is released
2420 // by HWC only when the release fence from this frame (if any) is
2421 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002422 if (displayId && layer->hasHwcLayer(*displayId)) {
2423 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2424 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002425 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002426
2427 // If the layer was client composited in the previous frame, we
2428 // need to merge with the previous client target acquire fence.
2429 // Since we do not track that, always merge with the current
2430 // client target acquire fence when it is available, even though
2431 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002432 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002433 releaseFence =
2434 Fence::merge("LayerRelease", releaseFence,
2435 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002436 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002437
David Sodman15094112018-10-11 09:39:37 -07002438 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002439 }
Chia-I Wu83806892017-11-16 10:50:20 -08002440
2441 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002442 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002443 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002444 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002445 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002446 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002447 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002448 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002449 }
2450 }
2451
Dominik Laskowski075d3172018-05-24 15:50:06 -07002452 if (displayId) {
2453 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002454 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002455 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002456}
2457
Mathias Agopian87baae12012-07-31 12:38:26 -07002458void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002459{
Mathias Agopian841cde52012-03-01 15:44:37 -08002460 ATRACE_CALL();
2461
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002462 // here we keep a copy of the drawing state (that is the state that's
2463 // going to be overwritten by handleTransactionLocked()) outside of
2464 // mStateLock so that the side-effects of the State assignment
2465 // don't happen with mStateLock held (which can cause deadlocks).
2466 State drawingState(mDrawingState);
2467
Mathias Agopianca4d3602011-05-19 15:38:14 -07002468 Mutex::Autolock _l(mStateLock);
2469 const nsecs_t now = systemTime();
2470 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002471
Mathias Agopianca4d3602011-05-19 15:38:14 -07002472 // Here we're guaranteed that some transaction flags are set
2473 // so we can call handleTransactionLocked() unconditionally.
2474 // We call getTransactionFlags(), which will also clear the flags,
2475 // with mStateLock held to guarantee that mCurrentState won't change
2476 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002477
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002478 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002479 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002480 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002481
Mathias Agopianca4d3602011-05-19 15:38:14 -07002482 mLastTransactionTime = systemTime() - now;
2483 mDebugInTransaction = 0;
2484 invalidateHwcGeometry();
2485 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002486}
2487
Lloyd Piqueba04e622017-12-14 17:11:26 -08002488void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2489 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002490 const std::optional<DisplayIdentificationInfo> info =
2491 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002492
Dominik Laskowski075d3172018-05-24 15:50:06 -07002493 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002494 continue;
2495 }
2496
Lloyd Piqueba04e622017-12-14 17:11:26 -08002497 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002498 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002499 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002500 mPhysicalDisplayTokens[info->id] = new BBinder();
2501 DisplayDeviceState state;
2502 state.displayId = info->id;
2503 state.isSecure = true; // All physical displays are currently considered secure.
2504 state.displayName = info->name;
2505 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2506 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002507 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002508 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002509 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002510
Dominik Laskowski075d3172018-05-24 15:50:06 -07002511 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2512 if (index >= 0) {
2513 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2514 mInterceptor->saveDisplayDeletion(state.sequenceId);
2515 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002516 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002517 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002518 }
2519
2520 processDisplayChangesLocked();
2521 }
2522
2523 mPendingHotplugEvents.clear();
2524}
2525
Lloyd Pique99d3da52018-01-22 17:48:03 -08002526sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002527 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002528 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002529 const sp<IGraphicBufferProducer>& producer) {
2530 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002531 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002532 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002533 creationArgs.isSecure = state.isSecure;
2534 creationArgs.displaySurface = dispSurface;
2535 creationArgs.hasWideColorGamut = false;
2536 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002537
Dominik Laskowski075d3172018-05-24 15:50:06 -07002538 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2539 creationArgs.isPrimary = isInternalDisplay;
2540
2541 if (useColorManagement && displayId) {
2542 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002543 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002544 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002545 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002546 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002547
Dominik Laskowski7e045462018-05-30 13:02:02 -07002548 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002549 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002550 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002551 }
tangrobin6753a022018-08-10 10:58:54 +08002552 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002553
Dominik Laskowski075d3172018-05-24 15:50:06 -07002554 if (displayId) {
2555 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002556 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002557 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002558 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002559
Lloyd Pique90c115d2018-09-18 21:39:42 -07002560 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002561 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002562 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002563
Lloyd Pique99d3da52018-01-22 17:48:03 -08002564 // Make sure that composition can never be stalled by a virtual display
2565 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002566 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002567 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002568 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2569 }
2570
Dominik Laskowski075d3172018-05-24 15:50:06 -07002571 creationArgs.displayInstallOrientation =
2572 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002573
Lloyd Pique99d3da52018-01-22 17:48:03 -08002574 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002575 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002576
Lloyd Pique90c115d2018-09-18 21:39:42 -07002577 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002578
2579 if (maxFrameBufferAcquiredBuffers >= 3) {
2580 nativeWindowSurface->preallocateBuffers();
2581 }
2582
2583 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002584 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002585 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002586 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002587 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002588 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002589 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2590 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002591 if (!state.isVirtual()) {
2592 LOG_ALWAYS_FATAL_IF(!displayId);
2593 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002594 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002595
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002596 display->setLayerStack(state.layerStack);
2597 display->setProjection(state.orientation, state.viewport, state.frame);
2598 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002599
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002600 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002601}
2602
Lloyd Pique347200f2017-12-14 17:00:15 -08002603void SurfaceFlinger::processDisplayChangesLocked() {
2604 // here we take advantage of Vector's copy-on-write semantics to
2605 // improve performance by skipping the transaction entirely when
2606 // know that the lists are identical
2607 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2608 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2609 if (!curr.isIdenticalTo(draw)) {
2610 mVisibleRegionsDirty = true;
2611 const size_t cc = curr.size();
2612 size_t dc = draw.size();
2613
2614 // find the displays that were removed
2615 // (ie: in drawing state but not in current state)
2616 // also handle displays that changed
2617 // (ie: displays that are in both lists)
2618 for (size_t i = 0; i < dc;) {
2619 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2620 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002621 // Save display IDs before disconnecting.
2622 const auto internalDisplayId = getInternalDisplayId();
2623 const auto externalDisplayId = getExternalDisplayId();
2624
Lloyd Pique347200f2017-12-14 17:00:15 -08002625 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002626 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002627 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002628 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002629 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002630 if (mUseScheduler) {
2631 mScheduler->hotplugReceived(mAppConnectionHandle,
2632 EventThread::DisplayType::Primary, false);
2633 } else {
2634 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2635 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002636 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002637 if (mUseScheduler) {
2638 mScheduler->hotplugReceived(mAppConnectionHandle,
2639 EventThread::DisplayType::External, false);
2640 } else {
2641 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2642 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002643 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002644 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002645 } else {
2646 // this display is in both lists. see if something changed.
2647 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002648 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002649 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2650 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2651 if (state_binder != draw_binder) {
2652 // changing the surface is like destroying and
2653 // recreating the DisplayDevice, so we just remove it
2654 // from the drawing state, so that it get re-added
2655 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002656 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002657 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002658 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002659 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002660 mDrawingState.displays.removeItemsAt(i);
2661 dc--;
2662 // at this point we must loop to the next item
2663 continue;
2664 }
2665
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002666 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002667 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002668 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002669 }
2670 if ((state.orientation != draw[i].orientation) ||
2671 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002672 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002673 }
2674 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002675 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002676 }
2677 }
2678 }
2679 ++i;
2680 }
2681
2682 // find displays that were added
2683 // (ie: in current state but not in drawing state)
2684 for (size_t i = 0; i < cc; i++) {
2685 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2686 const DisplayDeviceState& state(curr[i]);
2687
Lloyd Pique542307f2018-10-19 13:24:08 -07002688 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002689 sp<IGraphicBufferProducer> producer;
2690 sp<IGraphicBufferProducer> bqProducer;
2691 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002692 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002693
Dominik Laskowski075d3172018-05-24 15:50:06 -07002694 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002695 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002696 // Virtual displays without a surface are dormant:
2697 // they have external state (layer stack, projection,
2698 // etc.) but no internal state (i.e. a DisplayDevice).
2699 if (state.surface != nullptr) {
2700 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002701 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002702 int width = 0;
2703 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2704 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2705 int height = 0;
2706 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2707 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2708 int intFormat = 0;
2709 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2710 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002711 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002712
Dominik Laskowski075d3172018-05-24 15:50:06 -07002713 displayId =
2714 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002715 }
2716
2717 // TODO: Plumb requested format back up to consumer
2718
2719 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002720 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002721 bqProducer, bqConsumer,
2722 state.displayName);
2723
2724 dispSurface = vds;
2725 producer = vds;
2726 }
2727 } else {
2728 ALOGE_IF(state.surface != nullptr,
2729 "adding a supported display, but rendering "
2730 "surface is provided (%p), ignoring it",
2731 state.surface.get());
2732
Dominik Laskowski075d3172018-05-24 15:50:06 -07002733 displayId = state.displayId;
2734 LOG_ALWAYS_FATAL_IF(!displayId);
2735 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002736 producer = bqProducer;
2737 }
2738
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002739 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002740 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002741 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002742 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002743 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002744 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002745 LOG_ALWAYS_FATAL_IF(!displayId);
2746
2747 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002748 if (mUseScheduler) {
2749 mScheduler->hotplugReceived(mAppConnectionHandle,
2750 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002751 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002752 } else {
2753 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2754 true);
2755 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002756 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002757 if (mUseScheduler) {
2758 mScheduler->hotplugReceived(mAppConnectionHandle,
2759 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002760 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002761 } else {
2762 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2763 true);
2764 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002765 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002766 }
2767 }
2768 }
2769 }
2770 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002771
2772 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002773}
2774
Mathias Agopian87baae12012-07-31 12:38:26 -07002775void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002776{
Dan Stoza7dde5992015-05-22 09:51:44 -07002777 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002778 mCurrentState.traverseInZOrder([](Layer* layer) {
2779 layer->notifyAvailableFrames();
2780 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002781
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002782 /*
2783 * Traversal of the children
2784 * (perform the transaction for each of them if needed)
2785 */
2786
Robert Carr720e5062018-07-30 17:45:14 -07002787 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002788 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002789 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002790 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002791 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002792
2793 const uint32_t flags = layer->doTransaction(0);
2794 if (flags & Layer::eVisibleRegion)
2795 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002796
2797 if (flags & Layer::eInputInfoChanged) {
2798 inputChanged = true;
2799 }
Robert Carr2047fae2016-11-28 14:09:09 -08002800 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002801 }
2802
2803 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002804 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002805 */
2806
Mathias Agopiane57f2922012-08-09 16:29:12 -07002807 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002808 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002809 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002810 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002811
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002812 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002813 // The transform hint might have changed for some layers
2814 // (either because a display has changed, or because a layer
2815 // as changed).
2816 //
2817 // Walk through all the layers in currentLayers,
2818 // and update their transform hint.
2819 //
2820 // If a layer is visible only on a single display, then that
2821 // display is used to calculate the hint, otherwise we use the
2822 // default display.
2823 //
2824 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2825 // the hint is set before we acquire a buffer from the surface texture.
2826 //
2827 // NOTE: layer transactions have taken place already, so we use their
2828 // drawing state. However, SurfaceFlinger's own transaction has not
2829 // happened yet, so we must use the current state layer list
2830 // (soon to become the drawing state list).
2831 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002832 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002833 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002834 bool first = true;
2835 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002836 // NOTE: we rely on the fact that layers are sorted by
2837 // layerStack first (so we don't have to traverse the list
2838 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002839 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002840 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002841 currentlayerStack = layerStack;
2842 // figure out if this layerstack is mirrored
2843 // (more than one display) if so, pick the default display,
2844 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002845 hintDisplay = nullptr;
2846 for (const auto& [token, display] : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002847 if (display->getCompositionDisplay()->belongsInOutput(layer->getLayerStack())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002848 if (hintDisplay) {
2849 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002850 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002851 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002852 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002853 }
2854 }
2855 }
2856 }
Chet Haase91d25932013-04-11 15:24:55 -07002857
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002858 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002859 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2860 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002861
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002862 // could be null when this layer is using a layerStack
2863 // that is not visible on any display. Also can occur at
2864 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002865 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002866 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002867
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002868 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002869 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002870 if (hintDisplay) {
2871 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002872 }
Robert Carr2047fae2016-11-28 14:09:09 -08002873
2874 first = false;
2875 });
Mathias Agopian84300952012-11-21 16:02:13 -08002876 }
2877
2878
Mathias Agopian3559b072012-08-15 13:46:03 -07002879 /*
2880 * Perform our own transaction if needed
2881 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002882
2883 if (mLayersAdded) {
2884 mLayersAdded = false;
2885 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002886 mVisibleRegionsDirty = true;
2887 }
2888
2889 // some layers might have been removed, so
2890 // we need to update the regions they're exposing.
2891 if (mLayersRemoved) {
2892 mLayersRemoved = false;
2893 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002894 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002895 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002896 // this layer is not visible anymore
2897 // TODO: we could traverse the tree from front to back and
2898 // compute the actual visible region
2899 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002900 Region visibleReg;
2901 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002902 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002903 }
Robert Carr2047fae2016-11-28 14:09:09 -08002904 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002905 }
2906
2907 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002908
Vishnu Nairde19f852018-12-18 16:11:53 -08002909 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002910 updateInputWindows();
2911 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002912 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002913
Riley Andrews03414a12014-07-01 14:22:59 -07002914 updateCursorAsync();
2915}
2916
Robert Carr720e5062018-07-30 17:45:14 -07002917void SurfaceFlinger::updateInputWindows() {
2918 ATRACE_CALL();
2919
Vishnu Nairde19f852018-12-18 16:11:53 -08002920 if (mInputFlinger == nullptr) {
2921 return;
2922 }
2923
Robert Carr720e5062018-07-30 17:45:14 -07002924 Vector<InputWindowInfo> inputHandles;
2925
2926 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2927 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002928 // When calculating the screen bounds we ignore the transparent region since it may
2929 // result in an unwanted offset.
2930 inputHandles.add(layer->fillInputInfo(
2931 layer->computeScreenBounds(false /* reduceTransparentRegion */)));
Robert Carr720e5062018-07-30 17:45:14 -07002932 }
2933 });
2934 mInputFlinger->setInputWindows(inputHandles);
2935}
2936
chaviwfbe5d9c2018-12-26 12:23:37 -08002937void SurfaceFlinger::executeInputWindowCommands() {
2938 if (!mInputFlinger) {
2939 return;
2940 }
2941
2942 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2943 if (transferTouchFocusCommand.fromToken != nullptr &&
2944 transferTouchFocusCommand.toToken != nullptr &&
2945 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2946 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2947 transferTouchFocusCommand.toToken);
2948 }
2949 }
2950
2951 mInputWindowCommands.clear();
2952}
2953
Riley Andrews03414a12014-07-01 14:22:59 -07002954void SurfaceFlinger::updateCursorAsync()
2955{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002956 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002957 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002958 continue;
2959 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002960
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002961 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2962 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002963 }
2964 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002965}
2966
chaviw61626f22018-11-15 16:26:27 -08002967void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2968 if (layer->hasReadyFrame()) {
2969 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2970 if (layer->shouldPresentNow(expectedPresentTime)) {
2971 bool ignored = false;
2972 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
2973 }
2974 }
2975 layer->releasePendingBuffer(systemTime());
2976}
2977
Mathias Agopian4fec8732012-06-29 14:12:52 -07002978void SurfaceFlinger::commitTransaction()
2979{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002980 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002981 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002982 for (const auto& l : mLayersPendingRemoval) {
2983 recordBufferingStats(l->getName().string(),
2984 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002985
2986 // We need to release the HWC layers when the Layer is removed
2987 // from the current state otherwise the HWC layer just continues
2988 // showing at its last configured state until we eventually
2989 // abandon the buffer queue.
2990 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08002991 l->destroyHwcLayersForAllDisplays();
2992 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07002993 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002994 }
2995 mLayersPendingRemoval.clear();
2996 }
2997
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002998 // If this transaction is part of a window animation then the next frame
2999 // we composite should be considered an animation as well.
3000 mAnimCompositionPending = mAnimTransactionPending;
3001
Mathias Agopian4fec8732012-06-29 14:12:52 -07003002 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003003 // clear the "changed" flags in current state
3004 mCurrentState.colorMatrixChanged = false;
3005
Robert Carr1f0a16a2016-10-24 16:27:39 -07003006 mDrawingState.traverseInZOrder([](Layer* layer) {
3007 layer->commitChildList();
3008 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003009 mTransactionPending = false;
3010 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003011 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003012}
3013
Lloyd Pique32cbe282018-10-19 13:09:22 -07003014void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003015 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003016 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003017 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003018
Lloyd Pique32cbe282018-10-19 13:09:22 -07003019 auto display = displayDevice->getCompositionDisplay();
3020
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003021 Region aboveOpaqueLayers;
3022 Region aboveCoveredLayers;
3023 Region dirty;
3024
Mathias Agopian87baae12012-07-31 12:38:26 -07003025 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003026
Robert Carr2047fae2016-11-28 14:09:09 -08003027 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003028 // start with the whole surface at its current location
3029 const Layer::State& s(layer->getDrawingState());
3030
Jesse Hall01e29052013-02-19 16:13:35 -08003031 // only consider the layers on the given layer stack
Lloyd Pique32cbe282018-10-19 13:09:22 -07003032 if (!display->belongsInOutput(layer->getLayerStack())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003033 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003034 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003035
Mathias Agopianab028732010-03-16 16:41:46 -07003036 /*
3037 * opaqueRegion: area of a surface that is fully opaque.
3038 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003039 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003040
3041 /*
3042 * visibleRegion: area of a surface that is visible on screen
3043 * and not fully transparent. This is essentially the layer's
3044 * footprint minus the opaque regions above it.
3045 * Areas covered by a translucent surface are considered visible.
3046 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003047 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003048
3049 /*
3050 * coveredRegion: area of a surface that is covered by all
3051 * visible regions above it (which includes the translucent areas).
3052 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003053 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003054
Jesse Halla8026d22012-09-25 13:25:04 -07003055 /*
3056 * transparentRegion: area of a surface that is hinted to be completely
3057 * transparent. This is only used to tell when the layer has no visible
3058 * non-transparent regions and can be removed from the layer list. It
3059 * does not affect the visibleRegion of this layer or any layers
3060 * beneath it. The hint may not be correct if apps don't respect the
3061 * SurfaceView restrictions (which, sadly, some don't).
3062 */
3063 Region transparentRegion;
3064
Mathias Agopianab028732010-03-16 16:41:46 -07003065
3066 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003067 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003068 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003069 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003070
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003071 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003072 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003073 if (!visibleRegion.isEmpty()) {
3074 // Remove the transparent area from the visible region
3075 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003076 if (tr.preserveRects()) {
3077 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003078 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003079 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003080 // transformation too complex, can't do the
3081 // transparent region optimization.
3082 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003083 }
Mathias Agopianab028732010-03-16 16:41:46 -07003084 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003085
Mathias Agopianab028732010-03-16 16:41:46 -07003086 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003087 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003088 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003089 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003090 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003091 // the opaque region is the layer's footprint
3092 opaqueRegion = visibleRegion;
3093 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003094 }
3095 }
3096
Robert Carre5f4f692018-01-12 13:12:28 -08003097 if (visibleRegion.isEmpty()) {
3098 layer->clearVisibilityRegions();
3099 return;
3100 }
3101
Mathias Agopianab028732010-03-16 16:41:46 -07003102 // Clip the covered region to the visible region
3103 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3104
3105 // Update aboveCoveredLayers for next (lower) layer
3106 aboveCoveredLayers.orSelf(visibleRegion);
3107
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003108 // subtract the opaque region covered by the layers above us
3109 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003110
3111 // compute this layer's dirty region
3112 if (layer->contentDirty) {
3113 // we need to invalidate the whole region
3114 dirty = visibleRegion;
3115 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003116 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003117 layer->contentDirty = false;
3118 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003119 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003120 * the exposed region consists of two components:
3121 * 1) what's VISIBLE now and was COVERED before
3122 * 2) what's EXPOSED now less what was EXPOSED before
3123 *
3124 * note that (1) is conservative, we start with the whole
3125 * visible region but only keep what used to be covered by
3126 * something -- which mean it may have been exposed.
3127 *
3128 * (2) handles areas that were not covered by anything but got
3129 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003130 */
Mathias Agopianab028732010-03-16 16:41:46 -07003131 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003132 const Region oldVisibleRegion = layer->visibleRegion;
3133 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003134 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3135 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003136 }
3137 dirty.subtractSelf(aboveOpaqueLayers);
3138
3139 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003140 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003141
Mathias Agopianab028732010-03-16 16:41:46 -07003142 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003143 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003144
Jesse Halla8026d22012-09-25 13:25:04 -07003145 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003146 layer->setVisibleRegion(visibleRegion);
3147 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003148 layer->setVisibleNonTransparentRegion(
3149 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003150 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003151
Mathias Agopian87baae12012-07-31 12:38:26 -07003152 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003153}
3154
Chia-I Wuab0c3192017-08-01 11:29:00 -07003155void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003156 for (const auto& [token, displayDevice] : mDisplays) {
3157 auto display = displayDevice->getCompositionDisplay();
3158 if (display->belongsInOutput(layer->getLayerStack())) {
3159 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003160 }
3161 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003162}
3163
Dan Stoza6b9454d2014-11-07 16:00:59 -08003164bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003165{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003166 ALOGV("handlePageFlip");
3167
Brian Andersond6927fb2016-07-23 23:37:30 -07003168 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003169
Mathias Agopian4fec8732012-06-29 14:12:52 -07003170 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003171 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003172 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003173
3174 // Store the set of layers that need updates. This set must not change as
3175 // buffers are being latched, as this could result in a deadlock.
3176 // Example: Two producers share the same command stream and:
3177 // 1.) Layer 0 is latched
3178 // 2.) Layer 0 gets a new frame
3179 // 2.) Layer 1 gets a new frame
3180 // 3.) Layer 1 is latched.
3181 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3182 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003183 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003184 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003185 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003186 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3187 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003188 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003189 } else {
3190 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003191 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003192 } else {
3193 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003194 }
Robert Carr2047fae2016-11-28 14:09:09 -08003195 });
3196
Lloyd Piquef2c79392018-12-20 16:23:33 -08003197 if (!mLayersWithQueuedFrames.empty()) {
3198 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3199 // writes to Layer current state. See also b/119481871
3200 Mutex::Autolock lock(mStateLock);
3201
3202 for (auto& layer : mLayersWithQueuedFrames) {
3203 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3204 layer->useSurfaceDamage();
3205 invalidateLayerStack(layer, dirty);
3206 if (layer->isBufferLatched()) {
3207 newDataLatched = true;
3208 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003209 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003210 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003211
Alec Mouri86770e52018-09-24 22:40:58 +00003212 // Clear the renderengine fence here...
3213 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3214 // clear instead of sp::clear.
3215 getBE().flushFence = Fence::NO_FENCE;
3216
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003217 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003218
Vishnu Nairde19f852018-12-18 16:11:53 -08003219 if (visibleRegions) {
3220 // Update input window info if the layer receives its first buffer.
3221 updateInputWindows();
3222 }
3223
Dan Stoza6b9454d2014-11-07 16:00:59 -08003224 // If we will need to wake up at some time in the future to deal with a
3225 // queued frame that shouldn't be displayed during this vsync period, wake
3226 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003227 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003228 signalLayerUpdate();
3229 }
3230
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003231 // enter boot animation on first buffer latch
3232 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3233 ALOGI("Enter boot animation");
3234 mBootStage = BootStage::BOOTANIMATION;
3235 }
3236
Dan Stoza6b9454d2014-11-07 16:00:59 -08003237 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003238 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003239}
3240
Mathias Agopianad456f92011-01-13 17:53:01 -08003241void SurfaceFlinger::invalidateHwcGeometry()
3242{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003243 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003244}
3245
Lloyd Pique32cbe282018-10-19 13:09:22 -07003246void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003247 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003248 auto display = displayDevice->getCompositionDisplay();
3249
Dan Stoza71433162014-02-04 16:22:36 -08003250 // We only need to actually compose the display if:
3251 // 1) It is being handled by hardware composer, which may need this to
3252 // keep its virtual display state machine in sync, or
3253 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003254 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003255 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003256 return;
3257 }
3258
Dan Stoza9e56aa02015-11-02 13:00:03 -08003259 ALOGV("doDisplayComposition");
Lloyd Pique32cbe282018-10-19 13:09:22 -07003260 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003261
3262 // swap buffers (presentation)
Lloyd Pique31cb2942018-10-19 17:23:03 -07003263 display->getRenderSurface()->queueBuffer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003264}
3265
Lloyd Pique32cbe282018-10-19 13:09:22 -07003266bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003267 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003268
Lloyd Pique32cbe282018-10-19 13:09:22 -07003269 auto display = displayDevice->getCompositionDisplay();
3270 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003271 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003272
3273 const Region bounds(displayState.bounds);
3274 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003275 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003276 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003277
Peiyong Lind3788632018-09-18 16:01:31 -07003278 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003279 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003280
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003281 // Framebuffer will live in this scope for GPU composition.
3282 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
3283
Dan Stoza9e56aa02015-11-02 13:00:03 -08003284 if (hasClientComposition) {
3285 ALOGV("hasClientComposition");
3286
Lloyd Pique31cb2942018-10-19 17:23:03 -07003287 sp<GraphicBuffer> buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003288
3289 if (buf == nullptr) {
3290 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3291 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003292 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003293 return false;
3294 }
3295
3296 // Bind the framebuffer in this scope.
3297 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3298 buf->getNativeBuffer());
3299
3300 if (fbo->getStatus() != NO_ERROR) {
3301 ALOGW("Binding buffer for display [%s] failed with status: %d",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003302 displayDevice->getDisplayName().c_str(), fbo->getStatus());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003303 return false;
3304 }
3305
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003306 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003307 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003308 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003309 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003310 }
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003311 getRenderEngine().setOutputDataSpace(outputDataspace);
3312 getRenderEngine().setDisplayMaxLuminance(
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003313 profile->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003314
Lloyd Pique441d5042018-10-18 16:49:51 -07003315 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003316 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003317 getHwComposer()
3318 .hasDisplayCapability(displayId,
3319 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003320
Peiyong Lind3788632018-09-18 16:01:31 -07003321 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003322 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3323 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003324 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003325 }
3326
Lloyd Pique31cb2942018-10-19 17:23:03 -07003327 display->getRenderSurface()->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003328
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003329 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003330 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003331 // when using overlays, we assume a fully transparent framebuffer
3332 // NOTE: we could reduce how much we need to clear, for instance
3333 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003334 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003335 // We'll revisit later if needed.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003336 getRenderEngine().clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003337 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003338 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003339 // we're left with the letterbox region
3340 // (common case is that letterbox ends-up being empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003341 const Region letterbox = bounds.subtract(displayState.scissor);
Mathias Agopian766dc492012-10-30 18:08:06 -07003342
3343 // compute the area to clear
Lloyd Pique32cbe282018-10-19 13:09:22 -07003344 const Region region = displayState.undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003345
Mathias Agopianb9494d52012-04-18 02:28:45 -07003346 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003347 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003348 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003349 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003350 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003351 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003352
Lloyd Pique32cbe282018-10-19 13:09:22 -07003353 const Rect& bounds = displayState.bounds;
3354 const Rect& scissor = displayState.scissor;
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003355 if (scissor != bounds) {
3356 // scissor doesn't match the screen's dimensions, so we
3357 // need to clear everything outside of it and enable
3358 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003359
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003360 // enable scissor for this frame
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003361 getRenderEngine().setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003362 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003363 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003364
Mathias Agopian85d751c2012-08-29 16:59:24 -07003365 /*
3366 * and then, render the layers targeted at the framebuffer
3367 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003368
Dan Stoza9e56aa02015-11-02 13:00:03 -08003369 ALOGV("Rendering client layers");
Lloyd Pique32cbe282018-10-19 13:09:22 -07003370 const ui::Transform& displayTransform = displayState.transform;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003371 bool firstLayer = true;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003372 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003373 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003374 displayTransform.transform(layer->visibleRegion)));
3375 ALOGV("Layer: %s", layer->getName().string());
3376 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003377 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003378 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003379 case HWC2::Composition::Cursor:
3380 case HWC2::Composition::Device:
3381 case HWC2::Composition::Sideband:
3382 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003383 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003384 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003385 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003386 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003387 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003388 // never clear the very first layer since we're
3389 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003390 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003391 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003392 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003393 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003394 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003395 if (layer->hasColorTransform()) {
3396 mat4 tmpMatrix;
3397 if (applyColorMatrix) {
3398 tmpMatrix = mDrawingState.colorMatrix;
3399 }
3400 tmpMatrix *= layer->getColorTransform();
Peiyong Lind3788632018-09-18 16:01:31 -07003401 getRenderEngine().setColorTransform(tmpMatrix);
3402 } else {
3403 getRenderEngine().setColorTransform(colorMatrix);
3404 }
David Sodmanc1498e62018-09-12 14:36:26 -07003405 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003406 break;
3407 }
3408 default:
3409 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003410 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003411 } else {
3412 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003413 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003414 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003415 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003416
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003417 // Perform some cleanup steps if we used client composition.
3418 if (hasClientComposition) {
3419 getRenderEngine().setColorTransform(mat4());
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003420 getRenderEngine().disableScissor();
Lloyd Pique31cb2942018-10-19 17:23:03 -07003421 display->getRenderSurface()->finishBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003422 // Clear out error flags here so that we don't wait until next
3423 // composition to log.
3424 getRenderEngine().checkErrors();
3425 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003426 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003427}
3428
Chia-I Wu28e3a252018-09-07 12:05:02 -07003429void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003430 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003431 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003432}
3433
Dan Stoza7d89d062015-04-30 13:29:25 -07003434status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003435 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003436 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003437 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003438 const sp<Layer>& parent,
3439 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003440{
Dan Stoza7d89d062015-04-30 13:29:25 -07003441 // add this layer to the current state list
3442 {
3443 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003444 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003445 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3446 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003447 return NO_MEMORY;
3448 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003449 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003450 mCurrentState.layersSortedByZ.add(lbc);
Robert Carrb89ea9d2018-12-10 13:01:14 -08003451 } else if (parent == nullptr || parent->isRemovedFromCurrentState()) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003452 ALOGE("addClientLayer called with a removed parent");
chaviw61626f22018-11-15 16:26:27 -08003453 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003454 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003455 parent->addChild(lbc);
3456 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003457
Yiwei Zhang243b3782018-05-15 17:40:04 -07003458 if (gbc != nullptr) {
3459 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3460 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3461 mMaxGraphicBufferProducerListSize,
3462 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3463 mGraphicBufferProducerList.size(),
3464 mMaxGraphicBufferProducerListSize, mNumLayers);
3465 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003466 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003467 }
3468
Mathias Agopian96f08192010-06-02 23:28:45 -07003469 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003470 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003471
Dan Stoza7d89d062015-04-30 13:29:25 -07003472 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003473}
3474
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003475uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003476 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003477}
3478
Mathias Agopian3f844832013-08-07 21:24:32 -07003479uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003480 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003481}
3482
Mathias Agopian3f844832013-08-07 21:24:32 -07003483uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003484 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003485}
3486
3487uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003488 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003489 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003490 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003491 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003492 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003493 }
3494 return old;
3495}
3496
Marissa Wall713b63f2018-10-17 15:42:43 -07003497bool SurfaceFlinger::flushTransactionQueues() {
3498 Mutex::Autolock _l(mStateLock);
3499 auto it = mTransactionQueues.begin();
3500 while (it != mTransactionQueues.end()) {
3501 auto& [applyToken, transactionQueue] = *it;
3502
3503 while (!transactionQueue.empty()) {
3504 const auto& [states, displays, flags] = transactionQueue.front();
3505 if (composerStateContainsUnsignaledFences(states)) {
3506 break;
3507 }
chaviw273171b2018-12-26 11:46:30 -08003508 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003509 transactionQueue.pop();
3510 }
3511
3512 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3513 }
3514 return mTransactionQueues.empty();
3515}
3516
chaviwca27f252018-02-06 16:46:39 -08003517bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3518 for (const ComposerState& state : states) {
3519 // Here we need to check that the interface we're given is indeed
3520 // one of our own. A malicious client could give us a nullptr
3521 // IInterface, or one of its own or even one of our own but a
3522 // different type. All these situations would cause us to crash.
3523 if (state.client == nullptr) {
3524 return true;
3525 }
3526
3527 sp<IBinder> binder = IInterface::asBinder(state.client);
3528 if (binder == nullptr) {
3529 return true;
3530 }
3531
3532 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3533 return true;
3534 }
3535 }
3536 return false;
3537}
3538
Marissa Wall713b63f2018-10-17 15:42:43 -07003539bool SurfaceFlinger::composerStateContainsUnsignaledFences(const Vector<ComposerState>& states) {
3540 for (const ComposerState& state : states) {
3541 const layer_state_t& s = state.state;
3542 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3543 continue;
3544 }
3545 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
3546 return true;
3547 }
3548 }
3549 return false;
3550}
3551
3552void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3553 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003554 const sp<IBinder>& applyToken,
3555 const InputWindowCommands& inputWindowCommands) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003556 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003557 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003558
chaviwca27f252018-02-06 16:46:39 -08003559 if (containsAnyInvalidClientState(states)) {
3560 return;
3561 }
3562
Marissa Wall713b63f2018-10-17 15:42:43 -07003563 // If its TransactionQueue already has a pending TransactionState or if it is pending
3564 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
3565 composerStateContainsUnsignaledFences(states)) {
3566 mTransactionQueues[applyToken].emplace(states, displays, flags);
3567 setTransactionFlags(eTransactionNeeded);
3568 return;
3569 }
3570
chaviw273171b2018-12-26 11:46:30 -08003571 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003572}
3573
3574void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003575 const Vector<DisplayState>& displays, uint32_t flags,
3576 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003577 uint32_t transactionFlags = 0;
3578
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003579 if (flags & eAnimation) {
3580 // For window updates that are part of an animation we must wait for
3581 // previous animation "frames" to be handled.
3582 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003583 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003584 if (CC_UNLIKELY(err != NO_ERROR)) {
3585 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003586 // caller after a few seconds.
3587 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3588 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003589 mAnimTransactionPending = false;
3590 break;
3591 }
3592 }
3593 }
3594
chaviwca27f252018-02-06 16:46:39 -08003595 for (const DisplayState& display : displays) {
3596 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003597 }
3598
Marissa Walle2ffb422018-10-12 11:33:52 -07003599 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003600 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003601 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003602 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003603 // If the state doesn't require a traversal and there are callbacks, send them now
3604 if (!(clientStateFlags & eTraversalNeeded)) {
3605 mTransactionCompletedThread.sendCallbacks();
3606 }
3607 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003608
chaviw273171b2018-12-26 11:46:30 -08003609 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3610
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003611 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3612 // anyway. This can be used as a flush mechanism for previous async transactions.
3613 // Empty animation transaction can be used to simulate back-pressure, so also force a
3614 // transaction for empty animation transactions.
3615 if (transactionFlags == 0 &&
3616 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003617 transactionFlags = eTransactionNeeded;
3618 }
3619
Mathias Agopian386aa982011-11-07 21:58:03 -08003620 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003621 if (mInterceptor->isEnabled()) {
3622 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003623 }
Irvel468051e2016-06-13 16:44:44 -07003624
Mathias Agopian386aa982011-11-07 21:58:03 -08003625 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003626 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3627 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003628 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003629
3630 // if this is a synchronous transaction, wait for it to take effect
3631 // before returning.
3632 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003633 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003634 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003635 if (flags & eAnimation) {
3636 mAnimTransactionPending = true;
3637 }
3638 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003639 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3640 if (CC_UNLIKELY(err != NO_ERROR)) {
3641 // just in case something goes wrong in SF, return to the
3642 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003643 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3644 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003645 break;
3646 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003647 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003648 }
3649}
3650
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003651uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3652 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3653 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003654
Mathias Agopiane57f2922012-08-09 16:29:12 -07003655 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003656 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3657
3658 const uint32_t what = s.what;
3659 if (what & DisplayState::eSurfaceChanged) {
3660 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3661 state.surface = s.surface;
3662 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003663 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003664 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003665 if (what & DisplayState::eLayerStackChanged) {
3666 if (state.layerStack != s.layerStack) {
3667 state.layerStack = s.layerStack;
3668 flags |= eDisplayTransactionNeeded;
3669 }
3670 }
3671 if (what & DisplayState::eDisplayProjectionChanged) {
3672 if (state.orientation != s.orientation) {
3673 state.orientation = s.orientation;
3674 flags |= eDisplayTransactionNeeded;
3675 }
3676 if (state.frame != s.frame) {
3677 state.frame = s.frame;
3678 flags |= eDisplayTransactionNeeded;
3679 }
3680 if (state.viewport != s.viewport) {
3681 state.viewport = s.viewport;
3682 flags |= eDisplayTransactionNeeded;
3683 }
3684 }
3685 if (what & DisplayState::eDisplaySizeChanged) {
3686 if (state.width != s.width) {
3687 state.width = s.width;
3688 flags |= eDisplayTransactionNeeded;
3689 }
3690 if (state.height != s.height) {
3691 state.height = s.height;
3692 flags |= eDisplayTransactionNeeded;
3693 }
3694 }
3695
Mathias Agopiane57f2922012-08-09 16:29:12 -07003696 return flags;
3697}
3698
Robert Carrd4ae7f32018-06-07 16:10:57 -07003699bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3700 IPCThreadState* ipc = IPCThreadState::self();
3701 const int pid = ipc->getCallingPid();
3702 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003703 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003704 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003705 return false;
3706 }
3707 return true;
3708}
3709
chaviwca27f252018-02-06 16:46:39 -08003710uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3711 const layer_state_t& s = composerState.state;
3712 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3713
Mathias Agopian13127d82013-03-05 17:47:11 -08003714 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003715 if (layer == nullptr) {
3716 return 0;
3717 }
3718
chaviw8b3871a2017-11-01 17:41:01 -07003719 uint32_t flags = 0;
3720
Garfield Tan8a3083e2018-12-03 13:21:07 -08003721 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003722 bool geometryAppliesWithResize =
3723 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003724
3725 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3726 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003727 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003728 layer->pushPendingState();
3729 }
3730
chaviw8b3871a2017-11-01 17:41:01 -07003731 if (what & layer_state_t::ePositionChanged) {
3732 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3733 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003734 }
chaviw8b3871a2017-11-01 17:41:01 -07003735 }
3736 if (what & layer_state_t::eLayerChanged) {
3737 // NOTE: index needs to be calculated before we update the state
3738 const auto& p = layer->getParent();
3739 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003740 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003741 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003742 mCurrentState.layersSortedByZ.removeAt(idx);
3743 mCurrentState.layersSortedByZ.add(layer);
3744 // we need traversal (state changed)
3745 // AND transaction (list changed)
3746 flags |= eTransactionNeeded|eTraversalNeeded;
3747 }
chaviw8b3871a2017-11-01 17:41:01 -07003748 } else {
3749 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003750 flags |= eTransactionNeeded|eTraversalNeeded;
3751 }
3752 }
chaviw8b3871a2017-11-01 17:41:01 -07003753 }
3754 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003755 // NOTE: index needs to be calculated before we update the state
3756 const auto& p = layer->getParent();
3757 if (p == nullptr) {
3758 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3759 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3760 mCurrentState.layersSortedByZ.removeAt(idx);
3761 mCurrentState.layersSortedByZ.add(layer);
3762 // we need traversal (state changed)
3763 // AND transaction (list changed)
3764 flags |= eTransactionNeeded|eTraversalNeeded;
3765 }
3766 } else {
3767 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3768 flags |= eTransactionNeeded|eTraversalNeeded;
3769 }
chaviw8b3871a2017-11-01 17:41:01 -07003770 }
3771 }
3772 if (what & layer_state_t::eSizeChanged) {
3773 if (layer->setSize(s.w, s.h)) {
3774 flags |= eTraversalNeeded;
3775 }
3776 }
3777 if (what & layer_state_t::eAlphaChanged) {
3778 if (layer->setAlpha(s.alpha))
3779 flags |= eTraversalNeeded;
3780 }
3781 if (what & layer_state_t::eColorChanged) {
3782 if (layer->setColor(s.color))
3783 flags |= eTraversalNeeded;
3784 }
Peiyong Lind3788632018-09-18 16:01:31 -07003785 if (what & layer_state_t::eColorTransformChanged) {
3786 if (layer->setColorTransform(s.colorTransform)) {
3787 flags |= eTraversalNeeded;
3788 }
3789 }
chaviw8b3871a2017-11-01 17:41:01 -07003790 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003791 // TODO: b/109894387
3792 //
3793 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3794 // rotation. To see the problem observe that if we have a square parent, and a child
3795 // of the same size, then we rotate the child 45 degrees around it's center, the child
3796 // must now be cropped to a non rectangular 8 sided region.
3797 //
3798 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3799 // private API, and the WindowManager only uses rotation in one case, which is on a top
3800 // level layer in which cropping is not an issue.
3801 //
3802 // However given that abuse of rotation matrices could lead to surfaces extending outside
3803 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3804 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3805 // transformations.
3806 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003807 flags |= eTraversalNeeded;
3808 }
3809 if (what & layer_state_t::eTransparentRegionChanged) {
3810 if (layer->setTransparentRegionHint(s.transparentRegion))
3811 flags |= eTraversalNeeded;
3812 }
3813 if (what & layer_state_t::eFlagsChanged) {
3814 if (layer->setFlags(s.flags, s.mask))
3815 flags |= eTraversalNeeded;
3816 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003817 if (what & layer_state_t::eCropChanged_legacy) {
3818 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003819 flags |= eTraversalNeeded;
3820 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003821 if (what & layer_state_t::eCornerRadiusChanged) {
3822 if (layer->setCornerRadius(s.cornerRadius))
3823 flags |= eTraversalNeeded;
3824 }
chaviw8b3871a2017-11-01 17:41:01 -07003825 if (what & layer_state_t::eLayerStackChanged) {
3826 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3827 // We only allow setting layer stacks for top level layers,
3828 // everything else inherits layer stack from its parent.
3829 if (layer->hasParent()) {
3830 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3831 layer->getName().string());
3832 } else if (idx < 0) {
3833 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3834 "that also does not appear in the top level layer list. Something"
3835 " has gone wrong.", layer->getName().string());
3836 } else if (layer->setLayerStack(s.layerStack)) {
3837 mCurrentState.layersSortedByZ.removeAt(idx);
3838 mCurrentState.layersSortedByZ.add(layer);
3839 // we need traversal (state changed)
3840 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003841 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003842 }
3843 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003844 if (what & layer_state_t::eDeferTransaction_legacy) {
3845 if (s.barrierHandle_legacy != nullptr) {
3846 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3847 } else if (s.barrierGbp_legacy != nullptr) {
3848 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003849 if (authenticateSurfaceTextureLocked(gbp)) {
3850 const auto& otherLayer =
3851 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003852 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003853 } else {
3854 ALOGE("Attempt to defer transaction to to an"
3855 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003856 }
3857 }
chaviw8b3871a2017-11-01 17:41:01 -07003858 // We don't trigger a traversal here because if no other state is
3859 // changed, we don't want this to cause any more work
3860 }
3861 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003862 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003863 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003864 if (!hadParent) {
3865 mCurrentState.layersSortedByZ.remove(layer);
3866 }
chaviw8b3871a2017-11-01 17:41:01 -07003867 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003868 }
chaviw8b3871a2017-11-01 17:41:01 -07003869 }
3870 if (what & layer_state_t::eReparentChildren) {
3871 if (layer->reparentChildren(s.reparentHandle)) {
3872 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003873 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003874 }
chaviw8b3871a2017-11-01 17:41:01 -07003875 if (what & layer_state_t::eDetachChildren) {
3876 layer->detachChildren();
3877 }
3878 if (what & layer_state_t::eOverrideScalingModeChanged) {
3879 layer->setOverrideScalingMode(s.overrideScalingMode);
3880 // We don't trigger a traversal here because if no other state is
3881 // changed, we don't want this to cause any more work
3882 }
Marissa Wall61c58622018-07-18 10:12:20 -07003883 if (what & layer_state_t::eTransformChanged) {
3884 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3885 }
3886 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3887 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3888 flags |= eTraversalNeeded;
3889 }
3890 if (what & layer_state_t::eCropChanged) {
3891 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3892 }
Marissa Wall861616d2018-10-22 12:52:23 -07003893 if (what & layer_state_t::eFrameChanged) {
3894 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3895 }
Marissa Wall61c58622018-07-18 10:12:20 -07003896 if (what & layer_state_t::eBufferChanged) {
3897 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3898 }
3899 if (what & layer_state_t::eAcquireFenceChanged) {
3900 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3901 }
3902 if (what & layer_state_t::eDataspaceChanged) {
3903 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3904 }
3905 if (what & layer_state_t::eHdrMetadataChanged) {
3906 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3907 }
3908 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3909 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3910 }
3911 if (what & layer_state_t::eApiChanged) {
3912 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3913 }
3914 if (what & layer_state_t::eSidebandStreamChanged) {
3915 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3916 }
Robert Carr720e5062018-07-30 17:45:14 -07003917 if (what & layer_state_t::eInputInfoChanged) {
3918 layer->setInputInfo(s.inputInfo);
3919 flags |= eTraversalNeeded;
3920 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003921 std::vector<sp<CallbackHandle>> callbackHandles;
3922 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3923 mTransactionCompletedThread.run();
3924 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3925 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3926 }
3927 }
3928 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3929 // Do not put anything that updates layer state or modifies flags after
3930 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003931 return flags;
3932}
3933
chaviw273171b2018-12-26 11:46:30 -08003934uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3935 uint32_t flags = 0;
3936 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3937 flags |= eTraversalNeeded;
3938 }
3939
3940 mInputWindowCommands.merge(inputWindowCommands);
3941 return flags;
3942}
3943
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003944status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003945 const String8& name,
3946 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003947 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003948 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003949 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003950{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003951 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003952 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003953 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003954 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003955 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003956
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003957 status_t result = NO_ERROR;
3958
3959 sp<Layer> layer;
3960
Cody Northropbc755282017-03-31 12:00:08 -06003961 String8 uniqueName = getUniqueLayerName(name);
3962
Mathias Agopian3165cc22012-08-08 19:42:09 -07003963 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003964 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003965 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3966 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003967
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003968 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003969 case ISurfaceComposerClient::eFXSurfaceBufferState:
3970 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3971 break;
chaviw13fdc492017-06-27 12:40:18 -07003972 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003973 // check if buffer size is set for color layer.
3974 if (w > 0 || h > 0) {
3975 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3976 int(w), int(h));
3977 return BAD_VALUE;
3978 }
3979
chaviw13fdc492017-06-27 12:40:18 -07003980 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003981 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003982 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003983 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003984 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003985 // check if buffer size is set for container layer.
3986 if (w > 0 || h > 0) {
3987 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3988 int(w), int(h));
3989 return BAD_VALUE;
3990 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07003991 result = createContainerLayer(client,
3992 uniqueName, w, h, flags,
3993 handle, &layer);
3994 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003995 default:
3996 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003997 break;
3998 }
3999
Dan Stoza7d89d062015-04-30 13:29:25 -07004000 if (result != NO_ERROR) {
4001 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004002 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004003
Chia-I Wuab0c3192017-08-01 11:29:00 -07004004 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4005 // TODO b/64227542
4006 if (windowType == 441731) {
4007 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
4008 layer->setPrimaryDisplayOnly();
4009 }
4010
Albert Chaulk479c60c2017-01-27 14:21:34 -05004011 layer->setInfo(windowType, ownerUid);
4012
Robert Carrb89ea9d2018-12-10 13:01:14 -08004013 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4014 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4015 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004016 if (result != NO_ERROR) {
4017 return result;
4018 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004019 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004020
4021 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004022 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004023}
4024
Cody Northropbc755282017-03-31 12:00:08 -06004025String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4026{
4027 bool matchFound = true;
4028 uint32_t dupeCounter = 0;
4029
4030 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4031 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4032
Dan Stoza436ccf32018-06-21 12:10:12 -07004033 // Grab the state lock since we're accessing mCurrentState
4034 Mutex::Autolock lock(mStateLock);
4035
Cody Northropbc755282017-03-31 12:00:08 -06004036 // Loop over layers until we're sure there is no matching name
4037 while (matchFound) {
4038 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004039 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004040 if (layer->getName() == uniqueName) {
4041 matchFound = true;
4042 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4043 }
4044 });
4045 }
4046
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004047 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4048 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004049
4050 return uniqueName;
4051}
4052
Marissa Wallfd668622018-05-10 10:21:13 -07004053status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4054 uint32_t w, uint32_t h, uint32_t flags,
4055 PixelFormat& format, sp<IBinder>* handle,
4056 sp<IGraphicBufferProducer>* gbp,
4057 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004058 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004059 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004060 case PIXEL_FORMAT_TRANSPARENT:
4061 case PIXEL_FORMAT_TRANSLUCENT:
4062 format = PIXEL_FORMAT_RGBA_8888;
4063 break;
4064 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004065 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004066 break;
4067 }
4068
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004069 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004070 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004071 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004072 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004073 *handle = layer->getHandle();
4074 *gbp = layer->getProducer();
4075 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004076 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004077
Marissa Wallfd668622018-05-10 10:21:13 -07004078 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004079 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004080}
4081
Marissa Wall61c58622018-07-18 10:12:20 -07004082status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4083 uint32_t w, uint32_t h, uint32_t flags,
4084 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004085 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004086 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004087 *handle = layer->getHandle();
4088 *outLayer = layer;
4089
4090 return NO_ERROR;
4091}
4092
chaviw13fdc492017-06-27 12:40:18 -07004093status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004094 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004095 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004096{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004097 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004098 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004099 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004100}
4101
Robert Carr6b3f6c52018-08-13 13:05:17 -07004102status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4103 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4104 sp<IBinder>* handle, sp<Layer>* outLayer)
4105{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004106 *outLayer =
4107 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004108 *handle = (*outLayer)->getHandle();
4109 return NO_ERROR;
4110}
4111
4112
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004113void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004114 mLayersPendingRemoval.add(layer);
4115 mLayersRemoved = true;
4116 setTransactionFlags(eTransactionNeeded);
4117}
4118
Robert Carr695d5282018-12-18 15:27:58 -08004119void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004120{
Robert Carr2e102c92018-10-23 12:11:15 -07004121 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004122 // If a layer has a parent, we allow it to out-live it's handle
4123 // with the idea that the parent holds a reference and will eventually
4124 // be cleaned up. However no one cleans up the top-level so we do so
4125 // here.
4126 if (layer->getParent() == nullptr) {
4127 mCurrentState.layersSortedByZ.remove(layer);
4128 }
4129 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004130 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004131}
4132
Mathias Agopianb60314a2012-04-10 22:09:54 -07004133// ---------------------------------------------------------------------------
4134
Andy McFadden13a082e2012-08-24 10:16:42 -07004135void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004136 const auto displayToken = getInternalDisplayToken();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004137 if (!displayToken) return;
4138
Jesse Hall01e29052013-02-19 16:13:35 -08004139 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004140 Vector<ComposerState> state;
4141 Vector<DisplayState> displays;
4142 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004143 d.what = DisplayState::eDisplayProjectionChanged |
4144 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004145 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08004146 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004147 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004148 d.frame.makeInvalid();
4149 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004150 d.width = 0;
4151 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004152 displays.add(d);
chaviw273171b2018-12-26 11:46:30 -08004153 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004154
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004155 const auto display = getDisplayDevice(displayToken);
4156 if (!display) return;
4157
Dominik Laskowskie9774092018-12-11 10:04:24 -08004158 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004159
Dominik Laskowski075d3172018-05-24 15:50:06 -07004160 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08004161 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07004162 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004163
Brian Andersond0010582017-03-07 13:20:31 -08004164 // Use phase of 0 since phase is not known.
4165 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07004166 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
4167 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004168}
4169
4170void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004171 // Async since we may be called from the main thread.
4172 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004173}
4174
Dominik Laskowskie9774092018-12-11 10:04:24 -08004175void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004176 if (display->isVirtual()) {
4177 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004178 return;
4179 }
4180
Dominik Laskowski075d3172018-05-24 15:50:06 -07004181 const auto displayId = display->getId();
4182 LOG_ALWAYS_FATAL_IF(!displayId);
4183
Dominik Laskowski34157762018-10-31 13:07:19 -07004184 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004185
4186 int currentMode = display->getPowerMode();
4187 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004188 return;
4189 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004190
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004191 display->setPowerMode(mode);
4192
Lloyd Pique4dccc412018-01-22 17:21:36 -08004193 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004194 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004195 }
4196
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004197 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004198 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004199 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004200 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004201 if (mUseScheduler) {
4202 mScheduler->onScreenAcquired(mAppConnectionHandle);
4203 } else {
4204 mEventThread->onScreenAcquired();
4205 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07004206 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004207 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004208
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004209 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004210 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004211 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004212
4213 struct sched_param param = {0};
4214 param.sched_priority = 1;
4215 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4216 ALOGW("Couldn't set SCHED_FIFO on display on");
4217 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004218 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004219 // Turn off the display
4220 struct sched_param param = {0};
4221 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4222 ALOGW("Couldn't set SCHED_OTHER on display off");
4223 }
4224
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004225 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004226 if (mUseScheduler) {
4227 mScheduler->disableHardwareVsync(true);
4228 } else {
4229 disableHardwareVsync(true); // also cancels any in-progress resync
4230 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004231 if (mUseScheduler) {
4232 mScheduler->onScreenReleased(mAppConnectionHandle);
4233 } else {
4234 mEventThread->onScreenReleased();
4235 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004236 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004237
Dominik Laskowski075d3172018-05-24 15:50:06 -07004238 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004239 mVisibleRegionsDirty = true;
4240 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004241 } else if (mode == HWC_POWER_MODE_DOZE ||
4242 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004243 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004244 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004245 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004246 if (mUseScheduler) {
4247 mScheduler->onScreenAcquired(mAppConnectionHandle);
4248 } else {
4249 mEventThread->onScreenAcquired();
4250 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004251 resyncToHardwareVsync(true);
4252 }
4253 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4254 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004255 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004256 if (mUseScheduler) {
4257 mScheduler->disableHardwareVsync(true);
4258 } else {
4259 disableHardwareVsync(true); // also cancels any in-progress resync
4260 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004261 if (mUseScheduler) {
4262 mScheduler->onScreenReleased(mAppConnectionHandle);
4263 } else {
4264 mEventThread->onScreenReleased();
4265 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004266 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004267 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004268 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004269 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004270 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004271 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004272
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004273 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004274 mTimeStats->setPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004275 }
4276
Dominik Laskowski34157762018-10-31 13:07:19 -07004277 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004278}
4279
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004280void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004281 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004282 const auto display = getDisplayDevice(displayToken);
4283 if (!display) {
4284 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4285 displayToken.get());
4286 } else if (display->isVirtual()) {
4287 ALOGW("Attempt to set power mode %d for virtual display", mode);
4288 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004289 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004290 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004291 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004292}
4293
4294// ---------------------------------------------------------------------------
4295
Lloyd Pique755e3192018-01-31 16:46:15 -08004296status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4297 NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004298 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004299
Mathias Agopianbd115332013-04-18 16:41:04 -07004300 IPCThreadState* ipc = IPCThreadState::self();
4301 const int pid = ipc->getCallingPid();
4302 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004303
Mathias Agopianbd115332013-04-18 16:41:04 -07004304 if ((uid != AID_SHELL) &&
4305 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004306 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4307 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004308 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004309 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004310 // (this would indicate SF is stuck, but we want to be able to
4311 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004312 status_t err = mStateLock.timedLock(s2ns(1));
4313 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004314 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004315 StringAppendF(&result,
4316 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4317 "(no locks held)\n",
4318 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004319 }
4320
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004321 bool dumpAll = true;
4322 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004323 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004324
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004325 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004326 if ((index < numArgs) &&
4327 (args[index] == String16("--list"))) {
4328 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004329 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004330 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004331 }
4332
4333 if ((index < numArgs) &&
4334 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004335 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004336 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004337 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004338 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004339
4340 if ((index < numArgs) &&
4341 (args[index] == String16("--latency-clear"))) {
4342 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004343 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004344 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004345 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004346
4347 if ((index < numArgs) &&
4348 (args[index] == String16("--dispsync"))) {
4349 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004350 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004351 dumpAll = false;
4352 }
Dan Stozab90cf072015-03-05 11:05:59 -08004353
4354 if ((index < numArgs) &&
4355 (args[index] == String16("--static-screen"))) {
4356 index++;
4357 dumpStaticScreenStats(result);
4358 dumpAll = false;
4359 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004360
4361 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004362 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004363 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004364 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004365 dumpAll = false;
4366 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004367
4368 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4369 index++;
4370 dumpWideColorInfo(result);
4371 dumpAll = false;
4372 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004373
4374 if ((index < numArgs) &&
4375 (args[index] == String16("--enable-layer-stats"))) {
4376 index++;
4377 mLayerStats.enable();
4378 dumpAll = false;
4379 }
4380
4381 if ((index < numArgs) &&
4382 (args[index] == String16("--disable-layer-stats"))) {
4383 index++;
4384 mLayerStats.disable();
4385 dumpAll = false;
4386 }
4387
4388 if ((index < numArgs) &&
4389 (args[index] == String16("--clear-layer-stats"))) {
4390 index++;
4391 mLayerStats.clear();
4392 dumpAll = false;
4393 }
4394
4395 if ((index < numArgs) &&
4396 (args[index] == String16("--dump-layer-stats"))) {
4397 index++;
4398 mLayerStats.dump(result);
4399 dumpAll = false;
4400 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004401
4402 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004403 (args[index] == String16("--frame-composition"))) {
4404 index++;
4405 dumpFrameCompositionInfo(result);
4406 dumpAll = false;
4407 }
4408
4409 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004410 (args[index] == String16("--display-identification"))) {
4411 index++;
4412 dumpDisplayIdentificationData(result);
4413 dumpAll = false;
4414 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004415
4416 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4417 index++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004418 mTimeStats->parseArgs(asProto, args, index, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004419 dumpAll = false;
4420 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004421 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004422
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004423 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004424 if (asProto) {
4425 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4426 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4427 } else {
4428 dumpAllLocked(args, index, result);
4429 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004430 }
4431
Mathias Agopian9795c422009-08-26 16:36:26 -07004432 if (locked) {
4433 mStateLock.unlock();
4434 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004435 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004436 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004437 return NO_ERROR;
4438}
4439
Yiwei Zhang5434a782018-12-05 18:06:32 -08004440void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */, size_t& /* index */,
4441 std::string& result) const {
4442 mCurrentState.traverseInZOrder(
4443 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004444}
4445
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004446void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004447 std::string& result) const {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004448 String8 name;
4449 if (index < args.size()) {
4450 name = String8(args[index]);
4451 index++;
4452 }
4453
Dominik Laskowski075d3172018-05-24 15:50:06 -07004454 if (const auto displayId = getInternalDisplayId();
4455 displayId && getHwComposer().isConnected(*displayId)) {
4456 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004457 const nsecs_t period = activeConfig->getVsyncPeriod();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004458 StringAppendF(&result, "%" PRId64 "\n", period);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004459 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004460
4461 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004462 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004463 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004464 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004465 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004466 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004467 }
Robert Carr2047fae2016-11-28 14:09:09 -08004468 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004469 }
4470}
4471
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004472void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004473 std::string& /* result */) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004474 String8 name;
4475 if (index < args.size()) {
4476 name = String8(args[index]);
4477 index++;
4478 }
4479
Robert Carr2047fae2016-11-28 14:09:09 -08004480 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004481 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004482 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004483 }
Robert Carr2047fae2016-11-28 14:09:09 -08004484 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004485
Svetoslavd85084b2014-03-20 10:28:31 -07004486 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004487}
4488
Jamie Gennis6547ff42013-07-16 20:12:42 -07004489// This should only be called from the main thread. Otherwise it would need
4490// the lock and should use mCurrentState rather than mDrawingState.
4491void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004492 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004493 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004494 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004495
4496 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4497}
4498
Yiwei Zhang5434a782018-12-05 18:06:32 -08004499void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004500 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004501
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004502 if (isLayerTripleBufferingDisabled())
4503 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004504
Yiwei Zhang5434a782018-12-05 18:06:32 -08004505 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4506 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4507 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4508 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4509 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4510 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004511 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004512}
4513
Yiwei Zhang5434a782018-12-05 18:06:32 -08004514void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4515 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004516 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4517 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004518 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004519 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004520 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004521 }
David Sodman4a36e932017-11-07 14:29:47 -08004522 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004523 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004524 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004525 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4526 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004527}
4528
Dan Stozae77c7662016-05-13 11:37:28 -07004529void SurfaceFlinger::recordBufferingStats(const char* layerName,
4530 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004531 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4532 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004533 for (const auto& segment : history) {
4534 if (!segment.usedThirdBuffer) {
4535 stats.twoBufferTime += segment.totalTime;
4536 }
4537 if (segment.occupancyAverage < 1.0f) {
4538 stats.doubleBufferedTime += segment.totalTime;
4539 } else if (segment.occupancyAverage < 2.0f) {
4540 stats.tripleBufferedTime += segment.totalTime;
4541 }
4542 ++stats.numSegments;
4543 stats.totalTime += segment.totalTime;
4544 }
4545}
4546
Yiwei Zhang5434a782018-12-05 18:06:32 -08004547void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4548 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004549
4550 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4551 const size_t count = currentLayers.size();
4552 for (size_t i=0 ; i<count ; i++) {
4553 currentLayers[i]->dumpFrameEvents(result);
4554 }
4555}
4556
Yiwei Zhang5434a782018-12-05 18:06:32 -08004557void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004558 result.append("Buffering stats:\n");
4559 result.append(" [Layer name] <Active time> <Two buffer> "
4560 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004561 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004562 typedef std::tuple<std::string, float, float, float> BufferTuple;
4563 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004564 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004565 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004566 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004567 if (stats.numSegments == 0) {
4568 continue;
4569 }
4570 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4571 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4572 stats.totalTime;
4573 float doubleBufferRatio = static_cast<float>(
4574 stats.doubleBufferedTime) / stats.totalTime;
4575 float tripleBufferRatio = static_cast<float>(
4576 stats.tripleBufferedTime) / stats.totalTime;
4577 sorted.insert({activeTime, {name, twoBufferRatio,
4578 doubleBufferRatio, tripleBufferRatio}});
4579 }
4580 for (const auto& sortedPair : sorted) {
4581 float activeTime = sortedPair.first;
4582 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004583 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4584 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004585 }
4586 result.append("\n");
4587}
4588
Yiwei Zhang5434a782018-12-05 18:06:32 -08004589void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004590 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004591 const auto displayId = display->getId();
4592 if (!displayId) {
4593 continue;
4594 }
4595 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004596 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004597 continue;
4598 }
4599
Yiwei Zhang5434a782018-12-05 18:06:32 -08004600 StringAppendF(&result,
4601 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4602 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004603 uint8_t port;
4604 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004605 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004606 result.append("no identification data\n");
4607 continue;
4608 }
4609
4610 if (!isEdid(data)) {
4611 result.append("unknown identification data: ");
4612 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004613 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004614 }
4615 result.append("\n");
4616 continue;
4617 }
4618
4619 const auto edid = parseEdid(data);
4620 if (!edid) {
4621 result.append("invalid EDID: ");
4622 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004623 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004624 }
4625 result.append("\n");
4626 continue;
4627 }
4628
Yiwei Zhang5434a782018-12-05 18:06:32 -08004629 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004630 result.append(edid->displayName.data(), edid->displayName.length());
4631 result.append("\"\n");
4632 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004633}
4634
Yiwei Zhang5434a782018-12-05 18:06:32 -08004635void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4636 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4637 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4638 StringAppendF(&result, "DisplayColorSetting: %s\n",
4639 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004640
4641 // TODO: print out if wide-color mode is active or not
4642
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004643 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004644 const auto displayId = display->getId();
4645 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004646 continue;
4647 }
4648
Yiwei Zhang5434a782018-12-05 18:06:32 -08004649 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004650 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004651 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004652 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004653 }
4654
Lloyd Pique32cbe282018-10-19 13:09:22 -07004655 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004656 StringAppendF(&result, " Current color mode: %s (%d)\n",
4657 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004658 }
4659 result.append("\n");
4660}
4661
Yiwei Zhang5434a782018-12-05 18:06:32 -08004662void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004663 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004664 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4665 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004666 continue;
4667 }
4668
Dominik Laskowski05275f12018-11-01 15:03:24 -07004669 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004670 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4671 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004672 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004673 compositionInfo.dump(result, nullptr);
4674 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004675 }
4676 }
David Sodman7e4ae112018-02-09 15:02:28 -08004677}
4678
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004679LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004680 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004681 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4682 const State& state = useDrawing ? mDrawingState : mCurrentState;
4683 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004684 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004685 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004686 });
4687
4688 return layersProto;
4689}
4690
Lloyd Pique32cbe282018-10-19 13:09:22 -07004691LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004692 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004693
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004694 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004695 resolution->set_w(displayDevice.getWidth());
4696 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004697
Lloyd Pique32cbe282018-10-19 13:09:22 -07004698 auto display = displayDevice.getCompositionDisplay();
4699 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004700
Lloyd Pique32cbe282018-10-19 13:09:22 -07004701 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4702 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4703 layersProto.set_global_transform(displayState.orientation);
4704
4705 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004706 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004707 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004708 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004709 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004710 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004711 }
4712 });
4713
4714 return layersProto;
4715}
4716
Mathias Agopian74d211a2013-04-22 16:55:35 +02004717void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004718 std::string& result) const {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004719 bool colorize = false;
4720 if (index < args.size()
4721 && (args[index] == String16("--color"))) {
4722 colorize = true;
4723 index++;
4724 }
4725
4726 Colorizer colorizer(colorize);
4727
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004728 // figure out if we're stuck somewhere
4729 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004730 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004731 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4732
4733 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004734 * Dump library configuration.
4735 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004736
4737 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004738 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004739 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004740 appendSfConfigString(result);
4741 appendUiConfigString(result);
4742 appendGuiConfigString(result);
4743 result.append("\n");
4744
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004745 result.append("\nDisplay identification data:\n");
4746 dumpDisplayIdentificationData(result);
4747
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004748 result.append("\nWide-Color information:\n");
4749 dumpWideColorInfo(result);
4750
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004751 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004752 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004753 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004754 result.append(SyncFeatures::getInstance().toString());
4755 result.append("\n");
4756
Andy McFadden41d67d72014-04-25 16:58:34 -07004757 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004758 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004759 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004760
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004761 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4762 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004763 if (const auto displayId = getInternalDisplayId();
4764 displayId && getHwComposer().isConnected(*displayId)) {
4765 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004766 StringAppendF(&result,
4767 "Display %s: app phase %" PRId64 " ns, "
4768 "sf phase %" PRId64 " ns, "
4769 "early app phase %" PRId64 " ns, "
4770 "early sf phase %" PRId64 " ns, "
4771 "early app gl phase %" PRId64 " ns, "
4772 "early sf gl phase %" PRId64 " ns, "
4773 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4774 to_string(*displayId).c_str(), vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
4775 appEarlyOffset, sfEarlyOffset, appEarlyGlOffset, sfEarlyGlOffset,
4776 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004777 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004778 result.append("\n");
4779
Dan Stozab90cf072015-03-05 11:05:59 -08004780 // Dump static screen stats
4781 result.append("\n");
4782 dumpStaticScreenStats(result);
4783 result.append("\n");
4784
Yiwei Zhang5434a782018-12-05 18:06:32 -08004785 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004786
Dan Stozae77c7662016-05-13 11:37:28 -07004787 dumpBufferingStats(result);
4788
Andy McFadden4803b742012-09-24 19:07:20 -07004789 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004790 * Dump the visible layer list
4791 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004792 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004793 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4794 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4795 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004796 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004797
Chia-I Wu2f884132018-09-13 15:17:58 -07004798 {
4799 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4800 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004801 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004802 result.append("\n");
4803 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004804
David Sodman7e4ae112018-02-09 15:02:28 -08004805 result.append("\nFrame-Composition information:\n");
4806 dumpFrameCompositionInfo(result);
4807 result.append("\n");
4808
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004809 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004810 * Dump Display state
4811 */
4812
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004813 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004814 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004815 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004816 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004817 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004818 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004819 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004820
4821 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004822 * Dump SurfaceFlinger global state
4823 */
4824
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004825 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004826 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004827 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004828
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004829 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004830
Dominik Laskowski075d3172018-05-24 15:50:06 -07004831 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004832 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4833 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004834 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4835 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004836 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004837 StringAppendF(&result,
4838 " transaction-flags : %08x\n"
4839 " gpu_to_cpu_unsupported : %d\n",
4840 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004841
Dominik Laskowski075d3172018-05-24 15:50:06 -07004842 if (const auto displayId = getInternalDisplayId();
4843 displayId && getHwComposer().isConnected(*displayId)) {
4844 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004845 StringAppendF(&result,
4846 " refresh-rate : %f fps\n"
4847 " x-dpi : %f\n"
4848 " y-dpi : %f\n",
4849 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4850 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004851 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004852
Yiwei Zhang5434a782018-12-05 18:06:32 -08004853 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004854
Yiwei Zhang5434a782018-12-05 18:06:32 -08004855 StringAppendF(&result, " use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004856 /*
4857 * VSYNC state
4858 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004859 if (mUseScheduler) {
4860 mScheduler->dump(mAppConnectionHandle, result);
4861 } else {
4862 mEventThread->dump(result);
4863 }
Dan Stozae22aec72016-08-01 13:20:59 -07004864 result.append("\n");
4865
4866 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004867 * Tracing state
4868 */
4869 mTracing.dump(result);
4870 result.append("\n");
4871
4872 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004873 * HWC layer minidump
4874 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004875 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004876 const auto displayId = display->getId();
4877 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004878 continue;
4879 }
4880
Yiwei Zhang5434a782018-12-05 18:06:32 -08004881 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004882 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004883 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004884 result.append("\n");
4885 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004886
4887 /*
4888 * Dump HWComposer state
4889 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004890 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004891 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004892 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004893 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004894 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004895 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004896
4897 /*
4898 * Dump gralloc state
4899 */
4900 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4901 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004902
4903 /*
4904 * Dump VrFlinger state if in use.
4905 */
4906 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4907 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004908 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004909 result.append("\n");
4910 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004911}
4912
Dominik Laskowski075d3172018-05-24 15:50:06 -07004913const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004914 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004915 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004916 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004917 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004918 }
4919 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004920
Dominik Laskowski34157762018-10-31 13:07:19 -07004921 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004922 static const Vector<sp<Layer>> empty;
4923 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004924}
4925
Keun young Park63f165f2012-08-31 10:53:36 -07004926bool SurfaceFlinger::startDdmConnection()
4927{
4928 void* libddmconnection_dso =
4929 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4930 if (!libddmconnection_dso) {
4931 return false;
4932 }
4933 void (*DdmConnection_start)(const char* name);
4934 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004935 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004936 if (!DdmConnection_start) {
4937 dlclose(libddmconnection_dso);
4938 return false;
4939 }
4940 (*DdmConnection_start)(getServiceName());
4941 return true;
4942}
4943
Chia-I Wu28f320b2018-05-03 11:02:56 -07004944void SurfaceFlinger::updateColorMatrixLocked() {
4945 mat4 colorMatrix;
4946 if (mGlobalSaturationFactor != 1.0f) {
4947 // Rec.709 luma coefficients
4948 float3 luminance{0.213f, 0.715f, 0.072f};
4949 luminance *= 1.0f - mGlobalSaturationFactor;
4950 mat4 saturationMatrix = mat4(
4951 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4952 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4953 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4954 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4955 );
4956 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4957 } else {
4958 colorMatrix = mClientColorMatrix * mDaltonizer();
4959 }
4960
4961 if (mCurrentState.colorMatrix != colorMatrix) {
4962 mCurrentState.colorMatrix = colorMatrix;
4963 mCurrentState.colorMatrixChanged = true;
4964 setTransactionFlags(eTransactionNeeded);
4965 }
4966}
4967
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004968status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004969#pragma clang diagnostic push
4970#pragma clang diagnostic error "-Wswitch-enum"
4971 switch (static_cast<ISurfaceComposerTag>(code)) {
4972 // These methods should at minimum make sure that the client requested
4973 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004974 case BOOT_FINISHED:
4975 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004976 case CREATE_DISPLAY:
4977 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004978 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004979 case GET_ACTIVE_COLOR_MODE:
4980 case GET_ANIMATION_FRAME_STATS:
4981 case GET_HDR_CAPABILITIES:
4982 case SET_ACTIVE_CONFIG:
4983 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004984 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004985 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004986 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004987 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4988 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004989 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4990 IPCThreadState* ipc = IPCThreadState::self();
4991 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4992 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004993 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004994 }
Robert Carr1db73f62016-12-21 12:58:51 -08004995 return OK;
4996 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004997 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004998 IPCThreadState* ipc = IPCThreadState::self();
4999 const int pid = ipc->getCallingPid();
5000 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005001 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5002 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005003 return PERMISSION_DENIED;
5004 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005005 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005006 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005007 // Used by apps to hook Choreographer to SurfaceFlinger.
5008 case CREATE_DISPLAY_EVENT_CONNECTION:
5009 // The following calls are currently used by clients that do not
5010 // request necessary permissions. However, they do not expose any secret
5011 // information, so it is OK to pass them.
5012 case AUTHENTICATE_SURFACE:
5013 case GET_ACTIVE_CONFIG:
5014 case GET_BUILT_IN_DISPLAY:
5015 case GET_DISPLAY_COLOR_MODES:
5016 case GET_DISPLAY_CONFIGS:
5017 case GET_DISPLAY_STATS:
5018 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5019 // Calling setTransactionState is safe, because you need to have been
5020 // granted a reference to Client* and Handle* to do anything with it.
5021 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005022 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005023 case GET_COLOR_MANAGEMENT:
Peiyong Lin0256f722018-08-31 15:45:10 -07005024 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005025 return OK;
5026 }
5027 case CAPTURE_LAYERS:
5028 case CAPTURE_SCREEN: {
5029 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005030 IPCThreadState* ipc = IPCThreadState::self();
5031 const int pid = ipc->getCallingPid();
5032 const int uid = ipc->getCallingUid();
5033 if ((uid != AID_GRAPHICS) &&
5034 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5035 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5036 return PERMISSION_DENIED;
5037 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005038 return OK;
5039 }
5040 // The following codes are deprecated and should never be allowed to access SF.
5041 case CONNECT_DISPLAY_UNUSED:
5042 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5043 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5044 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005045 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005046 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005047
5048 // These codes are used for the IBinder protocol to either interrogate the recipient
5049 // side of the transaction for its canonical interface descriptor or to dump its state.
5050 // We let them pass by default.
5051 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5052 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5053 code == IBinder::SYSPROPS_TRANSACTION) {
5054 return OK;
5055 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005056 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005057 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005058 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005059 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5060 return OK;
5061 }
5062 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5063 return PERMISSION_DENIED;
5064#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005065}
5066
Ana Krulec13be8ad2018-08-21 02:43:56 +00005067status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5068 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005069 status_t credentialCheck = CheckTransactCodeCredentials(code);
5070 if (credentialCheck != OK) {
5071 return credentialCheck;
5072 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005073
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005074 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5075 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005076 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005077 IPCThreadState* ipc = IPCThreadState::self();
5078 const int uid = ipc->getCallingUid();
5079 if (CC_UNLIKELY(uid != AID_SYSTEM
5080 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005081 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005082 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005083 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005084 return PERMISSION_DENIED;
5085 }
5086 int n;
5087 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005088 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005089 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005090 return NO_ERROR;
5091 case 1002: // SHOW_UPDATES
5092 n = data.readInt32();
5093 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005094 invalidateHwcGeometry();
5095 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005096 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005097 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005098 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005099 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005100 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005101 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005102 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005103 setTransactionFlags(
5104 eTransactionNeeded|
5105 eDisplayTransactionNeeded|
5106 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005107 return NO_ERROR;
5108 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005109 case 1006:{ // send empty update
5110 signalRefresh();
5111 return NO_ERROR;
5112 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005113 case 1008: // toggle use of hw composer
5114 n = data.readInt32();
5115 mDebugDisableHWC = n ? 1 : 0;
5116 invalidateHwcGeometry();
5117 repaintEverything();
5118 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005119 case 1009: // toggle use of transform hint
5120 n = data.readInt32();
5121 mDebugDisableTransformHint = n ? 1 : 0;
5122 invalidateHwcGeometry();
5123 repaintEverything();
5124 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005125 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005126 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005127 reply->writeInt32(0);
5128 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005129 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005130 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005131 return NO_ERROR;
5132 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005133 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005134 if (!display) {
5135 return NAME_NOT_FOUND;
5136 }
5137
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005138 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005139 return NO_ERROR;
5140 }
5141 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005142 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005143 // daltonize
5144 n = data.readInt32();
5145 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005146 case 1:
5147 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5148 break;
5149 case 2:
5150 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5151 break;
5152 case 3:
5153 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5154 break;
5155 default:
5156 mDaltonizer.setType(ColorBlindnessType::None);
5157 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005158 }
5159 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005160 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005161 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005162 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005163 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005164
5165 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005166 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005167 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005168 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005169 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005170 // apply a color matrix
5171 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005172 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005173 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005174 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005175 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005176 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005177 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005178 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005179 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005180 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005181 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005182
5183 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5184 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005185 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005186 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5187 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5188 }
5189
Chia-I Wu28f320b2018-05-03 11:02:56 -07005190 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005191 return NO_ERROR;
5192 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005193 // This is an experimental interface
5194 // Needs to be shifted to proper binder interface when we productize
5195 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005196 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005197 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005198 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005199 return NO_ERROR;
5200 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005201 case 1017: {
5202 n = data.readInt32();
5203 mForceFullDamage = static_cast<bool>(n);
5204 return NO_ERROR;
5205 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005206 case 1018: { // Modify Choreographer's phase offset
5207 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005208 if (mUseScheduler) {
5209 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5210 } else {
5211 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5212 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005213 return NO_ERROR;
5214 }
5215 case 1019: { // Modify SurfaceFlinger's phase offset
5216 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005217 if (mUseScheduler) {
5218 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5219 } else {
5220 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5221 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005222 return NO_ERROR;
5223 }
Irvel468051e2016-06-13 16:44:44 -07005224 case 1020: { // Layer updates interceptor
5225 n = data.readInt32();
5226 if (n) {
5227 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005228 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005229 }
5230 else{
5231 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005232 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005233 }
5234 return NO_ERROR;
5235 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005236 case 1021: { // Disable HWC virtual displays
5237 n = data.readInt32();
5238 mUseHwcVirtualDisplays = !n;
5239 return NO_ERROR;
5240 }
Romain Guy0147a172017-06-01 13:53:56 -07005241 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005242 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005243 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005244
Chia-I Wu28f320b2018-05-03 11:02:56 -07005245 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005246 return NO_ERROR;
5247 }
Romain Guy54f154a2017-10-24 21:40:32 +01005248 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005249 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005250 invalidateHwcGeometry();
5251 repaintEverything();
5252 return NO_ERROR;
5253 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005254 // Deprecate, use 1030 to check whether the device is color managed.
5255 case 1024: {
5256 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005257 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005258 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005259 n = data.readInt32();
5260 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005261 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005262 mTracing.enable();
5263 doTracing("tracing.enable");
5264 reply->writeInt32(NO_ERROR);
5265 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005266 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005267 status_t err = mTracing.disable();
5268 reply->writeInt32(err);
5269 }
5270 return NO_ERROR;
5271 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005272 case 1026: { // Get layer tracing status
5273 reply->writeBool(mTracing.isEnabled());
5274 return NO_ERROR;
5275 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005276 // Is a DisplayColorSetting supported?
5277 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005278 const auto display = getDefaultDisplayDevice();
5279 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005280 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005281 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005282
5283 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5284 switch (setting) {
5285 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005286 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005287 break;
5288 case DisplayColorSetting::UNMANAGED:
5289 reply->writeBool(true);
5290 break;
5291 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005292 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005293 break;
5294 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005295 reply->writeBool(
5296 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005297 break;
5298 }
5299 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005300 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005301 // Is VrFlinger active?
5302 case 1028: {
5303 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005304 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005305 return NO_ERROR;
5306 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005307 // Is device color managed?
5308 case 1030: {
5309 reply->writeBool(useColorManagement);
5310 return NO_ERROR;
5311 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005312 // Override default composition data space
5313 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5314 // && adb shell stop zygote && adb shell start zygote
5315 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5316 // adb shell stop zygote && adb shell start zygote
5317 case 1031: {
5318 Mutex::Autolock _l(mStateLock);
5319 n = data.readInt32();
5320 if (n) {
5321 n = data.readInt32();
5322 if (n) {
5323 Dataspace dataspace = static_cast<Dataspace>(n);
5324 if (!validateCompositionDataspace(dataspace)) {
5325 return BAD_VALUE;
5326 }
5327 mDefaultCompositionDataspace = dataspace;
5328 }
5329 n = data.readInt32();
5330 if (n) {
5331 Dataspace dataspace = static_cast<Dataspace>(n);
5332 if (!validateCompositionDataspace(dataspace)) {
5333 return BAD_VALUE;
5334 }
5335 mWideColorGamutCompositionDataspace = dataspace;
5336 }
5337 } else {
5338 // restore composition data space.
5339 mDefaultCompositionDataspace = defaultCompositionDataspace;
5340 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5341 }
5342 return NO_ERROR;
5343 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005344 }
5345 }
5346 return err;
5347}
5348
Steven Thomas6d8110b2017-08-31 18:24:21 -07005349void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005350 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005351 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005352}
5353
Ana Krulec7d1d6832018-12-27 11:10:09 -08005354void SurfaceFlinger::repaintEverythingForHWC() {
5355 mRepaintEverything = true;
5356 mEventQueue->invalidateForHWC();
5357}
5358
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005359// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5360class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005361public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005362 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5363 ~WindowDisconnector() {
5364 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005365 }
5366
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005367private:
5368 ANativeWindow* mWindow;
5369 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005370};
5371
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005372status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005373 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5374 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005375 uint32_t reqWidth, uint32_t reqHeight,
5376 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005377 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005378 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005379
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005380 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005381
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005382 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5383
Chia-I Wu20261cb2018-08-23 12:55:44 -07005384 sp<DisplayDevice> display;
5385 {
5386 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005387
Chia-I Wu20261cb2018-08-23 12:55:44 -07005388 display = getDisplayDeviceLocked(displayToken);
5389 if (!display) return BAD_VALUE;
5390
Chia-I Wucb023152018-08-28 12:57:23 -07005391 // set the requested width/height to the logical display viewport size
5392 // by default
5393 if (reqWidth == 0 || reqHeight == 0) {
5394 reqWidth = uint32_t(display->getViewport().width());
5395 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005396 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005397 }
5398
Peiyong Lin0e003c92018-09-17 11:09:51 -07005399 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5400 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005401
5402 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005403 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005404 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5405 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005406}
5407
5408status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005409 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5410 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005411 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005412 ATRACE_CALL();
5413
5414 class LayerRenderArea : public RenderArea {
5415 public:
Robert Carr578038f2018-03-09 12:25:24 -08005416 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005417 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5418 bool childrenOnly)
5419 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005420 mLayer(layer),
5421 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005422 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005423 mFlinger(flinger),
5424 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005425 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005426 Rect getBounds() const override {
5427 const Layer::State& layerState(mLayer->getDrawingState());
5428 return mLayer->getBufferSize(layerState);
5429 }
Marissa Wall61c58622018-07-18 10:12:20 -07005430 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005431 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005432 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005433 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005434 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005435 }
chaviwa76b2712017-09-20 12:02:26 -07005436 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005437 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005438 Rect getSourceCrop() const override {
5439 if (mCrop.isEmpty()) {
5440 return getBounds();
5441 } else {
5442 return mCrop;
5443 }
5444 }
Robert Carr578038f2018-03-09 12:25:24 -08005445 class ReparentForDrawing {
5446 public:
5447 const sp<Layer>& oldParent;
5448 const sp<Layer>& newParent;
5449
5450 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5451 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005452 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005453 }
Robert Carr15eae092018-03-23 13:43:53 -07005454 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005455 };
5456
5457 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005458 const Rect sourceCrop = getSourceCrop();
5459 // no need to check rotation because there is none
5460 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5461 sourceCrop.height() != getReqHeight();
5462
Robert Carr578038f2018-03-09 12:25:24 -08005463 if (!mChildrenOnly) {
5464 mTransform = mLayer->getTransform().inverse();
5465 drawLayers();
5466 } else {
5467 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005468 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005469 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5470 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005471
5472 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5473 drawLayers();
5474 }
5475 }
chaviwa76b2712017-09-20 12:02:26 -07005476
chaviwa76b2712017-09-20 12:02:26 -07005477 private:
chaviw7206d492017-11-10 16:16:12 -08005478 const sp<Layer> mLayer;
5479 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005480
5481 // In the "childrenOnly" case we reparent the children to a screenshot
5482 // layer which has no properties set and which does not draw.
5483 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005484 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005485 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005486
5487 SurfaceFlinger* mFlinger;
5488 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005489 };
5490
5491 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5492 auto parent = layerHandle->owner.promote();
5493
Robert Carr2e102c92018-10-23 12:11:15 -07005494 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005495 ALOGE("captureLayers called with a removed parent");
5496 return NAME_NOT_FOUND;
5497 }
5498
Robert Carr578038f2018-03-09 12:25:24 -08005499 const int uid = IPCThreadState::self()->getCallingUid();
5500 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005501 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005502 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5503 return PERMISSION_DENIED;
5504 }
5505
chaviw7206d492017-11-10 16:16:12 -08005506 Rect crop(sourceCrop);
5507 if (sourceCrop.width() <= 0) {
5508 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005509 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005510 }
5511
5512 if (sourceCrop.height() <= 0) {
5513 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005514 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005515 }
5516
5517 int32_t reqWidth = crop.width() * frameScale;
5518 int32_t reqHeight = crop.height() * frameScale;
5519
Chia-I Wu20261cb2018-08-23 12:55:44 -07005520 // really small crop or frameScale
5521 if (reqWidth <= 0) {
5522 reqWidth = 1;
5523 }
5524 if (reqHeight <= 0) {
5525 reqHeight = 1;
5526 }
5527
Peiyong Lin0e003c92018-09-17 11:09:51 -07005528 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005529
Robert Carr578038f2018-03-09 12:25:24 -08005530 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005531 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5532 if (!layer->isVisible()) {
5533 return;
Robert Carr578038f2018-03-09 12:25:24 -08005534 } else if (childrenOnly && layer == parent.get()) {
5535 return;
chaviwa76b2712017-09-20 12:02:26 -07005536 }
5537 visitor(layer);
5538 });
5539 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005540 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005541}
5542
5543status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5544 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005545 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005546 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005547 bool useIdentityTransform) {
5548 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005549
Peiyong Lin0e003c92018-09-17 11:09:51 -07005550 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005551 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5552 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005553 *outBuffer =
5554 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5555 static_cast<android_pixel_format>(reqPixelFormat), 1,
5556 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005557
5558 // This mutex protects syncFd and captureResult for communication of the return values from the
5559 // main thread back to this Binder thread
5560 std::mutex captureMutex;
5561 std::condition_variable captureCondition;
5562 std::unique_lock<std::mutex> captureLock(captureMutex);
5563 int syncFd = -1;
5564 std::optional<status_t> captureResult;
5565
Robert Carr03480e22018-01-04 16:02:06 -08005566 const int uid = IPCThreadState::self()->getCallingUid();
5567 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5568
Dominik Laskowski8c001672018-05-30 16:52:06 -07005569 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005570 // If there is a refresh pending, bug out early and tell the binder thread to try again
5571 // after the refresh.
5572 if (mRefreshPending) {
5573 ATRACE_NAME("Skipping screenshot for now");
5574 std::unique_lock<std::mutex> captureLock(captureMutex);
5575 captureResult = std::make_optional<status_t>(EAGAIN);
5576 captureCondition.notify_one();
5577 return;
5578 }
5579
5580 status_t result = NO_ERROR;
5581 int fd = -1;
5582 {
5583 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005584 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005585 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5586 useIdentityTransform, forSystem, &fd);
5587 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005588 }
5589
5590 {
5591 std::unique_lock<std::mutex> captureLock(captureMutex);
5592 syncFd = fd;
5593 captureResult = std::make_optional<status_t>(result);
5594 captureCondition.notify_one();
5595 }
5596 });
5597
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005598 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005599 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005600 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005601 while (*captureResult == EAGAIN) {
5602 captureResult.reset();
5603 result = postMessageAsync(message);
5604 if (result != NO_ERROR) {
5605 return result;
5606 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005607 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005608 }
5609 result = *captureResult;
5610 }
5611
5612 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005613 sync_wait(syncFd, -1);
5614 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005615 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005616
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005617 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005618}
5619
chaviwa76b2712017-09-20 12:02:26 -07005620void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005621 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005622 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005623 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005624
Lloyd Pique144e1162017-12-20 16:44:52 -08005625 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005626
chaviwa76b2712017-09-20 12:02:26 -07005627 const auto reqWidth = renderArea.getReqWidth();
5628 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005629 const auto sourceCrop = renderArea.getSourceCrop();
5630 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005631
Peiyong Lin0e003c92018-09-17 11:09:51 -07005632 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005633 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005634
Mathias Agopian180f10d2013-04-10 22:55:41 -07005635 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005636 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005637
5638 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005639 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005640 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005641
chaviw50da5042018-04-09 13:49:37 -07005642 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005643 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005644 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005645
chaviwa76b2712017-09-20 12:02:26 -07005646 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005647 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005648 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005649 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005650 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005651}
5652
chaviwa76b2712017-09-20 12:02:26 -07005653status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5654 TraverseLayersFunction traverseLayers,
5655 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005656 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005657 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005658 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005659 ATRACE_CALL();
5660
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005661 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005662
5663 traverseLayers([&](Layer* layer) {
5664 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5665 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005666
Robert Carr03480e22018-01-04 16:02:06 -08005667 // We allow the system server to take screenshots of secure layers for
5668 // use in situations like the Screen-rotation animation and place
5669 // the impetus on WindowManager to not persist them.
5670 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005671 ALOGW("FB is protected: PERMISSION_DENIED");
5672 return PERMISSION_DENIED;
5673 }
Peiyong Linfb530cf2018-12-15 05:07:38 +00005674 auto& engine(getRenderEngine());
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005675
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005676 // this binds the given EGLImage as a framebuffer for the
5677 // duration of this scope.
Peiyong Linfb530cf2018-12-15 05:07:38 +00005678 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005679 if (bufferBond.getStatus() != NO_ERROR) {
5680 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005681 return INVALID_OPERATION;
5682 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005683
Dan Stozaabcda352017-06-01 14:37:39 -07005684 // this will in fact render into our dequeued buffer
5685 // via an FBO, which means we didn't have to create
5686 // an EGLSurface and therefore we're not
5687 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005688 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005689
Peiyong Linfb530cf2018-12-15 05:07:38 +00005690 base::unique_fd syncFd = engine.flush();
Alec Mouri492bc572018-09-11 21:40:04 +00005691 if (syncFd < 0) {
Peiyong Linfb530cf2018-12-15 05:07:38 +00005692 engine.finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005693 }
Alec Mouri492bc572018-09-11 21:40:04 +00005694 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005695
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005696 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005697}
5698
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005699// ---------------------------------------------------------------------------
5700
Dan Stoza412903f2017-04-27 13:42:17 -07005701void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5702 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005703}
5704
Dan Stoza412903f2017-04-27 13:42:17 -07005705void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5706 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005707}
5708
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005709void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005710 const LayerVector::Visitor& visitor) {
5711 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005712 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005713 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005714 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005715 continue;
5716 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005717 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005718 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005719 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005720 return;
5721 }
chaviwa76b2712017-09-20 12:02:26 -07005722 if (!layer->isVisible()) {
5723 return;
5724 }
5725 visitor(layer);
5726 });
5727 }
5728}
5729
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005730}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005731
Lloyd Pique074e8122018-07-26 12:57:23 -07005732
Mathias Agopian3f844832013-08-07 21:24:32 -07005733#if defined(__gl_h_)
5734#error "don't include gl/gl.h in this file"
5735#endif
5736
5737#if defined(__gl2_h_)
5738#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005739#endif