blob: 9410cdd0103eec2a9fb201dfccb924ce9918e950 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070022#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080023
24#include <algorithm>
25#include <cinttypes>
26#include <cmath>
27#include <cstdint>
28#include <functional>
29#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070030#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070031
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080032#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070033#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080034
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070035#include <binder/IPCThreadState.h>
36#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070037#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070038
Lloyd Pique70d91362018-10-18 16:02:55 -070039#include <compositionengine/CompositionEngine.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070040#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070041#include <compositionengine/DisplayColorProfile.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070042#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070043#include <compositionengine/impl/OutputCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080044#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080048#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080049#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080050#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070051#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070052#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070053#include <ui/ColorSpace.h>
54#include <ui/DebugUtils.h>
55#include <ui/DisplayInfo.h>
56#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070057#include <ui/GraphicBufferAllocator.h>
58#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070059#include <ui/UiConfig.h>
Ady Abraham8164d482019-01-11 14:47:59 -080060#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070062#include <utils/String16.h>
63#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070064#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080065#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070066#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080067
Mathias Agopian921e6ac2012-07-23 23:11:29 -070068#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070069#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080070
Robert Carr578038f2018-03-09 12:25:24 -080071#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070072#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070073#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020074#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080075#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020076#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080077#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080078#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080079#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070081#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080082#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070083#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070084#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070086#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080087
Steven Thomasb02664d2017-07-26 18:48:28 -070088#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070089#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070090#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070091#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070092#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070093#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070094#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070095#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070096#include "Scheduler/EventControlThread.h"
97#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070098#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070099#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700100#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800101#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700102
Mathias Agopianff2ed702013-09-01 21:36:12 -0700103#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700104
David Sodman7e4ae112018-02-09 15:02:28 -0800105#include "android-base/stringprintf.h"
106
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900107#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800108#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700109#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800110#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900111#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900112
chaviw1d044282017-09-27 12:19:28 -0700113#include <layerproto/LayerProtoParser.h>
114
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800115namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700116
Jaesoo Lee43518572017-01-23 19:03:16 +0900117using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900118using namespace android::hardware::configstore::V1_0;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800119using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700120using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700121using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700122using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700123using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900124
Steven Thomasb02664d2017-07-26 18:48:28 -0700125namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700126
127#pragma clang diagnostic push
128#pragma clang diagnostic error "-Wswitch-enum"
129
130bool isWideColorMode(const ColorMode colorMode) {
131 switch (colorMode) {
132 case ColorMode::DISPLAY_P3:
133 case ColorMode::ADOBE_RGB:
134 case ColorMode::DCI_P3:
135 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700136 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700137 case ColorMode::BT2100_PQ:
138 case ColorMode::BT2100_HLG:
139 return true;
140 case ColorMode::NATIVE:
141 case ColorMode::STANDARD_BT601_625:
142 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
143 case ColorMode::STANDARD_BT601_525:
144 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
145 case ColorMode::STANDARD_BT709:
146 case ColorMode::SRGB:
147 return false;
148 }
149 return false;
150}
151
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700152ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
153 switch (rotation) {
154 case ISurfaceComposer::eRotateNone:
155 return ui::Transform::ROT_0;
156 case ISurfaceComposer::eRotate90:
157 return ui::Transform::ROT_90;
158 case ISurfaceComposer::eRotate180:
159 return ui::Transform::ROT_180;
160 case ISurfaceComposer::eRotate270:
161 return ui::Transform::ROT_270;
162 }
163 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
164 return ui::Transform::ROT_0;
165}
166
Peiyong Linfca547f2018-07-09 13:03:33 -0700167#pragma clang diagnostic pop
168
Steven Thomasb02664d2017-07-26 18:48:28 -0700169class ConditionalLock {
170public:
171 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
172 if (lock) {
173 mMutex.lock();
174 }
175 }
176 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
177private:
178 Mutex& mMutex;
179 bool mLocked;
180};
Peiyong Linfca547f2018-07-09 13:03:33 -0700181
Peiyong Lin9d846a52018-11-05 13:18:20 -0800182// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
183bool validateCompositionDataspace(Dataspace dataspace) {
184 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
185}
186
Steven Thomasb02664d2017-07-26 18:48:28 -0700187} // namespace anonymous
188
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800189// ---------------------------------------------------------------------------
190
Mathias Agopian99b49842011-06-27 16:05:52 -0700191const String16 sHardwareTest("android.permission.HARDWARE_TEST");
192const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
193const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
194const String16 sDump("android.permission.DUMP");
195
196// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800197int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
198int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700199int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700200bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800201uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800202bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800203bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800204int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600205bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700206int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700207bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700208bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700209Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
210ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
211Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
212ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700213
Kalle Raitaa099a242017-01-11 11:17:29 -0800214std::string getHwcServiceName() {
215 char value[PROPERTY_VALUE_MAX] = {};
216 property_get("debug.sf.hwc_service_name", value, "default");
217 ALOGI("Using HWComposer service: '%s'", value);
218 return std::string(value);
219}
220
221bool useTrebleTestingOverride() {
222 char value[PROPERTY_VALUE_MAX] = {};
223 property_get("debug.sf.treble_testing_override", value, "false");
224 ALOGI("Treble testing override: '%s'", value);
225 return std::string(value) == "true";
226}
227
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800228std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
229 switch(displayColorSetting) {
230 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700231 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800232 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700233 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800234 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700235 return std::string("Enhanced");
236 default:
237 return std::string("Unknown ") +
238 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800239 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800240}
241
David Sodmanbc815282017-11-05 18:57:52 -0800242SurfaceFlingerBE::SurfaceFlingerBE()
243 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800244 mFrameBuckets(),
245 mTotalTime(0),
246 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800247 mComposerSequenceId(0) {
248}
249
Lloyd Pique90c115d2018-09-18 21:39:42 -0700250SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
251 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800252 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700253 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700254 mTransactionPending(false),
255 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700256 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700257 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800258 mBootTime(systemTime()),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800259 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800260 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800261 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800262 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800263 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700264 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700265 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700266 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700267 mDebugInTransaction(0),
268 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700269 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800270 mTimeStats(factory.createTimeStats()),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700271 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700272 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800273 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800274 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800275 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700276 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700277 mMainThreadId(std::this_thread::get_id()),
278 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800279
Lloyd Pique90c115d2018-09-18 21:39:42 -0700280SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
281 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800282 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800283
284 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
285 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
286
287 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
288 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
289
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800290 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
291 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800292
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700293 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
294 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
295
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700296 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
297 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
298
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800299 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
300 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
301
Steven Thomas050b2c82017-03-06 11:45:16 -0800302 // Vr flinger is only enabled on Daydream ready devices.
303 useVrFlinger = getBool< ISurfaceFlingerConfigs,
304 &ISurfaceFlingerConfigs::useVrFlinger>(false);
305
Fabien Sanglard1971b632017-03-10 14:50:03 -0800306 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
307 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
308
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600309 hasWideColorDisplay =
310 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700311 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700312 getBool<V1_2::ISurfaceFlingerConfigs,
313 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
314
315 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
316 if (surfaceFlingerConfigsServiceV1_2) {
317 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
Peiyong Linc6780972018-10-28 15:24:08 -0700318 [&](auto tmpDefaultDataspace, auto tmpDefaultPixelFormat,
319 auto tmpWideColorGamutDataspace, auto tmpWideColorGamutPixelFormat) {
320 defaultCompositionDataspace = tmpDefaultDataspace;
321 defaultCompositionPixelFormat = tmpDefaultPixelFormat;
322 wideColorGamutCompositionDataspace = tmpWideColorGamutDataspace;
323 wideColorGamutCompositionPixelFormat = tmpWideColorGamutPixelFormat;
324 });
Peiyong Lin0256f722018-08-31 15:45:10 -0700325 }
Peiyong Lin9d846a52018-11-05 13:18:20 -0800326 mDefaultCompositionDataspace = defaultCompositionDataspace;
327 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600328
Peiyong Linb3839ad2018-09-05 15:37:19 -0700329 useContextPriority = getBool<ISurfaceFlingerConfigs,
330 &ISurfaceFlingerConfigs::useContextPriority>(true);
331
Iris Chang7501ed62018-04-30 14:45:42 +0800332 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700333 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
334 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800335 V1_1::DisplayOrientation::ORIENTATION_0);
336
337 switch (primaryDisplayOrientation) {
338 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700339 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800340 break;
341 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700342 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800343 break;
344 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700345 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800346 break;
347 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700348 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800349 break;
350 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700351 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800352
Lloyd Pique90c115d2018-09-18 21:39:42 -0700353 mPrimaryDispSync =
354 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
355 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700356
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800357 // debugging stuff...
358 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700359
Mathias Agopianb4b17302013-03-20 18:36:41 -0700360 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700361 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700362
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800363 property_get("debug.sf.showupdates", value, "0");
364 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700365
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700366 property_get("debug.sf.ddms", value, "0");
367 mDebugDDMS = atoi(value);
368 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700369 if (!startDdmConnection()) {
370 // start failed, and DDMS debugging not enabled
371 mDebugDDMS = 0;
372 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700373 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700374 ALOGI_IF(mDebugRegion, "showupdates enabled");
375 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700376
377 property_get("debug.sf.disable_backpressure", value, "0");
378 mPropagateBackpressure = !atoi(value);
379 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700380
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800381 property_get("debug.sf.enable_hwc_vds", value, "0");
382 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800383 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800384
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800385 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800386 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800387 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700388
Yiwei Zhang243b3782018-05-15 17:40:04 -0700389 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700390 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
391 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
392
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200393 property_get("debug.sf.early_phase_offset_ns", value, "-1");
394 const int earlySfOffsetNs = atoi(value);
395
396 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
397 const int earlyGlSfOffsetNs = atoi(value);
398
399 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
400 const int earlyAppOffsetNs = atoi(value);
401
402 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
403 const int earlyGlAppOffsetNs = atoi(value);
404
Ana Krulec98b5b242018-08-10 15:03:23 -0700405 property_get("debug.sf.use_scheduler", value, "0");
406 mUseScheduler = atoi(value);
407
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200408 const VSyncModulator::Offsets earlyOffsets =
409 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
410 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
411 const VSyncModulator::Offsets earlyGlOffsets =
412 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
413 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
414 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
415 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700416
Romain Guy11d63f42017-07-20 12:47:14 -0700417 // We should be reading 'persist.sys.sf.color_saturation' here
418 // but since /data may be encrypted, we need to wait until after vold
419 // comes online to attempt to read the property. The property is
420 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800421
422 if (useTrebleTestingOverride()) {
423 // Without the override SurfaceFlinger cannot connect to HIDL
424 // services that are not listed in the manifests. Considered
425 // deriving the setting from the set service name, but it
426 // would be brittle if the name that's not 'default' is used
427 // for production purposes later on.
428 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
429 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800430}
431
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800432void SurfaceFlinger::onFirstRef()
433{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800434 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800435}
436
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800437SurfaceFlinger::~SurfaceFlinger()
438{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800439}
440
Dan Stozac7014012014-02-14 15:03:43 -0800441void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800442{
443 // the window manager died on us. prepare its eulogy.
444
Andy McFadden13a082e2012-08-24 10:16:42 -0700445 // restore initial conditions (default device unblank, etc)
446 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800447
448 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700449 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800450}
451
Robert Carr1db73f62016-12-21 12:58:51 -0800452static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700453 status_t err = client->initCheck();
454 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800455 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800456 }
Robert Carr1db73f62016-12-21 12:58:51 -0800457 return nullptr;
458}
459
460sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
461 return initClient(new Client(this));
462}
463
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700464sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
465 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700466{
467 class DisplayToken : public BBinder {
468 sp<SurfaceFlinger> flinger;
469 virtual ~DisplayToken() {
470 // no more references, this display must be terminated
471 Mutex::Autolock _l(flinger->mStateLock);
472 flinger->mCurrentState.displays.removeItem(this);
473 flinger->setTransactionFlags(eDisplayTransactionNeeded);
474 }
475 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700476 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700477 : flinger(flinger) {
478 }
479 };
480
481 sp<BBinder> token = new DisplayToken(this);
482
483 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700484 // Display ID is assigned when virtual display is allocated by HWC.
485 DisplayDeviceState state;
486 state.isSecure = secure;
487 state.displayName = displayName;
488 mCurrentState.displays.add(token, state);
489 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700490 return token;
491}
492
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700493void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700494 Mutex::Autolock _l(mStateLock);
495
Dominik Laskowski075d3172018-05-24 15:50:06 -0700496 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
497 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700498 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700499 return;
500 }
501
Dominik Laskowski075d3172018-05-24 15:50:06 -0700502 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
503 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700504 ALOGE("destroyDisplay called for non-virtual display");
505 return;
506 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700507 mInterceptor->saveDisplayDeletion(state.sequenceId);
508 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700509 setTransactionFlags(eDisplayTransactionNeeded);
510}
511
Mathias Agopiane57f2922012-08-09 16:29:12 -0700512sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700513 std::optional<DisplayId> displayId;
514
515 if (id == HWC_DISPLAY_PRIMARY) {
516 displayId = getInternalDisplayId();
517 } else if (id == HWC_DISPLAY_EXTERNAL) {
518 displayId = getExternalDisplayId();
519 }
520
521 if (!displayId) {
522 ALOGE("%s: Invalid display %d", __FUNCTION__, id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800523 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700524 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700525
526 return getPhysicalDisplayToken(*displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700527}
528
Ady Abraham37965d42018-11-01 13:43:32 -0700529status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
530 if (!outGetColorManagement) {
531 return BAD_VALUE;
532 }
533 *outGetColorManagement = useColorManagement;
534 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700535}
536
Lloyd Pique441d5042018-10-18 16:49:51 -0700537HWComposer& SurfaceFlinger::getHwComposer() const {
538 return mCompositionEngine->getHwComposer();
539}
540
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700541renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
542 return mCompositionEngine->getRenderEngine();
543}
544
Lloyd Pique70d91362018-10-18 16:02:55 -0700545compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
546 return *mCompositionEngine.get();
547}
548
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800549void SurfaceFlinger::bootFinished()
550{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700551 if (mStartPropertySetThread->join() != NO_ERROR) {
552 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800553 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800554 const nsecs_t now = systemTime();
555 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000556 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700557
558 // wait patiently for the window manager death
559 const String16 name("window");
560 sp<IBinder> window(defaultServiceManager()->getService(name));
561 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700562 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700563 }
Robert Carr720e5062018-07-30 17:45:14 -0700564 sp<IBinder> input(defaultServiceManager()->getService(
565 String16("inputflinger")));
566 if (input == nullptr) {
567 ALOGE("Failed to link to input service");
568 } else {
569 mInputFlinger = interface_cast<IInputFlinger>(input);
570 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700571
Steven Thomas050b2c82017-03-06 11:45:16 -0800572 if (mVrFlinger) {
573 mVrFlinger->OnBootFinished();
574 }
575
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700576 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700577 // formerly we would just kill the process, but we now ask it to exit so it
578 // can choose where to stop the animation.
579 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700580
581 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
582 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
583 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700584
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800585 postMessageAsync(new LambdaMessage([this] {
586 readPersistentProperties();
587 mBootStage = BootStage::FINISHED;
588 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800589}
590
Dan Stoza436ccf32018-06-21 12:10:12 -0700591uint32_t SurfaceFlinger::getNewTexture() {
592 {
593 std::lock_guard lock(mTexturePoolMutex);
594 if (!mTexturePool.empty()) {
595 uint32_t name = mTexturePool.back();
596 mTexturePool.pop_back();
597 ATRACE_INT("TexturePoolSize", mTexturePool.size());
598 return name;
599 }
600
601 // The pool was too small, so increase it for the future
602 ++mTexturePoolSize;
603 }
604
605 // The pool was empty, so we need to get a new texture name directly using a
606 // blocking call to the main thread
607 uint32_t name = 0;
608 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
609 return name;
610}
611
Mathias Agopian3f844832013-08-07 21:24:32 -0700612void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700613 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700614}
615
Wei Wangf9b05ee2017-07-19 20:59:39 -0700616// Do not call property_set on main thread which will be blocked by init
617// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700618void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700619 ALOGI( "SurfaceFlinger's main thread ready to run. "
620 "Initializing graphics H/W...");
621
Thierry Strudel2924d012017-08-14 15:19:37 -0700622 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900623
Steven Thomasb02664d2017-07-26 18:48:28 -0700624 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800625
Dominik Laskowski83b88212018-12-11 13:34:06 -0800626 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -0800627
Steven Thomasb02664d2017-07-26 18:48:28 -0700628 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700629 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700630 mScheduler = getFactory().createScheduler([this](bool enabled) {
631 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
632 });
633
Ana Krulec98b5b242018-08-10 15:03:23 -0700634 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700635 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Dominik Laskowskif654d572018-12-20 11:03:06 -0800636 resyncCallback,
Ana Krulec98b5b242018-08-10 15:03:23 -0700637 impl::EventThread::InterceptVSyncsCallback());
638 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700639 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Dominik Laskowskif654d572018-12-20 11:03:06 -0800640 resyncCallback, [this](nsecs_t timestamp) {
Ana Krulec98b5b242018-08-10 15:03:23 -0700641 mInterceptor->saveVSyncEvent(timestamp);
642 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800643
Ana Krulec98b5b242018-08-10 15:03:23 -0700644 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700645 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
646 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700647 } else {
648 mEventThreadSource =
649 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
650 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
651 mEventThread =
652 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700653 impl::EventThread::InterceptVSyncsCallback(),
654 "appEventThread");
655 mSfEventThreadSource =
656 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
657 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
658
659 mSFEventThread =
660 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700661 [this](nsecs_t timestamp) {
662 mInterceptor->saveVSyncEvent(timestamp);
663 },
664 "sfEventThread");
Dominik Laskowskif654d572018-12-20 11:03:06 -0800665 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Ana Krulec98b5b242018-08-10 15:03:23 -0700666 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 */); });
Ana Krulecb43429d2019-01-09 14:28:51 -0800740 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(
741 getHwComposer().getConfigs(*display->getId()));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800742 }
743
Dan Stoza9e56aa02015-11-02 13:00:03 -0800744 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700745}
746
Romain Guy11d63f42017-07-20 12:47:14 -0700747void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700748 Mutex::Autolock _l(mStateLock);
749
Romain Guy11d63f42017-07-20 12:47:14 -0700750 char value[PROPERTY_VALUE_MAX];
751
752 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800753 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700754 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800755 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100756
757 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700758 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700759}
760
Mathias Agopiana67e4182012-06-19 17:26:12 -0700761void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800762 // Start boot animation service by setting a property mailbox
763 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700764 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800765 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700766 if (mStartPropertySetThread->join() != NO_ERROR) {
767 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800768 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700769}
770
Mathias Agopian875d8e12013-06-07 15:35:48 -0700771size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700772 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700773}
774
Mathias Agopian875d8e12013-06-07 15:35:48 -0700775size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700776 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700777}
778
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800779// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800780
Jamie Gennis582270d2011-08-17 18:19:00 -0700781bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800782 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800783 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800784 return authenticateSurfaceTextureLocked(bufferProducer);
785}
786
787bool SurfaceFlinger::authenticateSurfaceTextureLocked(
788 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800789 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800790 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800791}
792
Brian Anderson6b376712017-04-04 10:51:39 -0700793status_t SurfaceFlinger::getSupportedFrameTimestamps(
794 std::vector<FrameEvent>* outSupported) const {
795 *outSupported = {
796 FrameEvent::REQUESTED_PRESENT,
797 FrameEvent::ACQUIRE,
798 FrameEvent::LATCH,
799 FrameEvent::FIRST_REFRESH_START,
800 FrameEvent::LAST_REFRESH_START,
801 FrameEvent::GPU_COMPOSITION_DONE,
802 FrameEvent::DEQUEUE_READY,
803 FrameEvent::RELEASE,
804 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700805 ConditionalLock _l(mStateLock,
806 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700807 if (!getHwComposer().hasCapability(
808 HWC2::Capability::PresentFenceIsNotReliable)) {
809 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
810 }
811 return NO_ERROR;
812}
813
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700814status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
815 Vector<DisplayInfo>* configs) {
816 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700817 return BAD_VALUE;
818 }
819
Dominik Laskowski075d3172018-05-24 15:50:06 -0700820 const auto displayId = getPhysicalDisplayId(displayToken);
821 if (!displayId) {
822 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700823 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700824
Mathias Agopian8b736f12012-08-13 17:54:26 -0700825 // TODO: Not sure if display density should handled by SF any longer
826 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700827 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700828 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700829 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800830 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700831 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700832 }
833 return density;
834 }
835 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700836 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700837 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700838 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700839 return getDensityFromProperty("ro.sf.lcd_density"); }
840 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700841
Dan Stoza7f7da322014-05-02 15:26:25 -0700842 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700843
Steven Thomas6d8110b2017-08-31 18:24:21 -0700844 ConditionalLock _l(mStateLock,
845 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700846 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700847 DisplayInfo info = DisplayInfo();
848
Dan Stoza9e56aa02015-11-02 13:00:03 -0800849 float xdpi = hwConfig->getDpiX();
850 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700851
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700852 info.w = hwConfig->getWidth();
853 info.h = hwConfig->getHeight();
854 // Default display viewport to display width and height
855 info.viewportW = info.w;
856 info.viewportH = info.h;
857
Dominik Laskowski075d3172018-05-24 15:50:06 -0700858 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700859 // The density of the device is provided by a build property
860 float density = Density::getBuildDensity() / 160.0f;
861 if (density == 0) {
862 // the build doesn't provide a density -- this is wrong!
863 // use xdpi instead
864 ALOGE("ro.sf.lcd_density must be defined as a build property");
865 density = xdpi / 160.0f;
866 }
867 if (Density::getEmuDensity()) {
868 // if "qemu.sf.lcd_density" is specified, it overrides everything
869 xdpi = ydpi = density = Density::getEmuDensity();
870 density /= 160.0f;
871 }
872 info.density = density;
873
874 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700875 const auto display = getDefaultDisplayDeviceLocked();
876 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700877
878 // This is for screenrecord
879 const Rect viewport = display->getViewport();
880 if (viewport.isValid()) {
881 info.viewportW = uint32_t(viewport.getWidth());
882 info.viewportH = uint32_t(viewport.getHeight());
883 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700884 } else {
885 // TODO: where should this value come from?
886 static const int TV_DENSITY = 213;
887 info.density = TV_DENSITY / 160.0f;
888 info.orientation = 0;
889 }
890
Dan Stoza7f7da322014-05-02 15:26:25 -0700891 info.xdpi = xdpi;
892 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800893 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900894 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800895
Andy McFadden91b2ca82014-06-13 14:04:23 -0700896 // This is how far in advance a buffer must be queued for
897 // presentation at a given time. If you want a buffer to appear
898 // on the screen at time N, you must submit the buffer before
899 // (N - presentationDeadline).
900 //
901 // Normally it's one full refresh period (to give SF a chance to
902 // latch the buffer), but this can be reduced by configuring a
903 // DispSync offset. Any additional delays introduced by the hardware
904 // composer or panel must be accounted for here.
905 //
906 // We add an additional 1ms to allow for processing time and
907 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800908 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800909 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700910
911 // All non-virtual displays are currently considered secure.
912 info.secure = true;
913
Dominik Laskowski075d3172018-05-24 15:50:06 -0700914 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700915 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800916 std::swap(info.w, info.h);
917 }
918
Michael Wright28f24d02016-07-12 13:30:53 -0700919 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700920 }
921
Dan Stoza7f7da322014-05-02 15:26:25 -0700922 return NO_ERROR;
923}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700924
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700925status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
926 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700927 return BAD_VALUE;
928 }
929
Ana Krulece588e312018-09-18 12:32:24 -0700930 if (mUseScheduler) {
931 mScheduler->getDisplayStatInfo(stats);
932 } else {
933 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
934 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
935 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700936 return NO_ERROR;
937}
938
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700939int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
940 const auto display = getDisplayDevice(displayToken);
941 if (!display) {
942 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800943 return BAD_VALUE;
944 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700945
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700946 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700947}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700948
Ana Krulec7d1d6832018-12-27 11:10:09 -0800949status_t SurfaceFlinger::setActiveConfigAsync(const sp<IBinder>& displayToken, int mode) {
950 ATRACE_NAME("setActiveConfigAsync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800951 postMessageAsync(new LambdaMessage(
952 [=]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800953 return NO_ERROR;
954}
955
956status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
957 ATRACE_NAME("setActiveConfigSync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800958 postMessageSync(new LambdaMessage(
959 [&]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800960 return NO_ERROR;
961}
962
963void SurfaceFlinger::setActiveConfigInternal(const sp<IBinder>& displayToken, int mode) {
964 Vector<DisplayInfo> configs;
965 getDisplayConfigs(displayToken, &configs);
966 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
967 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
968 return;
969 }
970
971 const auto display = getDisplayDevice(displayToken);
972 if (!display) {
973 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
974 displayToken.get());
975 return;
976 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700977 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800978 ALOGW("Attempt to set active config %d for virtual display", mode);
979 return;
980 }
981 int currentDisplayPowerMode = display->getPowerMode();
982 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
983 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700984 return;
985 }
986
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700987 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700988 if (mode == currentMode) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800989 // Don't update config if we are already running in the desired mode.
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700990 return;
991 }
Ana Krulecb43429d2019-01-09 14:28:51 -0800992 if (mUseScheduler) {
993 mRefreshRateStats->setConfigMode(mode);
994 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700995
Dominik Laskowski075d3172018-05-24 15:50:06 -0700996 const auto displayId = display->getId();
997 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700998
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700999 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001000 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001001
Ana Krulec7d1d6832018-12-27 11:10:09 -08001002 ATRACE_INT("ActiveConfigMode", mode);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001003 resyncToHardwareVsync(true, getVsyncPeriod());
Mathias Agopianc666cae2012-07-25 18:56:13 -07001004}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001005
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001006status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1007 Vector<ColorMode>* outColorModes) {
1008 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001009 return BAD_VALUE;
1010 }
1011
Dominik Laskowski075d3172018-05-24 15:50:06 -07001012 const auto displayId = getPhysicalDisplayId(displayToken);
1013 if (!displayId) {
1014 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -07001015 }
1016
Peiyong Lina52f0292018-03-14 17:26:31 -07001017 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001018 {
1019 ConditionalLock _l(mStateLock,
1020 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001021 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001022 }
Michael Wright28f24d02016-07-12 13:30:53 -07001023 outColorModes->clear();
1024 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1025
1026 return NO_ERROR;
1027}
1028
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001029ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1030 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001031 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001032 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001033 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001034}
1035
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001036status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001037 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001038 Vector<ColorMode> modes;
1039 getDisplayColorModes(displayToken, &modes);
1040 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1041 if (mode < ColorMode::NATIVE || !exists) {
1042 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1043 decodeColorMode(mode).c_str(), mode, displayToken.get());
1044 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001045 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001046 const auto display = getDisplayDevice(displayToken);
1047 if (!display) {
1048 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1049 decodeColorMode(mode).c_str(), mode, displayToken.get());
1050 } else if (display->isVirtual()) {
1051 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1052 decodeColorMode(mode).c_str(), mode);
1053 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001054 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1055 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001056 }
1057 }));
1058
Michael Wright28f24d02016-07-12 13:30:53 -07001059 return NO_ERROR;
1060}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001061
Svetoslavd85084b2014-03-20 10:28:31 -07001062status_t SurfaceFlinger::clearAnimationFrameStats() {
1063 Mutex::Autolock _l(mStateLock);
1064 mAnimFrameTracker.clearStats();
1065 return NO_ERROR;
1066}
1067
1068status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1069 Mutex::Autolock _l(mStateLock);
1070 mAnimFrameTracker.getStats(outStats);
1071 return NO_ERROR;
1072}
1073
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001074status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1075 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001076 Mutex::Autolock _l(mStateLock);
1077
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001078 const auto display = getDisplayDeviceLocked(displayToken);
1079 if (!display) {
1080 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001081 return BAD_VALUE;
1082 }
1083
Peiyong Linfb069302018-04-25 14:34:31 -07001084 // At this point the DisplayDeivce should already be set up,
1085 // meaning the luminance information is already queried from
1086 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001087 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001088 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1089 capabilities.getDesiredMaxLuminance(),
1090 capabilities.getDesiredMaxAverageLuminance(),
1091 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001092
1093 return NO_ERROR;
1094}
1095
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001096status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1097 ui::PixelFormat* outFormat,
1098 ui::Dataspace* outDataspace,
1099 uint8_t* outComponentMask) const {
1100 if (!outFormat || !outDataspace || !outComponentMask) {
1101 return BAD_VALUE;
1102 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001103 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001104 if (!display || !display->getId()) {
1105 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1106 return BAD_VALUE;
1107 }
1108 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1109 outDataspace, outComponentMask);
1110}
1111
Kevin DuBois74e53772018-11-19 10:52:38 -08001112status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1113 bool enable, uint8_t componentMask,
1114 uint64_t maxFrames) const {
1115 const auto display = getDisplayDevice(displayToken);
1116 if (!display || !display->getId()) {
1117 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1118 return BAD_VALUE;
1119 }
1120
1121 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1122 componentMask, maxFrames);
1123}
1124
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001125status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1126 uint64_t maxFrames, uint64_t timestamp,
1127 DisplayedFrameStats* outStats) const {
1128 const auto display = getDisplayDevice(displayToken);
1129 if (!display || !display->getId()) {
1130 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1131 return BAD_VALUE;
1132 }
1133
1134 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1135 outStats);
1136}
1137
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001138status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1139 if (!outSupported) {
1140 return BAD_VALUE;
1141 }
1142 *outSupported = getRenderEngine().supportsProtectedContent();
1143 return NO_ERROR;
1144}
1145
Marissa Wallebc2c052019-01-16 19:16:55 -08001146status_t SurfaceFlinger::cacheBuffer(const sp<IBinder>& token, const sp<GraphicBuffer>& buffer,
1147 int32_t* outBufferId) {
1148 if (!outBufferId) {
1149 return BAD_VALUE;
1150 }
1151 *outBufferId = mBufferStateLayerCache.add(token, buffer);
1152 return NO_ERROR;
1153}
1154
1155status_t SurfaceFlinger::uncacheBuffer(const sp<IBinder>& token, int32_t bufferId) {
1156 mBufferStateLayerCache.release(token, bufferId);
1157 return NO_ERROR;
1158}
1159
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001160status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001161 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001162 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001163
Chia-I Wu90f669f2017-10-05 14:24:41 -07001164 if (mInjectVSyncs == enable) {
1165 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001166 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001167
Dominik Laskowski83b88212018-12-11 13:34:06 -08001168 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001169
Ana Krulec98b5b242018-08-10 15:03:23 -07001170 // TODO(akrulec): Part of the Injector should be refactored, so that it
1171 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001172 if (enable) {
1173 ALOGV("VSync Injections enabled");
1174 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001175 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001176 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001177 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001178 impl::EventThread::InterceptVSyncsCallback(),
1179 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001180 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001181 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001182 } else {
1183 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001184 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001185 }
1186
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001187 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001188 }));
1189
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001190 return NO_ERROR;
1191}
1192
1193status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001194 Mutex::Autolock _l(mStateLock);
1195
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001196 if (!mInjectVSyncs) {
1197 ALOGE("VSync Injections not enabled");
1198 return BAD_VALUE;
1199 }
1200 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1201 ALOGV("Injecting VSync inside SurfaceFlinger");
1202 mVSyncInjector->onInjectSyncEvent(when);
1203 }
1204 return NO_ERROR;
1205}
1206
Lloyd Pique755e3192018-01-31 16:46:15 -08001207status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1208 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001209 // Try to acquire a lock for 1s, fail gracefully
1210 const status_t err = mStateLock.timedLock(s2ns(1));
1211 const bool locked = (err == NO_ERROR);
1212 if (!locked) {
1213 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1214 return TIMED_OUT;
1215 }
1216
1217 outLayers->clear();
1218 mCurrentState.traverseInZOrder([&](Layer* layer) {
1219 outLayers->push_back(layer->getLayerDebugInfo());
1220 });
1221
1222 mStateLock.unlock();
1223 return NO_ERROR;
1224}
1225
Peiyong Linc6780972018-10-28 15:24:08 -07001226status_t SurfaceFlinger::getCompositionPreference(
1227 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1228 Dataspace* outWideColorGamutDataspace,
1229 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001230 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001231 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001232 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001233 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001234 return NO_ERROR;
1235}
1236
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001237// ----------------------------------------------------------------------------
1238
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001239sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1240 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001241 auto resyncCallback = makeResyncCallback([this] {
1242 Mutex::Autolock lock(mStateLock);
1243 return getVsyncPeriod();
1244 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001245
Ana Krulec98b5b242018-08-10 15:03:23 -07001246 if (mUseScheduler) {
1247 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001248 return mScheduler->createDisplayEventConnection(mSfConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001249 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001250 return mScheduler->createDisplayEventConnection(mAppConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001251 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001252 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001253 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001254 return mSFEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001255 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001256 return mEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001257 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001258 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001259}
1260
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001261// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001262
1263void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001264 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001265}
1266
1267void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001268 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001269}
1270
1271void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001272 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001273}
1274
1275void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001276 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001277 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001278}
1279
1280status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001281 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001282 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001283}
1284
1285status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001286 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001287 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001288 if (res == NO_ERROR) {
1289 msg->wait();
1290 }
1291 return res;
1292}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001293
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001294void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001295 do {
1296 waitForEvent();
1297 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001298}
1299
Dominik Laskowski83b88212018-12-11 13:34:06 -08001300nsecs_t SurfaceFlinger::getVsyncPeriod() const {
1301 const auto displayId = getInternalDisplayId();
1302 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1303 return 0;
1304 }
1305
1306 const auto config = getHwComposer().getActiveConfig(*displayId);
1307 return config ? config->getVsyncPeriod() : 0;
1308}
1309
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001310void SurfaceFlinger::enableHardwareVsync() {
1311 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001312 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001313 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001314 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001315 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001316 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001317}
1318
Dominik Laskowski83b88212018-12-11 13:34:06 -08001319void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001320 Mutex::Autolock _l(mHWVsyncLock);
1321
Jesse Hall948fe0c2013-10-14 12:56:09 -07001322 if (makeAvailable) {
1323 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001324 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1325 if (mUseScheduler) {
1326 mScheduler->makeHWSyncAvailable(true);
1327 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001328 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001329 // Hardware vsync is not currently available, so abort the resync
1330 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001331 return;
1332 }
1333
Dominik Laskowski83b88212018-12-11 13:34:06 -08001334 if (period <= 0) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001335 return;
1336 }
1337
Ana Krulece588e312018-09-18 12:32:24 -07001338 if (mUseScheduler) {
1339 mScheduler->setVsyncPeriod(period);
1340 } else {
1341 mPrimaryDispSync->reset();
1342 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001343
Ana Krulece588e312018-09-18 12:32:24 -07001344 if (!mPrimaryHWVsyncEnabled) {
1345 mPrimaryDispSync->beginResync();
1346 mEventControlThread->setVsyncEnabled(true);
1347 mPrimaryHWVsyncEnabled = true;
1348 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001349 }
1350}
1351
Jesse Hall948fe0c2013-10-14 12:56:09 -07001352void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001353 Mutex::Autolock _l(mHWVsyncLock);
1354 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001355 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001356 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001357 mPrimaryHWVsyncEnabled = false;
1358 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001359 if (makeUnavailable) {
1360 mHWVsyncAvailable = false;
1361 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001362}
1363
Dominik Laskowski83b88212018-12-11 13:34:06 -08001364void SurfaceFlinger::VsyncState::resync(const GetVsyncPeriod& getVsyncPeriod) {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001365 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001366
Dan Stoza57164302017-05-08 14:03:54 -07001367 const nsecs_t now = systemTime();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001368 const nsecs_t last = lastResyncTime.exchange(now);
1369
1370 if (now - last > kIgnoreDelay) {
1371 flinger.resyncToHardwareVsync(false, getVsyncPeriod());
Tim Murray4a4e4a22016-04-19 16:29:23 +00001372 }
1373}
1374
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001375void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1376 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001377 ATRACE_NAME("SF onVsync");
1378
Steven Thomas3cfac282017-02-06 12:29:30 -08001379 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001380 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001381 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001382 return;
1383 }
1384
Dominik Laskowski075d3172018-05-24 15:50:06 -07001385 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001386 return;
1387 }
1388
Dominik Laskowski075d3172018-05-24 15:50:06 -07001389 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001390 // For now, we don't do anything with external display vsyncs.
1391 return;
1392 }
1393
Ana Krulece588e312018-09-18 12:32:24 -07001394 if (mUseScheduler) {
1395 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001396 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001397 bool needsHwVsync = false;
1398 { // Scope for the lock
1399 Mutex::Autolock _l(mHWVsyncLock);
1400 if (mPrimaryHWVsyncEnabled) {
1401 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1402 }
1403 }
1404
1405 if (needsHwVsync) {
1406 enableHardwareVsync();
1407 } else {
1408 disableHardwareVsync(false);
1409 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001410 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001411}
1412
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001413void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001414 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1415 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001416}
1417
Ana Krulec7d1d6832018-12-27 11:10:09 -08001418void SurfaceFlinger::setRefreshRateTo(float newFps) {
1419 const auto displayId = getInternalDisplayId();
1420 if (!displayId || mBootStage != BootStage::FINISHED) {
1421 return;
1422 }
1423 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1424 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1425 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1426 // refresh cycle.
1427
1428 // Don't do any updating if the current fps is the same as the new one.
1429 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
1430 const nsecs_t currentVsyncPeriod = activeConfig->getVsyncPeriod();
1431 if (currentVsyncPeriod == 0) {
1432 return;
1433 }
1434 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1435 // floating numbers.
1436 const float currentFps = 1e9 / currentVsyncPeriod;
1437 if (std::abs(currentFps - newFps) <= 1) {
1438 return;
1439 }
1440
1441 auto configs = getHwComposer().getConfigs(*displayId);
1442 for (int i = 0; i < configs.size(); i++) {
1443 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1444 if (vsyncPeriod == 0) {
1445 continue;
1446 }
1447 const float fps = 1e9 / vsyncPeriod;
1448 // TODO(b/113612090): There should be a better way at determining which config
1449 // has the right refresh rate.
1450 if (std::abs(fps - newFps) <= 1) {
1451 const auto display = getBuiltInDisplay(HWC_DISPLAY_PRIMARY);
1452 if (!display) return;
1453 // This is posted in async function to avoid deadlock when getDisplayDevice
1454 // requires mStateLock.
1455 setActiveConfigAsync(display, i);
1456 ATRACE_INT("FPS", newFps);
1457 }
1458 }
1459}
1460
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001461void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001462 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001463 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001464 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001465
Lloyd Piqueba04e622017-12-14 17:11:26 -08001466 // Ignore events that do not have the right sequenceId.
1467 if (sequenceId != getBE().mComposerSequenceId) {
1468 return;
1469 }
1470
Steven Thomasb02664d2017-07-26 18:48:28 -07001471 // Only lock if we're not on the main thread. This function is normally
1472 // called on a hwbinder thread, but for the primary display it's called on
1473 // the main thread with the state lock already held, so don't attempt to
1474 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001475 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001476
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001477 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001478
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001479 if (std::this_thread::get_id() == mMainThreadId) {
1480 // Process all pending hot plug events immediately if we are on the main thread.
1481 processDisplayHotplugEventsLocked();
1482 }
1483
Lloyd Piqueba04e622017-12-14 17:11:26 -08001484 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001485}
1486
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001487void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001488 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001489 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001490 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001491 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001492 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001493}
1494
Dominik Laskowski075d3172018-05-24 15:50:06 -07001495void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001496 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001497 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001498 if (const auto displayId = getInternalDisplayId()) {
1499 getHwComposer().setVsyncEnabled(*displayId,
1500 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1501 }
Mathias Agopian86303202012-07-24 22:46:10 -07001502}
1503
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001504// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001505void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001506 if (mUseScheduler) {
1507 mScheduler->disableHardwareVsync(true);
1508 } else {
1509 disableHardwareVsync(true);
1510 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001511 // Clear the drawing state so that the logic inside of
1512 // handleTransactionLocked will fire. It will determine the delta between
1513 // mCurrentState and mDrawingState and re-apply all changes when we make the
1514 // transition.
1515 mDrawingState.displays.clear();
1516 mDisplays.clear();
1517}
1518
Steven Thomas050b2c82017-03-06 11:45:16 -08001519void SurfaceFlinger::updateVrFlinger() {
1520 if (!mVrFlinger)
1521 return;
1522 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001523 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001524 return;
1525 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001526
Lloyd Pique441d5042018-10-18 16:49:51 -07001527 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001528 ALOGE("Vr flinger is only supported for remote hardware composer"
1529 " service connections. Ignoring request to transition to vr"
1530 " flinger.");
1531 mVrFlingerRequestsDisplay = false;
1532 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001533 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001534
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001535 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001536
Steven Thomas0123ac62018-07-12 11:32:34 -07001537 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001538 LOG_ALWAYS_FATAL_IF(!display);
1539 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001540 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1541 // called below. Clear the reference now so we don't accidentally use it
1542 // later.
1543 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001544
Steven Thomasb02664d2017-07-26 18:48:28 -07001545 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001546 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001547 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001548
Steven Thomasb02664d2017-07-26 18:48:28 -07001549 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001550 // Delete the current instance before creating the new one
1551 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1552 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1553 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1554 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001555
Lloyd Pique441d5042018-10-18 16:49:51 -07001556 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001557 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001558
1559 if (vrFlingerRequestsDisplay) {
1560 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001561 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001562
1563 mVisibleRegionsDirty = true;
1564 invalidateHwcGeometry();
1565
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001566 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001567 display = getDefaultDisplayDeviceLocked();
1568 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001569 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001570
Steven Thomasb02664d2017-07-26 18:48:28 -07001571 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001572 const nsecs_t vsyncPeriod = getVsyncPeriod();
1573 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001574
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001575 // The present fences returned from vr_hwc are not an accurate
1576 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001577 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001578 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1579 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001580 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001581 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001582 !hasSyncFramework);
1583 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001584
Steven Thomasb02664d2017-07-26 18:48:28 -07001585 // Use phase of 0 since phase is not known.
1586 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001587 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001588 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001589
Dominik Laskowski83b88212018-12-11 13:34:06 -08001590 resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001591
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001592 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001593 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001594}
1595
Mathias Agopian4fec8732012-06-29 14:12:52 -07001596void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001597 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001598 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001599 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001600 if (mUseScheduler) {
1601 // This call is made each time SF wakes up and creates a new frame.
1602 mScheduler->incrementFrameCounter();
1603 }
Dan Stoza50182882016-07-08 12:02:20 -07001604 bool frameMissed = !mHadClientComposition &&
1605 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001606 (mPreviousPresentFence->getSignalTime() ==
1607 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001608 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001609 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001610 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001611 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001612 if (mPropagateBackpressure) {
1613 signalLayerUpdate();
1614 break;
1615 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001616 }
Dan Stoza50182882016-07-08 12:02:20 -07001617
Steven Thomas050b2c82017-03-06 11:45:16 -08001618 // Now that we're going to make it to the handleMessageTransaction()
1619 // call below it's safe to call updateVrFlinger(), which will
1620 // potentially trigger a display handoff.
1621 updateVrFlinger();
1622
Dan Stoza6b9454d2014-11-07 16:00:59 -08001623 bool refreshNeeded = handleMessageTransaction();
1624 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001625 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001626 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001627 // Signal a refresh if a transaction modified the window state,
1628 // a new buffer was latched, or if HWC has requested a full
1629 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001630 signalRefresh();
1631 }
1632 break;
1633 }
1634 case MessageQueue::REFRESH: {
1635 handleMessageRefresh();
1636 break;
1637 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001638 }
1639}
1640
Dan Stoza6b9454d2014-11-07 16:00:59 -08001641bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001642 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001643
1644 // Apply any ready transactions in the queues if there are still transactions that have not been
1645 // applied, wake up during the next vsync period and check again
1646 bool transactionNeeded = false;
1647 if (!flushTransactionQueues()) {
1648 transactionNeeded = true;
1649 }
1650
Mathias Agopian4fec8732012-06-29 14:12:52 -07001651 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001652 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001653 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001654
1655 if (transactionNeeded) {
1656 setTransactionFlags(eTransactionNeeded);
1657 }
1658
1659 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001660}
1661
Mathias Agopian4fec8732012-06-29 14:12:52 -07001662void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001663 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001664
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001665 mRefreshPending = false;
1666
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001667 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001668 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001669 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001670 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001671 for (const auto& [token, display] : mDisplays) {
1672 beginFrame(display);
1673 prepareFrame(display);
1674 doDebugFlashRegions(display, repaintEverything);
1675 doComposition(display, repaintEverything);
1676 }
1677
Adrian Roos1e1a1282017-11-01 19:05:31 +01001678 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001679 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001680
1681 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001682 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001683
Dan Stozabfbffeb2016-07-21 14:49:33 -07001684 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001685 for (const auto& [token, displayDevice] : mDisplays) {
1686 auto display = displayDevice->getCompositionDisplay();
1687 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001688 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001689 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001690 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001691
Alec Mouri86770e52018-09-24 22:40:58 +00001692 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001693 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001694 if (mHadClientComposition) {
1695 base::unique_fd flushFence(getRenderEngine().flush());
1696 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1697 getBE().flushFence = new Fence(std::move(flushFence));
1698 } else {
1699 // Cleanup for hygiene.
1700 getBE().flushFence = Fence::NO_FENCE;
1701 }
1702 }
1703
Jorim Jaggi90535212018-05-23 23:44:06 +02001704 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001705
David Sodman7e4ae112018-02-09 15:02:28 -08001706 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001707 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001708 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001709 compositionInfo.hwc.hwcLayer = nullptr;
1710 }
David Sodmanba340492018-08-05 21:51:33 -07001711 }
David Sodman7e4ae112018-02-09 15:02:28 -08001712
1713 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001714}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001715
David Sodmanfa9b2af2017-12-24 13:28:59 -08001716
1717bool SurfaceFlinger::handleMessageInvalidate() {
1718 ATRACE_CALL();
1719 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001720}
1721
David Sodman79bba0e2018-08-05 18:07:49 -07001722void SurfaceFlinger::calculateWorkingSet() {
1723 ATRACE_CALL();
1724 ALOGV(__FUNCTION__);
1725
David Sodman79bba0e2018-08-05 18:07:49 -07001726 // build the h/w work list
1727 if (CC_UNLIKELY(mGeometryInvalid)) {
1728 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001729 for (const auto& [token, displayDevice] : mDisplays) {
1730 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001731 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001732 if (!displayId) {
1733 continue;
1734 }
David Sodman79bba0e2018-08-05 18:07:49 -07001735
Lloyd Pique32cbe282018-10-19 13:09:22 -07001736 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001737 for (size_t i = 0; i < currentLayers.size(); i++) {
1738 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001739
Dominik Laskowski075d3172018-05-24 15:50:06 -07001740 if (!layer->hasHwcLayer(*displayId)) {
1741 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1742 layer->forceClientComposition(*displayId);
1743 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001744 }
1745 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001746
Lloyd Pique32cbe282018-10-19 13:09:22 -07001747 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001748 if (mDebugDisableHWC || mDebugRegion) {
1749 layer->forceClientComposition(*displayId);
1750 }
David Sodman79bba0e2018-08-05 18:07:49 -07001751 }
1752 }
1753 }
1754
1755 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001756 for (const auto& [token, displayDevice] : mDisplays) {
1757 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001758 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001759 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001760 continue;
1761 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001762 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001763
1764 if (mDrawingState.colorMatrixChanged) {
1765 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001766 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001767 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001768 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001769 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001770 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1771 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001772 !profile->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001773 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001774 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1775 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001776 !profile->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001777 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001778 }
1779
Peiyong Lind3788632018-09-18 16:01:31 -07001780 // TODO(b/111562338) remove when composer 2.3 is shipped.
1781 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001782 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001783 }
1784
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001785 if (layer->getRoundedCornerState().radius > 0.0f) {
1786 layer->forceClientComposition(*displayId);
1787 }
1788
Dominik Laskowski075d3172018-05-24 15:50:06 -07001789 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001790 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001791 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001792 continue;
1793 }
1794
Lloyd Pique32cbe282018-10-19 13:09:22 -07001795 const auto& displayState = display->getState();
1796 layer->setPerFrameData(*displayId, displayState.transform, displayState.viewport,
1797 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001798 }
1799
Peiyong Lin13effd12018-07-24 17:01:47 -07001800 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001801 ColorMode colorMode;
1802 Dataspace dataSpace;
1803 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001804 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001805 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001806 }
1807 }
1808
1809 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001810
1811 for (const auto& [token, display] : mDisplays) {
1812 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001813 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001814 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001815
1816 if (displayId) {
1817 if (!layer->setHwcLayer(*displayId)) {
1818 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1819 }
1820 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001821 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001822
Dominik Laskowski05275f12018-11-01 15:03:24 -07001823 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001824 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1825 }
1826 }
David Sodman79bba0e2018-08-05 18:07:49 -07001827}
1828
Lloyd Pique32cbe282018-10-19 13:09:22 -07001829void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1830 bool repaintEverything) {
1831 auto display = displayDevice->getCompositionDisplay();
1832 const auto& displayState = display->getState();
1833
Mathias Agopiancd60f992012-08-16 16:28:27 -07001834 // is debugging enabled
1835 if (CC_LIKELY(!mDebugRegion))
1836 return;
1837
Lloyd Pique32cbe282018-10-19 13:09:22 -07001838 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001839 // transform the dirty region into this screen's coordinate space
Lloyd Pique32cbe282018-10-19 13:09:22 -07001840 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001841 if (!dirtyRegion.isEmpty()) {
1842 // redraw the whole screen
Lloyd Pique32cbe282018-10-19 13:09:22 -07001843 doComposeSurfaces(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001844
David Sodmanfa9b2af2017-12-24 13:28:59 -08001845 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001846 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001847 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001848
Lloyd Pique31cb2942018-10-19 17:23:03 -07001849 display->getRenderSurface()->queueBuffer();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001850 }
1851 }
1852
Lloyd Pique32cbe282018-10-19 13:09:22 -07001853 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001854
1855 if (mDebugRegion > 1) {
1856 usleep(mDebugRegion * 1000);
1857 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001858
Lloyd Pique32cbe282018-10-19 13:09:22 -07001859 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001860}
1861
Adrian Roos1e1a1282017-11-01 19:05:31 +01001862void SurfaceFlinger::doTracing(const char* where) {
1863 ATRACE_CALL();
1864 ATRACE_NAME(where);
1865 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001866 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001867 }
1868}
1869
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001870void SurfaceFlinger::logLayerStats() {
1871 ATRACE_CALL();
1872 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001873 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001874 if (display->isPrimary()) {
1875 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001876 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001877 }
1878 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001879
1880 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001881 }
1882}
1883
David Sodman2b406362017-12-15 13:33:47 -08001884void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001885{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001886 ATRACE_CALL();
1887 ALOGV("preComposition");
1888
David Sodman2b406362017-12-15 13:33:47 -08001889 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1890
Mathias Agopiancd60f992012-08-16 16:28:27 -07001891 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001892 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001893 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001894 needExtraInvalidate = true;
1895 }
Robert Carr2047fae2016-11-28 14:09:09 -08001896 });
1897
Mathias Agopiancd60f992012-08-16 16:28:27 -07001898 if (needExtraInvalidate) {
1899 signalLayerUpdate();
1900 }
1901}
1902
Ana Krulece588e312018-09-18 12:32:24 -07001903void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1904 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001905 // Update queue of past composite+present times and determine the
1906 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001907 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001908 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001909 while (!getBE().mCompositePresentTimes.empty()) {
1910 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001911 // Cached values should have been updated before calling this method,
1912 // which helps avoid duplicate syscalls.
1913 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1914 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1915 break;
1916 }
1917 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001918 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001919 }
1920
1921 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001922 while (getBE().mCompositePresentTimes.size() > 16) {
1923 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001924 }
1925
Ana Krulece588e312018-09-18 12:32:24 -07001926 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001927}
1928
Ana Krulece588e312018-09-18 12:32:24 -07001929void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1930 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001931 // Integer division and modulo round toward 0 not -inf, so we need to
1932 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001933 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1934 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1935 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001936
Brian Andersond0010582017-03-07 13:20:31 -08001937 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1938 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001939 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001940 }
1941
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001942 // Snap the latency to a value that removes scheduling jitter from the
1943 // composition and present times, which often have >1ms of jitter.
1944 // Reducing jitter is important if an app attempts to extrapolate
1945 // something (such as user input) to an accurate diasplay time.
1946 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1947 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001948 nsecs_t bias = stats.vsyncPeriod / 2;
1949 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1950 nsecs_t snappedCompositeToPresentLatency =
1951 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001952
David Sodman99974d22017-11-28 12:04:33 -08001953 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001954 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1955 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001956 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001957}
1958
Ady Abraham8164d482019-01-11 14:47:59 -08001959// debug patch for b/119477596 - add stack guards to catch stack
1960// corruptions and disable clang optimizations.
1961// The code below is temporary and planned to be removed once stack
1962// corruptions are found.
1963#pragma clang optimize off
1964class StackGuard {
1965public:
1966 StackGuard(const char* name, const char* func, int line) {
1967 guarders.reserve(MIN_CAPACITY);
1968 guarders.push_back({this, name, func, line});
1969 validate();
1970 }
1971 ~StackGuard() {
1972 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1973 if (i->guard == this) {
1974 guarders.erase(i);
1975 break;
1976 }
1977 }
1978 }
1979
1980 static void validate() {
1981 for (const auto& guard : guarders) {
1982 if (guard.guard->cookie != COOKIE_VALUE) {
1983 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1984 CallStack stack(LOG_TAG);
1985 abort();
1986 }
1987 }
1988 }
1989
1990private:
1991 uint64_t cookie = COOKIE_VALUE;
1992 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
1993 static constexpr size_t MIN_CAPACITY = 16;
1994
1995 struct GuarderElement {
1996 StackGuard* guard;
1997 const char* name;
1998 const char* func;
1999 int line;
2000 };
2001
2002 static std::vector<GuarderElement> guarders;
2003};
2004std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2005
2006#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2007
2008#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002009void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002010{
Ady Abraham8164d482019-01-11 14:47:59 -08002011 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002012 ATRACE_CALL();
2013 ALOGV("postComposition");
2014
Brian Anderson3546a3f2016-07-14 11:51:14 -07002015 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002016 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002017 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002018 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002019 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002020 }
Ady Abraham8164d482019-01-11 14:47:59 -08002021 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002022
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002023 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002024 const auto displayDevice = getDefaultDisplayDeviceLocked();
2025 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002026
David Sodman73beded2017-11-15 11:56:06 -08002027 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002028 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002029 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2030
Lloyd Pique32cbe282018-10-19 13:09:22 -07002031 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002032 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002033 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2034 ->getRenderSurface()
2035 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002036 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002037 } else {
2038 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2039 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002040
Ady Abraham8164d482019-01-11 14:47:59 -08002041 ASSERT_ON_STACK_GUARD();
2042
David Sodman73beded2017-11-15 11:56:06 -08002043 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002044 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2045 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002046 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002047 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002048 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002049
Ana Krulece588e312018-09-18 12:32:24 -07002050 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002051 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002052 if (mUseScheduler) {
2053 mScheduler->getDisplayStatInfo(&stats);
2054 } else {
2055 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2056 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2057 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002058
Ady Abraham8164d482019-01-11 14:47:59 -08002059 ASSERT_ON_STACK_GUARD();
2060
David Sodman2b406362017-12-15 13:33:47 -08002061 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002062 // when we started doing work for this frame, but that should be okay
2063 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002064 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002065 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002066 DEFINE_STACK_GUARD(compositorTiming);
2067
Brian Andersond0010582017-03-07 13:20:31 -08002068 {
David Sodman99974d22017-11-28 12:04:33 -08002069 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002070 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002071 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002072
2073 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002074 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002075
Robert Carr2047fae2016-11-28 14:09:09 -08002076 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002077 bool frameLatched =
2078 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2079 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002080 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002081 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002082 recordBufferingStats(layer->getName().string(),
2083 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002084 }
Ady Abraham8164d482019-01-11 14:47:59 -08002085 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002086 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002087
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002088 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002089 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002090 if (mUseScheduler) {
2091 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002092 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002093 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002094 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2095 enableHardwareVsync();
2096 } else {
2097 disableHardwareVsync(false);
2098 }
Ady Abraham8164d482019-01-11 14:47:59 -08002099 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002100 }
2101 }
2102
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002103 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002104 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2105 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002106 if (mUseScheduler) {
2107 mScheduler->enableHardwareVsync();
2108 } else {
2109 enableHardwareVsync();
2110 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002111 }
2112 }
2113
Ady Abraham8164d482019-01-11 14:47:59 -08002114 ASSERT_ON_STACK_GUARD();
2115
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002116 if (mAnimCompositionPending) {
2117 mAnimCompositionPending = false;
2118
Brian Anderson4e606e32017-03-16 15:34:57 -07002119 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002120 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002121 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002122
2123 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002124 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002125 // The HWC doesn't support present fences, so use the refresh
2126 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002127 const nsecs_t presentTime =
2128 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002129 DEFINE_STACK_GUARD(presentTime);
2130
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002131 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002132 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002133 }
2134 mAnimFrameTracker.advanceFrame();
2135 }
Dan Stozab90cf072015-03-05 11:05:59 -08002136
Ady Abraham8164d482019-01-11 14:47:59 -08002137 ASSERT_ON_STACK_GUARD();
2138
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002139 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002140 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002141 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002142 }
2143
Ady Abraham8164d482019-01-11 14:47:59 -08002144 ASSERT_ON_STACK_GUARD();
2145
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002146 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002147
Ady Abraham8164d482019-01-11 14:47:59 -08002148 ASSERT_ON_STACK_GUARD();
2149
Lloyd Pique32cbe282018-10-19 13:09:22 -07002150 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2151 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002152 return;
2153 }
2154
2155 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002156 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002157 if (mHasPoweredOff) {
2158 mHasPoweredOff = false;
2159 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002160 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002161 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002162 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002163 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002164 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2165 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002166 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002167 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002168 }
David Sodman4a36e932017-11-07 14:29:47 -08002169 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002170
2171 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002172 }
David Sodman4a36e932017-11-07 14:29:47 -08002173 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002174 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002175
2176 {
2177 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002178 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002179 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002180 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002181 if (refillCount > 0) {
2182 const size_t offset = mTexturePool.size();
2183 mTexturePool.resize(mTexturePoolSize);
2184 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2185 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2186 }
Ady Abraham8164d482019-01-11 14:47:59 -08002187 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002188 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002189
Marissa Wallfda30bb2018-10-12 11:34:28 -07002190 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002191 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002192
2193 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002194}
Ady Abraham8164d482019-01-11 14:47:59 -08002195#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002196
2197void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002198 ATRACE_CALL();
2199 ALOGV("rebuildLayerStacks");
2200
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002201 // We need to clear these out now as these may be holding on to a
2202 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2203 // also holds a reference. When the set of visible layers is recomputed,
2204 // some layers may be destroyed if the only thing keeping them alive was
2205 // that list of visible layers associated with each display. The layer
2206 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2207 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2208 for (const auto& [token, display] : mDisplays) {
2209 getBE().mCompositionInfo[token].clear();
2210 }
2211
Mathias Agopiancd60f992012-08-16 16:28:27 -07002212 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002213 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002214 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002215 mVisibleRegionsDirty = false;
2216 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002217
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002218 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002219 const auto& displayDevice = pair.second;
2220 auto display = displayDevice->getCompositionDisplay();
2221 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002222 Region opaqueRegion;
2223 Region dirtyRegion;
2224 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002225 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002226 const ui::Transform& tr = displayState.transform;
2227 const Rect bounds = displayState.bounds;
2228 if (displayState.isEnabled) {
2229 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002230
Jeff Sharkey76488112017-02-27 14:15:18 -07002231 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002232 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002233 const auto displayId = displayDevice->getId();
2234 if (display->belongsInOutput(layer->getLayerStack())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002235 Region drawRegion(tr.transform(
2236 layer->visibleNonTransparentRegion));
2237 drawRegion.andSelf(bounds);
2238 if (!drawRegion.isEmpty()) {
2239 layersSortedByZ.add(layer);
2240 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002241 // Clear out the HWC layer if this layer was
2242 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002243 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002244 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002245 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002246 // WM changes display->layerStack upon sleep/awake.
2247 // Here we make sure we delete the HWC layers even if
2248 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002249 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002250 }
2251
2252 // If a layer is not going to get a release fence because
2253 // it is invisible, but it is also going to release its
2254 // old buffer, add it to the list of layers needing
2255 // fences.
2256 if (hwcLayerDestroyed) {
2257 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2258 mLayersWithQueuedFrames.cend(), layer);
2259 if (found != mLayersWithQueuedFrames.cend()) {
2260 layersNeedingFences.add(layer);
2261 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002262 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002263 });
2264 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002265 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
2266 displayDevice->setLayersNeedingFences(layersNeedingFences);
2267
2268 Region undefinedRegion{bounds};
2269 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2270
2271 display->editState().undefinedRegion = undefinedRegion;
2272 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002273 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002274 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002275}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002276
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002277// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002278// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002279// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002280// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002281// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002282// The returned HDR data space is one of
2283// - Dataspace::UNKNOWN
2284// - Dataspace::BT2020_HLG
2285// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002286Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2287 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002288 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002289 *outHdrDataSpace = Dataspace::UNKNOWN;
2290
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002291 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002292 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002293 case Dataspace::V0_SCRGB:
2294 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002295 case Dataspace::BT2020:
2296 case Dataspace::BT2020_ITU:
2297 case Dataspace::BT2020_LINEAR:
2298 case Dataspace::DISPLAY_BT2020:
2299 bestDataSpace = Dataspace::DISPLAY_BT2020;
2300 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002301 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002302 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002303 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002304 case Dataspace::BT2020_PQ:
2305 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002306 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002307 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002308 case Dataspace::BT2020_HLG:
2309 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002310 // When there's mixed PQ content and HLG content, we set the HDR
2311 // data space to be BT2020_PQ and convert HLG to PQ.
2312 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2313 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002314 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002315 break;
2316 default:
2317 break;
2318 }
Romain Guy54f154a2017-10-24 21:40:32 +01002319 }
2320
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002321 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002322}
2323
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002324// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002325void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2326 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002327 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2328 *outMode = ColorMode::NATIVE;
2329 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002330 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002331 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002332 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002333
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002334 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002335 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002336
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002337 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2338
Peiyong Lindfde5112018-06-05 10:58:41 -07002339 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002340 const bool isHdr =
2341 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002342 if (isHdr) {
2343 bestDataSpace = hdrDataSpace;
2344 }
2345
Chia-I Wu0d711262018-05-21 15:19:35 -07002346 RenderIntent intent;
2347 switch (mDisplayColorSetting) {
2348 case DisplayColorSetting::MANAGED:
2349 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002350 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002351 break;
2352 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002353 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002354 break;
2355 default: // vendor display color setting
2356 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2357 break;
2358 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002359
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002360 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002361}
2362
Lloyd Pique32cbe282018-10-19 13:09:22 -07002363void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2364 auto display = displayDevice->getCompositionDisplay();
2365 const auto& displayState = display->getState();
2366
2367 bool dirty = !display->getPhysicalSpaceDirtyRegion(false).isEmpty();
2368 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2369 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002370
David Sodmanfa9b2af2017-12-24 13:28:59 -08002371 // If nothing has changed (!dirty), don't recompose.
2372 // If something changed, but we don't currently have any visible layers,
2373 // and didn't when we last did a composition, then skip it this time.
2374 // The second rule does two things:
2375 // - When all layers are removed from a display, we'll emit one black
2376 // frame, then nothing more until we get new layers.
2377 // - When a display is created with a private layer stack, we won't
2378 // emit any black frames until a layer is added to the layer stack.
2379 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002380
Dominik Laskowski075d3172018-05-24 15:50:06 -07002381 const char flagPrefix[] = {'-', '+'};
2382 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002383 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2384 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2385 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2386 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002387
Lloyd Pique31cb2942018-10-19 17:23:03 -07002388 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002389
David Sodmanfa9b2af2017-12-24 13:28:59 -08002390 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002391 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002392 }
2393}
2394
Lloyd Pique32cbe282018-10-19 13:09:22 -07002395void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2396 auto display = displayDevice->getCompositionDisplay();
2397 const auto& displayState = display->getState();
2398
2399 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002400 return;
David Sodman2b406362017-12-15 13:33:47 -08002401 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002402
Lloyd Pique31cb2942018-10-19 17:23:03 -07002403 status_t result = display->getRenderSurface()->prepareFrame(
2404 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002405 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002406 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002407}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002408
Lloyd Pique32cbe282018-10-19 13:09:22 -07002409void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002410 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002411 ALOGV("doComposition");
2412
Lloyd Pique32cbe282018-10-19 13:09:22 -07002413 auto display = displayDevice->getCompositionDisplay();
2414 const auto& displayState = display->getState();
2415
2416 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002417 // transform the dirty region into this screen's coordinate space
Lloyd Pique32cbe282018-10-19 13:09:22 -07002418 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002419
David Sodmanfa9b2af2017-12-24 13:28:59 -08002420 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002421 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002422
Lloyd Pique32cbe282018-10-19 13:09:22 -07002423 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002424 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002425 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002426 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002427}
2428
David Sodmanfa9b2af2017-12-24 13:28:59 -08002429void SurfaceFlinger::postFrame()
2430{
2431 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002432 const auto display = getDefaultDisplayDeviceLocked();
2433 if (display && getHwComposer().isConnected(*display->getId())) {
2434 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002435 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2436 logFrameStats();
2437 }
2438 }
2439}
2440
Lloyd Pique32cbe282018-10-19 13:09:22 -07002441void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002442 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002443 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002444
Lloyd Pique32cbe282018-10-19 13:09:22 -07002445 auto display = displayDevice->getCompositionDisplay();
2446 const auto& displayState = display->getState();
2447 const auto displayId = display->getId();
2448
David Sodmanfa9b2af2017-12-24 13:28:59 -08002449 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002450
Lloyd Pique32cbe282018-10-19 13:09:22 -07002451 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002452 if (displayId) {
2453 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002454 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002455 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002456 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002457 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002458
Chia-I Wu7b549592017-11-15 09:14:57 -08002459 // The layer buffer from the previous frame (if any) is released
2460 // by HWC only when the release fence from this frame (if any) is
2461 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002462 if (displayId && layer->hasHwcLayer(*displayId)) {
2463 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2464 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002465 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002466
2467 // If the layer was client composited in the previous frame, we
2468 // need to merge with the previous client target acquire fence.
2469 // Since we do not track that, always merge with the current
2470 // client target acquire fence when it is available, even though
2471 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002472 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002473 releaseFence =
2474 Fence::merge("LayerRelease", releaseFence,
2475 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002476 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002477
David Sodman15094112018-10-11 09:39:37 -07002478 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002479 }
Chia-I Wu83806892017-11-16 10:50:20 -08002480
2481 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002482 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002483 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002484 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002485 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002486 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002487 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002488 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002489 }
2490 }
2491
Dominik Laskowski075d3172018-05-24 15:50:06 -07002492 if (displayId) {
2493 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002494 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002495 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002496}
2497
Mathias Agopian87baae12012-07-31 12:38:26 -07002498void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002499{
Mathias Agopian841cde52012-03-01 15:44:37 -08002500 ATRACE_CALL();
2501
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002502 // here we keep a copy of the drawing state (that is the state that's
2503 // going to be overwritten by handleTransactionLocked()) outside of
2504 // mStateLock so that the side-effects of the State assignment
2505 // don't happen with mStateLock held (which can cause deadlocks).
2506 State drawingState(mDrawingState);
2507
Mathias Agopianca4d3602011-05-19 15:38:14 -07002508 Mutex::Autolock _l(mStateLock);
2509 const nsecs_t now = systemTime();
2510 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002511
Mathias Agopianca4d3602011-05-19 15:38:14 -07002512 // Here we're guaranteed that some transaction flags are set
2513 // so we can call handleTransactionLocked() unconditionally.
2514 // We call getTransactionFlags(), which will also clear the flags,
2515 // with mStateLock held to guarantee that mCurrentState won't change
2516 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002517
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002518 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002519 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002520 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002521
Mathias Agopianca4d3602011-05-19 15:38:14 -07002522 mLastTransactionTime = systemTime() - now;
2523 mDebugInTransaction = 0;
2524 invalidateHwcGeometry();
2525 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002526}
2527
Lloyd Piqueba04e622017-12-14 17:11:26 -08002528void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2529 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002530 const std::optional<DisplayIdentificationInfo> info =
2531 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002532
Dominik Laskowski075d3172018-05-24 15:50:06 -07002533 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002534 continue;
2535 }
2536
Lloyd Piqueba04e622017-12-14 17:11:26 -08002537 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002538 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002539 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002540 mPhysicalDisplayTokens[info->id] = new BBinder();
2541 DisplayDeviceState state;
2542 state.displayId = info->id;
2543 state.isSecure = true; // All physical displays are currently considered secure.
2544 state.displayName = info->name;
2545 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2546 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002547 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002548 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002549 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002550
Dominik Laskowski075d3172018-05-24 15:50:06 -07002551 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2552 if (index >= 0) {
2553 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2554 mInterceptor->saveDisplayDeletion(state.sequenceId);
2555 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002556 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002557 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002558 }
2559
2560 processDisplayChangesLocked();
2561 }
2562
2563 mPendingHotplugEvents.clear();
2564}
2565
Lloyd Pique99d3da52018-01-22 17:48:03 -08002566sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002567 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002568 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002569 const sp<IGraphicBufferProducer>& producer) {
2570 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002571 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002572 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002573 creationArgs.isSecure = state.isSecure;
2574 creationArgs.displaySurface = dispSurface;
2575 creationArgs.hasWideColorGamut = false;
2576 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002577
Dominik Laskowski075d3172018-05-24 15:50:06 -07002578 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2579 creationArgs.isPrimary = isInternalDisplay;
2580
2581 if (useColorManagement && displayId) {
2582 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002583 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002584 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002585 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002586 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002587
Dominik Laskowski7e045462018-05-30 13:02:02 -07002588 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002589 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002590 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002591 }
tangrobin6753a022018-08-10 10:58:54 +08002592 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002593
Dominik Laskowski075d3172018-05-24 15:50:06 -07002594 if (displayId) {
2595 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002596 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002597 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002598 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002599
Lloyd Pique90c115d2018-09-18 21:39:42 -07002600 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002601 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002602 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002603
Lloyd Pique99d3da52018-01-22 17:48:03 -08002604 // Make sure that composition can never be stalled by a virtual display
2605 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002606 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002607 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002608 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2609 }
2610
Dominik Laskowski075d3172018-05-24 15:50:06 -07002611 creationArgs.displayInstallOrientation =
2612 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002613
Lloyd Pique99d3da52018-01-22 17:48:03 -08002614 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002615 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002616
Lloyd Pique90c115d2018-09-18 21:39:42 -07002617 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002618
2619 if (maxFrameBufferAcquiredBuffers >= 3) {
2620 nativeWindowSurface->preallocateBuffers();
2621 }
2622
2623 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002624 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002625 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002626 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002627 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002628 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002629 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2630 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002631 if (!state.isVirtual()) {
2632 LOG_ALWAYS_FATAL_IF(!displayId);
2633 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002634 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002635
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002636 display->setLayerStack(state.layerStack);
2637 display->setProjection(state.orientation, state.viewport, state.frame);
2638 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002639
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002640 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002641}
2642
Lloyd Pique347200f2017-12-14 17:00:15 -08002643void SurfaceFlinger::processDisplayChangesLocked() {
2644 // here we take advantage of Vector's copy-on-write semantics to
2645 // improve performance by skipping the transaction entirely when
2646 // know that the lists are identical
2647 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2648 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2649 if (!curr.isIdenticalTo(draw)) {
2650 mVisibleRegionsDirty = true;
2651 const size_t cc = curr.size();
2652 size_t dc = draw.size();
2653
2654 // find the displays that were removed
2655 // (ie: in drawing state but not in current state)
2656 // also handle displays that changed
2657 // (ie: displays that are in both lists)
2658 for (size_t i = 0; i < dc;) {
2659 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2660 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002661 // Save display IDs before disconnecting.
2662 const auto internalDisplayId = getInternalDisplayId();
2663 const auto externalDisplayId = getExternalDisplayId();
2664
Lloyd Pique347200f2017-12-14 17:00:15 -08002665 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002666 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002667 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002668 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002669 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002670 if (mUseScheduler) {
2671 mScheduler->hotplugReceived(mAppConnectionHandle,
2672 EventThread::DisplayType::Primary, false);
2673 } else {
2674 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2675 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002676 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002677 if (mUseScheduler) {
2678 mScheduler->hotplugReceived(mAppConnectionHandle,
2679 EventThread::DisplayType::External, false);
2680 } else {
2681 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2682 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002683 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002684 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002685 } else {
2686 // this display is in both lists. see if something changed.
2687 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002688 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002689 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2690 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2691 if (state_binder != draw_binder) {
2692 // changing the surface is like destroying and
2693 // recreating the DisplayDevice, so we just remove it
2694 // from the drawing state, so that it get re-added
2695 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002696 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002697 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002698 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002699 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002700 mDrawingState.displays.removeItemsAt(i);
2701 dc--;
2702 // at this point we must loop to the next item
2703 continue;
2704 }
2705
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002706 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002707 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002708 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002709 }
2710 if ((state.orientation != draw[i].orientation) ||
2711 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002712 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002713 }
2714 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002715 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002716 }
2717 }
2718 }
2719 ++i;
2720 }
2721
2722 // find displays that were added
2723 // (ie: in current state but not in drawing state)
2724 for (size_t i = 0; i < cc; i++) {
2725 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2726 const DisplayDeviceState& state(curr[i]);
2727
Lloyd Pique542307f2018-10-19 13:24:08 -07002728 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002729 sp<IGraphicBufferProducer> producer;
2730 sp<IGraphicBufferProducer> bqProducer;
2731 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002732 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002733
Dominik Laskowski075d3172018-05-24 15:50:06 -07002734 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002735 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002736 // Virtual displays without a surface are dormant:
2737 // they have external state (layer stack, projection,
2738 // etc.) but no internal state (i.e. a DisplayDevice).
2739 if (state.surface != nullptr) {
2740 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002741 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002742 int width = 0;
2743 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2744 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2745 int height = 0;
2746 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2747 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2748 int intFormat = 0;
2749 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2750 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002751 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002752
Dominik Laskowski075d3172018-05-24 15:50:06 -07002753 displayId =
2754 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002755 }
2756
2757 // TODO: Plumb requested format back up to consumer
2758
2759 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002760 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002761 bqProducer, bqConsumer,
2762 state.displayName);
2763
2764 dispSurface = vds;
2765 producer = vds;
2766 }
2767 } else {
2768 ALOGE_IF(state.surface != nullptr,
2769 "adding a supported display, but rendering "
2770 "surface is provided (%p), ignoring it",
2771 state.surface.get());
2772
Dominik Laskowski075d3172018-05-24 15:50:06 -07002773 displayId = state.displayId;
2774 LOG_ALWAYS_FATAL_IF(!displayId);
2775 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002776 producer = bqProducer;
2777 }
2778
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002779 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002780 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002781 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002782 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002783 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002784 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002785 LOG_ALWAYS_FATAL_IF(!displayId);
2786
2787 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002788 if (mUseScheduler) {
2789 mScheduler->hotplugReceived(mAppConnectionHandle,
2790 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002791 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002792 } else {
2793 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2794 true);
2795 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002796 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002797 if (mUseScheduler) {
2798 mScheduler->hotplugReceived(mAppConnectionHandle,
2799 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002800 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002801 } else {
2802 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2803 true);
2804 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002805 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002806 }
2807 }
2808 }
2809 }
2810 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002811
2812 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002813}
2814
Mathias Agopian87baae12012-07-31 12:38:26 -07002815void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002816{
Dan Stoza7dde5992015-05-22 09:51:44 -07002817 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002818 mCurrentState.traverseInZOrder([](Layer* layer) {
2819 layer->notifyAvailableFrames();
2820 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002821
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002822 /*
2823 * Traversal of the children
2824 * (perform the transaction for each of them if needed)
2825 */
2826
Robert Carr720e5062018-07-30 17:45:14 -07002827 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002828 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002829 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002830 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002831 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002832
2833 const uint32_t flags = layer->doTransaction(0);
2834 if (flags & Layer::eVisibleRegion)
2835 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002836
2837 if (flags & Layer::eInputInfoChanged) {
2838 inputChanged = true;
2839 }
Robert Carr2047fae2016-11-28 14:09:09 -08002840 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002841 }
2842
2843 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002844 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002845 */
2846
Mathias Agopiane57f2922012-08-09 16:29:12 -07002847 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002848 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002849 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002850 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002851
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002852 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002853 // The transform hint might have changed for some layers
2854 // (either because a display has changed, or because a layer
2855 // as changed).
2856 //
2857 // Walk through all the layers in currentLayers,
2858 // and update their transform hint.
2859 //
2860 // If a layer is visible only on a single display, then that
2861 // display is used to calculate the hint, otherwise we use the
2862 // default display.
2863 //
2864 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2865 // the hint is set before we acquire a buffer from the surface texture.
2866 //
2867 // NOTE: layer transactions have taken place already, so we use their
2868 // drawing state. However, SurfaceFlinger's own transaction has not
2869 // happened yet, so we must use the current state layer list
2870 // (soon to become the drawing state list).
2871 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002872 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002873 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002874 bool first = true;
2875 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002876 // NOTE: we rely on the fact that layers are sorted by
2877 // layerStack first (so we don't have to traverse the list
2878 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002879 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002880 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002881 currentlayerStack = layerStack;
2882 // figure out if this layerstack is mirrored
2883 // (more than one display) if so, pick the default display,
2884 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002885 hintDisplay = nullptr;
2886 for (const auto& [token, display] : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002887 if (display->getCompositionDisplay()->belongsInOutput(layer->getLayerStack())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002888 if (hintDisplay) {
2889 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002890 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002891 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002892 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002893 }
2894 }
2895 }
2896 }
Chet Haase91d25932013-04-11 15:24:55 -07002897
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002898 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002899 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2900 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002901
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002902 // could be null when this layer is using a layerStack
2903 // that is not visible on any display. Also can occur at
2904 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002905 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002906 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002907
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002908 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002909 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002910 if (hintDisplay) {
2911 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002912 }
Robert Carr2047fae2016-11-28 14:09:09 -08002913
2914 first = false;
2915 });
Mathias Agopian84300952012-11-21 16:02:13 -08002916 }
2917
2918
Mathias Agopian3559b072012-08-15 13:46:03 -07002919 /*
2920 * Perform our own transaction if needed
2921 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002922
2923 if (mLayersAdded) {
2924 mLayersAdded = false;
2925 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002926 mVisibleRegionsDirty = true;
2927 }
2928
2929 // some layers might have been removed, so
2930 // we need to update the regions they're exposing.
2931 if (mLayersRemoved) {
2932 mLayersRemoved = false;
2933 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002934 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002935 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002936 // this layer is not visible anymore
2937 // TODO: we could traverse the tree from front to back and
2938 // compute the actual visible region
2939 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002940 Region visibleReg;
2941 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002942 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002943 }
Robert Carr2047fae2016-11-28 14:09:09 -08002944 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002945 }
2946
2947 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002948
Vishnu Nairde19f852018-12-18 16:11:53 -08002949 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002950 updateInputWindows();
2951 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002952 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002953
Riley Andrews03414a12014-07-01 14:22:59 -07002954 updateCursorAsync();
2955}
2956
Robert Carr720e5062018-07-30 17:45:14 -07002957void SurfaceFlinger::updateInputWindows() {
2958 ATRACE_CALL();
2959
Vishnu Nairde19f852018-12-18 16:11:53 -08002960 if (mInputFlinger == nullptr) {
2961 return;
2962 }
2963
Robert Carr720e5062018-07-30 17:45:14 -07002964 Vector<InputWindowInfo> inputHandles;
2965
2966 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2967 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002968 // When calculating the screen bounds we ignore the transparent region since it may
2969 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002970 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002971 }
2972 });
2973 mInputFlinger->setInputWindows(inputHandles);
2974}
2975
chaviwfbe5d9c2018-12-26 12:23:37 -08002976void SurfaceFlinger::executeInputWindowCommands() {
2977 if (!mInputFlinger) {
2978 return;
2979 }
2980
2981 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2982 if (transferTouchFocusCommand.fromToken != nullptr &&
2983 transferTouchFocusCommand.toToken != nullptr &&
2984 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2985 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2986 transferTouchFocusCommand.toToken);
2987 }
2988 }
2989
2990 mInputWindowCommands.clear();
2991}
2992
Riley Andrews03414a12014-07-01 14:22:59 -07002993void SurfaceFlinger::updateCursorAsync()
2994{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002995 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002996 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002997 continue;
2998 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002999
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003000 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3001 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003002 }
3003 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003004}
3005
chaviw61626f22018-11-15 16:26:27 -08003006void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3007 if (layer->hasReadyFrame()) {
3008 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3009 if (layer->shouldPresentNow(expectedPresentTime)) {
3010 bool ignored = false;
3011 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
3012 }
3013 }
3014 layer->releasePendingBuffer(systemTime());
3015}
3016
Mathias Agopian4fec8732012-06-29 14:12:52 -07003017void SurfaceFlinger::commitTransaction()
3018{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003019 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003020 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003021 for (const auto& l : mLayersPendingRemoval) {
3022 recordBufferingStats(l->getName().string(),
3023 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003024
3025 // We need to release the HWC layers when the Layer is removed
3026 // from the current state otherwise the HWC layer just continues
3027 // showing at its last configured state until we eventually
3028 // abandon the buffer queue.
3029 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003030 l->destroyHwcLayersForAllDisplays();
3031 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003032 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003033 }
3034 mLayersPendingRemoval.clear();
3035 }
3036
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003037 // If this transaction is part of a window animation then the next frame
3038 // we composite should be considered an animation as well.
3039 mAnimCompositionPending = mAnimTransactionPending;
3040
Mathias Agopian4fec8732012-06-29 14:12:52 -07003041 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003042 // clear the "changed" flags in current state
3043 mCurrentState.colorMatrixChanged = false;
3044
Robert Carr1f0a16a2016-10-24 16:27:39 -07003045 mDrawingState.traverseInZOrder([](Layer* layer) {
3046 layer->commitChildList();
3047 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003048 mTransactionPending = false;
3049 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003050 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003051}
3052
Lloyd Pique32cbe282018-10-19 13:09:22 -07003053void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003054 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003055 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003056 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003057
Lloyd Pique32cbe282018-10-19 13:09:22 -07003058 auto display = displayDevice->getCompositionDisplay();
3059
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003060 Region aboveOpaqueLayers;
3061 Region aboveCoveredLayers;
3062 Region dirty;
3063
Mathias Agopian87baae12012-07-31 12:38:26 -07003064 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003065
Robert Carr2047fae2016-11-28 14:09:09 -08003066 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003067 // start with the whole surface at its current location
3068 const Layer::State& s(layer->getDrawingState());
3069
Jesse Hall01e29052013-02-19 16:13:35 -08003070 // only consider the layers on the given layer stack
Lloyd Pique32cbe282018-10-19 13:09:22 -07003071 if (!display->belongsInOutput(layer->getLayerStack())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003072 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003073 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003074
Mathias Agopianab028732010-03-16 16:41:46 -07003075 /*
3076 * opaqueRegion: area of a surface that is fully opaque.
3077 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003078 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003079
3080 /*
3081 * visibleRegion: area of a surface that is visible on screen
3082 * and not fully transparent. This is essentially the layer's
3083 * footprint minus the opaque regions above it.
3084 * Areas covered by a translucent surface are considered visible.
3085 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003086 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003087
3088 /*
3089 * coveredRegion: area of a surface that is covered by all
3090 * visible regions above it (which includes the translucent areas).
3091 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003092 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003093
Jesse Halla8026d22012-09-25 13:25:04 -07003094 /*
3095 * transparentRegion: area of a surface that is hinted to be completely
3096 * transparent. This is only used to tell when the layer has no visible
3097 * non-transparent regions and can be removed from the layer list. It
3098 * does not affect the visibleRegion of this layer or any layers
3099 * beneath it. The hint may not be correct if apps don't respect the
3100 * SurfaceView restrictions (which, sadly, some don't).
3101 */
3102 Region transparentRegion;
3103
Mathias Agopianab028732010-03-16 16:41:46 -07003104
3105 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003106 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003107 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003108 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003109
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003110 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003111 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003112 if (!visibleRegion.isEmpty()) {
3113 // Remove the transparent area from the visible region
3114 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003115 if (tr.preserveRects()) {
3116 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003117 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003118 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003119 // transformation too complex, can't do the
3120 // transparent region optimization.
3121 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003122 }
Mathias Agopianab028732010-03-16 16:41:46 -07003123 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003124
Mathias Agopianab028732010-03-16 16:41:46 -07003125 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003126 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003127 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003128 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003129 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003130 // the opaque region is the layer's footprint
3131 opaqueRegion = visibleRegion;
3132 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003133 }
3134 }
3135
Robert Carre5f4f692018-01-12 13:12:28 -08003136 if (visibleRegion.isEmpty()) {
3137 layer->clearVisibilityRegions();
3138 return;
3139 }
3140
Mathias Agopianab028732010-03-16 16:41:46 -07003141 // Clip the covered region to the visible region
3142 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3143
3144 // Update aboveCoveredLayers for next (lower) layer
3145 aboveCoveredLayers.orSelf(visibleRegion);
3146
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003147 // subtract the opaque region covered by the layers above us
3148 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003149
3150 // compute this layer's dirty region
3151 if (layer->contentDirty) {
3152 // we need to invalidate the whole region
3153 dirty = visibleRegion;
3154 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003155 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003156 layer->contentDirty = false;
3157 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003158 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003159 * the exposed region consists of two components:
3160 * 1) what's VISIBLE now and was COVERED before
3161 * 2) what's EXPOSED now less what was EXPOSED before
3162 *
3163 * note that (1) is conservative, we start with the whole
3164 * visible region but only keep what used to be covered by
3165 * something -- which mean it may have been exposed.
3166 *
3167 * (2) handles areas that were not covered by anything but got
3168 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003169 */
Mathias Agopianab028732010-03-16 16:41:46 -07003170 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003171 const Region oldVisibleRegion = layer->visibleRegion;
3172 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003173 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3174 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003175 }
3176 dirty.subtractSelf(aboveOpaqueLayers);
3177
3178 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003179 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003180
Mathias Agopianab028732010-03-16 16:41:46 -07003181 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003182 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003183
Jesse Halla8026d22012-09-25 13:25:04 -07003184 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003185 layer->setVisibleRegion(visibleRegion);
3186 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003187 layer->setVisibleNonTransparentRegion(
3188 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003189 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003190
Mathias Agopian87baae12012-07-31 12:38:26 -07003191 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003192}
3193
Chia-I Wuab0c3192017-08-01 11:29:00 -07003194void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003195 for (const auto& [token, displayDevice] : mDisplays) {
3196 auto display = displayDevice->getCompositionDisplay();
3197 if (display->belongsInOutput(layer->getLayerStack())) {
3198 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003199 }
3200 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003201}
3202
Dan Stoza6b9454d2014-11-07 16:00:59 -08003203bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003204{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003205 ALOGV("handlePageFlip");
3206
Brian Andersond6927fb2016-07-23 23:37:30 -07003207 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003208
Mathias Agopian4fec8732012-06-29 14:12:52 -07003209 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003210 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003211 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003212
3213 // Store the set of layers that need updates. This set must not change as
3214 // buffers are being latched, as this could result in a deadlock.
3215 // Example: Two producers share the same command stream and:
3216 // 1.) Layer 0 is latched
3217 // 2.) Layer 0 gets a new frame
3218 // 2.) Layer 1 gets a new frame
3219 // 3.) Layer 1 is latched.
3220 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3221 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003222 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003223 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003224 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003225 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3226 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003227 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003228 } else {
3229 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003230 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003231 } else {
3232 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003233 }
Robert Carr2047fae2016-11-28 14:09:09 -08003234 });
3235
Lloyd Piquef2c79392018-12-20 16:23:33 -08003236 if (!mLayersWithQueuedFrames.empty()) {
3237 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3238 // writes to Layer current state. See also b/119481871
3239 Mutex::Autolock lock(mStateLock);
3240
3241 for (auto& layer : mLayersWithQueuedFrames) {
3242 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3243 layer->useSurfaceDamage();
3244 invalidateLayerStack(layer, dirty);
3245 if (layer->isBufferLatched()) {
3246 newDataLatched = true;
3247 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003248 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003249 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003250
Alec Mouri86770e52018-09-24 22:40:58 +00003251 // Clear the renderengine fence here...
3252 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3253 // clear instead of sp::clear.
3254 getBE().flushFence = Fence::NO_FENCE;
3255
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003256 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003257
Vishnu Nairde19f852018-12-18 16:11:53 -08003258 if (visibleRegions) {
3259 // Update input window info if the layer receives its first buffer.
3260 updateInputWindows();
3261 }
3262
Dan Stoza6b9454d2014-11-07 16:00:59 -08003263 // If we will need to wake up at some time in the future to deal with a
3264 // queued frame that shouldn't be displayed during this vsync period, wake
3265 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003266 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003267 signalLayerUpdate();
3268 }
3269
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003270 // enter boot animation on first buffer latch
3271 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3272 ALOGI("Enter boot animation");
3273 mBootStage = BootStage::BOOTANIMATION;
3274 }
3275
Dan Stoza6b9454d2014-11-07 16:00:59 -08003276 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003277 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003278}
3279
Mathias Agopianad456f92011-01-13 17:53:01 -08003280void SurfaceFlinger::invalidateHwcGeometry()
3281{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003282 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003283}
3284
Lloyd Pique32cbe282018-10-19 13:09:22 -07003285void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003286 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003287 auto display = displayDevice->getCompositionDisplay();
3288
Dan Stoza71433162014-02-04 16:22:36 -08003289 // We only need to actually compose the display if:
3290 // 1) It is being handled by hardware composer, which may need this to
3291 // keep its virtual display state machine in sync, or
3292 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003293 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003294 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003295 return;
3296 }
3297
Dan Stoza9e56aa02015-11-02 13:00:03 -08003298 ALOGV("doDisplayComposition");
Lloyd Pique32cbe282018-10-19 13:09:22 -07003299 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003300
3301 // swap buffers (presentation)
Lloyd Pique31cb2942018-10-19 17:23:03 -07003302 display->getRenderSurface()->queueBuffer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003303}
3304
Lloyd Pique32cbe282018-10-19 13:09:22 -07003305bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003306 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003307
Lloyd Pique32cbe282018-10-19 13:09:22 -07003308 auto display = displayDevice->getCompositionDisplay();
3309 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003310 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003311
3312 const Region bounds(displayState.bounds);
3313 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003314 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003315 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003316
Peiyong Lind3788632018-09-18 16:01:31 -07003317 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003318 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003319
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003320 // Framebuffer will live in this scope for GPU composition.
3321 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
3322
Dan Stoza9e56aa02015-11-02 13:00:03 -08003323 if (hasClientComposition) {
3324 ALOGV("hasClientComposition");
3325
Lloyd Pique31cb2942018-10-19 17:23:03 -07003326 sp<GraphicBuffer> buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003327
3328 if (buf == nullptr) {
3329 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3330 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003331 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003332 return false;
3333 }
3334
3335 // Bind the framebuffer in this scope.
3336 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3337 buf->getNativeBuffer());
3338
3339 if (fbo->getStatus() != NO_ERROR) {
3340 ALOGW("Binding buffer for display [%s] failed with status: %d",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003341 displayDevice->getDisplayName().c_str(), fbo->getStatus());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003342 return false;
3343 }
3344
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003345 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003346 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003347 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003348 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003349 }
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003350 getRenderEngine().setOutputDataSpace(outputDataspace);
3351 getRenderEngine().setDisplayMaxLuminance(
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003352 profile->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003353
Lloyd Pique441d5042018-10-18 16:49:51 -07003354 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003355 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003356 getHwComposer()
3357 .hasDisplayCapability(displayId,
3358 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003359
Peiyong Lind3788632018-09-18 16:01:31 -07003360 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003361 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3362 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003363 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003364 }
3365
Lloyd Pique31cb2942018-10-19 17:23:03 -07003366 display->getRenderSurface()->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003367
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003368 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003369 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003370 // when using overlays, we assume a fully transparent framebuffer
3371 // NOTE: we could reduce how much we need to clear, for instance
3372 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003373 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003374 // We'll revisit later if needed.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003375 getRenderEngine().clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003376 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003377 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003378 // we're left with the letterbox region
3379 // (common case is that letterbox ends-up being empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003380 const Region letterbox = bounds.subtract(displayState.scissor);
Mathias Agopian766dc492012-10-30 18:08:06 -07003381
3382 // compute the area to clear
Lloyd Pique32cbe282018-10-19 13:09:22 -07003383 const Region region = displayState.undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003384
Mathias Agopianb9494d52012-04-18 02:28:45 -07003385 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003386 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003387 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003388 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003389 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003390 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003391
Lloyd Pique32cbe282018-10-19 13:09:22 -07003392 const Rect& bounds = displayState.bounds;
3393 const Rect& scissor = displayState.scissor;
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003394 if (scissor != bounds) {
3395 // scissor doesn't match the screen's dimensions, so we
3396 // need to clear everything outside of it and enable
3397 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003398
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003399 // enable scissor for this frame
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003400 getRenderEngine().setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003401 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003402 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003403
Mathias Agopian85d751c2012-08-29 16:59:24 -07003404 /*
3405 * and then, render the layers targeted at the framebuffer
3406 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003407
Dan Stoza9e56aa02015-11-02 13:00:03 -08003408 ALOGV("Rendering client layers");
Lloyd Pique32cbe282018-10-19 13:09:22 -07003409 const ui::Transform& displayTransform = displayState.transform;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003410 bool firstLayer = true;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003411 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003412 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003413 displayTransform.transform(layer->visibleRegion)));
3414 ALOGV("Layer: %s", layer->getName().string());
3415 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003416 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003417 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003418 case HWC2::Composition::Cursor:
3419 case HWC2::Composition::Device:
3420 case HWC2::Composition::Sideband:
3421 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003422 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003423 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003424 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003425 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003426 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003427 // never clear the very first layer since we're
3428 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003429 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003430 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003431 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003432 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003433 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003434 if (layer->hasColorTransform()) {
3435 mat4 tmpMatrix;
3436 if (applyColorMatrix) {
3437 tmpMatrix = mDrawingState.colorMatrix;
3438 }
3439 tmpMatrix *= layer->getColorTransform();
Peiyong Lind3788632018-09-18 16:01:31 -07003440 getRenderEngine().setColorTransform(tmpMatrix);
3441 } else {
3442 getRenderEngine().setColorTransform(colorMatrix);
3443 }
David Sodmanc1498e62018-09-12 14:36:26 -07003444 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003445 break;
3446 }
3447 default:
3448 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003449 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003450 } else {
3451 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003452 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003453 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003454 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003455
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003456 // Perform some cleanup steps if we used client composition.
3457 if (hasClientComposition) {
3458 getRenderEngine().setColorTransform(mat4());
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003459 getRenderEngine().disableScissor();
Lloyd Pique31cb2942018-10-19 17:23:03 -07003460 display->getRenderSurface()->finishBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003461 // Clear out error flags here so that we don't wait until next
3462 // composition to log.
3463 getRenderEngine().checkErrors();
3464 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003465 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003466}
3467
Chia-I Wu28e3a252018-09-07 12:05:02 -07003468void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003469 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003470 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003471}
3472
Dan Stoza7d89d062015-04-30 13:29:25 -07003473status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003474 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003475 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003476 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003477 const sp<Layer>& parent,
3478 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003479{
Dan Stoza7d89d062015-04-30 13:29:25 -07003480 // add this layer to the current state list
3481 {
3482 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003483 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003484 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3485 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003486 return NO_MEMORY;
3487 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003488 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003489 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003490 } else if (parent == nullptr) {
3491 lbc->onRemovedFromCurrentState();
3492 } else if (parent->isRemovedFromCurrentState()) {
3493 parent->addChild(lbc);
3494 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003495 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003496 parent->addChild(lbc);
3497 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003498
Yiwei Zhang243b3782018-05-15 17:40:04 -07003499 if (gbc != nullptr) {
3500 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3501 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3502 mMaxGraphicBufferProducerListSize,
3503 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3504 mGraphicBufferProducerList.size(),
3505 mMaxGraphicBufferProducerListSize, mNumLayers);
3506 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003507 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003508 }
3509
Mathias Agopian96f08192010-06-02 23:28:45 -07003510 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003511 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003512
Dan Stoza7d89d062015-04-30 13:29:25 -07003513 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003514}
3515
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003516uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003517 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003518}
3519
Mathias Agopian3f844832013-08-07 21:24:32 -07003520uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003521 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003522}
3523
Mathias Agopian3f844832013-08-07 21:24:32 -07003524uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003525 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003526}
3527
3528uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003529 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003530 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003531 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003532 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003533 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003534 }
3535 return old;
3536}
3537
Marissa Wall713b63f2018-10-17 15:42:43 -07003538bool SurfaceFlinger::flushTransactionQueues() {
3539 Mutex::Autolock _l(mStateLock);
3540 auto it = mTransactionQueues.begin();
3541 while (it != mTransactionQueues.end()) {
3542 auto& [applyToken, transactionQueue] = *it;
3543
3544 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003545 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3546 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003547 break;
3548 }
chaviw273171b2018-12-26 11:46:30 -08003549 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003550 transactionQueue.pop();
3551 }
3552
3553 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3554 }
3555 return mTransactionQueues.empty();
3556}
3557
chaviwca27f252018-02-06 16:46:39 -08003558bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3559 for (const ComposerState& state : states) {
3560 // Here we need to check that the interface we're given is indeed
3561 // one of our own. A malicious client could give us a nullptr
3562 // IInterface, or one of its own or even one of our own but a
3563 // different type. All these situations would cause us to crash.
3564 if (state.client == nullptr) {
3565 return true;
3566 }
3567
3568 sp<IBinder> binder = IInterface::asBinder(state.client);
3569 if (binder == nullptr) {
3570 return true;
3571 }
3572
3573 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3574 return true;
3575 }
3576 }
3577 return false;
3578}
3579
Marissa Wall17b4e452018-12-26 16:32:34 -08003580bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3581 const Vector<ComposerState>& states) {
3582 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3583 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3584 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3585 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3586 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3587 return false;
3588 }
3589
Marissa Wall713b63f2018-10-17 15:42:43 -07003590 for (const ComposerState& state : states) {
3591 const layer_state_t& s = state.state;
3592 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3593 continue;
3594 }
3595 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003596 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003597 }
3598 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003599 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003600}
3601
3602void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3603 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003604 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003605 const InputWindowCommands& inputWindowCommands,
3606 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003607 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003608 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003609
chaviwca27f252018-02-06 16:46:39 -08003610 if (containsAnyInvalidClientState(states)) {
3611 return;
3612 }
3613
Marissa Wall713b63f2018-10-17 15:42:43 -07003614 // If its TransactionQueue already has a pending TransactionState or if it is pending
3615 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003616 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3617 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003618 setTransactionFlags(eTransactionNeeded);
3619 return;
3620 }
3621
chaviw273171b2018-12-26 11:46:30 -08003622 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003623}
3624
3625void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003626 const Vector<DisplayState>& displays, uint32_t flags,
3627 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003628 uint32_t transactionFlags = 0;
3629
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003630 if (flags & eAnimation) {
3631 // For window updates that are part of an animation we must wait for
3632 // previous animation "frames" to be handled.
3633 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003634 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003635 if (CC_UNLIKELY(err != NO_ERROR)) {
3636 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003637 // caller after a few seconds.
3638 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3639 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003640 mAnimTransactionPending = false;
3641 break;
3642 }
3643 }
3644 }
3645
chaviwca27f252018-02-06 16:46:39 -08003646 for (const DisplayState& display : displays) {
3647 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003648 }
3649
Marissa Walle2ffb422018-10-12 11:33:52 -07003650 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003651 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003652 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003653 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003654 // If the state doesn't require a traversal and there are callbacks, send them now
3655 if (!(clientStateFlags & eTraversalNeeded)) {
3656 mTransactionCompletedThread.sendCallbacks();
3657 }
3658 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003659
chaviw273171b2018-12-26 11:46:30 -08003660 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3661
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003662 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3663 // anyway. This can be used as a flush mechanism for previous async transactions.
3664 // Empty animation transaction can be used to simulate back-pressure, so also force a
3665 // transaction for empty animation transactions.
3666 if (transactionFlags == 0 &&
3667 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003668 transactionFlags = eTransactionNeeded;
3669 }
3670
Mathias Agopian386aa982011-11-07 21:58:03 -08003671 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003672 if (mInterceptor->isEnabled()) {
3673 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003674 }
Irvel468051e2016-06-13 16:44:44 -07003675
Mathias Agopian386aa982011-11-07 21:58:03 -08003676 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003677 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3678 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003679 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003680
3681 // if this is a synchronous transaction, wait for it to take effect
3682 // before returning.
3683 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003684 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003685 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003686 if (flags & eAnimation) {
3687 mAnimTransactionPending = true;
3688 }
3689 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003690 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3691 if (CC_UNLIKELY(err != NO_ERROR)) {
3692 // just in case something goes wrong in SF, return to the
3693 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003694 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3695 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003696 break;
3697 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003698 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003699 }
3700}
3701
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003702uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3703 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3704 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003705
Mathias Agopiane57f2922012-08-09 16:29:12 -07003706 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003707 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3708
3709 const uint32_t what = s.what;
3710 if (what & DisplayState::eSurfaceChanged) {
3711 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3712 state.surface = s.surface;
3713 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003714 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003715 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003716 if (what & DisplayState::eLayerStackChanged) {
3717 if (state.layerStack != s.layerStack) {
3718 state.layerStack = s.layerStack;
3719 flags |= eDisplayTransactionNeeded;
3720 }
3721 }
3722 if (what & DisplayState::eDisplayProjectionChanged) {
3723 if (state.orientation != s.orientation) {
3724 state.orientation = s.orientation;
3725 flags |= eDisplayTransactionNeeded;
3726 }
3727 if (state.frame != s.frame) {
3728 state.frame = s.frame;
3729 flags |= eDisplayTransactionNeeded;
3730 }
3731 if (state.viewport != s.viewport) {
3732 state.viewport = s.viewport;
3733 flags |= eDisplayTransactionNeeded;
3734 }
3735 }
3736 if (what & DisplayState::eDisplaySizeChanged) {
3737 if (state.width != s.width) {
3738 state.width = s.width;
3739 flags |= eDisplayTransactionNeeded;
3740 }
3741 if (state.height != s.height) {
3742 state.height = s.height;
3743 flags |= eDisplayTransactionNeeded;
3744 }
3745 }
3746
Mathias Agopiane57f2922012-08-09 16:29:12 -07003747 return flags;
3748}
3749
Robert Carrd4ae7f32018-06-07 16:10:57 -07003750bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3751 IPCThreadState* ipc = IPCThreadState::self();
3752 const int pid = ipc->getCallingPid();
3753 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003754 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003755 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003756 return false;
3757 }
3758 return true;
3759}
3760
chaviwca27f252018-02-06 16:46:39 -08003761uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3762 const layer_state_t& s = composerState.state;
3763 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3764
Mathias Agopian13127d82013-03-05 17:47:11 -08003765 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003766 if (layer == nullptr) {
3767 return 0;
3768 }
3769
chaviw8b3871a2017-11-01 17:41:01 -07003770 uint32_t flags = 0;
3771
Garfield Tan8a3083e2018-12-03 13:21:07 -08003772 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003773 bool geometryAppliesWithResize =
3774 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003775
3776 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3777 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003778 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003779 layer->pushPendingState();
3780 }
3781
chaviw8b3871a2017-11-01 17:41:01 -07003782 if (what & layer_state_t::ePositionChanged) {
3783 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3784 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003785 }
chaviw8b3871a2017-11-01 17:41:01 -07003786 }
3787 if (what & layer_state_t::eLayerChanged) {
3788 // NOTE: index needs to be calculated before we update the state
3789 const auto& p = layer->getParent();
3790 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003791 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003792 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003793 mCurrentState.layersSortedByZ.removeAt(idx);
3794 mCurrentState.layersSortedByZ.add(layer);
3795 // we need traversal (state changed)
3796 // AND transaction (list changed)
3797 flags |= eTransactionNeeded|eTraversalNeeded;
3798 }
chaviw8b3871a2017-11-01 17:41:01 -07003799 } else {
3800 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003801 flags |= eTransactionNeeded|eTraversalNeeded;
3802 }
3803 }
chaviw8b3871a2017-11-01 17:41:01 -07003804 }
3805 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003806 // NOTE: index needs to be calculated before we update the state
3807 const auto& p = layer->getParent();
3808 if (p == nullptr) {
3809 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3810 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3811 mCurrentState.layersSortedByZ.removeAt(idx);
3812 mCurrentState.layersSortedByZ.add(layer);
3813 // we need traversal (state changed)
3814 // AND transaction (list changed)
3815 flags |= eTransactionNeeded|eTraversalNeeded;
3816 }
3817 } else {
3818 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3819 flags |= eTransactionNeeded|eTraversalNeeded;
3820 }
chaviw8b3871a2017-11-01 17:41:01 -07003821 }
3822 }
3823 if (what & layer_state_t::eSizeChanged) {
3824 if (layer->setSize(s.w, s.h)) {
3825 flags |= eTraversalNeeded;
3826 }
3827 }
3828 if (what & layer_state_t::eAlphaChanged) {
3829 if (layer->setAlpha(s.alpha))
3830 flags |= eTraversalNeeded;
3831 }
3832 if (what & layer_state_t::eColorChanged) {
3833 if (layer->setColor(s.color))
3834 flags |= eTraversalNeeded;
3835 }
Peiyong Lind3788632018-09-18 16:01:31 -07003836 if (what & layer_state_t::eColorTransformChanged) {
3837 if (layer->setColorTransform(s.colorTransform)) {
3838 flags |= eTraversalNeeded;
3839 }
3840 }
chaviw8b3871a2017-11-01 17:41:01 -07003841 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003842 // TODO: b/109894387
3843 //
3844 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3845 // rotation. To see the problem observe that if we have a square parent, and a child
3846 // of the same size, then we rotate the child 45 degrees around it's center, the child
3847 // must now be cropped to a non rectangular 8 sided region.
3848 //
3849 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3850 // private API, and the WindowManager only uses rotation in one case, which is on a top
3851 // level layer in which cropping is not an issue.
3852 //
3853 // However given that abuse of rotation matrices could lead to surfaces extending outside
3854 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3855 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3856 // transformations.
3857 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003858 flags |= eTraversalNeeded;
3859 }
3860 if (what & layer_state_t::eTransparentRegionChanged) {
3861 if (layer->setTransparentRegionHint(s.transparentRegion))
3862 flags |= eTraversalNeeded;
3863 }
3864 if (what & layer_state_t::eFlagsChanged) {
3865 if (layer->setFlags(s.flags, s.mask))
3866 flags |= eTraversalNeeded;
3867 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003868 if (what & layer_state_t::eCropChanged_legacy) {
3869 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003870 flags |= eTraversalNeeded;
3871 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003872 if (what & layer_state_t::eCornerRadiusChanged) {
3873 if (layer->setCornerRadius(s.cornerRadius))
3874 flags |= eTraversalNeeded;
3875 }
chaviw8b3871a2017-11-01 17:41:01 -07003876 if (what & layer_state_t::eLayerStackChanged) {
3877 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3878 // We only allow setting layer stacks for top level layers,
3879 // everything else inherits layer stack from its parent.
3880 if (layer->hasParent()) {
3881 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3882 layer->getName().string());
3883 } else if (idx < 0) {
3884 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3885 "that also does not appear in the top level layer list. Something"
3886 " has gone wrong.", layer->getName().string());
3887 } else if (layer->setLayerStack(s.layerStack)) {
3888 mCurrentState.layersSortedByZ.removeAt(idx);
3889 mCurrentState.layersSortedByZ.add(layer);
3890 // we need traversal (state changed)
3891 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003892 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003893 }
3894 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003895 if (what & layer_state_t::eDeferTransaction_legacy) {
3896 if (s.barrierHandle_legacy != nullptr) {
3897 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3898 } else if (s.barrierGbp_legacy != nullptr) {
3899 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003900 if (authenticateSurfaceTextureLocked(gbp)) {
3901 const auto& otherLayer =
3902 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003903 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003904 } else {
3905 ALOGE("Attempt to defer transaction to to an"
3906 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003907 }
3908 }
chaviw8b3871a2017-11-01 17:41:01 -07003909 // We don't trigger a traversal here because if no other state is
3910 // changed, we don't want this to cause any more work
3911 }
3912 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003913 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003914 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003915 if (!hadParent) {
3916 mCurrentState.layersSortedByZ.remove(layer);
3917 }
chaviw8b3871a2017-11-01 17:41:01 -07003918 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003919 }
chaviw8b3871a2017-11-01 17:41:01 -07003920 }
3921 if (what & layer_state_t::eReparentChildren) {
3922 if (layer->reparentChildren(s.reparentHandle)) {
3923 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003924 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003925 }
chaviw8b3871a2017-11-01 17:41:01 -07003926 if (what & layer_state_t::eDetachChildren) {
3927 layer->detachChildren();
3928 }
3929 if (what & layer_state_t::eOverrideScalingModeChanged) {
3930 layer->setOverrideScalingMode(s.overrideScalingMode);
3931 // We don't trigger a traversal here because if no other state is
3932 // changed, we don't want this to cause any more work
3933 }
Marissa Wall61c58622018-07-18 10:12:20 -07003934 if (what & layer_state_t::eTransformChanged) {
3935 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3936 }
3937 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3938 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3939 flags |= eTraversalNeeded;
3940 }
3941 if (what & layer_state_t::eCropChanged) {
3942 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3943 }
Marissa Wall861616d2018-10-22 12:52:23 -07003944 if (what & layer_state_t::eFrameChanged) {
3945 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3946 }
Marissa Wall61c58622018-07-18 10:12:20 -07003947 if (what & layer_state_t::eBufferChanged) {
3948 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3949 }
3950 if (what & layer_state_t::eAcquireFenceChanged) {
3951 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3952 }
3953 if (what & layer_state_t::eDataspaceChanged) {
3954 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3955 }
3956 if (what & layer_state_t::eHdrMetadataChanged) {
3957 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3958 }
3959 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3960 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3961 }
3962 if (what & layer_state_t::eApiChanged) {
3963 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3964 }
3965 if (what & layer_state_t::eSidebandStreamChanged) {
3966 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3967 }
Robert Carr720e5062018-07-30 17:45:14 -07003968 if (what & layer_state_t::eInputInfoChanged) {
3969 layer->setInputInfo(s.inputInfo);
3970 flags |= eTraversalNeeded;
3971 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003972 std::vector<sp<CallbackHandle>> callbackHandles;
3973 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3974 mTransactionCompletedThread.run();
3975 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3976 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3977 }
3978 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003979 if (what & layer_state_t::eCachedBufferChanged) {
3980 sp<GraphicBuffer> buffer =
3981 mBufferStateLayerCache.get(s.cachedBuffer.token, s.cachedBuffer.bufferId);
3982 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
3983 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003984 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3985 // Do not put anything that updates layer state or modifies flags after
3986 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003987 return flags;
3988}
3989
chaviw273171b2018-12-26 11:46:30 -08003990uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3991 uint32_t flags = 0;
3992 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3993 flags |= eTraversalNeeded;
3994 }
3995
3996 mInputWindowCommands.merge(inputWindowCommands);
3997 return flags;
3998}
3999
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004000status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07004001 const String8& name,
4002 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004003 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07004004 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05004005 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004006{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004007 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004008 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004009 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004010 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004011 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004012
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004013 status_t result = NO_ERROR;
4014
4015 sp<Layer> layer;
4016
Cody Northropbc755282017-03-31 12:00:08 -06004017 String8 uniqueName = getUniqueLayerName(name);
4018
Mathias Agopian3165cc22012-08-08 19:42:09 -07004019 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004020 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004021 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4022 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004023
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004024 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004025 case ISurfaceComposerClient::eFXSurfaceBufferState:
4026 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4027 break;
chaviw13fdc492017-06-27 12:40:18 -07004028 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004029 // check if buffer size is set for color layer.
4030 if (w > 0 || h > 0) {
4031 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4032 int(w), int(h));
4033 return BAD_VALUE;
4034 }
4035
chaviw13fdc492017-06-27 12:40:18 -07004036 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004037 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004038 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004039 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004040 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004041 // check if buffer size is set for container layer.
4042 if (w > 0 || h > 0) {
4043 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4044 int(w), int(h));
4045 return BAD_VALUE;
4046 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004047 result = createContainerLayer(client,
4048 uniqueName, w, h, flags,
4049 handle, &layer);
4050 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004051 default:
4052 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004053 break;
4054 }
4055
Dan Stoza7d89d062015-04-30 13:29:25 -07004056 if (result != NO_ERROR) {
4057 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004058 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004059
Chia-I Wuab0c3192017-08-01 11:29:00 -07004060 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4061 // TODO b/64227542
4062 if (windowType == 441731) {
4063 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
4064 layer->setPrimaryDisplayOnly();
4065 }
4066
Albert Chaulk479c60c2017-01-27 14:21:34 -05004067 layer->setInfo(windowType, ownerUid);
4068
Robert Carrb89ea9d2018-12-10 13:01:14 -08004069 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4070 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4071 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004072 if (result != NO_ERROR) {
4073 return result;
4074 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004075 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004076
4077 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004078 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004079}
4080
Cody Northropbc755282017-03-31 12:00:08 -06004081String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4082{
4083 bool matchFound = true;
4084 uint32_t dupeCounter = 0;
4085
4086 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4087 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4088
Dan Stoza436ccf32018-06-21 12:10:12 -07004089 // Grab the state lock since we're accessing mCurrentState
4090 Mutex::Autolock lock(mStateLock);
4091
Cody Northropbc755282017-03-31 12:00:08 -06004092 // Loop over layers until we're sure there is no matching name
4093 while (matchFound) {
4094 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004095 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004096 if (layer->getName() == uniqueName) {
4097 matchFound = true;
4098 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4099 }
4100 });
4101 }
4102
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004103 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4104 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004105
4106 return uniqueName;
4107}
4108
Marissa Wallfd668622018-05-10 10:21:13 -07004109status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4110 uint32_t w, uint32_t h, uint32_t flags,
4111 PixelFormat& format, sp<IBinder>* handle,
4112 sp<IGraphicBufferProducer>* gbp,
4113 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004114 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004115 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004116 case PIXEL_FORMAT_TRANSPARENT:
4117 case PIXEL_FORMAT_TRANSLUCENT:
4118 format = PIXEL_FORMAT_RGBA_8888;
4119 break;
4120 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004121 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004122 break;
4123 }
4124
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004125 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004126 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004127 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004128 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004129 *handle = layer->getHandle();
4130 *gbp = layer->getProducer();
4131 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004132 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004133
Marissa Wallfd668622018-05-10 10:21:13 -07004134 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004135 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004136}
4137
Marissa Wall61c58622018-07-18 10:12:20 -07004138status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4139 uint32_t w, uint32_t h, uint32_t flags,
4140 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004141 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004142 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004143 *handle = layer->getHandle();
4144 *outLayer = layer;
4145
4146 return NO_ERROR;
4147}
4148
chaviw13fdc492017-06-27 12:40:18 -07004149status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004150 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004151 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004152{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004153 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004154 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004155 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004156}
4157
Robert Carr6b3f6c52018-08-13 13:05:17 -07004158status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4159 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4160 sp<IBinder>* handle, sp<Layer>* outLayer)
4161{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004162 *outLayer =
4163 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004164 *handle = (*outLayer)->getHandle();
4165 return NO_ERROR;
4166}
4167
4168
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004169void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004170 mLayersPendingRemoval.add(layer);
4171 mLayersRemoved = true;
4172 setTransactionFlags(eTransactionNeeded);
4173}
4174
Robert Carr695d5282018-12-18 15:27:58 -08004175void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004176{
Robert Carr2e102c92018-10-23 12:11:15 -07004177 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004178 // If a layer has a parent, we allow it to out-live it's handle
4179 // with the idea that the parent holds a reference and will eventually
4180 // be cleaned up. However no one cleans up the top-level so we do so
4181 // here.
4182 if (layer->getParent() == nullptr) {
4183 mCurrentState.layersSortedByZ.remove(layer);
4184 }
4185 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004186 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004187}
4188
Mathias Agopianb60314a2012-04-10 22:09:54 -07004189// ---------------------------------------------------------------------------
4190
Andy McFadden13a082e2012-08-24 10:16:42 -07004191void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004192 const auto display = getDefaultDisplayDeviceLocked();
4193 if (!display) return;
4194
4195 const sp<IBinder> token = display->getDisplayToken().promote();
4196 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004197
Jesse Hall01e29052013-02-19 16:13:35 -08004198 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004199 Vector<ComposerState> state;
4200 Vector<DisplayState> displays;
4201 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004202 d.what = DisplayState::eDisplayProjectionChanged |
4203 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004204 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004205 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004206 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004207 d.frame.makeInvalid();
4208 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004209 d.width = 0;
4210 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004211 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004212 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004213
Dominik Laskowskie9774092018-12-11 10:04:24 -08004214 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004215
Dominik Laskowski83b88212018-12-11 13:34:06 -08004216 const nsecs_t vsyncPeriod = getVsyncPeriod();
4217 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004218
Brian Andersond0010582017-03-07 13:20:31 -08004219 // Use phase of 0 since phase is not known.
4220 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004221 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004222 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004223}
4224
4225void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004226 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004227 postMessageAsync(
4228 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004229}
4230
Dominik Laskowskie9774092018-12-11 10:04:24 -08004231void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004232 if (display->isVirtual()) {
4233 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004234 return;
4235 }
4236
Dominik Laskowski075d3172018-05-24 15:50:06 -07004237 const auto displayId = display->getId();
4238 LOG_ALWAYS_FATAL_IF(!displayId);
4239
Dominik Laskowski34157762018-10-31 13:07:19 -07004240 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004241
4242 int currentMode = display->getPowerMode();
4243 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004244 return;
4245 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004246
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004247 display->setPowerMode(mode);
4248
Lloyd Pique4dccc412018-01-22 17:21:36 -08004249 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004250 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004251 }
4252
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004253 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004254 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004255 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004256 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004257 if (mUseScheduler) {
4258 mScheduler->onScreenAcquired(mAppConnectionHandle);
4259 } else {
4260 mEventThread->onScreenAcquired();
4261 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004262 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004263 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004264
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004265 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004266 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004267 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004268
4269 struct sched_param param = {0};
4270 param.sched_priority = 1;
4271 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4272 ALOGW("Couldn't set SCHED_FIFO on display on");
4273 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004274 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004275 // Turn off the display
4276 struct sched_param param = {0};
4277 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4278 ALOGW("Couldn't set SCHED_OTHER on display off");
4279 }
4280
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004281 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004282 if (mUseScheduler) {
4283 mScheduler->disableHardwareVsync(true);
4284 } else {
4285 disableHardwareVsync(true); // also cancels any in-progress resync
4286 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004287 if (mUseScheduler) {
4288 mScheduler->onScreenReleased(mAppConnectionHandle);
4289 } else {
4290 mEventThread->onScreenReleased();
4291 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004292 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004293
Dominik Laskowski075d3172018-05-24 15:50:06 -07004294 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004295 mVisibleRegionsDirty = true;
4296 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004297 } else if (mode == HWC_POWER_MODE_DOZE ||
4298 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004299 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004300 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004301 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004302 if (mUseScheduler) {
4303 mScheduler->onScreenAcquired(mAppConnectionHandle);
4304 } else {
4305 mEventThread->onScreenAcquired();
4306 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004307 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004308 }
4309 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4310 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004311 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004312 if (mUseScheduler) {
4313 mScheduler->disableHardwareVsync(true);
4314 } else {
4315 disableHardwareVsync(true); // also cancels any in-progress resync
4316 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004317 if (mUseScheduler) {
4318 mScheduler->onScreenReleased(mAppConnectionHandle);
4319 } else {
4320 mEventThread->onScreenReleased();
4321 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004322 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004323 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004324 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004325 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004326 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004327 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004328
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004329 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004330 mTimeStats->setPowerMode(mode);
Ana Krulecb43429d2019-01-09 14:28:51 -08004331 if (mUseScheduler) {
4332 // Update refresh rate stats.
4333 mRefreshRateStats->setPowerMode(mode);
4334 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004335 }
4336
Dominik Laskowski34157762018-10-31 13:07:19 -07004337 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004338}
4339
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004340void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004341 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004342 const auto display = getDisplayDevice(displayToken);
4343 if (!display) {
4344 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4345 displayToken.get());
4346 } else if (display->isVirtual()) {
4347 ALOGW("Attempt to set power mode %d for virtual display", mode);
4348 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004349 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004350 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004351 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004352}
4353
4354// ---------------------------------------------------------------------------
4355
Lloyd Pique755e3192018-01-31 16:46:15 -08004356status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4357 NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004358 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004359
Mathias Agopianbd115332013-04-18 16:41:04 -07004360 IPCThreadState* ipc = IPCThreadState::self();
4361 const int pid = ipc->getCallingPid();
4362 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004363
Mathias Agopianbd115332013-04-18 16:41:04 -07004364 if ((uid != AID_SHELL) &&
4365 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004366 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4367 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004368 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004369 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004370 // (this would indicate SF is stuck, but we want to be able to
4371 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004372 status_t err = mStateLock.timedLock(s2ns(1));
4373 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004374 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004375 StringAppendF(&result,
4376 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4377 "(no locks held)\n",
4378 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004379 }
4380
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004381 bool dumpAll = true;
4382 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004383 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004384
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004385 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004386 if ((index < numArgs) &&
4387 (args[index] == String16("--list"))) {
4388 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004389 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004390 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004391 }
4392
4393 if ((index < numArgs) &&
4394 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004395 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004396 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004397 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004398 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004399
4400 if ((index < numArgs) &&
4401 (args[index] == String16("--latency-clear"))) {
4402 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004403 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004404 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004405 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004406
4407 if ((index < numArgs) &&
4408 (args[index] == String16("--dispsync"))) {
4409 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004410 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004411 dumpAll = false;
4412 }
Dan Stozab90cf072015-03-05 11:05:59 -08004413
4414 if ((index < numArgs) &&
4415 (args[index] == String16("--static-screen"))) {
4416 index++;
4417 dumpStaticScreenStats(result);
4418 dumpAll = false;
4419 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004420
4421 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004422 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004423 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004424 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004425 dumpAll = false;
4426 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004427
4428 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4429 index++;
4430 dumpWideColorInfo(result);
4431 dumpAll = false;
4432 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004433
4434 if ((index < numArgs) &&
4435 (args[index] == String16("--enable-layer-stats"))) {
4436 index++;
4437 mLayerStats.enable();
4438 dumpAll = false;
4439 }
4440
4441 if ((index < numArgs) &&
4442 (args[index] == String16("--disable-layer-stats"))) {
4443 index++;
4444 mLayerStats.disable();
4445 dumpAll = false;
4446 }
4447
4448 if ((index < numArgs) &&
4449 (args[index] == String16("--clear-layer-stats"))) {
4450 index++;
4451 mLayerStats.clear();
4452 dumpAll = false;
4453 }
4454
4455 if ((index < numArgs) &&
4456 (args[index] == String16("--dump-layer-stats"))) {
4457 index++;
4458 mLayerStats.dump(result);
4459 dumpAll = false;
4460 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004461
4462 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004463 (args[index] == String16("--frame-composition"))) {
4464 index++;
4465 dumpFrameCompositionInfo(result);
4466 dumpAll = false;
4467 }
4468
4469 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004470 (args[index] == String16("--display-identification"))) {
4471 index++;
4472 dumpDisplayIdentificationData(result);
4473 dumpAll = false;
4474 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004475
4476 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4477 index++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004478 mTimeStats->parseArgs(asProto, args, index, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004479 dumpAll = false;
4480 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004481 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004482
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004483 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004484 if (asProto) {
4485 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4486 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4487 } else {
4488 dumpAllLocked(args, index, result);
4489 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004490 }
4491
Mathias Agopian9795c422009-08-26 16:36:26 -07004492 if (locked) {
4493 mStateLock.unlock();
4494 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004495 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004496 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004497 return NO_ERROR;
4498}
4499
Yiwei Zhang5434a782018-12-05 18:06:32 -08004500void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */, size_t& /* index */,
4501 std::string& result) const {
4502 mCurrentState.traverseInZOrder(
4503 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004504}
4505
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004506void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004507 std::string& result) const {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004508 String8 name;
4509 if (index < args.size()) {
4510 name = String8(args[index]);
4511 index++;
4512 }
4513
Dominik Laskowski83b88212018-12-11 13:34:06 -08004514 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004515
4516 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004517 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004518 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004519 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004520 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004521 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004522 }
Robert Carr2047fae2016-11-28 14:09:09 -08004523 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004524 }
4525}
4526
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004527void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004528 std::string& /* result */) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004529 String8 name;
4530 if (index < args.size()) {
4531 name = String8(args[index]);
4532 index++;
4533 }
4534
Robert Carr2047fae2016-11-28 14:09:09 -08004535 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004536 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004537 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004538 }
Robert Carr2047fae2016-11-28 14:09:09 -08004539 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004540
Svetoslavd85084b2014-03-20 10:28:31 -07004541 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004542}
4543
Jamie Gennis6547ff42013-07-16 20:12:42 -07004544// This should only be called from the main thread. Otherwise it would need
4545// the lock and should use mCurrentState rather than mDrawingState.
4546void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004547 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004548 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004549 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004550
4551 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4552}
4553
Yiwei Zhang5434a782018-12-05 18:06:32 -08004554void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004555 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004556
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004557 if (isLayerTripleBufferingDisabled())
4558 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004559
Yiwei Zhang5434a782018-12-05 18:06:32 -08004560 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4561 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4562 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4563 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4564 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4565 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004566 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004567}
4568
Yiwei Zhang5434a782018-12-05 18:06:32 -08004569void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4570 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004571 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4572 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004573 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004574 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004575 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004576 }
David Sodman4a36e932017-11-07 14:29:47 -08004577 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004578 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004579 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004580 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4581 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004582}
4583
Dan Stozae77c7662016-05-13 11:37:28 -07004584void SurfaceFlinger::recordBufferingStats(const char* layerName,
4585 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004586 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4587 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004588 for (const auto& segment : history) {
4589 if (!segment.usedThirdBuffer) {
4590 stats.twoBufferTime += segment.totalTime;
4591 }
4592 if (segment.occupancyAverage < 1.0f) {
4593 stats.doubleBufferedTime += segment.totalTime;
4594 } else if (segment.occupancyAverage < 2.0f) {
4595 stats.tripleBufferedTime += segment.totalTime;
4596 }
4597 ++stats.numSegments;
4598 stats.totalTime += segment.totalTime;
4599 }
4600}
4601
Yiwei Zhang5434a782018-12-05 18:06:32 -08004602void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4603 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004604
4605 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4606 const size_t count = currentLayers.size();
4607 for (size_t i=0 ; i<count ; i++) {
4608 currentLayers[i]->dumpFrameEvents(result);
4609 }
4610}
4611
Yiwei Zhang5434a782018-12-05 18:06:32 -08004612void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004613 result.append("Buffering stats:\n");
4614 result.append(" [Layer name] <Active time> <Two buffer> "
4615 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004616 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004617 typedef std::tuple<std::string, float, float, float> BufferTuple;
4618 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004619 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004620 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004621 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004622 if (stats.numSegments == 0) {
4623 continue;
4624 }
4625 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4626 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4627 stats.totalTime;
4628 float doubleBufferRatio = static_cast<float>(
4629 stats.doubleBufferedTime) / stats.totalTime;
4630 float tripleBufferRatio = static_cast<float>(
4631 stats.tripleBufferedTime) / stats.totalTime;
4632 sorted.insert({activeTime, {name, twoBufferRatio,
4633 doubleBufferRatio, tripleBufferRatio}});
4634 }
4635 for (const auto& sortedPair : sorted) {
4636 float activeTime = sortedPair.first;
4637 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004638 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4639 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004640 }
4641 result.append("\n");
4642}
4643
Yiwei Zhang5434a782018-12-05 18:06:32 -08004644void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004645 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004646 const auto displayId = display->getId();
4647 if (!displayId) {
4648 continue;
4649 }
4650 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004651 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004652 continue;
4653 }
4654
Yiwei Zhang5434a782018-12-05 18:06:32 -08004655 StringAppendF(&result,
4656 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4657 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004658 uint8_t port;
4659 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004660 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004661 result.append("no identification data\n");
4662 continue;
4663 }
4664
4665 if (!isEdid(data)) {
4666 result.append("unknown identification data: ");
4667 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004668 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004669 }
4670 result.append("\n");
4671 continue;
4672 }
4673
4674 const auto edid = parseEdid(data);
4675 if (!edid) {
4676 result.append("invalid EDID: ");
4677 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004678 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004679 }
4680 result.append("\n");
4681 continue;
4682 }
4683
Yiwei Zhang5434a782018-12-05 18:06:32 -08004684 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004685 result.append(edid->displayName.data(), edid->displayName.length());
4686 result.append("\"\n");
4687 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004688}
4689
Yiwei Zhang5434a782018-12-05 18:06:32 -08004690void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4691 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4692 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4693 StringAppendF(&result, "DisplayColorSetting: %s\n",
4694 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004695
4696 // TODO: print out if wide-color mode is active or not
4697
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004698 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004699 const auto displayId = display->getId();
4700 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004701 continue;
4702 }
4703
Yiwei Zhang5434a782018-12-05 18:06:32 -08004704 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004705 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004706 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004707 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004708 }
4709
Lloyd Pique32cbe282018-10-19 13:09:22 -07004710 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004711 StringAppendF(&result, " Current color mode: %s (%d)\n",
4712 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004713 }
4714 result.append("\n");
4715}
4716
Yiwei Zhang5434a782018-12-05 18:06:32 -08004717void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004718 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004719 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4720 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004721 continue;
4722 }
4723
Dominik Laskowski05275f12018-11-01 15:03:24 -07004724 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004725 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4726 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004727 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004728 compositionInfo.dump(result, nullptr);
4729 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004730 }
4731 }
David Sodman7e4ae112018-02-09 15:02:28 -08004732}
4733
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004734LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004735 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004736 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4737 const State& state = useDrawing ? mDrawingState : mCurrentState;
4738 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004739 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004740 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004741 });
4742
4743 return layersProto;
4744}
4745
Lloyd Pique32cbe282018-10-19 13:09:22 -07004746LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004747 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004748
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004749 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004750 resolution->set_w(displayDevice.getWidth());
4751 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004752
Lloyd Pique32cbe282018-10-19 13:09:22 -07004753 auto display = displayDevice.getCompositionDisplay();
4754 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004755
Lloyd Pique32cbe282018-10-19 13:09:22 -07004756 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4757 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4758 layersProto.set_global_transform(displayState.orientation);
4759
4760 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004761 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004762 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004763 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004764 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004765 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004766 }
4767 });
4768
4769 return layersProto;
4770}
4771
Mathias Agopian74d211a2013-04-22 16:55:35 +02004772void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004773 std::string& result) const {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004774 bool colorize = false;
4775 if (index < args.size()
4776 && (args[index] == String16("--color"))) {
4777 colorize = true;
4778 index++;
4779 }
4780
4781 Colorizer colorizer(colorize);
4782
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004783 // figure out if we're stuck somewhere
4784 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004785 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004786 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4787
4788 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004789 * Dump library configuration.
4790 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004791
4792 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004793 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004794 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004795 appendSfConfigString(result);
4796 appendUiConfigString(result);
4797 appendGuiConfigString(result);
4798 result.append("\n");
4799
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004800 result.append("\nDisplay identification data:\n");
4801 dumpDisplayIdentificationData(result);
4802
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004803 result.append("\nWide-Color information:\n");
4804 dumpWideColorInfo(result);
4805
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004806 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004807 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004808 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004809 result.append(SyncFeatures::getInstance().toString());
4810 result.append("\n");
4811
Andy McFadden41d67d72014-04-25 16:58:34 -07004812 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004813 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004814 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004815
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004816 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4817 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski83b88212018-12-11 13:34:06 -08004818 StringAppendF(&result,
4819 "app phase %" PRId64 " ns, "
4820 "sf phase %" PRId64 " ns, "
4821 "early app phase %" PRId64 " ns, "
4822 "early sf phase %" PRId64 " ns, "
4823 "early app gl phase %" PRId64 " ns, "
4824 "early sf gl phase %" PRId64 " ns, "
4825 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)\n",
4826 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, appEarlyOffset, sfEarlyOffset,
4827 appEarlyGlOffset, sfEarlyGlOffset, dispSyncPresentTimeOffset, getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004828
Dan Stozab90cf072015-03-05 11:05:59 -08004829 // Dump static screen stats
4830 result.append("\n");
4831 dumpStaticScreenStats(result);
4832 result.append("\n");
4833
Yiwei Zhang5434a782018-12-05 18:06:32 -08004834 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004835
Dan Stozae77c7662016-05-13 11:37:28 -07004836 dumpBufferingStats(result);
4837
Andy McFadden4803b742012-09-24 19:07:20 -07004838 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004839 * Dump the visible layer list
4840 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004841 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004842 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4843 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4844 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004845 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004846
Chia-I Wu2f884132018-09-13 15:17:58 -07004847 {
4848 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4849 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004850 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004851 result.append("\n");
4852 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004853
David Sodman7e4ae112018-02-09 15:02:28 -08004854 result.append("\nFrame-Composition information:\n");
4855 dumpFrameCompositionInfo(result);
4856 result.append("\n");
4857
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004858 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004859 * Dump Display state
4860 */
4861
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004862 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004863 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004864 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004865 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004866 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004867 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004868 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004869
4870 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004871 * Dump SurfaceFlinger global state
4872 */
4873
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004874 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004875 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004876 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004877
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004878 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004879
Dominik Laskowski075d3172018-05-24 15:50:06 -07004880 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004881 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4882 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004883 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4884 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004885 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004886 StringAppendF(&result,
4887 " transaction-flags : %08x\n"
4888 " gpu_to_cpu_unsupported : %d\n",
4889 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004890
Dominik Laskowski075d3172018-05-24 15:50:06 -07004891 if (const auto displayId = getInternalDisplayId();
4892 displayId && getHwComposer().isConnected(*displayId)) {
4893 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004894 StringAppendF(&result,
4895 " refresh-rate : %f fps\n"
4896 " x-dpi : %f\n"
4897 " y-dpi : %f\n",
4898 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4899 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004900 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004901
Yiwei Zhang5434a782018-12-05 18:06:32 -08004902 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004903
Yiwei Zhang5434a782018-12-05 18:06:32 -08004904 StringAppendF(&result, " use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004905 /*
4906 * VSYNC state
4907 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004908 if (mUseScheduler) {
4909 mScheduler->dump(mAppConnectionHandle, result);
4910 } else {
4911 mEventThread->dump(result);
4912 }
Dan Stozae22aec72016-08-01 13:20:59 -07004913 result.append("\n");
4914
4915 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004916 * Tracing state
4917 */
4918 mTracing.dump(result);
4919 result.append("\n");
4920
4921 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004922 * HWC layer minidump
4923 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004924 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004925 const auto displayId = display->getId();
4926 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004927 continue;
4928 }
4929
Yiwei Zhang5434a782018-12-05 18:06:32 -08004930 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004931 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004932 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004933 result.append("\n");
4934 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004935
4936 /*
4937 * Dump HWComposer state
4938 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004939 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004940 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004941 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004942 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004943 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004944 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004945
4946 /*
4947 * Dump gralloc state
4948 */
4949 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4950 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004951
4952 /*
4953 * Dump VrFlinger state if in use.
4954 */
4955 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4956 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004957 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004958 result.append("\n");
4959 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004960
4961 /**
4962 * Scheduler dump state.
4963 */
4964 if (mUseScheduler) {
4965 result.append("\nScheduler state:\n");
4966 result.append(mScheduler->doDump() + "\n");
4967 result.append(mRefreshRateStats->doDump() + "\n");
4968 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004969}
4970
Dominik Laskowski075d3172018-05-24 15:50:06 -07004971const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004972 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004973 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004974 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004975 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004976 }
4977 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004978
Dominik Laskowski34157762018-10-31 13:07:19 -07004979 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004980 static const Vector<sp<Layer>> empty;
4981 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004982}
4983
Keun young Park63f165f2012-08-31 10:53:36 -07004984bool SurfaceFlinger::startDdmConnection()
4985{
4986 void* libddmconnection_dso =
4987 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4988 if (!libddmconnection_dso) {
4989 return false;
4990 }
4991 void (*DdmConnection_start)(const char* name);
4992 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004993 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004994 if (!DdmConnection_start) {
4995 dlclose(libddmconnection_dso);
4996 return false;
4997 }
4998 (*DdmConnection_start)(getServiceName());
4999 return true;
5000}
5001
Chia-I Wu28f320b2018-05-03 11:02:56 -07005002void SurfaceFlinger::updateColorMatrixLocked() {
5003 mat4 colorMatrix;
5004 if (mGlobalSaturationFactor != 1.0f) {
5005 // Rec.709 luma coefficients
5006 float3 luminance{0.213f, 0.715f, 0.072f};
5007 luminance *= 1.0f - mGlobalSaturationFactor;
5008 mat4 saturationMatrix = mat4(
5009 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
5010 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
5011 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
5012 vec4{0.0f, 0.0f, 0.0f, 1.0f}
5013 );
5014 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
5015 } else {
5016 colorMatrix = mClientColorMatrix * mDaltonizer();
5017 }
5018
5019 if (mCurrentState.colorMatrix != colorMatrix) {
5020 mCurrentState.colorMatrix = colorMatrix;
5021 mCurrentState.colorMatrixChanged = true;
5022 setTransactionFlags(eTransactionNeeded);
5023 }
5024}
5025
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005026status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005027#pragma clang diagnostic push
5028#pragma clang diagnostic error "-Wswitch-enum"
5029 switch (static_cast<ISurfaceComposerTag>(code)) {
5030 // These methods should at minimum make sure that the client requested
5031 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005032 case BOOT_FINISHED:
5033 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005034 case CREATE_DISPLAY:
5035 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005036 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005037 case GET_ACTIVE_COLOR_MODE:
5038 case GET_ANIMATION_FRAME_STATS:
5039 case GET_HDR_CAPABILITIES:
5040 case SET_ACTIVE_CONFIG:
5041 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005042 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005043 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005044 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005045 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
5046 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005047 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5048 IPCThreadState* ipc = IPCThreadState::self();
5049 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5050 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005051 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005052 }
Robert Carr1db73f62016-12-21 12:58:51 -08005053 return OK;
5054 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005055 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005056 IPCThreadState* ipc = IPCThreadState::self();
5057 const int pid = ipc->getCallingPid();
5058 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005059 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5060 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005061 return PERMISSION_DENIED;
5062 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005063 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005064 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005065 // Used by apps to hook Choreographer to SurfaceFlinger.
5066 case CREATE_DISPLAY_EVENT_CONNECTION:
5067 // The following calls are currently used by clients that do not
5068 // request necessary permissions. However, they do not expose any secret
5069 // information, so it is OK to pass them.
5070 case AUTHENTICATE_SURFACE:
5071 case GET_ACTIVE_CONFIG:
5072 case GET_BUILT_IN_DISPLAY:
5073 case GET_DISPLAY_COLOR_MODES:
5074 case GET_DISPLAY_CONFIGS:
5075 case GET_DISPLAY_STATS:
5076 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5077 // Calling setTransactionState is safe, because you need to have been
5078 // granted a reference to Client* and Handle* to do anything with it.
5079 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005080 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005081 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005082 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005083 case GET_PROTECTED_CONTENT_SUPPORT:
5084 case CACHE_BUFFER:
5085 case UNCACHE_BUFFER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005086 return OK;
5087 }
5088 case CAPTURE_LAYERS:
5089 case CAPTURE_SCREEN: {
5090 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005091 IPCThreadState* ipc = IPCThreadState::self();
5092 const int pid = ipc->getCallingPid();
5093 const int uid = ipc->getCallingUid();
5094 if ((uid != AID_GRAPHICS) &&
5095 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5096 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5097 return PERMISSION_DENIED;
5098 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005099 return OK;
5100 }
5101 // The following codes are deprecated and should never be allowed to access SF.
5102 case CONNECT_DISPLAY_UNUSED:
5103 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5104 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5105 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005106 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005107 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005108
5109 // These codes are used for the IBinder protocol to either interrogate the recipient
5110 // side of the transaction for its canonical interface descriptor or to dump its state.
5111 // We let them pass by default.
5112 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5113 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5114 code == IBinder::SYSPROPS_TRANSACTION) {
5115 return OK;
5116 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005117 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005118 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005119 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005120 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5121 return OK;
5122 }
5123 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5124 return PERMISSION_DENIED;
5125#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005126}
5127
Ana Krulec13be8ad2018-08-21 02:43:56 +00005128status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5129 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005130 status_t credentialCheck = CheckTransactCodeCredentials(code);
5131 if (credentialCheck != OK) {
5132 return credentialCheck;
5133 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005134
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005135 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5136 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005137 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005138 IPCThreadState* ipc = IPCThreadState::self();
5139 const int uid = ipc->getCallingUid();
5140 if (CC_UNLIKELY(uid != AID_SYSTEM
5141 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005142 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005143 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005144 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005145 return PERMISSION_DENIED;
5146 }
5147 int n;
5148 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005149 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005150 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005151 return NO_ERROR;
5152 case 1002: // SHOW_UPDATES
5153 n = data.readInt32();
5154 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005155 invalidateHwcGeometry();
5156 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005157 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005158 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005159 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005160 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005161 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005162 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005163 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005164 setTransactionFlags(
5165 eTransactionNeeded|
5166 eDisplayTransactionNeeded|
5167 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005168 return NO_ERROR;
5169 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005170 case 1006:{ // send empty update
5171 signalRefresh();
5172 return NO_ERROR;
5173 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005174 case 1008: // toggle use of hw composer
5175 n = data.readInt32();
5176 mDebugDisableHWC = n ? 1 : 0;
5177 invalidateHwcGeometry();
5178 repaintEverything();
5179 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005180 case 1009: // toggle use of transform hint
5181 n = data.readInt32();
5182 mDebugDisableTransformHint = n ? 1 : 0;
5183 invalidateHwcGeometry();
5184 repaintEverything();
5185 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005186 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005187 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005188 reply->writeInt32(0);
5189 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005190 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005191 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005192 return NO_ERROR;
5193 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005194 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005195 if (!display) {
5196 return NAME_NOT_FOUND;
5197 }
5198
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005199 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005200 return NO_ERROR;
5201 }
5202 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005203 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005204 // daltonize
5205 n = data.readInt32();
5206 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005207 case 1:
5208 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5209 break;
5210 case 2:
5211 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5212 break;
5213 case 3:
5214 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5215 break;
5216 default:
5217 mDaltonizer.setType(ColorBlindnessType::None);
5218 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005219 }
5220 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005221 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005222 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005223 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005224 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005225
5226 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005227 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005228 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005229 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005230 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005231 // apply a color matrix
5232 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005233 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005234 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005235 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005236 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005237 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005238 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005239 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005240 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005241 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005242 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005243
5244 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5245 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005246 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005247 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5248 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5249 }
5250
Chia-I Wu28f320b2018-05-03 11:02:56 -07005251 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005252 return NO_ERROR;
5253 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005254 // This is an experimental interface
5255 // Needs to be shifted to proper binder interface when we productize
5256 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005257 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005258 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005259 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005260 return NO_ERROR;
5261 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005262 case 1017: {
5263 n = data.readInt32();
5264 mForceFullDamage = static_cast<bool>(n);
5265 return NO_ERROR;
5266 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005267 case 1018: { // Modify Choreographer's phase offset
5268 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005269 if (mUseScheduler) {
5270 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5271 } else {
5272 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5273 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005274 return NO_ERROR;
5275 }
5276 case 1019: { // Modify SurfaceFlinger's phase offset
5277 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005278 if (mUseScheduler) {
5279 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5280 } else {
5281 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5282 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005283 return NO_ERROR;
5284 }
Irvel468051e2016-06-13 16:44:44 -07005285 case 1020: { // Layer updates interceptor
5286 n = data.readInt32();
5287 if (n) {
5288 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005289 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005290 }
5291 else{
5292 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005293 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005294 }
5295 return NO_ERROR;
5296 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005297 case 1021: { // Disable HWC virtual displays
5298 n = data.readInt32();
5299 mUseHwcVirtualDisplays = !n;
5300 return NO_ERROR;
5301 }
Romain Guy0147a172017-06-01 13:53:56 -07005302 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005303 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005304 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005305
Chia-I Wu28f320b2018-05-03 11:02:56 -07005306 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005307 return NO_ERROR;
5308 }
Romain Guy54f154a2017-10-24 21:40:32 +01005309 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005310 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005311 invalidateHwcGeometry();
5312 repaintEverything();
5313 return NO_ERROR;
5314 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005315 // Deprecate, use 1030 to check whether the device is color managed.
5316 case 1024: {
5317 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005318 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005319 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005320 n = data.readInt32();
5321 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005322 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005323 mTracing.enable();
5324 doTracing("tracing.enable");
5325 reply->writeInt32(NO_ERROR);
5326 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005327 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005328 status_t err = mTracing.disable();
5329 reply->writeInt32(err);
5330 }
5331 return NO_ERROR;
5332 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005333 case 1026: { // Get layer tracing status
5334 reply->writeBool(mTracing.isEnabled());
5335 return NO_ERROR;
5336 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005337 // Is a DisplayColorSetting supported?
5338 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005339 const auto display = getDefaultDisplayDevice();
5340 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005341 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005342 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005343
5344 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5345 switch (setting) {
5346 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005347 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005348 break;
5349 case DisplayColorSetting::UNMANAGED:
5350 reply->writeBool(true);
5351 break;
5352 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005353 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005354 break;
5355 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005356 reply->writeBool(
5357 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005358 break;
5359 }
5360 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005361 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005362 // Is VrFlinger active?
5363 case 1028: {
5364 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005365 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005366 return NO_ERROR;
5367 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005368 // Is device color managed?
5369 case 1030: {
5370 reply->writeBool(useColorManagement);
5371 return NO_ERROR;
5372 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005373 // Override default composition data space
5374 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5375 // && adb shell stop zygote && adb shell start zygote
5376 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5377 // adb shell stop zygote && adb shell start zygote
5378 case 1031: {
5379 Mutex::Autolock _l(mStateLock);
5380 n = data.readInt32();
5381 if (n) {
5382 n = data.readInt32();
5383 if (n) {
5384 Dataspace dataspace = static_cast<Dataspace>(n);
5385 if (!validateCompositionDataspace(dataspace)) {
5386 return BAD_VALUE;
5387 }
5388 mDefaultCompositionDataspace = dataspace;
5389 }
5390 n = data.readInt32();
5391 if (n) {
5392 Dataspace dataspace = static_cast<Dataspace>(n);
5393 if (!validateCompositionDataspace(dataspace)) {
5394 return BAD_VALUE;
5395 }
5396 mWideColorGamutCompositionDataspace = dataspace;
5397 }
5398 } else {
5399 // restore composition data space.
5400 mDefaultCompositionDataspace = defaultCompositionDataspace;
5401 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5402 }
5403 return NO_ERROR;
5404 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005405 }
5406 }
5407 return err;
5408}
5409
Steven Thomas6d8110b2017-08-31 18:24:21 -07005410void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005411 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005412 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005413}
5414
Ana Krulec7d1d6832018-12-27 11:10:09 -08005415void SurfaceFlinger::repaintEverythingForHWC() {
5416 mRepaintEverything = true;
5417 mEventQueue->invalidateForHWC();
5418}
5419
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005420// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5421class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005422public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005423 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5424 ~WindowDisconnector() {
5425 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005426 }
5427
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005428private:
5429 ANativeWindow* mWindow;
5430 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005431};
5432
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005433status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005434 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5435 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005436 uint32_t reqWidth, uint32_t reqHeight,
5437 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005438 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005439 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005440
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005441 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005442
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005443 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5444
Chia-I Wu20261cb2018-08-23 12:55:44 -07005445 sp<DisplayDevice> display;
5446 {
5447 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005448
Chia-I Wu20261cb2018-08-23 12:55:44 -07005449 display = getDisplayDeviceLocked(displayToken);
5450 if (!display) return BAD_VALUE;
5451
Chia-I Wucb023152018-08-28 12:57:23 -07005452 // set the requested width/height to the logical display viewport size
5453 // by default
5454 if (reqWidth == 0 || reqHeight == 0) {
5455 reqWidth = uint32_t(display->getViewport().width());
5456 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005457 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005458 }
5459
Peiyong Lin0e003c92018-09-17 11:09:51 -07005460 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5461 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005462
5463 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005464 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005465 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5466 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005467}
5468
5469status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005470 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5471 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005472 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005473 ATRACE_CALL();
5474
5475 class LayerRenderArea : public RenderArea {
5476 public:
Robert Carr578038f2018-03-09 12:25:24 -08005477 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005478 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5479 bool childrenOnly)
5480 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005481 mLayer(layer),
5482 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005483 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005484 mFlinger(flinger),
5485 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005486 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005487 Rect getBounds() const override {
5488 const Layer::State& layerState(mLayer->getDrawingState());
5489 return mLayer->getBufferSize(layerState);
5490 }
Marissa Wall61c58622018-07-18 10:12:20 -07005491 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005492 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005493 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005494 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005495 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005496 }
chaviwa76b2712017-09-20 12:02:26 -07005497 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005498 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005499 Rect getSourceCrop() const override {
5500 if (mCrop.isEmpty()) {
5501 return getBounds();
5502 } else {
5503 return mCrop;
5504 }
5505 }
Robert Carr578038f2018-03-09 12:25:24 -08005506 class ReparentForDrawing {
5507 public:
5508 const sp<Layer>& oldParent;
5509 const sp<Layer>& newParent;
5510
5511 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5512 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005513 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005514 }
Robert Carr15eae092018-03-23 13:43:53 -07005515 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005516 };
5517
5518 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005519 const Rect sourceCrop = getSourceCrop();
5520 // no need to check rotation because there is none
5521 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5522 sourceCrop.height() != getReqHeight();
5523
Robert Carr578038f2018-03-09 12:25:24 -08005524 if (!mChildrenOnly) {
5525 mTransform = mLayer->getTransform().inverse();
5526 drawLayers();
5527 } else {
5528 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005529 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005530 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5531 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005532
5533 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5534 drawLayers();
5535 }
5536 }
chaviwa76b2712017-09-20 12:02:26 -07005537
chaviwa76b2712017-09-20 12:02:26 -07005538 private:
chaviw7206d492017-11-10 16:16:12 -08005539 const sp<Layer> mLayer;
5540 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005541
5542 // In the "childrenOnly" case we reparent the children to a screenshot
5543 // layer which has no properties set and which does not draw.
5544 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005545 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005546 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005547
5548 SurfaceFlinger* mFlinger;
5549 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005550 };
5551
5552 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5553 auto parent = layerHandle->owner.promote();
5554
Robert Carr2e102c92018-10-23 12:11:15 -07005555 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005556 ALOGE("captureLayers called with a removed parent");
5557 return NAME_NOT_FOUND;
5558 }
5559
Robert Carr578038f2018-03-09 12:25:24 -08005560 const int uid = IPCThreadState::self()->getCallingUid();
5561 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005562 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005563 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5564 return PERMISSION_DENIED;
5565 }
5566
chaviw7206d492017-11-10 16:16:12 -08005567 Rect crop(sourceCrop);
5568 if (sourceCrop.width() <= 0) {
5569 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005570 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005571 }
5572
5573 if (sourceCrop.height() <= 0) {
5574 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005575 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005576 }
5577
5578 int32_t reqWidth = crop.width() * frameScale;
5579 int32_t reqHeight = crop.height() * frameScale;
5580
Chia-I Wu20261cb2018-08-23 12:55:44 -07005581 // really small crop or frameScale
5582 if (reqWidth <= 0) {
5583 reqWidth = 1;
5584 }
5585 if (reqHeight <= 0) {
5586 reqHeight = 1;
5587 }
5588
Peiyong Lin0e003c92018-09-17 11:09:51 -07005589 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005590
Robert Carr578038f2018-03-09 12:25:24 -08005591 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005592 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5593 if (!layer->isVisible()) {
5594 return;
Robert Carr578038f2018-03-09 12:25:24 -08005595 } else if (childrenOnly && layer == parent.get()) {
5596 return;
chaviwa76b2712017-09-20 12:02:26 -07005597 }
5598 visitor(layer);
5599 });
5600 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005601 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005602}
5603
5604status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5605 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005606 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005607 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005608 bool useIdentityTransform) {
5609 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005610
Peiyong Lin0e003c92018-09-17 11:09:51 -07005611 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005612 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5613 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005614 *outBuffer =
5615 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5616 static_cast<android_pixel_format>(reqPixelFormat), 1,
5617 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005618
5619 // This mutex protects syncFd and captureResult for communication of the return values from the
5620 // main thread back to this Binder thread
5621 std::mutex captureMutex;
5622 std::condition_variable captureCondition;
5623 std::unique_lock<std::mutex> captureLock(captureMutex);
5624 int syncFd = -1;
5625 std::optional<status_t> captureResult;
5626
Robert Carr03480e22018-01-04 16:02:06 -08005627 const int uid = IPCThreadState::self()->getCallingUid();
5628 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5629
Dominik Laskowski8c001672018-05-30 16:52:06 -07005630 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005631 // If there is a refresh pending, bug out early and tell the binder thread to try again
5632 // after the refresh.
5633 if (mRefreshPending) {
5634 ATRACE_NAME("Skipping screenshot for now");
5635 std::unique_lock<std::mutex> captureLock(captureMutex);
5636 captureResult = std::make_optional<status_t>(EAGAIN);
5637 captureCondition.notify_one();
5638 return;
5639 }
5640
5641 status_t result = NO_ERROR;
5642 int fd = -1;
5643 {
5644 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005645 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005646 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5647 useIdentityTransform, forSystem, &fd);
5648 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005649 }
5650
5651 {
5652 std::unique_lock<std::mutex> captureLock(captureMutex);
5653 syncFd = fd;
5654 captureResult = std::make_optional<status_t>(result);
5655 captureCondition.notify_one();
5656 }
5657 });
5658
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005659 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005660 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005661 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005662 while (*captureResult == EAGAIN) {
5663 captureResult.reset();
5664 result = postMessageAsync(message);
5665 if (result != NO_ERROR) {
5666 return result;
5667 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005668 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005669 }
5670 result = *captureResult;
5671 }
5672
5673 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005674 sync_wait(syncFd, -1);
5675 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005676 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005677
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005678 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005679}
5680
chaviwa76b2712017-09-20 12:02:26 -07005681void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005682 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005683 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005684 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005685
Lloyd Pique144e1162017-12-20 16:44:52 -08005686 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005687
chaviwa76b2712017-09-20 12:02:26 -07005688 const auto reqWidth = renderArea.getReqWidth();
5689 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005690 const auto sourceCrop = renderArea.getSourceCrop();
5691 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005692
Peiyong Lin0e003c92018-09-17 11:09:51 -07005693 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005694 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005695
Mathias Agopian180f10d2013-04-10 22:55:41 -07005696 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005697 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005698
5699 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005700 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005701 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005702
chaviw50da5042018-04-09 13:49:37 -07005703 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005704 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005705 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005706
chaviwa76b2712017-09-20 12:02:26 -07005707 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005708 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005709 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005710 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005711 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005712}
5713
chaviwa76b2712017-09-20 12:02:26 -07005714status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5715 TraverseLayersFunction traverseLayers,
5716 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005717 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005718 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005719 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005720 ATRACE_CALL();
5721
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005722 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005723
5724 traverseLayers([&](Layer* layer) {
5725 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5726 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005727
Robert Carr03480e22018-01-04 16:02:06 -08005728 // We allow the system server to take screenshots of secure layers for
5729 // use in situations like the Screen-rotation animation and place
5730 // the impetus on WindowManager to not persist them.
5731 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005732 ALOGW("FB is protected: PERMISSION_DENIED");
5733 return PERMISSION_DENIED;
5734 }
Peiyong Linfb530cf2018-12-15 05:07:38 +00005735 auto& engine(getRenderEngine());
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005736
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005737 // this binds the given EGLImage as a framebuffer for the
5738 // duration of this scope.
Peiyong Linfb530cf2018-12-15 05:07:38 +00005739 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005740 if (bufferBond.getStatus() != NO_ERROR) {
5741 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005742 return INVALID_OPERATION;
5743 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005744
Dan Stozaabcda352017-06-01 14:37:39 -07005745 // this will in fact render into our dequeued buffer
5746 // via an FBO, which means we didn't have to create
5747 // an EGLSurface and therefore we're not
5748 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005749 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005750
Peiyong Linfb530cf2018-12-15 05:07:38 +00005751 base::unique_fd syncFd = engine.flush();
Alec Mouri492bc572018-09-11 21:40:04 +00005752 if (syncFd < 0) {
Peiyong Linfb530cf2018-12-15 05:07:38 +00005753 engine.finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005754 }
Alec Mouri492bc572018-09-11 21:40:04 +00005755 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005756
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005757 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005758}
5759
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005760// ---------------------------------------------------------------------------
5761
Dan Stoza412903f2017-04-27 13:42:17 -07005762void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5763 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005764}
5765
Dan Stoza412903f2017-04-27 13:42:17 -07005766void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5767 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005768}
5769
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005770void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005771 const LayerVector::Visitor& visitor) {
5772 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005773 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005774 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005775 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005776 continue;
5777 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005778 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005779 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005780 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005781 return;
5782 }
chaviwa76b2712017-09-20 12:02:26 -07005783 if (!layer->isVisible()) {
5784 return;
5785 }
5786 visitor(layer);
5787 });
5788 }
5789}
5790
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005791}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005792
Lloyd Pique074e8122018-07-26 12:57:23 -07005793
Mathias Agopian3f844832013-08-07 21:24:32 -07005794#if defined(__gl_h_)
5795#error "don't include gl/gl.h in this file"
5796#endif
5797
5798#if defined(__gl2_h_)
5799#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005800#endif