blob: 3f6298f86b004a78e02561b273e64e406f8f986d [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 */); });
740 }
741
Dan Stoza9e56aa02015-11-02 13:00:03 -0800742 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700743}
744
Romain Guy11d63f42017-07-20 12:47:14 -0700745void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700746 Mutex::Autolock _l(mStateLock);
747
Romain Guy11d63f42017-07-20 12:47:14 -0700748 char value[PROPERTY_VALUE_MAX];
749
750 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800751 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700752 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800753 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100754
755 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700756 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700757}
758
Mathias Agopiana67e4182012-06-19 17:26:12 -0700759void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800760 // Start boot animation service by setting a property mailbox
761 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700762 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800763 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700764 if (mStartPropertySetThread->join() != NO_ERROR) {
765 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800766 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700767}
768
Mathias Agopian875d8e12013-06-07 15:35:48 -0700769size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700770 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700771}
772
Mathias Agopian875d8e12013-06-07 15:35:48 -0700773size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700774 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700775}
776
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800777// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800778
Jamie Gennis582270d2011-08-17 18:19:00 -0700779bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800780 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800781 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800782 return authenticateSurfaceTextureLocked(bufferProducer);
783}
784
785bool SurfaceFlinger::authenticateSurfaceTextureLocked(
786 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800787 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800788 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800789}
790
Brian Anderson6b376712017-04-04 10:51:39 -0700791status_t SurfaceFlinger::getSupportedFrameTimestamps(
792 std::vector<FrameEvent>* outSupported) const {
793 *outSupported = {
794 FrameEvent::REQUESTED_PRESENT,
795 FrameEvent::ACQUIRE,
796 FrameEvent::LATCH,
797 FrameEvent::FIRST_REFRESH_START,
798 FrameEvent::LAST_REFRESH_START,
799 FrameEvent::GPU_COMPOSITION_DONE,
800 FrameEvent::DEQUEUE_READY,
801 FrameEvent::RELEASE,
802 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700803 ConditionalLock _l(mStateLock,
804 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700805 if (!getHwComposer().hasCapability(
806 HWC2::Capability::PresentFenceIsNotReliable)) {
807 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
808 }
809 return NO_ERROR;
810}
811
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700812status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
813 Vector<DisplayInfo>* configs) {
814 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700815 return BAD_VALUE;
816 }
817
Dominik Laskowski075d3172018-05-24 15:50:06 -0700818 const auto displayId = getPhysicalDisplayId(displayToken);
819 if (!displayId) {
820 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700821 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700822
Mathias Agopian8b736f12012-08-13 17:54:26 -0700823 // TODO: Not sure if display density should handled by SF any longer
824 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700825 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700826 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700827 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800828 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700829 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700830 }
831 return density;
832 }
833 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700834 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700835 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700836 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700837 return getDensityFromProperty("ro.sf.lcd_density"); }
838 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700839
Dan Stoza7f7da322014-05-02 15:26:25 -0700840 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700841
Steven Thomas6d8110b2017-08-31 18:24:21 -0700842 ConditionalLock _l(mStateLock,
843 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700844 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700845 DisplayInfo info = DisplayInfo();
846
Dan Stoza9e56aa02015-11-02 13:00:03 -0800847 float xdpi = hwConfig->getDpiX();
848 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700849
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700850 info.w = hwConfig->getWidth();
851 info.h = hwConfig->getHeight();
852 // Default display viewport to display width and height
853 info.viewportW = info.w;
854 info.viewportH = info.h;
855
Dominik Laskowski075d3172018-05-24 15:50:06 -0700856 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700857 // The density of the device is provided by a build property
858 float density = Density::getBuildDensity() / 160.0f;
859 if (density == 0) {
860 // the build doesn't provide a density -- this is wrong!
861 // use xdpi instead
862 ALOGE("ro.sf.lcd_density must be defined as a build property");
863 density = xdpi / 160.0f;
864 }
865 if (Density::getEmuDensity()) {
866 // if "qemu.sf.lcd_density" is specified, it overrides everything
867 xdpi = ydpi = density = Density::getEmuDensity();
868 density /= 160.0f;
869 }
870 info.density = density;
871
872 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700873 const auto display = getDefaultDisplayDeviceLocked();
874 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700875
876 // This is for screenrecord
877 const Rect viewport = display->getViewport();
878 if (viewport.isValid()) {
879 info.viewportW = uint32_t(viewport.getWidth());
880 info.viewportH = uint32_t(viewport.getHeight());
881 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700882 } else {
883 // TODO: where should this value come from?
884 static const int TV_DENSITY = 213;
885 info.density = TV_DENSITY / 160.0f;
886 info.orientation = 0;
887 }
888
Dan Stoza7f7da322014-05-02 15:26:25 -0700889 info.xdpi = xdpi;
890 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800891 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900892 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800893
Andy McFadden91b2ca82014-06-13 14:04:23 -0700894 // This is how far in advance a buffer must be queued for
895 // presentation at a given time. If you want a buffer to appear
896 // on the screen at time N, you must submit the buffer before
897 // (N - presentationDeadline).
898 //
899 // Normally it's one full refresh period (to give SF a chance to
900 // latch the buffer), but this can be reduced by configuring a
901 // DispSync offset. Any additional delays introduced by the hardware
902 // composer or panel must be accounted for here.
903 //
904 // We add an additional 1ms to allow for processing time and
905 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800906 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800907 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700908
909 // All non-virtual displays are currently considered secure.
910 info.secure = true;
911
Dominik Laskowski075d3172018-05-24 15:50:06 -0700912 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700913 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800914 std::swap(info.w, info.h);
915 }
916
Michael Wright28f24d02016-07-12 13:30:53 -0700917 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700918 }
919
Dan Stoza7f7da322014-05-02 15:26:25 -0700920 return NO_ERROR;
921}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700922
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700923status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
924 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700925 return BAD_VALUE;
926 }
927
Ana Krulece588e312018-09-18 12:32:24 -0700928 if (mUseScheduler) {
929 mScheduler->getDisplayStatInfo(stats);
930 } else {
931 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
932 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
933 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700934 return NO_ERROR;
935}
936
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700937int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
938 const auto display = getDisplayDevice(displayToken);
939 if (!display) {
940 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800941 return BAD_VALUE;
942 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700943
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700944 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700945}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700946
Ana Krulec7d1d6832018-12-27 11:10:09 -0800947status_t SurfaceFlinger::setActiveConfigAsync(const sp<IBinder>& displayToken, int mode) {
948 ATRACE_NAME("setActiveConfigAsync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800949 postMessageAsync(new LambdaMessage(
950 [=]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800951 return NO_ERROR;
952}
953
954status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
955 ATRACE_NAME("setActiveConfigSync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800956 postMessageSync(new LambdaMessage(
957 [&]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800958 return NO_ERROR;
959}
960
961void SurfaceFlinger::setActiveConfigInternal(const sp<IBinder>& displayToken, int mode) {
962 Vector<DisplayInfo> configs;
963 getDisplayConfigs(displayToken, &configs);
964 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
965 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
966 return;
967 }
968
969 const auto display = getDisplayDevice(displayToken);
970 if (!display) {
971 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
972 displayToken.get());
973 return;
974 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700975 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800976 ALOGW("Attempt to set active config %d for virtual display", mode);
977 return;
978 }
979 int currentDisplayPowerMode = display->getPowerMode();
980 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
981 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700982 return;
983 }
984
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700985 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700986 if (mode == currentMode) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800987 // Don't update config if we are already running in the desired mode.
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700988 return;
989 }
990
Dominik Laskowski075d3172018-05-24 15:50:06 -0700991 const auto displayId = display->getId();
992 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700993
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700994 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700995 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700996
Ana Krulec7d1d6832018-12-27 11:10:09 -0800997 ATRACE_INT("ActiveConfigMode", mode);
Dominik Laskowski83b88212018-12-11 13:34:06 -0800998 resyncToHardwareVsync(true, getVsyncPeriod());
Mathias Agopianc666cae2012-07-25 18:56:13 -0700999}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001000
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001001status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1002 Vector<ColorMode>* outColorModes) {
1003 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001004 return BAD_VALUE;
1005 }
1006
Dominik Laskowski075d3172018-05-24 15:50:06 -07001007 const auto displayId = getPhysicalDisplayId(displayToken);
1008 if (!displayId) {
1009 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -07001010 }
1011
Peiyong Lina52f0292018-03-14 17:26:31 -07001012 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001013 {
1014 ConditionalLock _l(mStateLock,
1015 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001016 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001017 }
Michael Wright28f24d02016-07-12 13:30:53 -07001018 outColorModes->clear();
1019 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1020
1021 return NO_ERROR;
1022}
1023
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001024ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1025 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001026 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001027 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001028 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001029}
1030
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001031status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001032 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001033 Vector<ColorMode> modes;
1034 getDisplayColorModes(displayToken, &modes);
1035 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1036 if (mode < ColorMode::NATIVE || !exists) {
1037 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1038 decodeColorMode(mode).c_str(), mode, displayToken.get());
1039 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001040 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001041 const auto display = getDisplayDevice(displayToken);
1042 if (!display) {
1043 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1044 decodeColorMode(mode).c_str(), mode, displayToken.get());
1045 } else if (display->isVirtual()) {
1046 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1047 decodeColorMode(mode).c_str(), mode);
1048 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001049 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1050 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001051 }
1052 }));
1053
Michael Wright28f24d02016-07-12 13:30:53 -07001054 return NO_ERROR;
1055}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001056
Svetoslavd85084b2014-03-20 10:28:31 -07001057status_t SurfaceFlinger::clearAnimationFrameStats() {
1058 Mutex::Autolock _l(mStateLock);
1059 mAnimFrameTracker.clearStats();
1060 return NO_ERROR;
1061}
1062
1063status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1064 Mutex::Autolock _l(mStateLock);
1065 mAnimFrameTracker.getStats(outStats);
1066 return NO_ERROR;
1067}
1068
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001069status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1070 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001071 Mutex::Autolock _l(mStateLock);
1072
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001073 const auto display = getDisplayDeviceLocked(displayToken);
1074 if (!display) {
1075 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001076 return BAD_VALUE;
1077 }
1078
Peiyong Linfb069302018-04-25 14:34:31 -07001079 // At this point the DisplayDeivce should already be set up,
1080 // meaning the luminance information is already queried from
1081 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001082 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001083 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1084 capabilities.getDesiredMaxLuminance(),
1085 capabilities.getDesiredMaxAverageLuminance(),
1086 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001087
1088 return NO_ERROR;
1089}
1090
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001091status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1092 ui::PixelFormat* outFormat,
1093 ui::Dataspace* outDataspace,
1094 uint8_t* outComponentMask) const {
1095 if (!outFormat || !outDataspace || !outComponentMask) {
1096 return BAD_VALUE;
1097 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001098 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001099 if (!display || !display->getId()) {
1100 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1101 return BAD_VALUE;
1102 }
1103 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1104 outDataspace, outComponentMask);
1105}
1106
Kevin DuBois74e53772018-11-19 10:52:38 -08001107status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1108 bool enable, uint8_t componentMask,
1109 uint64_t maxFrames) const {
1110 const auto display = getDisplayDevice(displayToken);
1111 if (!display || !display->getId()) {
1112 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1113 return BAD_VALUE;
1114 }
1115
1116 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1117 componentMask, maxFrames);
1118}
1119
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001120status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1121 uint64_t maxFrames, uint64_t timestamp,
1122 DisplayedFrameStats* outStats) const {
1123 const auto display = getDisplayDevice(displayToken);
1124 if (!display || !display->getId()) {
1125 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1126 return BAD_VALUE;
1127 }
1128
1129 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1130 outStats);
1131}
1132
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001133status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1134 if (!outSupported) {
1135 return BAD_VALUE;
1136 }
1137 *outSupported = getRenderEngine().supportsProtectedContent();
1138 return NO_ERROR;
1139}
1140
Marissa Wallebc2c052019-01-16 19:16:55 -08001141status_t SurfaceFlinger::cacheBuffer(const sp<IBinder>& token, const sp<GraphicBuffer>& buffer,
1142 int32_t* outBufferId) {
1143 if (!outBufferId) {
1144 return BAD_VALUE;
1145 }
1146 *outBufferId = mBufferStateLayerCache.add(token, buffer);
1147 return NO_ERROR;
1148}
1149
1150status_t SurfaceFlinger::uncacheBuffer(const sp<IBinder>& token, int32_t bufferId) {
1151 mBufferStateLayerCache.release(token, bufferId);
1152 return NO_ERROR;
1153}
1154
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001155status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001156 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001157 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001158
Chia-I Wu90f669f2017-10-05 14:24:41 -07001159 if (mInjectVSyncs == enable) {
1160 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001161 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001162
Dominik Laskowski83b88212018-12-11 13:34:06 -08001163 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001164
Ana Krulec98b5b242018-08-10 15:03:23 -07001165 // TODO(akrulec): Part of the Injector should be refactored, so that it
1166 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001167 if (enable) {
1168 ALOGV("VSync Injections enabled");
1169 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001170 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001171 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001172 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001173 impl::EventThread::InterceptVSyncsCallback(),
1174 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001175 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001176 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001177 } else {
1178 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001179 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001180 }
1181
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001182 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001183 }));
1184
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001185 return NO_ERROR;
1186}
1187
1188status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001189 Mutex::Autolock _l(mStateLock);
1190
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001191 if (!mInjectVSyncs) {
1192 ALOGE("VSync Injections not enabled");
1193 return BAD_VALUE;
1194 }
1195 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1196 ALOGV("Injecting VSync inside SurfaceFlinger");
1197 mVSyncInjector->onInjectSyncEvent(when);
1198 }
1199 return NO_ERROR;
1200}
1201
Lloyd Pique755e3192018-01-31 16:46:15 -08001202status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1203 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001204 // Try to acquire a lock for 1s, fail gracefully
1205 const status_t err = mStateLock.timedLock(s2ns(1));
1206 const bool locked = (err == NO_ERROR);
1207 if (!locked) {
1208 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1209 return TIMED_OUT;
1210 }
1211
1212 outLayers->clear();
1213 mCurrentState.traverseInZOrder([&](Layer* layer) {
1214 outLayers->push_back(layer->getLayerDebugInfo());
1215 });
1216
1217 mStateLock.unlock();
1218 return NO_ERROR;
1219}
1220
Peiyong Linc6780972018-10-28 15:24:08 -07001221status_t SurfaceFlinger::getCompositionPreference(
1222 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1223 Dataspace* outWideColorGamutDataspace,
1224 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001225 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001226 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001227 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001228 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001229 return NO_ERROR;
1230}
1231
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001232// ----------------------------------------------------------------------------
1233
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001234sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1235 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001236 auto resyncCallback = makeResyncCallback([this] {
1237 Mutex::Autolock lock(mStateLock);
1238 return getVsyncPeriod();
1239 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001240
Ana Krulec98b5b242018-08-10 15:03:23 -07001241 if (mUseScheduler) {
1242 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001243 return mScheduler->createDisplayEventConnection(mSfConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001244 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001245 return mScheduler->createDisplayEventConnection(mAppConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001246 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001247 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001248 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001249 return mSFEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001250 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001251 return mEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001252 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001253 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001254}
1255
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001256// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001257
1258void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001259 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001260}
1261
1262void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001263 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001264}
1265
1266void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001267 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001268}
1269
1270void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001271 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001272 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001273}
1274
1275status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001276 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001277 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001278}
1279
1280status_t SurfaceFlinger::postMessageSync(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 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001283 if (res == NO_ERROR) {
1284 msg->wait();
1285 }
1286 return res;
1287}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001288
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001289void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001290 do {
1291 waitForEvent();
1292 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001293}
1294
Dominik Laskowski83b88212018-12-11 13:34:06 -08001295nsecs_t SurfaceFlinger::getVsyncPeriod() const {
1296 const auto displayId = getInternalDisplayId();
1297 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1298 return 0;
1299 }
1300
1301 const auto config = getHwComposer().getActiveConfig(*displayId);
1302 return config ? config->getVsyncPeriod() : 0;
1303}
1304
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001305void SurfaceFlinger::enableHardwareVsync() {
1306 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001307 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001308 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001309 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001310 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001311 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001312}
1313
Dominik Laskowski83b88212018-12-11 13:34:06 -08001314void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001315 Mutex::Autolock _l(mHWVsyncLock);
1316
Jesse Hall948fe0c2013-10-14 12:56:09 -07001317 if (makeAvailable) {
1318 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001319 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1320 if (mUseScheduler) {
1321 mScheduler->makeHWSyncAvailable(true);
1322 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001323 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001324 // Hardware vsync is not currently available, so abort the resync
1325 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001326 return;
1327 }
1328
Dominik Laskowski83b88212018-12-11 13:34:06 -08001329 if (period <= 0) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001330 return;
1331 }
1332
Ana Krulece588e312018-09-18 12:32:24 -07001333 if (mUseScheduler) {
1334 mScheduler->setVsyncPeriod(period);
1335 } else {
1336 mPrimaryDispSync->reset();
1337 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001338
Ana Krulece588e312018-09-18 12:32:24 -07001339 if (!mPrimaryHWVsyncEnabled) {
1340 mPrimaryDispSync->beginResync();
1341 mEventControlThread->setVsyncEnabled(true);
1342 mPrimaryHWVsyncEnabled = true;
1343 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001344 }
1345}
1346
Jesse Hall948fe0c2013-10-14 12:56:09 -07001347void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001348 Mutex::Autolock _l(mHWVsyncLock);
1349 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001350 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001351 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001352 mPrimaryHWVsyncEnabled = false;
1353 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001354 if (makeUnavailable) {
1355 mHWVsyncAvailable = false;
1356 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001357}
1358
Dominik Laskowski83b88212018-12-11 13:34:06 -08001359void SurfaceFlinger::VsyncState::resync(const GetVsyncPeriod& getVsyncPeriod) {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001360 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001361
Dan Stoza57164302017-05-08 14:03:54 -07001362 const nsecs_t now = systemTime();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001363 const nsecs_t last = lastResyncTime.exchange(now);
1364
1365 if (now - last > kIgnoreDelay) {
1366 flinger.resyncToHardwareVsync(false, getVsyncPeriod());
Tim Murray4a4e4a22016-04-19 16:29:23 +00001367 }
1368}
1369
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001370void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1371 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001372 ATRACE_NAME("SF onVsync");
1373
Steven Thomas3cfac282017-02-06 12:29:30 -08001374 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001375 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001376 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001377 return;
1378 }
1379
Dominik Laskowski075d3172018-05-24 15:50:06 -07001380 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001381 return;
1382 }
1383
Dominik Laskowski075d3172018-05-24 15:50:06 -07001384 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001385 // For now, we don't do anything with external display vsyncs.
1386 return;
1387 }
1388
Ana Krulece588e312018-09-18 12:32:24 -07001389 if (mUseScheduler) {
1390 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001391 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001392 bool needsHwVsync = false;
1393 { // Scope for the lock
1394 Mutex::Autolock _l(mHWVsyncLock);
1395 if (mPrimaryHWVsyncEnabled) {
1396 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1397 }
1398 }
1399
1400 if (needsHwVsync) {
1401 enableHardwareVsync();
1402 } else {
1403 disableHardwareVsync(false);
1404 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001405 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001406}
1407
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001408void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001409 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1410 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001411}
1412
Ana Krulec7d1d6832018-12-27 11:10:09 -08001413void SurfaceFlinger::setRefreshRateTo(float newFps) {
1414 const auto displayId = getInternalDisplayId();
1415 if (!displayId || mBootStage != BootStage::FINISHED) {
1416 return;
1417 }
1418 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1419 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1420 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1421 // refresh cycle.
1422
1423 // Don't do any updating if the current fps is the same as the new one.
1424 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
1425 const nsecs_t currentVsyncPeriod = activeConfig->getVsyncPeriod();
1426 if (currentVsyncPeriod == 0) {
1427 return;
1428 }
1429 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1430 // floating numbers.
1431 const float currentFps = 1e9 / currentVsyncPeriod;
1432 if (std::abs(currentFps - newFps) <= 1) {
1433 return;
1434 }
1435
1436 auto configs = getHwComposer().getConfigs(*displayId);
1437 for (int i = 0; i < configs.size(); i++) {
1438 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1439 if (vsyncPeriod == 0) {
1440 continue;
1441 }
1442 const float fps = 1e9 / vsyncPeriod;
1443 // TODO(b/113612090): There should be a better way at determining which config
1444 // has the right refresh rate.
1445 if (std::abs(fps - newFps) <= 1) {
1446 const auto display = getBuiltInDisplay(HWC_DISPLAY_PRIMARY);
1447 if (!display) return;
1448 // This is posted in async function to avoid deadlock when getDisplayDevice
1449 // requires mStateLock.
1450 setActiveConfigAsync(display, i);
1451 ATRACE_INT("FPS", newFps);
1452 }
1453 }
1454}
1455
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001456void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001457 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001458 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001459 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001460
Lloyd Piqueba04e622017-12-14 17:11:26 -08001461 // Ignore events that do not have the right sequenceId.
1462 if (sequenceId != getBE().mComposerSequenceId) {
1463 return;
1464 }
1465
Steven Thomasb02664d2017-07-26 18:48:28 -07001466 // Only lock if we're not on the main thread. This function is normally
1467 // called on a hwbinder thread, but for the primary display it's called on
1468 // the main thread with the state lock already held, so don't attempt to
1469 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001470 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001471
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001472 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001473
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001474 if (std::this_thread::get_id() == mMainThreadId) {
1475 // Process all pending hot plug events immediately if we are on the main thread.
1476 processDisplayHotplugEventsLocked();
1477 }
1478
Lloyd Piqueba04e622017-12-14 17:11:26 -08001479 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001480}
1481
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001482void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001483 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001484 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001485 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001486 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001487 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001488}
1489
Dominik Laskowski075d3172018-05-24 15:50:06 -07001490void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001491 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001492 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001493 if (const auto displayId = getInternalDisplayId()) {
1494 getHwComposer().setVsyncEnabled(*displayId,
1495 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1496 }
Mathias Agopian86303202012-07-24 22:46:10 -07001497}
1498
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001499// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001500void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001501 if (mUseScheduler) {
1502 mScheduler->disableHardwareVsync(true);
1503 } else {
1504 disableHardwareVsync(true);
1505 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001506 // Clear the drawing state so that the logic inside of
1507 // handleTransactionLocked will fire. It will determine the delta between
1508 // mCurrentState and mDrawingState and re-apply all changes when we make the
1509 // transition.
1510 mDrawingState.displays.clear();
1511 mDisplays.clear();
1512}
1513
Steven Thomas050b2c82017-03-06 11:45:16 -08001514void SurfaceFlinger::updateVrFlinger() {
1515 if (!mVrFlinger)
1516 return;
1517 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001518 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001519 return;
1520 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001521
Lloyd Pique441d5042018-10-18 16:49:51 -07001522 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001523 ALOGE("Vr flinger is only supported for remote hardware composer"
1524 " service connections. Ignoring request to transition to vr"
1525 " flinger.");
1526 mVrFlingerRequestsDisplay = false;
1527 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001528 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001529
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001530 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001531
Steven Thomas0123ac62018-07-12 11:32:34 -07001532 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001533 LOG_ALWAYS_FATAL_IF(!display);
1534 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001535 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1536 // called below. Clear the reference now so we don't accidentally use it
1537 // later.
1538 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001539
Steven Thomasb02664d2017-07-26 18:48:28 -07001540 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001541 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001542 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001543
Steven Thomasb02664d2017-07-26 18:48:28 -07001544 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001545 // Delete the current instance before creating the new one
1546 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1547 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1548 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1549 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001550
Lloyd Pique441d5042018-10-18 16:49:51 -07001551 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001552 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001553
1554 if (vrFlingerRequestsDisplay) {
1555 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001556 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001557
1558 mVisibleRegionsDirty = true;
1559 invalidateHwcGeometry();
1560
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001561 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001562 display = getDefaultDisplayDeviceLocked();
1563 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001564 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001565
Steven Thomasb02664d2017-07-26 18:48:28 -07001566 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001567 const nsecs_t vsyncPeriod = getVsyncPeriod();
1568 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001569
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001570 // The present fences returned from vr_hwc are not an accurate
1571 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001572 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001573 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1574 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001575 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001576 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001577 !hasSyncFramework);
1578 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001579
Steven Thomasb02664d2017-07-26 18:48:28 -07001580 // Use phase of 0 since phase is not known.
1581 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001582 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001583 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001584
Dominik Laskowski83b88212018-12-11 13:34:06 -08001585 resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001586
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001587 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001588 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001589}
1590
Mathias Agopian4fec8732012-06-29 14:12:52 -07001591void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001592 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001593 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001594 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001595 if (mUseScheduler) {
1596 // This call is made each time SF wakes up and creates a new frame.
1597 mScheduler->incrementFrameCounter();
1598 }
Dan Stoza50182882016-07-08 12:02:20 -07001599 bool frameMissed = !mHadClientComposition &&
1600 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001601 (mPreviousPresentFence->getSignalTime() ==
1602 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001603 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001604 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001605 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001606 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001607 if (mPropagateBackpressure) {
1608 signalLayerUpdate();
1609 break;
1610 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001611 }
Dan Stoza50182882016-07-08 12:02:20 -07001612
Steven Thomas050b2c82017-03-06 11:45:16 -08001613 // Now that we're going to make it to the handleMessageTransaction()
1614 // call below it's safe to call updateVrFlinger(), which will
1615 // potentially trigger a display handoff.
1616 updateVrFlinger();
1617
Dan Stoza6b9454d2014-11-07 16:00:59 -08001618 bool refreshNeeded = handleMessageTransaction();
1619 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001620 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001621 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001622 // Signal a refresh if a transaction modified the window state,
1623 // a new buffer was latched, or if HWC has requested a full
1624 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001625 signalRefresh();
1626 }
1627 break;
1628 }
1629 case MessageQueue::REFRESH: {
1630 handleMessageRefresh();
1631 break;
1632 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001633 }
1634}
1635
Dan Stoza6b9454d2014-11-07 16:00:59 -08001636bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001637 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001638
1639 // Apply any ready transactions in the queues if there are still transactions that have not been
1640 // applied, wake up during the next vsync period and check again
1641 bool transactionNeeded = false;
1642 if (!flushTransactionQueues()) {
1643 transactionNeeded = true;
1644 }
1645
Mathias Agopian4fec8732012-06-29 14:12:52 -07001646 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001647 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001648 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001649
1650 if (transactionNeeded) {
1651 setTransactionFlags(eTransactionNeeded);
1652 }
1653
1654 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001655}
1656
Mathias Agopian4fec8732012-06-29 14:12:52 -07001657void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001658 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001659
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001660 mRefreshPending = false;
1661
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001662 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001663 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001664 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001665 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001666 for (const auto& [token, display] : mDisplays) {
1667 beginFrame(display);
1668 prepareFrame(display);
1669 doDebugFlashRegions(display, repaintEverything);
1670 doComposition(display, repaintEverything);
1671 }
1672
Adrian Roos1e1a1282017-11-01 19:05:31 +01001673 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001674 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001675
1676 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001677 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001678
Dan Stozabfbffeb2016-07-21 14:49:33 -07001679 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001680 for (const auto& [token, displayDevice] : mDisplays) {
1681 auto display = displayDevice->getCompositionDisplay();
1682 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001683 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001684 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001685 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001686
Alec Mouri86770e52018-09-24 22:40:58 +00001687 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001688 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001689 if (mHadClientComposition) {
1690 base::unique_fd flushFence(getRenderEngine().flush());
1691 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1692 getBE().flushFence = new Fence(std::move(flushFence));
1693 } else {
1694 // Cleanup for hygiene.
1695 getBE().flushFence = Fence::NO_FENCE;
1696 }
1697 }
1698
Jorim Jaggi90535212018-05-23 23:44:06 +02001699 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001700
David Sodman7e4ae112018-02-09 15:02:28 -08001701 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001702 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001703 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001704 compositionInfo.hwc.hwcLayer = nullptr;
1705 }
David Sodmanba340492018-08-05 21:51:33 -07001706 }
David Sodman7e4ae112018-02-09 15:02:28 -08001707
1708 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001709}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001710
David Sodmanfa9b2af2017-12-24 13:28:59 -08001711
1712bool SurfaceFlinger::handleMessageInvalidate() {
1713 ATRACE_CALL();
1714 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001715}
1716
David Sodman79bba0e2018-08-05 18:07:49 -07001717void SurfaceFlinger::calculateWorkingSet() {
1718 ATRACE_CALL();
1719 ALOGV(__FUNCTION__);
1720
David Sodman79bba0e2018-08-05 18:07:49 -07001721 // build the h/w work list
1722 if (CC_UNLIKELY(mGeometryInvalid)) {
1723 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001724 for (const auto& [token, displayDevice] : mDisplays) {
1725 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001726 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001727 if (!displayId) {
1728 continue;
1729 }
David Sodman79bba0e2018-08-05 18:07:49 -07001730
Lloyd Pique32cbe282018-10-19 13:09:22 -07001731 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001732 for (size_t i = 0; i < currentLayers.size(); i++) {
1733 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001734
Dominik Laskowski075d3172018-05-24 15:50:06 -07001735 if (!layer->hasHwcLayer(*displayId)) {
1736 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1737 layer->forceClientComposition(*displayId);
1738 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001739 }
1740 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001741
Lloyd Pique32cbe282018-10-19 13:09:22 -07001742 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001743 if (mDebugDisableHWC || mDebugRegion) {
1744 layer->forceClientComposition(*displayId);
1745 }
David Sodman79bba0e2018-08-05 18:07:49 -07001746 }
1747 }
1748 }
1749
1750 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001751 for (const auto& [token, displayDevice] : mDisplays) {
1752 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001753 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001754 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001755 continue;
1756 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001757 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001758
1759 if (mDrawingState.colorMatrixChanged) {
1760 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001761 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001762 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001763 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001764 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001765 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1766 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001767 !profile->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001768 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001769 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1770 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001771 !profile->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001772 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001773 }
1774
Peiyong Lind3788632018-09-18 16:01:31 -07001775 // TODO(b/111562338) remove when composer 2.3 is shipped.
1776 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001777 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001778 }
1779
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001780 if (layer->getRoundedCornerState().radius > 0.0f) {
1781 layer->forceClientComposition(*displayId);
1782 }
1783
Dominik Laskowski075d3172018-05-24 15:50:06 -07001784 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001785 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001786 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001787 continue;
1788 }
1789
Lloyd Pique32cbe282018-10-19 13:09:22 -07001790 const auto& displayState = display->getState();
1791 layer->setPerFrameData(*displayId, displayState.transform, displayState.viewport,
1792 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001793 }
1794
Peiyong Lin13effd12018-07-24 17:01:47 -07001795 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001796 ColorMode colorMode;
1797 Dataspace dataSpace;
1798 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001799 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001800 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001801 }
1802 }
1803
1804 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001805
1806 for (const auto& [token, display] : mDisplays) {
1807 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001808 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001809 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001810
1811 if (displayId) {
1812 if (!layer->setHwcLayer(*displayId)) {
1813 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1814 }
1815 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001816 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001817
Dominik Laskowski05275f12018-11-01 15:03:24 -07001818 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001819 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1820 }
1821 }
David Sodman79bba0e2018-08-05 18:07:49 -07001822}
1823
Lloyd Pique32cbe282018-10-19 13:09:22 -07001824void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1825 bool repaintEverything) {
1826 auto display = displayDevice->getCompositionDisplay();
1827 const auto& displayState = display->getState();
1828
Mathias Agopiancd60f992012-08-16 16:28:27 -07001829 // is debugging enabled
1830 if (CC_LIKELY(!mDebugRegion))
1831 return;
1832
Lloyd Pique32cbe282018-10-19 13:09:22 -07001833 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001834 // transform the dirty region into this screen's coordinate space
Lloyd Pique32cbe282018-10-19 13:09:22 -07001835 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001836 if (!dirtyRegion.isEmpty()) {
1837 // redraw the whole screen
Lloyd Pique32cbe282018-10-19 13:09:22 -07001838 doComposeSurfaces(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001839
David Sodmanfa9b2af2017-12-24 13:28:59 -08001840 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001841 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001842 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001843
Lloyd Pique31cb2942018-10-19 17:23:03 -07001844 display->getRenderSurface()->queueBuffer();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001845 }
1846 }
1847
Lloyd Pique32cbe282018-10-19 13:09:22 -07001848 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001849
1850 if (mDebugRegion > 1) {
1851 usleep(mDebugRegion * 1000);
1852 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001853
Lloyd Pique32cbe282018-10-19 13:09:22 -07001854 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001855}
1856
Adrian Roos1e1a1282017-11-01 19:05:31 +01001857void SurfaceFlinger::doTracing(const char* where) {
1858 ATRACE_CALL();
1859 ATRACE_NAME(where);
1860 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001861 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001862 }
1863}
1864
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001865void SurfaceFlinger::logLayerStats() {
1866 ATRACE_CALL();
1867 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001868 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001869 if (display->isPrimary()) {
1870 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001871 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001872 }
1873 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001874
1875 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001876 }
1877}
1878
David Sodman2b406362017-12-15 13:33:47 -08001879void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001880{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001881 ATRACE_CALL();
1882 ALOGV("preComposition");
1883
David Sodman2b406362017-12-15 13:33:47 -08001884 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1885
Mathias Agopiancd60f992012-08-16 16:28:27 -07001886 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001887 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001888 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001889 needExtraInvalidate = true;
1890 }
Robert Carr2047fae2016-11-28 14:09:09 -08001891 });
1892
Mathias Agopiancd60f992012-08-16 16:28:27 -07001893 if (needExtraInvalidate) {
1894 signalLayerUpdate();
1895 }
1896}
1897
Ana Krulece588e312018-09-18 12:32:24 -07001898void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1899 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001900 // Update queue of past composite+present times and determine the
1901 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001902 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001903 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001904 while (!getBE().mCompositePresentTimes.empty()) {
1905 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001906 // Cached values should have been updated before calling this method,
1907 // which helps avoid duplicate syscalls.
1908 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1909 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1910 break;
1911 }
1912 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001913 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001914 }
1915
1916 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001917 while (getBE().mCompositePresentTimes.size() > 16) {
1918 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001919 }
1920
Ana Krulece588e312018-09-18 12:32:24 -07001921 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001922}
1923
Ana Krulece588e312018-09-18 12:32:24 -07001924void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1925 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001926 // Integer division and modulo round toward 0 not -inf, so we need to
1927 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001928 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1929 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1930 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001931
Brian Andersond0010582017-03-07 13:20:31 -08001932 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1933 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001934 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001935 }
1936
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001937 // Snap the latency to a value that removes scheduling jitter from the
1938 // composition and present times, which often have >1ms of jitter.
1939 // Reducing jitter is important if an app attempts to extrapolate
1940 // something (such as user input) to an accurate diasplay time.
1941 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1942 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001943 nsecs_t bias = stats.vsyncPeriod / 2;
1944 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1945 nsecs_t snappedCompositeToPresentLatency =
1946 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001947
David Sodman99974d22017-11-28 12:04:33 -08001948 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001949 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1950 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001951 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001952}
1953
Ady Abraham8164d482019-01-11 14:47:59 -08001954// debug patch for b/119477596 - add stack guards to catch stack
1955// corruptions and disable clang optimizations.
1956// The code below is temporary and planned to be removed once stack
1957// corruptions are found.
1958#pragma clang optimize off
1959class StackGuard {
1960public:
1961 StackGuard(const char* name, const char* func, int line) {
1962 guarders.reserve(MIN_CAPACITY);
1963 guarders.push_back({this, name, func, line});
1964 validate();
1965 }
1966 ~StackGuard() {
1967 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1968 if (i->guard == this) {
1969 guarders.erase(i);
1970 break;
1971 }
1972 }
1973 }
1974
1975 static void validate() {
1976 for (const auto& guard : guarders) {
1977 if (guard.guard->cookie != COOKIE_VALUE) {
1978 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1979 CallStack stack(LOG_TAG);
1980 abort();
1981 }
1982 }
1983 }
1984
1985private:
1986 uint64_t cookie = COOKIE_VALUE;
1987 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
1988 static constexpr size_t MIN_CAPACITY = 16;
1989
1990 struct GuarderElement {
1991 StackGuard* guard;
1992 const char* name;
1993 const char* func;
1994 int line;
1995 };
1996
1997 static std::vector<GuarderElement> guarders;
1998};
1999std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2000
2001#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2002
2003#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002004void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002005{
Ady Abraham8164d482019-01-11 14:47:59 -08002006 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002007 ATRACE_CALL();
2008 ALOGV("postComposition");
2009
Brian Anderson3546a3f2016-07-14 11:51:14 -07002010 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002011 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002012 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002013 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002014 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002015 }
Ady Abraham8164d482019-01-11 14:47:59 -08002016 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002017
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002018 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002019 const auto displayDevice = getDefaultDisplayDeviceLocked();
2020 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002021
David Sodman73beded2017-11-15 11:56:06 -08002022 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002023 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002024 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2025
Lloyd Pique32cbe282018-10-19 13:09:22 -07002026 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002027 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002028 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2029 ->getRenderSurface()
2030 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002031 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002032 } else {
2033 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2034 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002035
Ady Abraham8164d482019-01-11 14:47:59 -08002036 ASSERT_ON_STACK_GUARD();
2037
David Sodman73beded2017-11-15 11:56:06 -08002038 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002039 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2040 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002041 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002042 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002043 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002044
Ana Krulece588e312018-09-18 12:32:24 -07002045 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002046 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002047 if (mUseScheduler) {
2048 mScheduler->getDisplayStatInfo(&stats);
2049 } else {
2050 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2051 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2052 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002053
Ady Abraham8164d482019-01-11 14:47:59 -08002054 ASSERT_ON_STACK_GUARD();
2055
David Sodman2b406362017-12-15 13:33:47 -08002056 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002057 // when we started doing work for this frame, but that should be okay
2058 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002059 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002060 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002061 DEFINE_STACK_GUARD(compositorTiming);
2062
Brian Andersond0010582017-03-07 13:20:31 -08002063 {
David Sodman99974d22017-11-28 12:04:33 -08002064 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002065 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002066 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002067
2068 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002069 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002070
Robert Carr2047fae2016-11-28 14:09:09 -08002071 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002072 bool frameLatched =
2073 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2074 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002075 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002076 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002077 recordBufferingStats(layer->getName().string(),
2078 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002079 }
Ady Abraham8164d482019-01-11 14:47:59 -08002080 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002081 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002082
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002083 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002084 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002085 if (mUseScheduler) {
2086 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002087 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002088 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002089 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2090 enableHardwareVsync();
2091 } else {
2092 disableHardwareVsync(false);
2093 }
Ady Abraham8164d482019-01-11 14:47:59 -08002094 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002095 }
2096 }
2097
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002098 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002099 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2100 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002101 if (mUseScheduler) {
2102 mScheduler->enableHardwareVsync();
2103 } else {
2104 enableHardwareVsync();
2105 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002106 }
2107 }
2108
Ady Abraham8164d482019-01-11 14:47:59 -08002109 ASSERT_ON_STACK_GUARD();
2110
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002111 if (mAnimCompositionPending) {
2112 mAnimCompositionPending = false;
2113
Brian Anderson4e606e32017-03-16 15:34:57 -07002114 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002115 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002116 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002117
2118 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002119 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002120 // The HWC doesn't support present fences, so use the refresh
2121 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002122 const nsecs_t presentTime =
2123 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002124 DEFINE_STACK_GUARD(presentTime);
2125
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002126 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002127 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002128 }
2129 mAnimFrameTracker.advanceFrame();
2130 }
Dan Stozab90cf072015-03-05 11:05:59 -08002131
Ady Abraham8164d482019-01-11 14:47:59 -08002132 ASSERT_ON_STACK_GUARD();
2133
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002134 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002135 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002136 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002137 }
2138
Ady Abraham8164d482019-01-11 14:47:59 -08002139 ASSERT_ON_STACK_GUARD();
2140
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002141 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002142
Ady Abraham8164d482019-01-11 14:47:59 -08002143 ASSERT_ON_STACK_GUARD();
2144
Lloyd Pique32cbe282018-10-19 13:09:22 -07002145 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2146 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002147 return;
2148 }
2149
2150 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002151 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002152 if (mHasPoweredOff) {
2153 mHasPoweredOff = false;
2154 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002155 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002156 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002157 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002158 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002159 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2160 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002161 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002162 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002163 }
David Sodman4a36e932017-11-07 14:29:47 -08002164 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002165
2166 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002167 }
David Sodman4a36e932017-11-07 14:29:47 -08002168 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002169 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002170
2171 {
2172 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002173 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002174 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002175 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002176 if (refillCount > 0) {
2177 const size_t offset = mTexturePool.size();
2178 mTexturePool.resize(mTexturePoolSize);
2179 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2180 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2181 }
Ady Abraham8164d482019-01-11 14:47:59 -08002182 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002183 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002184
Marissa Wallfda30bb2018-10-12 11:34:28 -07002185 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002186 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002187
2188 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002189}
Ady Abraham8164d482019-01-11 14:47:59 -08002190#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002191
2192void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002193 ATRACE_CALL();
2194 ALOGV("rebuildLayerStacks");
2195
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002196 // We need to clear these out now as these may be holding on to a
2197 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2198 // also holds a reference. When the set of visible layers is recomputed,
2199 // some layers may be destroyed if the only thing keeping them alive was
2200 // that list of visible layers associated with each display. The layer
2201 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2202 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2203 for (const auto& [token, display] : mDisplays) {
2204 getBE().mCompositionInfo[token].clear();
2205 }
2206
Mathias Agopiancd60f992012-08-16 16:28:27 -07002207 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002208 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002209 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002210 mVisibleRegionsDirty = false;
2211 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002212
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002213 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002214 const auto& displayDevice = pair.second;
2215 auto display = displayDevice->getCompositionDisplay();
2216 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002217 Region opaqueRegion;
2218 Region dirtyRegion;
2219 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002220 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002221 const ui::Transform& tr = displayState.transform;
2222 const Rect bounds = displayState.bounds;
2223 if (displayState.isEnabled) {
2224 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002225
Jeff Sharkey76488112017-02-27 14:15:18 -07002226 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002227 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002228 const auto displayId = displayDevice->getId();
2229 if (display->belongsInOutput(layer->getLayerStack())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002230 Region drawRegion(tr.transform(
2231 layer->visibleNonTransparentRegion));
2232 drawRegion.andSelf(bounds);
2233 if (!drawRegion.isEmpty()) {
2234 layersSortedByZ.add(layer);
2235 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002236 // Clear out the HWC layer if this layer was
2237 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002238 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002239 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002240 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002241 // WM changes display->layerStack upon sleep/awake.
2242 // Here we make sure we delete the HWC layers even if
2243 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002244 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002245 }
2246
2247 // If a layer is not going to get a release fence because
2248 // it is invisible, but it is also going to release its
2249 // old buffer, add it to the list of layers needing
2250 // fences.
2251 if (hwcLayerDestroyed) {
2252 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2253 mLayersWithQueuedFrames.cend(), layer);
2254 if (found != mLayersWithQueuedFrames.cend()) {
2255 layersNeedingFences.add(layer);
2256 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002257 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002258 });
2259 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002260 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
2261 displayDevice->setLayersNeedingFences(layersNeedingFences);
2262
2263 Region undefinedRegion{bounds};
2264 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2265
2266 display->editState().undefinedRegion = undefinedRegion;
2267 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002268 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002269 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002270}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002271
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002272// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002273// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002274// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002275// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002276// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002277// The returned HDR data space is one of
2278// - Dataspace::UNKNOWN
2279// - Dataspace::BT2020_HLG
2280// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002281Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2282 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002283 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002284 *outHdrDataSpace = Dataspace::UNKNOWN;
2285
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002286 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002287 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002288 case Dataspace::V0_SCRGB:
2289 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002290 case Dataspace::BT2020:
2291 case Dataspace::BT2020_ITU:
2292 case Dataspace::BT2020_LINEAR:
2293 case Dataspace::DISPLAY_BT2020:
2294 bestDataSpace = Dataspace::DISPLAY_BT2020;
2295 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002296 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002297 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002298 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002299 case Dataspace::BT2020_PQ:
2300 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002301 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002302 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002303 case Dataspace::BT2020_HLG:
2304 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002305 // When there's mixed PQ content and HLG content, we set the HDR
2306 // data space to be BT2020_PQ and convert HLG to PQ.
2307 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2308 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002309 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002310 break;
2311 default:
2312 break;
2313 }
Romain Guy54f154a2017-10-24 21:40:32 +01002314 }
2315
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002316 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002317}
2318
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002319// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002320void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2321 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002322 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2323 *outMode = ColorMode::NATIVE;
2324 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002325 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002326 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002327 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002328
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002329 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002330 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002331
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002332 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2333
Peiyong Lindfde5112018-06-05 10:58:41 -07002334 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002335 const bool isHdr =
2336 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002337 if (isHdr) {
2338 bestDataSpace = hdrDataSpace;
2339 }
2340
Chia-I Wu0d711262018-05-21 15:19:35 -07002341 RenderIntent intent;
2342 switch (mDisplayColorSetting) {
2343 case DisplayColorSetting::MANAGED:
2344 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002345 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002346 break;
2347 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002348 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002349 break;
2350 default: // vendor display color setting
2351 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2352 break;
2353 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002354
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002355 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002356}
2357
Lloyd Pique32cbe282018-10-19 13:09:22 -07002358void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2359 auto display = displayDevice->getCompositionDisplay();
2360 const auto& displayState = display->getState();
2361
2362 bool dirty = !display->getPhysicalSpaceDirtyRegion(false).isEmpty();
2363 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2364 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002365
David Sodmanfa9b2af2017-12-24 13:28:59 -08002366 // If nothing has changed (!dirty), don't recompose.
2367 // If something changed, but we don't currently have any visible layers,
2368 // and didn't when we last did a composition, then skip it this time.
2369 // The second rule does two things:
2370 // - When all layers are removed from a display, we'll emit one black
2371 // frame, then nothing more until we get new layers.
2372 // - When a display is created with a private layer stack, we won't
2373 // emit any black frames until a layer is added to the layer stack.
2374 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002375
Dominik Laskowski075d3172018-05-24 15:50:06 -07002376 const char flagPrefix[] = {'-', '+'};
2377 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002378 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2379 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2380 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2381 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002382
Lloyd Pique31cb2942018-10-19 17:23:03 -07002383 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002384
David Sodmanfa9b2af2017-12-24 13:28:59 -08002385 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002386 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002387 }
2388}
2389
Lloyd Pique32cbe282018-10-19 13:09:22 -07002390void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2391 auto display = displayDevice->getCompositionDisplay();
2392 const auto& displayState = display->getState();
2393
2394 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002395 return;
David Sodman2b406362017-12-15 13:33:47 -08002396 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002397
Lloyd Pique31cb2942018-10-19 17:23:03 -07002398 status_t result = display->getRenderSurface()->prepareFrame(
2399 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002400 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002401 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002402}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002403
Lloyd Pique32cbe282018-10-19 13:09:22 -07002404void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002405 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002406 ALOGV("doComposition");
2407
Lloyd Pique32cbe282018-10-19 13:09:22 -07002408 auto display = displayDevice->getCompositionDisplay();
2409 const auto& displayState = display->getState();
2410
2411 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002412 // transform the dirty region into this screen's coordinate space
Lloyd Pique32cbe282018-10-19 13:09:22 -07002413 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002414
David Sodmanfa9b2af2017-12-24 13:28:59 -08002415 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002416 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002417
Lloyd Pique32cbe282018-10-19 13:09:22 -07002418 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002419 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002420 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002421 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002422}
2423
David Sodmanfa9b2af2017-12-24 13:28:59 -08002424void SurfaceFlinger::postFrame()
2425{
2426 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002427 const auto display = getDefaultDisplayDeviceLocked();
2428 if (display && getHwComposer().isConnected(*display->getId())) {
2429 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002430 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2431 logFrameStats();
2432 }
2433 }
2434}
2435
Lloyd Pique32cbe282018-10-19 13:09:22 -07002436void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002437 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002438 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002439
Lloyd Pique32cbe282018-10-19 13:09:22 -07002440 auto display = displayDevice->getCompositionDisplay();
2441 const auto& displayState = display->getState();
2442 const auto displayId = display->getId();
2443
David Sodmanfa9b2af2017-12-24 13:28:59 -08002444 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002445
Lloyd Pique32cbe282018-10-19 13:09:22 -07002446 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002447 if (displayId) {
2448 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002449 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002450 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002451 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002452 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002453
Chia-I Wu7b549592017-11-15 09:14:57 -08002454 // The layer buffer from the previous frame (if any) is released
2455 // by HWC only when the release fence from this frame (if any) is
2456 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002457 if (displayId && layer->hasHwcLayer(*displayId)) {
2458 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2459 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002460 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002461
2462 // If the layer was client composited in the previous frame, we
2463 // need to merge with the previous client target acquire fence.
2464 // Since we do not track that, always merge with the current
2465 // client target acquire fence when it is available, even though
2466 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002467 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002468 releaseFence =
2469 Fence::merge("LayerRelease", releaseFence,
2470 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002471 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002472
David Sodman15094112018-10-11 09:39:37 -07002473 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002474 }
Chia-I Wu83806892017-11-16 10:50:20 -08002475
2476 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002477 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002478 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002479 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002480 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002481 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002482 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002483 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002484 }
2485 }
2486
Dominik Laskowski075d3172018-05-24 15:50:06 -07002487 if (displayId) {
2488 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002489 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002490 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002491}
2492
Mathias Agopian87baae12012-07-31 12:38:26 -07002493void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002494{
Mathias Agopian841cde52012-03-01 15:44:37 -08002495 ATRACE_CALL();
2496
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002497 // here we keep a copy of the drawing state (that is the state that's
2498 // going to be overwritten by handleTransactionLocked()) outside of
2499 // mStateLock so that the side-effects of the State assignment
2500 // don't happen with mStateLock held (which can cause deadlocks).
2501 State drawingState(mDrawingState);
2502
Mathias Agopianca4d3602011-05-19 15:38:14 -07002503 Mutex::Autolock _l(mStateLock);
2504 const nsecs_t now = systemTime();
2505 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002506
Mathias Agopianca4d3602011-05-19 15:38:14 -07002507 // Here we're guaranteed that some transaction flags are set
2508 // so we can call handleTransactionLocked() unconditionally.
2509 // We call getTransactionFlags(), which will also clear the flags,
2510 // with mStateLock held to guarantee that mCurrentState won't change
2511 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002512
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002513 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002514 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002515 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002516
Mathias Agopianca4d3602011-05-19 15:38:14 -07002517 mLastTransactionTime = systemTime() - now;
2518 mDebugInTransaction = 0;
2519 invalidateHwcGeometry();
2520 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002521}
2522
Lloyd Piqueba04e622017-12-14 17:11:26 -08002523void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2524 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002525 const std::optional<DisplayIdentificationInfo> info =
2526 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002527
Dominik Laskowski075d3172018-05-24 15:50:06 -07002528 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002529 continue;
2530 }
2531
Lloyd Piqueba04e622017-12-14 17:11:26 -08002532 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002533 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002534 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002535 mPhysicalDisplayTokens[info->id] = new BBinder();
2536 DisplayDeviceState state;
2537 state.displayId = info->id;
2538 state.isSecure = true; // All physical displays are currently considered secure.
2539 state.displayName = info->name;
2540 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2541 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002542 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002543 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002544 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002545
Dominik Laskowski075d3172018-05-24 15:50:06 -07002546 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2547 if (index >= 0) {
2548 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2549 mInterceptor->saveDisplayDeletion(state.sequenceId);
2550 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002551 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002552 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002553 }
2554
2555 processDisplayChangesLocked();
2556 }
2557
2558 mPendingHotplugEvents.clear();
2559}
2560
Lloyd Pique99d3da52018-01-22 17:48:03 -08002561sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002562 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002563 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002564 const sp<IGraphicBufferProducer>& producer) {
2565 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002566 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002567 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002568 creationArgs.isSecure = state.isSecure;
2569 creationArgs.displaySurface = dispSurface;
2570 creationArgs.hasWideColorGamut = false;
2571 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002572
Dominik Laskowski075d3172018-05-24 15:50:06 -07002573 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2574 creationArgs.isPrimary = isInternalDisplay;
2575
2576 if (useColorManagement && displayId) {
2577 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002578 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002579 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002580 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002581 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002582
Dominik Laskowski7e045462018-05-30 13:02:02 -07002583 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002584 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002585 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002586 }
tangrobin6753a022018-08-10 10:58:54 +08002587 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002588
Dominik Laskowski075d3172018-05-24 15:50:06 -07002589 if (displayId) {
2590 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002591 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002592 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002593 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002594
Lloyd Pique90c115d2018-09-18 21:39:42 -07002595 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002596 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002597 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002598
Lloyd Pique99d3da52018-01-22 17:48:03 -08002599 // Make sure that composition can never be stalled by a virtual display
2600 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002601 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002602 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002603 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2604 }
2605
Dominik Laskowski075d3172018-05-24 15:50:06 -07002606 creationArgs.displayInstallOrientation =
2607 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002608
Lloyd Pique99d3da52018-01-22 17:48:03 -08002609 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002610 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002611
Lloyd Pique90c115d2018-09-18 21:39:42 -07002612 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002613
2614 if (maxFrameBufferAcquiredBuffers >= 3) {
2615 nativeWindowSurface->preallocateBuffers();
2616 }
2617
2618 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002619 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002620 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002621 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002622 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002623 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002624 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2625 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002626 if (!state.isVirtual()) {
2627 LOG_ALWAYS_FATAL_IF(!displayId);
2628 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002629 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002630
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002631 display->setLayerStack(state.layerStack);
2632 display->setProjection(state.orientation, state.viewport, state.frame);
2633 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002634
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002635 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002636}
2637
Lloyd Pique347200f2017-12-14 17:00:15 -08002638void SurfaceFlinger::processDisplayChangesLocked() {
2639 // here we take advantage of Vector's copy-on-write semantics to
2640 // improve performance by skipping the transaction entirely when
2641 // know that the lists are identical
2642 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2643 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2644 if (!curr.isIdenticalTo(draw)) {
2645 mVisibleRegionsDirty = true;
2646 const size_t cc = curr.size();
2647 size_t dc = draw.size();
2648
2649 // find the displays that were removed
2650 // (ie: in drawing state but not in current state)
2651 // also handle displays that changed
2652 // (ie: displays that are in both lists)
2653 for (size_t i = 0; i < dc;) {
2654 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2655 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002656 // Save display IDs before disconnecting.
2657 const auto internalDisplayId = getInternalDisplayId();
2658 const auto externalDisplayId = getExternalDisplayId();
2659
Lloyd Pique347200f2017-12-14 17:00:15 -08002660 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002661 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002662 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002663 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002664 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002665 if (mUseScheduler) {
2666 mScheduler->hotplugReceived(mAppConnectionHandle,
2667 EventThread::DisplayType::Primary, false);
2668 } else {
2669 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2670 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002671 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002672 if (mUseScheduler) {
2673 mScheduler->hotplugReceived(mAppConnectionHandle,
2674 EventThread::DisplayType::External, false);
2675 } else {
2676 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2677 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002678 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002679 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002680 } else {
2681 // this display is in both lists. see if something changed.
2682 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002683 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002684 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2685 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2686 if (state_binder != draw_binder) {
2687 // changing the surface is like destroying and
2688 // recreating the DisplayDevice, so we just remove it
2689 // from the drawing state, so that it get re-added
2690 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002691 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002692 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002693 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002694 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002695 mDrawingState.displays.removeItemsAt(i);
2696 dc--;
2697 // at this point we must loop to the next item
2698 continue;
2699 }
2700
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002701 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002702 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002703 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002704 }
2705 if ((state.orientation != draw[i].orientation) ||
2706 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002707 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002708 }
2709 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002710 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002711 }
2712 }
2713 }
2714 ++i;
2715 }
2716
2717 // find displays that were added
2718 // (ie: in current state but not in drawing state)
2719 for (size_t i = 0; i < cc; i++) {
2720 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2721 const DisplayDeviceState& state(curr[i]);
2722
Lloyd Pique542307f2018-10-19 13:24:08 -07002723 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002724 sp<IGraphicBufferProducer> producer;
2725 sp<IGraphicBufferProducer> bqProducer;
2726 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002727 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002728
Dominik Laskowski075d3172018-05-24 15:50:06 -07002729 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002730 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002731 // Virtual displays without a surface are dormant:
2732 // they have external state (layer stack, projection,
2733 // etc.) but no internal state (i.e. a DisplayDevice).
2734 if (state.surface != nullptr) {
2735 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002736 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002737 int width = 0;
2738 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2739 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2740 int height = 0;
2741 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2742 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2743 int intFormat = 0;
2744 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2745 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002746 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002747
Dominik Laskowski075d3172018-05-24 15:50:06 -07002748 displayId =
2749 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002750 }
2751
2752 // TODO: Plumb requested format back up to consumer
2753
2754 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002755 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002756 bqProducer, bqConsumer,
2757 state.displayName);
2758
2759 dispSurface = vds;
2760 producer = vds;
2761 }
2762 } else {
2763 ALOGE_IF(state.surface != nullptr,
2764 "adding a supported display, but rendering "
2765 "surface is provided (%p), ignoring it",
2766 state.surface.get());
2767
Dominik Laskowski075d3172018-05-24 15:50:06 -07002768 displayId = state.displayId;
2769 LOG_ALWAYS_FATAL_IF(!displayId);
2770 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002771 producer = bqProducer;
2772 }
2773
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002774 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002775 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002776 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002777 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002778 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002779 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002780 LOG_ALWAYS_FATAL_IF(!displayId);
2781
2782 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002783 if (mUseScheduler) {
2784 mScheduler->hotplugReceived(mAppConnectionHandle,
2785 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002786 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002787 } else {
2788 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2789 true);
2790 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002791 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002792 if (mUseScheduler) {
2793 mScheduler->hotplugReceived(mAppConnectionHandle,
2794 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002795 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002796 } else {
2797 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2798 true);
2799 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002800 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002801 }
2802 }
2803 }
2804 }
2805 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002806
2807 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002808}
2809
Mathias Agopian87baae12012-07-31 12:38:26 -07002810void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002811{
Dan Stoza7dde5992015-05-22 09:51:44 -07002812 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002813 mCurrentState.traverseInZOrder([](Layer* layer) {
2814 layer->notifyAvailableFrames();
2815 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002816
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002817 /*
2818 * Traversal of the children
2819 * (perform the transaction for each of them if needed)
2820 */
2821
Robert Carr720e5062018-07-30 17:45:14 -07002822 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002823 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002824 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002825 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002826 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002827
2828 const uint32_t flags = layer->doTransaction(0);
2829 if (flags & Layer::eVisibleRegion)
2830 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002831
2832 if (flags & Layer::eInputInfoChanged) {
2833 inputChanged = true;
2834 }
Robert Carr2047fae2016-11-28 14:09:09 -08002835 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002836 }
2837
2838 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002839 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002840 */
2841
Mathias Agopiane57f2922012-08-09 16:29:12 -07002842 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002843 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002844 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002845 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002846
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002847 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002848 // The transform hint might have changed for some layers
2849 // (either because a display has changed, or because a layer
2850 // as changed).
2851 //
2852 // Walk through all the layers in currentLayers,
2853 // and update their transform hint.
2854 //
2855 // If a layer is visible only on a single display, then that
2856 // display is used to calculate the hint, otherwise we use the
2857 // default display.
2858 //
2859 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2860 // the hint is set before we acquire a buffer from the surface texture.
2861 //
2862 // NOTE: layer transactions have taken place already, so we use their
2863 // drawing state. However, SurfaceFlinger's own transaction has not
2864 // happened yet, so we must use the current state layer list
2865 // (soon to become the drawing state list).
2866 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002867 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002868 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002869 bool first = true;
2870 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002871 // NOTE: we rely on the fact that layers are sorted by
2872 // layerStack first (so we don't have to traverse the list
2873 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002874 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002875 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002876 currentlayerStack = layerStack;
2877 // figure out if this layerstack is mirrored
2878 // (more than one display) if so, pick the default display,
2879 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002880 hintDisplay = nullptr;
2881 for (const auto& [token, display] : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002882 if (display->getCompositionDisplay()->belongsInOutput(layer->getLayerStack())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002883 if (hintDisplay) {
2884 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002885 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002886 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002887 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002888 }
2889 }
2890 }
2891 }
Chet Haase91d25932013-04-11 15:24:55 -07002892
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002893 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002894 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2895 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002896
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002897 // could be null when this layer is using a layerStack
2898 // that is not visible on any display. Also can occur at
2899 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002900 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002901 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002902
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002903 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002904 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002905 if (hintDisplay) {
2906 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002907 }
Robert Carr2047fae2016-11-28 14:09:09 -08002908
2909 first = false;
2910 });
Mathias Agopian84300952012-11-21 16:02:13 -08002911 }
2912
2913
Mathias Agopian3559b072012-08-15 13:46:03 -07002914 /*
2915 * Perform our own transaction if needed
2916 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002917
2918 if (mLayersAdded) {
2919 mLayersAdded = false;
2920 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002921 mVisibleRegionsDirty = true;
2922 }
2923
2924 // some layers might have been removed, so
2925 // we need to update the regions they're exposing.
2926 if (mLayersRemoved) {
2927 mLayersRemoved = false;
2928 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002929 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002930 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002931 // this layer is not visible anymore
2932 // TODO: we could traverse the tree from front to back and
2933 // compute the actual visible region
2934 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002935 Region visibleReg;
2936 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002937 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002938 }
Robert Carr2047fae2016-11-28 14:09:09 -08002939 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002940 }
2941
2942 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002943
Vishnu Nairde19f852018-12-18 16:11:53 -08002944 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002945 updateInputWindows();
2946 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002947 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002948
Riley Andrews03414a12014-07-01 14:22:59 -07002949 updateCursorAsync();
2950}
2951
Robert Carr720e5062018-07-30 17:45:14 -07002952void SurfaceFlinger::updateInputWindows() {
2953 ATRACE_CALL();
2954
Vishnu Nairde19f852018-12-18 16:11:53 -08002955 if (mInputFlinger == nullptr) {
2956 return;
2957 }
2958
Robert Carr720e5062018-07-30 17:45:14 -07002959 Vector<InputWindowInfo> inputHandles;
2960
2961 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2962 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002963 // When calculating the screen bounds we ignore the transparent region since it may
2964 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002965 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002966 }
2967 });
2968 mInputFlinger->setInputWindows(inputHandles);
2969}
2970
chaviwfbe5d9c2018-12-26 12:23:37 -08002971void SurfaceFlinger::executeInputWindowCommands() {
2972 if (!mInputFlinger) {
2973 return;
2974 }
2975
2976 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2977 if (transferTouchFocusCommand.fromToken != nullptr &&
2978 transferTouchFocusCommand.toToken != nullptr &&
2979 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2980 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2981 transferTouchFocusCommand.toToken);
2982 }
2983 }
2984
2985 mInputWindowCommands.clear();
2986}
2987
Riley Andrews03414a12014-07-01 14:22:59 -07002988void SurfaceFlinger::updateCursorAsync()
2989{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002990 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002991 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002992 continue;
2993 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002994
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002995 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2996 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002997 }
2998 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002999}
3000
chaviw61626f22018-11-15 16:26:27 -08003001void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3002 if (layer->hasReadyFrame()) {
3003 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3004 if (layer->shouldPresentNow(expectedPresentTime)) {
3005 bool ignored = false;
3006 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
3007 }
3008 }
3009 layer->releasePendingBuffer(systemTime());
3010}
3011
Mathias Agopian4fec8732012-06-29 14:12:52 -07003012void SurfaceFlinger::commitTransaction()
3013{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003014 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003015 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003016 for (const auto& l : mLayersPendingRemoval) {
3017 recordBufferingStats(l->getName().string(),
3018 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003019
3020 // We need to release the HWC layers when the Layer is removed
3021 // from the current state otherwise the HWC layer just continues
3022 // showing at its last configured state until we eventually
3023 // abandon the buffer queue.
3024 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003025 l->destroyHwcLayersForAllDisplays();
3026 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003027 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003028 }
3029 mLayersPendingRemoval.clear();
3030 }
3031
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003032 // If this transaction is part of a window animation then the next frame
3033 // we composite should be considered an animation as well.
3034 mAnimCompositionPending = mAnimTransactionPending;
3035
Mathias Agopian4fec8732012-06-29 14:12:52 -07003036 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003037 // clear the "changed" flags in current state
3038 mCurrentState.colorMatrixChanged = false;
3039
Robert Carr1f0a16a2016-10-24 16:27:39 -07003040 mDrawingState.traverseInZOrder([](Layer* layer) {
3041 layer->commitChildList();
3042 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003043 mTransactionPending = false;
3044 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003045 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003046}
3047
Lloyd Pique32cbe282018-10-19 13:09:22 -07003048void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003049 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003050 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003051 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003052
Lloyd Pique32cbe282018-10-19 13:09:22 -07003053 auto display = displayDevice->getCompositionDisplay();
3054
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003055 Region aboveOpaqueLayers;
3056 Region aboveCoveredLayers;
3057 Region dirty;
3058
Mathias Agopian87baae12012-07-31 12:38:26 -07003059 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003060
Robert Carr2047fae2016-11-28 14:09:09 -08003061 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003062 // start with the whole surface at its current location
3063 const Layer::State& s(layer->getDrawingState());
3064
Jesse Hall01e29052013-02-19 16:13:35 -08003065 // only consider the layers on the given layer stack
Lloyd Pique32cbe282018-10-19 13:09:22 -07003066 if (!display->belongsInOutput(layer->getLayerStack())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003067 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003068 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003069
Mathias Agopianab028732010-03-16 16:41:46 -07003070 /*
3071 * opaqueRegion: area of a surface that is fully opaque.
3072 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003073 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003074
3075 /*
3076 * visibleRegion: area of a surface that is visible on screen
3077 * and not fully transparent. This is essentially the layer's
3078 * footprint minus the opaque regions above it.
3079 * Areas covered by a translucent surface are considered visible.
3080 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003081 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003082
3083 /*
3084 * coveredRegion: area of a surface that is covered by all
3085 * visible regions above it (which includes the translucent areas).
3086 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003087 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003088
Jesse Halla8026d22012-09-25 13:25:04 -07003089 /*
3090 * transparentRegion: area of a surface that is hinted to be completely
3091 * transparent. This is only used to tell when the layer has no visible
3092 * non-transparent regions and can be removed from the layer list. It
3093 * does not affect the visibleRegion of this layer or any layers
3094 * beneath it. The hint may not be correct if apps don't respect the
3095 * SurfaceView restrictions (which, sadly, some don't).
3096 */
3097 Region transparentRegion;
3098
Mathias Agopianab028732010-03-16 16:41:46 -07003099
3100 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003101 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003102 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003103 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003104
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003105 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003106 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003107 if (!visibleRegion.isEmpty()) {
3108 // Remove the transparent area from the visible region
3109 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003110 if (tr.preserveRects()) {
3111 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003112 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003113 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003114 // transformation too complex, can't do the
3115 // transparent region optimization.
3116 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003117 }
Mathias Agopianab028732010-03-16 16:41:46 -07003118 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003119
Mathias Agopianab028732010-03-16 16:41:46 -07003120 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003121 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003122 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003123 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003124 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003125 // the opaque region is the layer's footprint
3126 opaqueRegion = visibleRegion;
3127 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003128 }
3129 }
3130
Robert Carre5f4f692018-01-12 13:12:28 -08003131 if (visibleRegion.isEmpty()) {
3132 layer->clearVisibilityRegions();
3133 return;
3134 }
3135
Mathias Agopianab028732010-03-16 16:41:46 -07003136 // Clip the covered region to the visible region
3137 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3138
3139 // Update aboveCoveredLayers for next (lower) layer
3140 aboveCoveredLayers.orSelf(visibleRegion);
3141
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003142 // subtract the opaque region covered by the layers above us
3143 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003144
3145 // compute this layer's dirty region
3146 if (layer->contentDirty) {
3147 // we need to invalidate the whole region
3148 dirty = visibleRegion;
3149 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003150 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003151 layer->contentDirty = false;
3152 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003153 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003154 * the exposed region consists of two components:
3155 * 1) what's VISIBLE now and was COVERED before
3156 * 2) what's EXPOSED now less what was EXPOSED before
3157 *
3158 * note that (1) is conservative, we start with the whole
3159 * visible region but only keep what used to be covered by
3160 * something -- which mean it may have been exposed.
3161 *
3162 * (2) handles areas that were not covered by anything but got
3163 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003164 */
Mathias Agopianab028732010-03-16 16:41:46 -07003165 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003166 const Region oldVisibleRegion = layer->visibleRegion;
3167 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003168 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3169 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003170 }
3171 dirty.subtractSelf(aboveOpaqueLayers);
3172
3173 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003174 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003175
Mathias Agopianab028732010-03-16 16:41:46 -07003176 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003177 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003178
Jesse Halla8026d22012-09-25 13:25:04 -07003179 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003180 layer->setVisibleRegion(visibleRegion);
3181 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003182 layer->setVisibleNonTransparentRegion(
3183 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003184 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003185
Mathias Agopian87baae12012-07-31 12:38:26 -07003186 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003187}
3188
Chia-I Wuab0c3192017-08-01 11:29:00 -07003189void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003190 for (const auto& [token, displayDevice] : mDisplays) {
3191 auto display = displayDevice->getCompositionDisplay();
3192 if (display->belongsInOutput(layer->getLayerStack())) {
3193 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003194 }
3195 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003196}
3197
Dan Stoza6b9454d2014-11-07 16:00:59 -08003198bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003199{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003200 ALOGV("handlePageFlip");
3201
Brian Andersond6927fb2016-07-23 23:37:30 -07003202 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003203
Mathias Agopian4fec8732012-06-29 14:12:52 -07003204 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003205 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003206 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003207
3208 // Store the set of layers that need updates. This set must not change as
3209 // buffers are being latched, as this could result in a deadlock.
3210 // Example: Two producers share the same command stream and:
3211 // 1.) Layer 0 is latched
3212 // 2.) Layer 0 gets a new frame
3213 // 2.) Layer 1 gets a new frame
3214 // 3.) Layer 1 is latched.
3215 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3216 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003217 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003218 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003219 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003220 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3221 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003222 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003223 } else {
3224 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003225 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003226 } else {
3227 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003228 }
Robert Carr2047fae2016-11-28 14:09:09 -08003229 });
3230
Lloyd Piquef2c79392018-12-20 16:23:33 -08003231 if (!mLayersWithQueuedFrames.empty()) {
3232 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3233 // writes to Layer current state. See also b/119481871
3234 Mutex::Autolock lock(mStateLock);
3235
3236 for (auto& layer : mLayersWithQueuedFrames) {
3237 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3238 layer->useSurfaceDamage();
3239 invalidateLayerStack(layer, dirty);
3240 if (layer->isBufferLatched()) {
3241 newDataLatched = true;
3242 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003243 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003244 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003245
Alec Mouri86770e52018-09-24 22:40:58 +00003246 // Clear the renderengine fence here...
3247 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3248 // clear instead of sp::clear.
3249 getBE().flushFence = Fence::NO_FENCE;
3250
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003251 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003252
Vishnu Nairde19f852018-12-18 16:11:53 -08003253 if (visibleRegions) {
3254 // Update input window info if the layer receives its first buffer.
3255 updateInputWindows();
3256 }
3257
Dan Stoza6b9454d2014-11-07 16:00:59 -08003258 // If we will need to wake up at some time in the future to deal with a
3259 // queued frame that shouldn't be displayed during this vsync period, wake
3260 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003261 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003262 signalLayerUpdate();
3263 }
3264
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003265 // enter boot animation on first buffer latch
3266 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3267 ALOGI("Enter boot animation");
3268 mBootStage = BootStage::BOOTANIMATION;
3269 }
3270
Dan Stoza6b9454d2014-11-07 16:00:59 -08003271 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003272 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003273}
3274
Mathias Agopianad456f92011-01-13 17:53:01 -08003275void SurfaceFlinger::invalidateHwcGeometry()
3276{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003277 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003278}
3279
Lloyd Pique32cbe282018-10-19 13:09:22 -07003280void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003281 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003282 auto display = displayDevice->getCompositionDisplay();
3283
Dan Stoza71433162014-02-04 16:22:36 -08003284 // We only need to actually compose the display if:
3285 // 1) It is being handled by hardware composer, which may need this to
3286 // keep its virtual display state machine in sync, or
3287 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003288 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003289 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003290 return;
3291 }
3292
Dan Stoza9e56aa02015-11-02 13:00:03 -08003293 ALOGV("doDisplayComposition");
Lloyd Pique32cbe282018-10-19 13:09:22 -07003294 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003295
3296 // swap buffers (presentation)
Lloyd Pique31cb2942018-10-19 17:23:03 -07003297 display->getRenderSurface()->queueBuffer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003298}
3299
Lloyd Pique32cbe282018-10-19 13:09:22 -07003300bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003301 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003302
Lloyd Pique32cbe282018-10-19 13:09:22 -07003303 auto display = displayDevice->getCompositionDisplay();
3304 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003305 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003306
3307 const Region bounds(displayState.bounds);
3308 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003309 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003310 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003311
Peiyong Lind3788632018-09-18 16:01:31 -07003312 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003313 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003314
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003315 // Framebuffer will live in this scope for GPU composition.
3316 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
3317
Dan Stoza9e56aa02015-11-02 13:00:03 -08003318 if (hasClientComposition) {
3319 ALOGV("hasClientComposition");
3320
Lloyd Pique31cb2942018-10-19 17:23:03 -07003321 sp<GraphicBuffer> buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003322
3323 if (buf == nullptr) {
3324 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3325 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003326 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003327 return false;
3328 }
3329
3330 // Bind the framebuffer in this scope.
3331 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3332 buf->getNativeBuffer());
3333
3334 if (fbo->getStatus() != NO_ERROR) {
3335 ALOGW("Binding buffer for display [%s] failed with status: %d",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003336 displayDevice->getDisplayName().c_str(), fbo->getStatus());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003337 return false;
3338 }
3339
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003340 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003341 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003342 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003343 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003344 }
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003345 getRenderEngine().setOutputDataSpace(outputDataspace);
3346 getRenderEngine().setDisplayMaxLuminance(
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003347 profile->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003348
Lloyd Pique441d5042018-10-18 16:49:51 -07003349 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003350 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003351 getHwComposer()
3352 .hasDisplayCapability(displayId,
3353 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003354
Peiyong Lind3788632018-09-18 16:01:31 -07003355 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003356 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3357 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003358 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003359 }
3360
Lloyd Pique31cb2942018-10-19 17:23:03 -07003361 display->getRenderSurface()->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003362
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003363 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003364 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003365 // when using overlays, we assume a fully transparent framebuffer
3366 // NOTE: we could reduce how much we need to clear, for instance
3367 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003368 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003369 // We'll revisit later if needed.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003370 getRenderEngine().clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003371 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003372 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003373 // we're left with the letterbox region
3374 // (common case is that letterbox ends-up being empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003375 const Region letterbox = bounds.subtract(displayState.scissor);
Mathias Agopian766dc492012-10-30 18:08:06 -07003376
3377 // compute the area to clear
Lloyd Pique32cbe282018-10-19 13:09:22 -07003378 const Region region = displayState.undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003379
Mathias Agopianb9494d52012-04-18 02:28:45 -07003380 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003381 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003382 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003383 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003384 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003385 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003386
Lloyd Pique32cbe282018-10-19 13:09:22 -07003387 const Rect& bounds = displayState.bounds;
3388 const Rect& scissor = displayState.scissor;
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003389 if (scissor != bounds) {
3390 // scissor doesn't match the screen's dimensions, so we
3391 // need to clear everything outside of it and enable
3392 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003393
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003394 // enable scissor for this frame
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003395 getRenderEngine().setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003396 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003397 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003398
Mathias Agopian85d751c2012-08-29 16:59:24 -07003399 /*
3400 * and then, render the layers targeted at the framebuffer
3401 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003402
Dan Stoza9e56aa02015-11-02 13:00:03 -08003403 ALOGV("Rendering client layers");
Lloyd Pique32cbe282018-10-19 13:09:22 -07003404 const ui::Transform& displayTransform = displayState.transform;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003405 bool firstLayer = true;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003406 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003407 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003408 displayTransform.transform(layer->visibleRegion)));
3409 ALOGV("Layer: %s", layer->getName().string());
3410 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003411 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003412 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003413 case HWC2::Composition::Cursor:
3414 case HWC2::Composition::Device:
3415 case HWC2::Composition::Sideband:
3416 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003417 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003418 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003419 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003420 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003421 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003422 // never clear the very first layer since we're
3423 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003424 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003425 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003426 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003427 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003428 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003429 if (layer->hasColorTransform()) {
3430 mat4 tmpMatrix;
3431 if (applyColorMatrix) {
3432 tmpMatrix = mDrawingState.colorMatrix;
3433 }
3434 tmpMatrix *= layer->getColorTransform();
Peiyong Lind3788632018-09-18 16:01:31 -07003435 getRenderEngine().setColorTransform(tmpMatrix);
3436 } else {
3437 getRenderEngine().setColorTransform(colorMatrix);
3438 }
David Sodmanc1498e62018-09-12 14:36:26 -07003439 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003440 break;
3441 }
3442 default:
3443 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003444 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003445 } else {
3446 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003447 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003448 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003449 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003450
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003451 // Perform some cleanup steps if we used client composition.
3452 if (hasClientComposition) {
3453 getRenderEngine().setColorTransform(mat4());
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003454 getRenderEngine().disableScissor();
Lloyd Pique31cb2942018-10-19 17:23:03 -07003455 display->getRenderSurface()->finishBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003456 // Clear out error flags here so that we don't wait until next
3457 // composition to log.
3458 getRenderEngine().checkErrors();
3459 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003460 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003461}
3462
Chia-I Wu28e3a252018-09-07 12:05:02 -07003463void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003464 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003465 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003466}
3467
Dan Stoza7d89d062015-04-30 13:29:25 -07003468status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003469 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003470 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003471 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003472 const sp<Layer>& parent,
3473 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003474{
Dan Stoza7d89d062015-04-30 13:29:25 -07003475 // add this layer to the current state list
3476 {
3477 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003478 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003479 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3480 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003481 return NO_MEMORY;
3482 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003483 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003484 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003485 } else if (parent == nullptr) {
3486 lbc->onRemovedFromCurrentState();
3487 } else if (parent->isRemovedFromCurrentState()) {
3488 parent->addChild(lbc);
3489 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003490 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003491 parent->addChild(lbc);
3492 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003493
Yiwei Zhang243b3782018-05-15 17:40:04 -07003494 if (gbc != nullptr) {
3495 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3496 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3497 mMaxGraphicBufferProducerListSize,
3498 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3499 mGraphicBufferProducerList.size(),
3500 mMaxGraphicBufferProducerListSize, mNumLayers);
3501 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003502 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003503 }
3504
Mathias Agopian96f08192010-06-02 23:28:45 -07003505 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003506 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003507
Dan Stoza7d89d062015-04-30 13:29:25 -07003508 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003509}
3510
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003511uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003512 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003513}
3514
Mathias Agopian3f844832013-08-07 21:24:32 -07003515uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003516 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003517}
3518
Mathias Agopian3f844832013-08-07 21:24:32 -07003519uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003520 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003521}
3522
3523uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003524 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003525 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003526 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003527 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003528 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003529 }
3530 return old;
3531}
3532
Marissa Wall713b63f2018-10-17 15:42:43 -07003533bool SurfaceFlinger::flushTransactionQueues() {
3534 Mutex::Autolock _l(mStateLock);
3535 auto it = mTransactionQueues.begin();
3536 while (it != mTransactionQueues.end()) {
3537 auto& [applyToken, transactionQueue] = *it;
3538
3539 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003540 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3541 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003542 break;
3543 }
chaviw273171b2018-12-26 11:46:30 -08003544 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003545 transactionQueue.pop();
3546 }
3547
3548 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3549 }
3550 return mTransactionQueues.empty();
3551}
3552
chaviwca27f252018-02-06 16:46:39 -08003553bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3554 for (const ComposerState& state : states) {
3555 // Here we need to check that the interface we're given is indeed
3556 // one of our own. A malicious client could give us a nullptr
3557 // IInterface, or one of its own or even one of our own but a
3558 // different type. All these situations would cause us to crash.
3559 if (state.client == nullptr) {
3560 return true;
3561 }
3562
3563 sp<IBinder> binder = IInterface::asBinder(state.client);
3564 if (binder == nullptr) {
3565 return true;
3566 }
3567
3568 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3569 return true;
3570 }
3571 }
3572 return false;
3573}
3574
Marissa Wall17b4e452018-12-26 16:32:34 -08003575bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3576 const Vector<ComposerState>& states) {
3577 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3578 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3579 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3580 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3581 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3582 return false;
3583 }
3584
Marissa Wall713b63f2018-10-17 15:42:43 -07003585 for (const ComposerState& state : states) {
3586 const layer_state_t& s = state.state;
3587 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3588 continue;
3589 }
3590 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003591 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003592 }
3593 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003594 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003595}
3596
3597void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3598 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003599 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003600 const InputWindowCommands& inputWindowCommands,
3601 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003602 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003603 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003604
chaviwca27f252018-02-06 16:46:39 -08003605 if (containsAnyInvalidClientState(states)) {
3606 return;
3607 }
3608
Marissa Wall713b63f2018-10-17 15:42:43 -07003609 // If its TransactionQueue already has a pending TransactionState or if it is pending
3610 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003611 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3612 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003613 setTransactionFlags(eTransactionNeeded);
3614 return;
3615 }
3616
chaviw273171b2018-12-26 11:46:30 -08003617 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003618}
3619
3620void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003621 const Vector<DisplayState>& displays, uint32_t flags,
3622 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003623 uint32_t transactionFlags = 0;
3624
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003625 if (flags & eAnimation) {
3626 // For window updates that are part of an animation we must wait for
3627 // previous animation "frames" to be handled.
3628 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003629 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003630 if (CC_UNLIKELY(err != NO_ERROR)) {
3631 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003632 // caller after a few seconds.
3633 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3634 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003635 mAnimTransactionPending = false;
3636 break;
3637 }
3638 }
3639 }
3640
chaviwca27f252018-02-06 16:46:39 -08003641 for (const DisplayState& display : displays) {
3642 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003643 }
3644
Marissa Walle2ffb422018-10-12 11:33:52 -07003645 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003646 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003647 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003648 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003649 // If the state doesn't require a traversal and there are callbacks, send them now
3650 if (!(clientStateFlags & eTraversalNeeded)) {
3651 mTransactionCompletedThread.sendCallbacks();
3652 }
3653 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003654
chaviw273171b2018-12-26 11:46:30 -08003655 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3656
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003657 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3658 // anyway. This can be used as a flush mechanism for previous async transactions.
3659 // Empty animation transaction can be used to simulate back-pressure, so also force a
3660 // transaction for empty animation transactions.
3661 if (transactionFlags == 0 &&
3662 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003663 transactionFlags = eTransactionNeeded;
3664 }
3665
Mathias Agopian386aa982011-11-07 21:58:03 -08003666 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003667 if (mInterceptor->isEnabled()) {
3668 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003669 }
Irvel468051e2016-06-13 16:44:44 -07003670
Mathias Agopian386aa982011-11-07 21:58:03 -08003671 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003672 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3673 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003674 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003675
3676 // if this is a synchronous transaction, wait for it to take effect
3677 // before returning.
3678 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003679 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003680 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003681 if (flags & eAnimation) {
3682 mAnimTransactionPending = true;
3683 }
3684 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003685 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3686 if (CC_UNLIKELY(err != NO_ERROR)) {
3687 // just in case something goes wrong in SF, return to the
3688 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003689 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3690 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003691 break;
3692 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003693 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003694 }
3695}
3696
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003697uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3698 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3699 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003700
Mathias Agopiane57f2922012-08-09 16:29:12 -07003701 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003702 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3703
3704 const uint32_t what = s.what;
3705 if (what & DisplayState::eSurfaceChanged) {
3706 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3707 state.surface = s.surface;
3708 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003709 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003710 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003711 if (what & DisplayState::eLayerStackChanged) {
3712 if (state.layerStack != s.layerStack) {
3713 state.layerStack = s.layerStack;
3714 flags |= eDisplayTransactionNeeded;
3715 }
3716 }
3717 if (what & DisplayState::eDisplayProjectionChanged) {
3718 if (state.orientation != s.orientation) {
3719 state.orientation = s.orientation;
3720 flags |= eDisplayTransactionNeeded;
3721 }
3722 if (state.frame != s.frame) {
3723 state.frame = s.frame;
3724 flags |= eDisplayTransactionNeeded;
3725 }
3726 if (state.viewport != s.viewport) {
3727 state.viewport = s.viewport;
3728 flags |= eDisplayTransactionNeeded;
3729 }
3730 }
3731 if (what & DisplayState::eDisplaySizeChanged) {
3732 if (state.width != s.width) {
3733 state.width = s.width;
3734 flags |= eDisplayTransactionNeeded;
3735 }
3736 if (state.height != s.height) {
3737 state.height = s.height;
3738 flags |= eDisplayTransactionNeeded;
3739 }
3740 }
3741
Mathias Agopiane57f2922012-08-09 16:29:12 -07003742 return flags;
3743}
3744
Robert Carrd4ae7f32018-06-07 16:10:57 -07003745bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3746 IPCThreadState* ipc = IPCThreadState::self();
3747 const int pid = ipc->getCallingPid();
3748 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003749 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003750 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003751 return false;
3752 }
3753 return true;
3754}
3755
chaviwca27f252018-02-06 16:46:39 -08003756uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3757 const layer_state_t& s = composerState.state;
3758 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3759
Mathias Agopian13127d82013-03-05 17:47:11 -08003760 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003761 if (layer == nullptr) {
3762 return 0;
3763 }
3764
chaviw8b3871a2017-11-01 17:41:01 -07003765 uint32_t flags = 0;
3766
Garfield Tan8a3083e2018-12-03 13:21:07 -08003767 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003768 bool geometryAppliesWithResize =
3769 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003770
3771 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3772 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003773 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003774 layer->pushPendingState();
3775 }
3776
chaviw8b3871a2017-11-01 17:41:01 -07003777 if (what & layer_state_t::ePositionChanged) {
3778 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3779 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003780 }
chaviw8b3871a2017-11-01 17:41:01 -07003781 }
3782 if (what & layer_state_t::eLayerChanged) {
3783 // NOTE: index needs to be calculated before we update the state
3784 const auto& p = layer->getParent();
3785 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003786 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003787 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003788 mCurrentState.layersSortedByZ.removeAt(idx);
3789 mCurrentState.layersSortedByZ.add(layer);
3790 // we need traversal (state changed)
3791 // AND transaction (list changed)
3792 flags |= eTransactionNeeded|eTraversalNeeded;
3793 }
chaviw8b3871a2017-11-01 17:41:01 -07003794 } else {
3795 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003796 flags |= eTransactionNeeded|eTraversalNeeded;
3797 }
3798 }
chaviw8b3871a2017-11-01 17:41:01 -07003799 }
3800 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003801 // NOTE: index needs to be calculated before we update the state
3802 const auto& p = layer->getParent();
3803 if (p == nullptr) {
3804 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3805 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3806 mCurrentState.layersSortedByZ.removeAt(idx);
3807 mCurrentState.layersSortedByZ.add(layer);
3808 // we need traversal (state changed)
3809 // AND transaction (list changed)
3810 flags |= eTransactionNeeded|eTraversalNeeded;
3811 }
3812 } else {
3813 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3814 flags |= eTransactionNeeded|eTraversalNeeded;
3815 }
chaviw8b3871a2017-11-01 17:41:01 -07003816 }
3817 }
3818 if (what & layer_state_t::eSizeChanged) {
3819 if (layer->setSize(s.w, s.h)) {
3820 flags |= eTraversalNeeded;
3821 }
3822 }
3823 if (what & layer_state_t::eAlphaChanged) {
3824 if (layer->setAlpha(s.alpha))
3825 flags |= eTraversalNeeded;
3826 }
3827 if (what & layer_state_t::eColorChanged) {
3828 if (layer->setColor(s.color))
3829 flags |= eTraversalNeeded;
3830 }
Peiyong Lind3788632018-09-18 16:01:31 -07003831 if (what & layer_state_t::eColorTransformChanged) {
3832 if (layer->setColorTransform(s.colorTransform)) {
3833 flags |= eTraversalNeeded;
3834 }
3835 }
chaviw8b3871a2017-11-01 17:41:01 -07003836 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003837 // TODO: b/109894387
3838 //
3839 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3840 // rotation. To see the problem observe that if we have a square parent, and a child
3841 // of the same size, then we rotate the child 45 degrees around it's center, the child
3842 // must now be cropped to a non rectangular 8 sided region.
3843 //
3844 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3845 // private API, and the WindowManager only uses rotation in one case, which is on a top
3846 // level layer in which cropping is not an issue.
3847 //
3848 // However given that abuse of rotation matrices could lead to surfaces extending outside
3849 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3850 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3851 // transformations.
3852 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003853 flags |= eTraversalNeeded;
3854 }
3855 if (what & layer_state_t::eTransparentRegionChanged) {
3856 if (layer->setTransparentRegionHint(s.transparentRegion))
3857 flags |= eTraversalNeeded;
3858 }
3859 if (what & layer_state_t::eFlagsChanged) {
3860 if (layer->setFlags(s.flags, s.mask))
3861 flags |= eTraversalNeeded;
3862 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003863 if (what & layer_state_t::eCropChanged_legacy) {
3864 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003865 flags |= eTraversalNeeded;
3866 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003867 if (what & layer_state_t::eCornerRadiusChanged) {
3868 if (layer->setCornerRadius(s.cornerRadius))
3869 flags |= eTraversalNeeded;
3870 }
chaviw8b3871a2017-11-01 17:41:01 -07003871 if (what & layer_state_t::eLayerStackChanged) {
3872 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3873 // We only allow setting layer stacks for top level layers,
3874 // everything else inherits layer stack from its parent.
3875 if (layer->hasParent()) {
3876 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3877 layer->getName().string());
3878 } else if (idx < 0) {
3879 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3880 "that also does not appear in the top level layer list. Something"
3881 " has gone wrong.", layer->getName().string());
3882 } else if (layer->setLayerStack(s.layerStack)) {
3883 mCurrentState.layersSortedByZ.removeAt(idx);
3884 mCurrentState.layersSortedByZ.add(layer);
3885 // we need traversal (state changed)
3886 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003887 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003888 }
3889 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003890 if (what & layer_state_t::eDeferTransaction_legacy) {
3891 if (s.barrierHandle_legacy != nullptr) {
3892 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3893 } else if (s.barrierGbp_legacy != nullptr) {
3894 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003895 if (authenticateSurfaceTextureLocked(gbp)) {
3896 const auto& otherLayer =
3897 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003898 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003899 } else {
3900 ALOGE("Attempt to defer transaction to to an"
3901 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003902 }
3903 }
chaviw8b3871a2017-11-01 17:41:01 -07003904 // We don't trigger a traversal here because if no other state is
3905 // changed, we don't want this to cause any more work
3906 }
3907 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003908 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003909 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003910 if (!hadParent) {
3911 mCurrentState.layersSortedByZ.remove(layer);
3912 }
chaviw8b3871a2017-11-01 17:41:01 -07003913 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003914 }
chaviw8b3871a2017-11-01 17:41:01 -07003915 }
3916 if (what & layer_state_t::eReparentChildren) {
3917 if (layer->reparentChildren(s.reparentHandle)) {
3918 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003919 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003920 }
chaviw8b3871a2017-11-01 17:41:01 -07003921 if (what & layer_state_t::eDetachChildren) {
3922 layer->detachChildren();
3923 }
3924 if (what & layer_state_t::eOverrideScalingModeChanged) {
3925 layer->setOverrideScalingMode(s.overrideScalingMode);
3926 // We don't trigger a traversal here because if no other state is
3927 // changed, we don't want this to cause any more work
3928 }
Marissa Wall61c58622018-07-18 10:12:20 -07003929 if (what & layer_state_t::eTransformChanged) {
3930 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3931 }
3932 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3933 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3934 flags |= eTraversalNeeded;
3935 }
3936 if (what & layer_state_t::eCropChanged) {
3937 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3938 }
Marissa Wall861616d2018-10-22 12:52:23 -07003939 if (what & layer_state_t::eFrameChanged) {
3940 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3941 }
Marissa Wall61c58622018-07-18 10:12:20 -07003942 if (what & layer_state_t::eBufferChanged) {
3943 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3944 }
3945 if (what & layer_state_t::eAcquireFenceChanged) {
3946 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3947 }
3948 if (what & layer_state_t::eDataspaceChanged) {
3949 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3950 }
3951 if (what & layer_state_t::eHdrMetadataChanged) {
3952 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3953 }
3954 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3955 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3956 }
3957 if (what & layer_state_t::eApiChanged) {
3958 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3959 }
3960 if (what & layer_state_t::eSidebandStreamChanged) {
3961 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3962 }
Robert Carr720e5062018-07-30 17:45:14 -07003963 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003964 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
3965 layer->setInputInfo(s.inputInfo);
3966 flags |= eTraversalNeeded;
3967 } else {
3968 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3969 }
Robert Carr720e5062018-07-30 17:45:14 -07003970 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003971 std::vector<sp<CallbackHandle>> callbackHandles;
3972 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3973 mTransactionCompletedThread.run();
3974 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3975 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3976 }
3977 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003978 if (what & layer_state_t::eCachedBufferChanged) {
3979 sp<GraphicBuffer> buffer =
3980 mBufferStateLayerCache.get(s.cachedBuffer.token, s.cachedBuffer.bufferId);
3981 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
3982 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003983 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3984 // Do not put anything that updates layer state or modifies flags after
3985 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003986 return flags;
3987}
3988
chaviw273171b2018-12-26 11:46:30 -08003989uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3990 uint32_t flags = 0;
3991 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3992 flags |= eTraversalNeeded;
3993 }
3994
3995 mInputWindowCommands.merge(inputWindowCommands);
3996 return flags;
3997}
3998
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003999status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07004000 const String8& name,
4001 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004002 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07004003 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05004004 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004005{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004006 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004007 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004008 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004009 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004010 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004011
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004012 status_t result = NO_ERROR;
4013
4014 sp<Layer> layer;
4015
Cody Northropbc755282017-03-31 12:00:08 -06004016 String8 uniqueName = getUniqueLayerName(name);
4017
Mathias Agopian3165cc22012-08-08 19:42:09 -07004018 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004019 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004020 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4021 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004022
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004023 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004024 case ISurfaceComposerClient::eFXSurfaceBufferState:
4025 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4026 break;
chaviw13fdc492017-06-27 12:40:18 -07004027 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004028 // check if buffer size is set for color layer.
4029 if (w > 0 || h > 0) {
4030 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4031 int(w), int(h));
4032 return BAD_VALUE;
4033 }
4034
chaviw13fdc492017-06-27 12:40:18 -07004035 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004036 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004037 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004038 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004039 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004040 // check if buffer size is set for container layer.
4041 if (w > 0 || h > 0) {
4042 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4043 int(w), int(h));
4044 return BAD_VALUE;
4045 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004046 result = createContainerLayer(client,
4047 uniqueName, w, h, flags,
4048 handle, &layer);
4049 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004050 default:
4051 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004052 break;
4053 }
4054
Dan Stoza7d89d062015-04-30 13:29:25 -07004055 if (result != NO_ERROR) {
4056 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004057 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004058
Chia-I Wuab0c3192017-08-01 11:29:00 -07004059 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4060 // TODO b/64227542
4061 if (windowType == 441731) {
4062 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
4063 layer->setPrimaryDisplayOnly();
4064 }
4065
Albert Chaulk479c60c2017-01-27 14:21:34 -05004066 layer->setInfo(windowType, ownerUid);
4067
Robert Carrb89ea9d2018-12-10 13:01:14 -08004068 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4069 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4070 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004071 if (result != NO_ERROR) {
4072 return result;
4073 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004074 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004075
4076 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004077 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004078}
4079
Cody Northropbc755282017-03-31 12:00:08 -06004080String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4081{
4082 bool matchFound = true;
4083 uint32_t dupeCounter = 0;
4084
4085 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4086 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4087
Dan Stoza436ccf32018-06-21 12:10:12 -07004088 // Grab the state lock since we're accessing mCurrentState
4089 Mutex::Autolock lock(mStateLock);
4090
Cody Northropbc755282017-03-31 12:00:08 -06004091 // Loop over layers until we're sure there is no matching name
4092 while (matchFound) {
4093 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004094 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004095 if (layer->getName() == uniqueName) {
4096 matchFound = true;
4097 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4098 }
4099 });
4100 }
4101
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004102 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4103 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004104
4105 return uniqueName;
4106}
4107
Marissa Wallfd668622018-05-10 10:21:13 -07004108status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4109 uint32_t w, uint32_t h, uint32_t flags,
4110 PixelFormat& format, sp<IBinder>* handle,
4111 sp<IGraphicBufferProducer>* gbp,
4112 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004113 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004114 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004115 case PIXEL_FORMAT_TRANSPARENT:
4116 case PIXEL_FORMAT_TRANSLUCENT:
4117 format = PIXEL_FORMAT_RGBA_8888;
4118 break;
4119 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004120 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004121 break;
4122 }
4123
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004124 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004125 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004126 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004127 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004128 *handle = layer->getHandle();
4129 *gbp = layer->getProducer();
4130 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004131 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004132
Marissa Wallfd668622018-05-10 10:21:13 -07004133 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004134 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004135}
4136
Marissa Wall61c58622018-07-18 10:12:20 -07004137status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4138 uint32_t w, uint32_t h, uint32_t flags,
4139 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004140 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004141 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004142 *handle = layer->getHandle();
4143 *outLayer = layer;
4144
4145 return NO_ERROR;
4146}
4147
chaviw13fdc492017-06-27 12:40:18 -07004148status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004149 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004150 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004151{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004152 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004153 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004154 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004155}
4156
Robert Carr6b3f6c52018-08-13 13:05:17 -07004157status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4158 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4159 sp<IBinder>* handle, sp<Layer>* outLayer)
4160{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004161 *outLayer =
4162 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004163 *handle = (*outLayer)->getHandle();
4164 return NO_ERROR;
4165}
4166
4167
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004168void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004169 mLayersPendingRemoval.add(layer);
4170 mLayersRemoved = true;
4171 setTransactionFlags(eTransactionNeeded);
4172}
4173
Robert Carr695d5282018-12-18 15:27:58 -08004174void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004175{
Robert Carr2e102c92018-10-23 12:11:15 -07004176 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004177 // If a layer has a parent, we allow it to out-live it's handle
4178 // with the idea that the parent holds a reference and will eventually
4179 // be cleaned up. However no one cleans up the top-level so we do so
4180 // here.
4181 if (layer->getParent() == nullptr) {
4182 mCurrentState.layersSortedByZ.remove(layer);
4183 }
4184 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004185 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004186}
4187
Mathias Agopianb60314a2012-04-10 22:09:54 -07004188// ---------------------------------------------------------------------------
4189
Andy McFadden13a082e2012-08-24 10:16:42 -07004190void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004191 const auto display = getDefaultDisplayDeviceLocked();
4192 if (!display) return;
4193
4194 const sp<IBinder> token = display->getDisplayToken().promote();
4195 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004196
Jesse Hall01e29052013-02-19 16:13:35 -08004197 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004198 Vector<ComposerState> state;
4199 Vector<DisplayState> displays;
4200 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004201 d.what = DisplayState::eDisplayProjectionChanged |
4202 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004203 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004204 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004205 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004206 d.frame.makeInvalid();
4207 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004208 d.width = 0;
4209 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004210 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004211 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004212
Dominik Laskowskie9774092018-12-11 10:04:24 -08004213 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004214
Dominik Laskowski83b88212018-12-11 13:34:06 -08004215 const nsecs_t vsyncPeriod = getVsyncPeriod();
4216 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004217
Brian Andersond0010582017-03-07 13:20:31 -08004218 // Use phase of 0 since phase is not known.
4219 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004220 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004221 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004222}
4223
4224void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004225 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004226 postMessageAsync(
4227 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004228}
4229
Dominik Laskowskie9774092018-12-11 10:04:24 -08004230void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004231 if (display->isVirtual()) {
4232 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004233 return;
4234 }
4235
Dominik Laskowski075d3172018-05-24 15:50:06 -07004236 const auto displayId = display->getId();
4237 LOG_ALWAYS_FATAL_IF(!displayId);
4238
Dominik Laskowski34157762018-10-31 13:07:19 -07004239 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004240
4241 int currentMode = display->getPowerMode();
4242 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004243 return;
4244 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004245
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004246 display->setPowerMode(mode);
4247
Lloyd Pique4dccc412018-01-22 17:21:36 -08004248 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004249 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004250 }
4251
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004252 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004253 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004254 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004255 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004256 if (mUseScheduler) {
4257 mScheduler->onScreenAcquired(mAppConnectionHandle);
4258 } else {
4259 mEventThread->onScreenAcquired();
4260 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004261 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004262 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004263
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004264 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004265 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004266 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004267
4268 struct sched_param param = {0};
4269 param.sched_priority = 1;
4270 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4271 ALOGW("Couldn't set SCHED_FIFO on display on");
4272 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004273 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004274 // Turn off the display
4275 struct sched_param param = {0};
4276 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4277 ALOGW("Couldn't set SCHED_OTHER on display off");
4278 }
4279
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004280 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004281 if (mUseScheduler) {
4282 mScheduler->disableHardwareVsync(true);
4283 } else {
4284 disableHardwareVsync(true); // also cancels any in-progress resync
4285 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004286 if (mUseScheduler) {
4287 mScheduler->onScreenReleased(mAppConnectionHandle);
4288 } else {
4289 mEventThread->onScreenReleased();
4290 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004291 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004292
Dominik Laskowski075d3172018-05-24 15:50:06 -07004293 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004294 mVisibleRegionsDirty = true;
4295 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004296 } else if (mode == HWC_POWER_MODE_DOZE ||
4297 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004298 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004299 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004300 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004301 if (mUseScheduler) {
4302 mScheduler->onScreenAcquired(mAppConnectionHandle);
4303 } else {
4304 mEventThread->onScreenAcquired();
4305 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004306 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004307 }
4308 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4309 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004310 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004311 if (mUseScheduler) {
4312 mScheduler->disableHardwareVsync(true);
4313 } else {
4314 disableHardwareVsync(true); // also cancels any in-progress resync
4315 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004316 if (mUseScheduler) {
4317 mScheduler->onScreenReleased(mAppConnectionHandle);
4318 } else {
4319 mEventThread->onScreenReleased();
4320 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004321 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004322 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004323 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004324 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004325 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004326 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004327
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004328 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004329 mTimeStats->setPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004330 }
4331
Dominik Laskowski34157762018-10-31 13:07:19 -07004332 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004333}
4334
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004335void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004336 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004337 const auto display = getDisplayDevice(displayToken);
4338 if (!display) {
4339 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4340 displayToken.get());
4341 } else if (display->isVirtual()) {
4342 ALOGW("Attempt to set power mode %d for virtual display", mode);
4343 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004344 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004345 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004346 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004347}
4348
4349// ---------------------------------------------------------------------------
4350
Lloyd Pique755e3192018-01-31 16:46:15 -08004351status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4352 NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004353 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004354
Mathias Agopianbd115332013-04-18 16:41:04 -07004355 IPCThreadState* ipc = IPCThreadState::self();
4356 const int pid = ipc->getCallingPid();
4357 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004358
Mathias Agopianbd115332013-04-18 16:41:04 -07004359 if ((uid != AID_SHELL) &&
4360 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004361 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4362 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004363 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004364 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004365 // (this would indicate SF is stuck, but we want to be able to
4366 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004367 status_t err = mStateLock.timedLock(s2ns(1));
4368 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004369 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004370 StringAppendF(&result,
4371 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4372 "(no locks held)\n",
4373 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004374 }
4375
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004376 bool dumpAll = true;
4377 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004378 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004379
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004380 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004381 if ((index < numArgs) &&
4382 (args[index] == String16("--list"))) {
4383 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004384 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004385 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004386 }
4387
4388 if ((index < numArgs) &&
4389 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004390 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004391 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004392 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004393 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004394
4395 if ((index < numArgs) &&
4396 (args[index] == String16("--latency-clear"))) {
4397 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004398 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004399 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004400 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004401
4402 if ((index < numArgs) &&
4403 (args[index] == String16("--dispsync"))) {
4404 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004405 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004406 dumpAll = false;
4407 }
Dan Stozab90cf072015-03-05 11:05:59 -08004408
4409 if ((index < numArgs) &&
4410 (args[index] == String16("--static-screen"))) {
4411 index++;
4412 dumpStaticScreenStats(result);
4413 dumpAll = false;
4414 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004415
4416 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004417 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004418 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004419 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004420 dumpAll = false;
4421 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004422
4423 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4424 index++;
4425 dumpWideColorInfo(result);
4426 dumpAll = false;
4427 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004428
4429 if ((index < numArgs) &&
4430 (args[index] == String16("--enable-layer-stats"))) {
4431 index++;
4432 mLayerStats.enable();
4433 dumpAll = false;
4434 }
4435
4436 if ((index < numArgs) &&
4437 (args[index] == String16("--disable-layer-stats"))) {
4438 index++;
4439 mLayerStats.disable();
4440 dumpAll = false;
4441 }
4442
4443 if ((index < numArgs) &&
4444 (args[index] == String16("--clear-layer-stats"))) {
4445 index++;
4446 mLayerStats.clear();
4447 dumpAll = false;
4448 }
4449
4450 if ((index < numArgs) &&
4451 (args[index] == String16("--dump-layer-stats"))) {
4452 index++;
4453 mLayerStats.dump(result);
4454 dumpAll = false;
4455 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004456
4457 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004458 (args[index] == String16("--frame-composition"))) {
4459 index++;
4460 dumpFrameCompositionInfo(result);
4461 dumpAll = false;
4462 }
4463
4464 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004465 (args[index] == String16("--display-identification"))) {
4466 index++;
4467 dumpDisplayIdentificationData(result);
4468 dumpAll = false;
4469 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004470
4471 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4472 index++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004473 mTimeStats->parseArgs(asProto, args, index, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004474 dumpAll = false;
4475 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004476 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004477
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004478 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004479 if (asProto) {
4480 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4481 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4482 } else {
4483 dumpAllLocked(args, index, result);
4484 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004485 }
4486
Mathias Agopian9795c422009-08-26 16:36:26 -07004487 if (locked) {
4488 mStateLock.unlock();
4489 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004490 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004491 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004492 return NO_ERROR;
4493}
4494
Yiwei Zhang5434a782018-12-05 18:06:32 -08004495void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */, size_t& /* index */,
4496 std::string& result) const {
4497 mCurrentState.traverseInZOrder(
4498 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004499}
4500
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004501void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004502 std::string& result) const {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004503 String8 name;
4504 if (index < args.size()) {
4505 name = String8(args[index]);
4506 index++;
4507 }
4508
Dominik Laskowski83b88212018-12-11 13:34:06 -08004509 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004510
4511 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004512 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004513 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004514 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004515 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004516 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004517 }
Robert Carr2047fae2016-11-28 14:09:09 -08004518 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004519 }
4520}
4521
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004522void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004523 std::string& /* result */) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004524 String8 name;
4525 if (index < args.size()) {
4526 name = String8(args[index]);
4527 index++;
4528 }
4529
Robert Carr2047fae2016-11-28 14:09:09 -08004530 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004531 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004532 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004533 }
Robert Carr2047fae2016-11-28 14:09:09 -08004534 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004535
Svetoslavd85084b2014-03-20 10:28:31 -07004536 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004537}
4538
Jamie Gennis6547ff42013-07-16 20:12:42 -07004539// This should only be called from the main thread. Otherwise it would need
4540// the lock and should use mCurrentState rather than mDrawingState.
4541void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004542 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004543 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004544 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004545
4546 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4547}
4548
Yiwei Zhang5434a782018-12-05 18:06:32 -08004549void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004550 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004551
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004552 if (isLayerTripleBufferingDisabled())
4553 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004554
Yiwei Zhang5434a782018-12-05 18:06:32 -08004555 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4556 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4557 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4558 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4559 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4560 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004561 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004562}
4563
Yiwei Zhang5434a782018-12-05 18:06:32 -08004564void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4565 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004566 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4567 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004568 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004569 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004570 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004571 }
David Sodman4a36e932017-11-07 14:29:47 -08004572 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 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[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004575 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4576 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004577}
4578
Dan Stozae77c7662016-05-13 11:37:28 -07004579void SurfaceFlinger::recordBufferingStats(const char* layerName,
4580 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004581 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4582 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004583 for (const auto& segment : history) {
4584 if (!segment.usedThirdBuffer) {
4585 stats.twoBufferTime += segment.totalTime;
4586 }
4587 if (segment.occupancyAverage < 1.0f) {
4588 stats.doubleBufferedTime += segment.totalTime;
4589 } else if (segment.occupancyAverage < 2.0f) {
4590 stats.tripleBufferedTime += segment.totalTime;
4591 }
4592 ++stats.numSegments;
4593 stats.totalTime += segment.totalTime;
4594 }
4595}
4596
Yiwei Zhang5434a782018-12-05 18:06:32 -08004597void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4598 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004599
4600 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4601 const size_t count = currentLayers.size();
4602 for (size_t i=0 ; i<count ; i++) {
4603 currentLayers[i]->dumpFrameEvents(result);
4604 }
4605}
4606
Yiwei Zhang5434a782018-12-05 18:06:32 -08004607void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004608 result.append("Buffering stats:\n");
4609 result.append(" [Layer name] <Active time> <Two buffer> "
4610 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004611 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004612 typedef std::tuple<std::string, float, float, float> BufferTuple;
4613 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004614 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004615 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004616 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004617 if (stats.numSegments == 0) {
4618 continue;
4619 }
4620 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4621 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4622 stats.totalTime;
4623 float doubleBufferRatio = static_cast<float>(
4624 stats.doubleBufferedTime) / stats.totalTime;
4625 float tripleBufferRatio = static_cast<float>(
4626 stats.tripleBufferedTime) / stats.totalTime;
4627 sorted.insert({activeTime, {name, twoBufferRatio,
4628 doubleBufferRatio, tripleBufferRatio}});
4629 }
4630 for (const auto& sortedPair : sorted) {
4631 float activeTime = sortedPair.first;
4632 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004633 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4634 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004635 }
4636 result.append("\n");
4637}
4638
Yiwei Zhang5434a782018-12-05 18:06:32 -08004639void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004640 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004641 const auto displayId = display->getId();
4642 if (!displayId) {
4643 continue;
4644 }
4645 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004646 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004647 continue;
4648 }
4649
Yiwei Zhang5434a782018-12-05 18:06:32 -08004650 StringAppendF(&result,
4651 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4652 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004653 uint8_t port;
4654 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004655 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004656 result.append("no identification data\n");
4657 continue;
4658 }
4659
4660 if (!isEdid(data)) {
4661 result.append("unknown identification data: ");
4662 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004663 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004664 }
4665 result.append("\n");
4666 continue;
4667 }
4668
4669 const auto edid = parseEdid(data);
4670 if (!edid) {
4671 result.append("invalid EDID: ");
4672 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004673 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004674 }
4675 result.append("\n");
4676 continue;
4677 }
4678
Yiwei Zhang5434a782018-12-05 18:06:32 -08004679 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004680 result.append(edid->displayName.data(), edid->displayName.length());
4681 result.append("\"\n");
4682 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004683}
4684
Yiwei Zhang5434a782018-12-05 18:06:32 -08004685void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4686 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4687 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4688 StringAppendF(&result, "DisplayColorSetting: %s\n",
4689 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004690
4691 // TODO: print out if wide-color mode is active or not
4692
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004693 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004694 const auto displayId = display->getId();
4695 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004696 continue;
4697 }
4698
Yiwei Zhang5434a782018-12-05 18:06:32 -08004699 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004700 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004701 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004702 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004703 }
4704
Lloyd Pique32cbe282018-10-19 13:09:22 -07004705 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004706 StringAppendF(&result, " Current color mode: %s (%d)\n",
4707 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004708 }
4709 result.append("\n");
4710}
4711
Yiwei Zhang5434a782018-12-05 18:06:32 -08004712void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004713 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004714 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4715 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004716 continue;
4717 }
4718
Dominik Laskowski05275f12018-11-01 15:03:24 -07004719 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004720 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4721 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004722 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004723 compositionInfo.dump(result, nullptr);
4724 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004725 }
4726 }
David Sodman7e4ae112018-02-09 15:02:28 -08004727}
4728
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004729LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004730 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004731 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4732 const State& state = useDrawing ? mDrawingState : mCurrentState;
4733 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004734 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004735 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004736 });
4737
4738 return layersProto;
4739}
4740
Lloyd Pique32cbe282018-10-19 13:09:22 -07004741LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004742 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004743
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004744 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004745 resolution->set_w(displayDevice.getWidth());
4746 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004747
Lloyd Pique32cbe282018-10-19 13:09:22 -07004748 auto display = displayDevice.getCompositionDisplay();
4749 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004750
Lloyd Pique32cbe282018-10-19 13:09:22 -07004751 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4752 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4753 layersProto.set_global_transform(displayState.orientation);
4754
4755 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004756 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004757 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004758 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004759 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004760 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004761 }
4762 });
4763
4764 return layersProto;
4765}
4766
Mathias Agopian74d211a2013-04-22 16:55:35 +02004767void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004768 std::string& result) const {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004769 bool colorize = false;
4770 if (index < args.size()
4771 && (args[index] == String16("--color"))) {
4772 colorize = true;
4773 index++;
4774 }
4775
4776 Colorizer colorizer(colorize);
4777
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004778 // figure out if we're stuck somewhere
4779 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004780 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004781 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4782
4783 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004784 * Dump library configuration.
4785 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004786
4787 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004788 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004789 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004790 appendSfConfigString(result);
4791 appendUiConfigString(result);
4792 appendGuiConfigString(result);
4793 result.append("\n");
4794
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004795 result.append("\nDisplay identification data:\n");
4796 dumpDisplayIdentificationData(result);
4797
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004798 result.append("\nWide-Color information:\n");
4799 dumpWideColorInfo(result);
4800
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004801 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004802 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004803 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004804 result.append(SyncFeatures::getInstance().toString());
4805 result.append("\n");
4806
Andy McFadden41d67d72014-04-25 16:58:34 -07004807 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004808 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004809 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004810
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004811 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4812 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski83b88212018-12-11 13:34:06 -08004813 StringAppendF(&result,
4814 "app phase %" PRId64 " ns, "
4815 "sf phase %" PRId64 " ns, "
4816 "early app phase %" PRId64 " ns, "
4817 "early sf phase %" PRId64 " ns, "
4818 "early app gl phase %" PRId64 " ns, "
4819 "early sf gl phase %" PRId64 " ns, "
4820 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)\n",
4821 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, appEarlyOffset, sfEarlyOffset,
4822 appEarlyGlOffset, sfEarlyGlOffset, dispSyncPresentTimeOffset, getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004823
Dan Stozab90cf072015-03-05 11:05:59 -08004824 // Dump static screen stats
4825 result.append("\n");
4826 dumpStaticScreenStats(result);
4827 result.append("\n");
4828
Yiwei Zhang5434a782018-12-05 18:06:32 -08004829 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004830
Dan Stozae77c7662016-05-13 11:37:28 -07004831 dumpBufferingStats(result);
4832
Andy McFadden4803b742012-09-24 19:07:20 -07004833 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004834 * Dump the visible layer list
4835 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004836 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004837 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4838 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4839 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004840 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004841
Chia-I Wu2f884132018-09-13 15:17:58 -07004842 {
4843 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4844 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004845 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004846 result.append("\n");
4847 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004848
David Sodman7e4ae112018-02-09 15:02:28 -08004849 result.append("\nFrame-Composition information:\n");
4850 dumpFrameCompositionInfo(result);
4851 result.append("\n");
4852
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004853 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004854 * Dump Display state
4855 */
4856
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004857 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004858 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004859 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004860 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004861 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004862 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004863 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004864
4865 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004866 * Dump SurfaceFlinger global state
4867 */
4868
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004869 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004870 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004871 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004872
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004873 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004874
Dominik Laskowski075d3172018-05-24 15:50:06 -07004875 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004876 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4877 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004878 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4879 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004880 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004881 StringAppendF(&result,
4882 " transaction-flags : %08x\n"
4883 " gpu_to_cpu_unsupported : %d\n",
4884 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004885
Dominik Laskowski075d3172018-05-24 15:50:06 -07004886 if (const auto displayId = getInternalDisplayId();
4887 displayId && getHwComposer().isConnected(*displayId)) {
4888 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004889 StringAppendF(&result,
4890 " refresh-rate : %f fps\n"
4891 " x-dpi : %f\n"
4892 " y-dpi : %f\n",
4893 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4894 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004895 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004896
Yiwei Zhang5434a782018-12-05 18:06:32 -08004897 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004898
Yiwei Zhang5434a782018-12-05 18:06:32 -08004899 StringAppendF(&result, " use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004900 /*
4901 * VSYNC state
4902 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004903 if (mUseScheduler) {
4904 mScheduler->dump(mAppConnectionHandle, result);
4905 } else {
4906 mEventThread->dump(result);
4907 }
Dan Stozae22aec72016-08-01 13:20:59 -07004908 result.append("\n");
4909
4910 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004911 * Tracing state
4912 */
4913 mTracing.dump(result);
4914 result.append("\n");
4915
4916 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004917 * HWC layer minidump
4918 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004919 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004920 const auto displayId = display->getId();
4921 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004922 continue;
4923 }
4924
Yiwei Zhang5434a782018-12-05 18:06:32 -08004925 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004926 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004927 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004928 result.append("\n");
4929 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004930
4931 /*
4932 * Dump HWComposer state
4933 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004934 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004935 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004936 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004937 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004938 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004939 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004940
4941 /*
4942 * Dump gralloc state
4943 */
4944 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4945 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004946
4947 /*
4948 * Dump VrFlinger state if in use.
4949 */
4950 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4951 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004952 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004953 result.append("\n");
4954 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004955}
4956
Dominik Laskowski075d3172018-05-24 15:50:06 -07004957const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004958 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004959 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004960 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004961 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004962 }
4963 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004964
Dominik Laskowski34157762018-10-31 13:07:19 -07004965 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004966 static const Vector<sp<Layer>> empty;
4967 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004968}
4969
Keun young Park63f165f2012-08-31 10:53:36 -07004970bool SurfaceFlinger::startDdmConnection()
4971{
4972 void* libddmconnection_dso =
4973 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4974 if (!libddmconnection_dso) {
4975 return false;
4976 }
4977 void (*DdmConnection_start)(const char* name);
4978 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004979 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004980 if (!DdmConnection_start) {
4981 dlclose(libddmconnection_dso);
4982 return false;
4983 }
4984 (*DdmConnection_start)(getServiceName());
4985 return true;
4986}
4987
Chia-I Wu28f320b2018-05-03 11:02:56 -07004988void SurfaceFlinger::updateColorMatrixLocked() {
4989 mat4 colorMatrix;
4990 if (mGlobalSaturationFactor != 1.0f) {
4991 // Rec.709 luma coefficients
4992 float3 luminance{0.213f, 0.715f, 0.072f};
4993 luminance *= 1.0f - mGlobalSaturationFactor;
4994 mat4 saturationMatrix = mat4(
4995 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4996 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4997 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4998 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4999 );
5000 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
5001 } else {
5002 colorMatrix = mClientColorMatrix * mDaltonizer();
5003 }
5004
5005 if (mCurrentState.colorMatrix != colorMatrix) {
5006 mCurrentState.colorMatrix = colorMatrix;
5007 mCurrentState.colorMatrixChanged = true;
5008 setTransactionFlags(eTransactionNeeded);
5009 }
5010}
5011
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005012status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005013#pragma clang diagnostic push
5014#pragma clang diagnostic error "-Wswitch-enum"
5015 switch (static_cast<ISurfaceComposerTag>(code)) {
5016 // These methods should at minimum make sure that the client requested
5017 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005018 case BOOT_FINISHED:
5019 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005020 case CREATE_DISPLAY:
5021 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005022 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005023 case GET_ACTIVE_COLOR_MODE:
5024 case GET_ANIMATION_FRAME_STATS:
5025 case GET_HDR_CAPABILITIES:
5026 case SET_ACTIVE_CONFIG:
5027 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005028 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005029 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005030 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005031 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
5032 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005033 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5034 IPCThreadState* ipc = IPCThreadState::self();
5035 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5036 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005037 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005038 }
Robert Carr1db73f62016-12-21 12:58:51 -08005039 return OK;
5040 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005041 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005042 IPCThreadState* ipc = IPCThreadState::self();
5043 const int pid = ipc->getCallingPid();
5044 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005045 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5046 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005047 return PERMISSION_DENIED;
5048 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005049 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005050 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005051 // Used by apps to hook Choreographer to SurfaceFlinger.
5052 case CREATE_DISPLAY_EVENT_CONNECTION:
5053 // The following calls are currently used by clients that do not
5054 // request necessary permissions. However, they do not expose any secret
5055 // information, so it is OK to pass them.
5056 case AUTHENTICATE_SURFACE:
5057 case GET_ACTIVE_CONFIG:
5058 case GET_BUILT_IN_DISPLAY:
5059 case GET_DISPLAY_COLOR_MODES:
5060 case GET_DISPLAY_CONFIGS:
5061 case GET_DISPLAY_STATS:
5062 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5063 // Calling setTransactionState is safe, because you need to have been
5064 // granted a reference to Client* and Handle* to do anything with it.
5065 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005066 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005067 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005068 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005069 case GET_PROTECTED_CONTENT_SUPPORT:
5070 case CACHE_BUFFER:
5071 case UNCACHE_BUFFER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005072 return OK;
5073 }
5074 case CAPTURE_LAYERS:
5075 case CAPTURE_SCREEN: {
5076 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005077 IPCThreadState* ipc = IPCThreadState::self();
5078 const int pid = ipc->getCallingPid();
5079 const int uid = ipc->getCallingUid();
5080 if ((uid != AID_GRAPHICS) &&
5081 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5082 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5083 return PERMISSION_DENIED;
5084 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005085 return OK;
5086 }
5087 // The following codes are deprecated and should never be allowed to access SF.
5088 case CONNECT_DISPLAY_UNUSED:
5089 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5090 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5091 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005092 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005093 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005094
5095 // These codes are used for the IBinder protocol to either interrogate the recipient
5096 // side of the transaction for its canonical interface descriptor or to dump its state.
5097 // We let them pass by default.
5098 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5099 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5100 code == IBinder::SYSPROPS_TRANSACTION) {
5101 return OK;
5102 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005103 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005104 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005105 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005106 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5107 return OK;
5108 }
5109 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5110 return PERMISSION_DENIED;
5111#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005112}
5113
Ana Krulec13be8ad2018-08-21 02:43:56 +00005114status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5115 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005116 status_t credentialCheck = CheckTransactCodeCredentials(code);
5117 if (credentialCheck != OK) {
5118 return credentialCheck;
5119 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005120
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005121 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5122 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005123 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005124 IPCThreadState* ipc = IPCThreadState::self();
5125 const int uid = ipc->getCallingUid();
5126 if (CC_UNLIKELY(uid != AID_SYSTEM
5127 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005128 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005129 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005130 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005131 return PERMISSION_DENIED;
5132 }
5133 int n;
5134 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005135 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005136 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005137 return NO_ERROR;
5138 case 1002: // SHOW_UPDATES
5139 n = data.readInt32();
5140 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005141 invalidateHwcGeometry();
5142 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005143 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005144 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005145 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005146 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005147 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005148 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005149 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005150 setTransactionFlags(
5151 eTransactionNeeded|
5152 eDisplayTransactionNeeded|
5153 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005154 return NO_ERROR;
5155 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005156 case 1006:{ // send empty update
5157 signalRefresh();
5158 return NO_ERROR;
5159 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005160 case 1008: // toggle use of hw composer
5161 n = data.readInt32();
5162 mDebugDisableHWC = n ? 1 : 0;
5163 invalidateHwcGeometry();
5164 repaintEverything();
5165 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005166 case 1009: // toggle use of transform hint
5167 n = data.readInt32();
5168 mDebugDisableTransformHint = n ? 1 : 0;
5169 invalidateHwcGeometry();
5170 repaintEverything();
5171 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005172 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005173 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005174 reply->writeInt32(0);
5175 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005176 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005177 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005178 return NO_ERROR;
5179 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005180 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005181 if (!display) {
5182 return NAME_NOT_FOUND;
5183 }
5184
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005185 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005186 return NO_ERROR;
5187 }
5188 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005189 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005190 // daltonize
5191 n = data.readInt32();
5192 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005193 case 1:
5194 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5195 break;
5196 case 2:
5197 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5198 break;
5199 case 3:
5200 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5201 break;
5202 default:
5203 mDaltonizer.setType(ColorBlindnessType::None);
5204 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005205 }
5206 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005207 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005208 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005209 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005210 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005211
5212 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005213 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005214 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005215 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005216 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005217 // apply a color matrix
5218 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005219 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005220 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005221 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005222 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005223 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005224 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005225 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005226 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005227 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005228 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005229
5230 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5231 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005232 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005233 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5234 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5235 }
5236
Chia-I Wu28f320b2018-05-03 11:02:56 -07005237 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005238 return NO_ERROR;
5239 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005240 // This is an experimental interface
5241 // Needs to be shifted to proper binder interface when we productize
5242 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005243 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005244 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005245 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005246 return NO_ERROR;
5247 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005248 case 1017: {
5249 n = data.readInt32();
5250 mForceFullDamage = static_cast<bool>(n);
5251 return NO_ERROR;
5252 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005253 case 1018: { // Modify Choreographer's phase offset
5254 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005255 if (mUseScheduler) {
5256 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5257 } else {
5258 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5259 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005260 return NO_ERROR;
5261 }
5262 case 1019: { // Modify SurfaceFlinger's phase offset
5263 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005264 if (mUseScheduler) {
5265 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5266 } else {
5267 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5268 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005269 return NO_ERROR;
5270 }
Irvel468051e2016-06-13 16:44:44 -07005271 case 1020: { // Layer updates interceptor
5272 n = data.readInt32();
5273 if (n) {
5274 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005275 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005276 }
5277 else{
5278 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005279 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005280 }
5281 return NO_ERROR;
5282 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005283 case 1021: { // Disable HWC virtual displays
5284 n = data.readInt32();
5285 mUseHwcVirtualDisplays = !n;
5286 return NO_ERROR;
5287 }
Romain Guy0147a172017-06-01 13:53:56 -07005288 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005289 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005290 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005291
Chia-I Wu28f320b2018-05-03 11:02:56 -07005292 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005293 return NO_ERROR;
5294 }
Romain Guy54f154a2017-10-24 21:40:32 +01005295 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005296 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005297 invalidateHwcGeometry();
5298 repaintEverything();
5299 return NO_ERROR;
5300 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005301 // Deprecate, use 1030 to check whether the device is color managed.
5302 case 1024: {
5303 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005304 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005305 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005306 n = data.readInt32();
5307 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005308 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005309 mTracing.enable();
5310 doTracing("tracing.enable");
5311 reply->writeInt32(NO_ERROR);
5312 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005313 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005314 status_t err = mTracing.disable();
5315 reply->writeInt32(err);
5316 }
5317 return NO_ERROR;
5318 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005319 case 1026: { // Get layer tracing status
5320 reply->writeBool(mTracing.isEnabled());
5321 return NO_ERROR;
5322 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005323 // Is a DisplayColorSetting supported?
5324 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005325 const auto display = getDefaultDisplayDevice();
5326 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005327 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005328 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005329
5330 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5331 switch (setting) {
5332 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005333 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005334 break;
5335 case DisplayColorSetting::UNMANAGED:
5336 reply->writeBool(true);
5337 break;
5338 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005339 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005340 break;
5341 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005342 reply->writeBool(
5343 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005344 break;
5345 }
5346 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005347 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005348 // Is VrFlinger active?
5349 case 1028: {
5350 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005351 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005352 return NO_ERROR;
5353 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005354 // Is device color managed?
5355 case 1030: {
5356 reply->writeBool(useColorManagement);
5357 return NO_ERROR;
5358 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005359 // Override default composition data space
5360 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5361 // && adb shell stop zygote && adb shell start zygote
5362 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5363 // adb shell stop zygote && adb shell start zygote
5364 case 1031: {
5365 Mutex::Autolock _l(mStateLock);
5366 n = data.readInt32();
5367 if (n) {
5368 n = data.readInt32();
5369 if (n) {
5370 Dataspace dataspace = static_cast<Dataspace>(n);
5371 if (!validateCompositionDataspace(dataspace)) {
5372 return BAD_VALUE;
5373 }
5374 mDefaultCompositionDataspace = dataspace;
5375 }
5376 n = data.readInt32();
5377 if (n) {
5378 Dataspace dataspace = static_cast<Dataspace>(n);
5379 if (!validateCompositionDataspace(dataspace)) {
5380 return BAD_VALUE;
5381 }
5382 mWideColorGamutCompositionDataspace = dataspace;
5383 }
5384 } else {
5385 // restore composition data space.
5386 mDefaultCompositionDataspace = defaultCompositionDataspace;
5387 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5388 }
5389 return NO_ERROR;
5390 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005391 }
5392 }
5393 return err;
5394}
5395
Steven Thomas6d8110b2017-08-31 18:24:21 -07005396void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005397 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005398 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005399}
5400
Ana Krulec7d1d6832018-12-27 11:10:09 -08005401void SurfaceFlinger::repaintEverythingForHWC() {
5402 mRepaintEverything = true;
5403 mEventQueue->invalidateForHWC();
5404}
5405
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005406// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5407class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005408public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005409 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5410 ~WindowDisconnector() {
5411 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005412 }
5413
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005414private:
5415 ANativeWindow* mWindow;
5416 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005417};
5418
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005419status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005420 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5421 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005422 uint32_t reqWidth, uint32_t reqHeight,
5423 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005424 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005425 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005426
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005427 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005428
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005429 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5430
Chia-I Wu20261cb2018-08-23 12:55:44 -07005431 sp<DisplayDevice> display;
5432 {
5433 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005434
Chia-I Wu20261cb2018-08-23 12:55:44 -07005435 display = getDisplayDeviceLocked(displayToken);
5436 if (!display) return BAD_VALUE;
5437
Chia-I Wucb023152018-08-28 12:57:23 -07005438 // set the requested width/height to the logical display viewport size
5439 // by default
5440 if (reqWidth == 0 || reqHeight == 0) {
5441 reqWidth = uint32_t(display->getViewport().width());
5442 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005443 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005444 }
5445
Peiyong Lin0e003c92018-09-17 11:09:51 -07005446 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5447 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005448
5449 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005450 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005451 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5452 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005453}
5454
5455status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005456 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5457 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005458 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005459 ATRACE_CALL();
5460
5461 class LayerRenderArea : public RenderArea {
5462 public:
Robert Carr578038f2018-03-09 12:25:24 -08005463 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005464 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5465 bool childrenOnly)
5466 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005467 mLayer(layer),
5468 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005469 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005470 mFlinger(flinger),
5471 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005472 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005473 Rect getBounds() const override {
5474 const Layer::State& layerState(mLayer->getDrawingState());
5475 return mLayer->getBufferSize(layerState);
5476 }
Marissa Wall61c58622018-07-18 10:12:20 -07005477 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005478 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005479 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005480 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005481 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005482 }
chaviwa76b2712017-09-20 12:02:26 -07005483 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005484 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005485 Rect getSourceCrop() const override {
5486 if (mCrop.isEmpty()) {
5487 return getBounds();
5488 } else {
5489 return mCrop;
5490 }
5491 }
Robert Carr578038f2018-03-09 12:25:24 -08005492 class ReparentForDrawing {
5493 public:
5494 const sp<Layer>& oldParent;
5495 const sp<Layer>& newParent;
5496
5497 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5498 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005499 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005500 }
Robert Carr15eae092018-03-23 13:43:53 -07005501 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005502 };
5503
5504 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005505 const Rect sourceCrop = getSourceCrop();
5506 // no need to check rotation because there is none
5507 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5508 sourceCrop.height() != getReqHeight();
5509
Robert Carr578038f2018-03-09 12:25:24 -08005510 if (!mChildrenOnly) {
5511 mTransform = mLayer->getTransform().inverse();
5512 drawLayers();
5513 } else {
5514 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005515 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005516 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5517 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005518
5519 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5520 drawLayers();
5521 }
5522 }
chaviwa76b2712017-09-20 12:02:26 -07005523
chaviwa76b2712017-09-20 12:02:26 -07005524 private:
chaviw7206d492017-11-10 16:16:12 -08005525 const sp<Layer> mLayer;
5526 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005527
5528 // In the "childrenOnly" case we reparent the children to a screenshot
5529 // layer which has no properties set and which does not draw.
5530 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005531 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005532 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005533
5534 SurfaceFlinger* mFlinger;
5535 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005536 };
5537
5538 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5539 auto parent = layerHandle->owner.promote();
5540
Robert Carr2e102c92018-10-23 12:11:15 -07005541 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005542 ALOGE("captureLayers called with a removed parent");
5543 return NAME_NOT_FOUND;
5544 }
5545
Robert Carr578038f2018-03-09 12:25:24 -08005546 const int uid = IPCThreadState::self()->getCallingUid();
5547 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005548 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005549 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5550 return PERMISSION_DENIED;
5551 }
5552
chaviw7206d492017-11-10 16:16:12 -08005553 Rect crop(sourceCrop);
5554 if (sourceCrop.width() <= 0) {
5555 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005556 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005557 }
5558
5559 if (sourceCrop.height() <= 0) {
5560 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005561 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005562 }
5563
5564 int32_t reqWidth = crop.width() * frameScale;
5565 int32_t reqHeight = crop.height() * frameScale;
5566
Chia-I Wu20261cb2018-08-23 12:55:44 -07005567 // really small crop or frameScale
5568 if (reqWidth <= 0) {
5569 reqWidth = 1;
5570 }
5571 if (reqHeight <= 0) {
5572 reqHeight = 1;
5573 }
5574
Peiyong Lin0e003c92018-09-17 11:09:51 -07005575 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005576
Robert Carr578038f2018-03-09 12:25:24 -08005577 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005578 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5579 if (!layer->isVisible()) {
5580 return;
Robert Carr578038f2018-03-09 12:25:24 -08005581 } else if (childrenOnly && layer == parent.get()) {
5582 return;
chaviwa76b2712017-09-20 12:02:26 -07005583 }
5584 visitor(layer);
5585 });
5586 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005587 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005588}
5589
5590status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5591 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005592 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005593 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005594 bool useIdentityTransform) {
5595 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005596
Peiyong Lin0e003c92018-09-17 11:09:51 -07005597 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005598 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5599 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005600 *outBuffer =
5601 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5602 static_cast<android_pixel_format>(reqPixelFormat), 1,
5603 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005604
5605 // This mutex protects syncFd and captureResult for communication of the return values from the
5606 // main thread back to this Binder thread
5607 std::mutex captureMutex;
5608 std::condition_variable captureCondition;
5609 std::unique_lock<std::mutex> captureLock(captureMutex);
5610 int syncFd = -1;
5611 std::optional<status_t> captureResult;
5612
Robert Carr03480e22018-01-04 16:02:06 -08005613 const int uid = IPCThreadState::self()->getCallingUid();
5614 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5615
Dominik Laskowski8c001672018-05-30 16:52:06 -07005616 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005617 // If there is a refresh pending, bug out early and tell the binder thread to try again
5618 // after the refresh.
5619 if (mRefreshPending) {
5620 ATRACE_NAME("Skipping screenshot for now");
5621 std::unique_lock<std::mutex> captureLock(captureMutex);
5622 captureResult = std::make_optional<status_t>(EAGAIN);
5623 captureCondition.notify_one();
5624 return;
5625 }
5626
5627 status_t result = NO_ERROR;
5628 int fd = -1;
5629 {
5630 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005631 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005632 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5633 useIdentityTransform, forSystem, &fd);
5634 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005635 }
5636
5637 {
5638 std::unique_lock<std::mutex> captureLock(captureMutex);
5639 syncFd = fd;
5640 captureResult = std::make_optional<status_t>(result);
5641 captureCondition.notify_one();
5642 }
5643 });
5644
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005645 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005646 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005647 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005648 while (*captureResult == EAGAIN) {
5649 captureResult.reset();
5650 result = postMessageAsync(message);
5651 if (result != NO_ERROR) {
5652 return result;
5653 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005654 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005655 }
5656 result = *captureResult;
5657 }
5658
5659 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005660 sync_wait(syncFd, -1);
5661 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005662 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005663
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005664 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005665}
5666
chaviwa76b2712017-09-20 12:02:26 -07005667void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005668 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005669 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005670 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005671
Lloyd Pique144e1162017-12-20 16:44:52 -08005672 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005673
chaviwa76b2712017-09-20 12:02:26 -07005674 const auto reqWidth = renderArea.getReqWidth();
5675 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005676 const auto sourceCrop = renderArea.getSourceCrop();
5677 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005678
Peiyong Lin0e003c92018-09-17 11:09:51 -07005679 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005680 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005681
Mathias Agopian180f10d2013-04-10 22:55:41 -07005682 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005683 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005684
5685 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005686 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005687 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005688
chaviw50da5042018-04-09 13:49:37 -07005689 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005690 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005691 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005692
chaviwa76b2712017-09-20 12:02:26 -07005693 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005694 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005695 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005696 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005697 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005698}
5699
chaviwa76b2712017-09-20 12:02:26 -07005700status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5701 TraverseLayersFunction traverseLayers,
5702 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005703 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005704 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005705 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005706 ATRACE_CALL();
5707
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005708 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005709
5710 traverseLayers([&](Layer* layer) {
5711 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5712 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005713
Robert Carr03480e22018-01-04 16:02:06 -08005714 // We allow the system server to take screenshots of secure layers for
5715 // use in situations like the Screen-rotation animation and place
5716 // the impetus on WindowManager to not persist them.
5717 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005718 ALOGW("FB is protected: PERMISSION_DENIED");
5719 return PERMISSION_DENIED;
5720 }
Peiyong Linfb530cf2018-12-15 05:07:38 +00005721 auto& engine(getRenderEngine());
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005722
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005723 // this binds the given EGLImage as a framebuffer for the
5724 // duration of this scope.
Peiyong Linfb530cf2018-12-15 05:07:38 +00005725 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005726 if (bufferBond.getStatus() != NO_ERROR) {
5727 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005728 return INVALID_OPERATION;
5729 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005730
Dan Stozaabcda352017-06-01 14:37:39 -07005731 // this will in fact render into our dequeued buffer
5732 // via an FBO, which means we didn't have to create
5733 // an EGLSurface and therefore we're not
5734 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005735 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005736
Peiyong Linfb530cf2018-12-15 05:07:38 +00005737 base::unique_fd syncFd = engine.flush();
Alec Mouri492bc572018-09-11 21:40:04 +00005738 if (syncFd < 0) {
Peiyong Linfb530cf2018-12-15 05:07:38 +00005739 engine.finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005740 }
Alec Mouri492bc572018-09-11 21:40:04 +00005741 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005742
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005743 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005744}
5745
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005746// ---------------------------------------------------------------------------
5747
Dan Stoza412903f2017-04-27 13:42:17 -07005748void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5749 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005750}
5751
Dan Stoza412903f2017-04-27 13:42:17 -07005752void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5753 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005754}
5755
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005756void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005757 const LayerVector::Visitor& visitor) {
5758 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005759 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005760 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005761 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005762 continue;
5763 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005764 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005765 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005766 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005767 return;
5768 }
chaviwa76b2712017-09-20 12:02:26 -07005769 if (!layer->isVisible()) {
5770 return;
5771 }
5772 visitor(layer);
5773 });
5774 }
5775}
5776
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005777}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005778
Lloyd Pique074e8122018-07-26 12:57:23 -07005779
Mathias Agopian3f844832013-08-07 21:24:32 -07005780#if defined(__gl_h_)
5781#error "don't include gl/gl.h in this file"
5782#endif
5783
5784#if defined(__gl2_h_)
5785#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005786#endif