blob: 4443df4c84531731c6600abf409b052303101046 [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();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002229 if (display->belongsInOutput(layer->getLayerStack(),
2230 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002231 Region drawRegion(tr.transform(
2232 layer->visibleNonTransparentRegion));
2233 drawRegion.andSelf(bounds);
2234 if (!drawRegion.isEmpty()) {
2235 layersSortedByZ.add(layer);
2236 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002237 // Clear out the HWC layer if this layer was
2238 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002239 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002240 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002241 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002242 // WM changes display->layerStack upon sleep/awake.
2243 // Here we make sure we delete the HWC layers even if
2244 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002245 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002246 }
2247
2248 // If a layer is not going to get a release fence because
2249 // it is invisible, but it is also going to release its
2250 // old buffer, add it to the list of layers needing
2251 // fences.
2252 if (hwcLayerDestroyed) {
2253 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2254 mLayersWithQueuedFrames.cend(), layer);
2255 if (found != mLayersWithQueuedFrames.cend()) {
2256 layersNeedingFences.add(layer);
2257 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002258 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002259 });
2260 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002261 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
2262 displayDevice->setLayersNeedingFences(layersNeedingFences);
2263
2264 Region undefinedRegion{bounds};
2265 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2266
2267 display->editState().undefinedRegion = undefinedRegion;
2268 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002269 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002270 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002271}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002272
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002273// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002274// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002275// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002276// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002277// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002278// The returned HDR data space is one of
2279// - Dataspace::UNKNOWN
2280// - Dataspace::BT2020_HLG
2281// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002282Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2283 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002284 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002285 *outHdrDataSpace = Dataspace::UNKNOWN;
2286
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002287 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002288 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002289 case Dataspace::V0_SCRGB:
2290 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002291 case Dataspace::BT2020:
2292 case Dataspace::BT2020_ITU:
2293 case Dataspace::BT2020_LINEAR:
2294 case Dataspace::DISPLAY_BT2020:
2295 bestDataSpace = Dataspace::DISPLAY_BT2020;
2296 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002297 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002298 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002299 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002300 case Dataspace::BT2020_PQ:
2301 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002302 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002303 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002304 case Dataspace::BT2020_HLG:
2305 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002306 // When there's mixed PQ content and HLG content, we set the HDR
2307 // data space to be BT2020_PQ and convert HLG to PQ.
2308 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2309 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002310 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002311 break;
2312 default:
2313 break;
2314 }
Romain Guy54f154a2017-10-24 21:40:32 +01002315 }
2316
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002317 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002318}
2319
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002320// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002321void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2322 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002323 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2324 *outMode = ColorMode::NATIVE;
2325 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002326 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002327 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002328 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002329
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002330 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002331 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002332
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002333 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2334
Peiyong Lindfde5112018-06-05 10:58:41 -07002335 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002336 const bool isHdr =
2337 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002338 if (isHdr) {
2339 bestDataSpace = hdrDataSpace;
2340 }
2341
Chia-I Wu0d711262018-05-21 15:19:35 -07002342 RenderIntent intent;
2343 switch (mDisplayColorSetting) {
2344 case DisplayColorSetting::MANAGED:
2345 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002346 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002347 break;
2348 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002349 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002350 break;
2351 default: // vendor display color setting
2352 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2353 break;
2354 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002355
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002356 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002357}
2358
Lloyd Pique32cbe282018-10-19 13:09:22 -07002359void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2360 auto display = displayDevice->getCompositionDisplay();
2361 const auto& displayState = display->getState();
2362
2363 bool dirty = !display->getPhysicalSpaceDirtyRegion(false).isEmpty();
2364 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2365 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002366
David Sodmanfa9b2af2017-12-24 13:28:59 -08002367 // If nothing has changed (!dirty), don't recompose.
2368 // If something changed, but we don't currently have any visible layers,
2369 // and didn't when we last did a composition, then skip it this time.
2370 // The second rule does two things:
2371 // - When all layers are removed from a display, we'll emit one black
2372 // frame, then nothing more until we get new layers.
2373 // - When a display is created with a private layer stack, we won't
2374 // emit any black frames until a layer is added to the layer stack.
2375 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002376
Dominik Laskowski075d3172018-05-24 15:50:06 -07002377 const char flagPrefix[] = {'-', '+'};
2378 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002379 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2380 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2381 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2382 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002383
Lloyd Pique31cb2942018-10-19 17:23:03 -07002384 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002385
David Sodmanfa9b2af2017-12-24 13:28:59 -08002386 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002387 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002388 }
2389}
2390
Lloyd Pique32cbe282018-10-19 13:09:22 -07002391void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2392 auto display = displayDevice->getCompositionDisplay();
2393 const auto& displayState = display->getState();
2394
2395 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002396 return;
David Sodman2b406362017-12-15 13:33:47 -08002397 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002398
Lloyd Pique31cb2942018-10-19 17:23:03 -07002399 status_t result = display->getRenderSurface()->prepareFrame(
2400 getBE().mCompositionInfo[displayDevice->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002401 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002402 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002403}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002404
Lloyd Pique32cbe282018-10-19 13:09:22 -07002405void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002406 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002407 ALOGV("doComposition");
2408
Lloyd Pique32cbe282018-10-19 13:09:22 -07002409 auto display = displayDevice->getCompositionDisplay();
2410 const auto& displayState = display->getState();
2411
2412 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002413 // transform the dirty region into this screen's coordinate space
Lloyd Pique32cbe282018-10-19 13:09:22 -07002414 const Region dirtyRegion = display->getPhysicalSpaceDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002415
David Sodmanfa9b2af2017-12-24 13:28:59 -08002416 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002417 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002418
Lloyd Pique32cbe282018-10-19 13:09:22 -07002419 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002420 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002421 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002422 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002423}
2424
David Sodmanfa9b2af2017-12-24 13:28:59 -08002425void SurfaceFlinger::postFrame()
2426{
2427 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002428 const auto display = getDefaultDisplayDeviceLocked();
2429 if (display && getHwComposer().isConnected(*display->getId())) {
2430 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002431 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2432 logFrameStats();
2433 }
2434 }
2435}
2436
Lloyd Pique32cbe282018-10-19 13:09:22 -07002437void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002438 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002439 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002440
Lloyd Pique32cbe282018-10-19 13:09:22 -07002441 auto display = displayDevice->getCompositionDisplay();
2442 const auto& displayState = display->getState();
2443 const auto displayId = display->getId();
2444
David Sodmanfa9b2af2017-12-24 13:28:59 -08002445 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002446
Lloyd Pique32cbe282018-10-19 13:09:22 -07002447 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002448 if (displayId) {
2449 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002450 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002451 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002452 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002453 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002454
Chia-I Wu7b549592017-11-15 09:14:57 -08002455 // The layer buffer from the previous frame (if any) is released
2456 // by HWC only when the release fence from this frame (if any) is
2457 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002458 if (displayId && layer->hasHwcLayer(*displayId)) {
2459 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2460 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002461 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002462
2463 // If the layer was client composited in the previous frame, we
2464 // need to merge with the previous client target acquire fence.
2465 // Since we do not track that, always merge with the current
2466 // client target acquire fence when it is available, even though
2467 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002468 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002469 releaseFence =
2470 Fence::merge("LayerRelease", releaseFence,
2471 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002472 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002473
David Sodman15094112018-10-11 09:39:37 -07002474 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002475 }
Chia-I Wu83806892017-11-16 10:50:20 -08002476
2477 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002478 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002479 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002480 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002481 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002482 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002483 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002484 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002485 }
2486 }
2487
Dominik Laskowski075d3172018-05-24 15:50:06 -07002488 if (displayId) {
2489 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002490 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002491 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002492}
2493
Mathias Agopian87baae12012-07-31 12:38:26 -07002494void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002495{
Mathias Agopian841cde52012-03-01 15:44:37 -08002496 ATRACE_CALL();
2497
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002498 // here we keep a copy of the drawing state (that is the state that's
2499 // going to be overwritten by handleTransactionLocked()) outside of
2500 // mStateLock so that the side-effects of the State assignment
2501 // don't happen with mStateLock held (which can cause deadlocks).
2502 State drawingState(mDrawingState);
2503
Mathias Agopianca4d3602011-05-19 15:38:14 -07002504 Mutex::Autolock _l(mStateLock);
2505 const nsecs_t now = systemTime();
2506 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002507
Mathias Agopianca4d3602011-05-19 15:38:14 -07002508 // Here we're guaranteed that some transaction flags are set
2509 // so we can call handleTransactionLocked() unconditionally.
2510 // We call getTransactionFlags(), which will also clear the flags,
2511 // with mStateLock held to guarantee that mCurrentState won't change
2512 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002513
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002514 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002515 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002516 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002517
Mathias Agopianca4d3602011-05-19 15:38:14 -07002518 mLastTransactionTime = systemTime() - now;
2519 mDebugInTransaction = 0;
2520 invalidateHwcGeometry();
2521 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002522}
2523
Lloyd Piqueba04e622017-12-14 17:11:26 -08002524void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2525 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002526 const std::optional<DisplayIdentificationInfo> info =
2527 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002528
Dominik Laskowski075d3172018-05-24 15:50:06 -07002529 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002530 continue;
2531 }
2532
Lloyd Piqueba04e622017-12-14 17:11:26 -08002533 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002534 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002535 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002536 mPhysicalDisplayTokens[info->id] = new BBinder();
2537 DisplayDeviceState state;
2538 state.displayId = info->id;
2539 state.isSecure = true; // All physical displays are currently considered secure.
2540 state.displayName = info->name;
2541 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2542 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002543 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002544 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002545 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002546
Dominik Laskowski075d3172018-05-24 15:50:06 -07002547 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2548 if (index >= 0) {
2549 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2550 mInterceptor->saveDisplayDeletion(state.sequenceId);
2551 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002552 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002553 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002554 }
2555
2556 processDisplayChangesLocked();
2557 }
2558
2559 mPendingHotplugEvents.clear();
2560}
2561
Lloyd Pique99d3da52018-01-22 17:48:03 -08002562sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002563 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002564 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002565 const sp<IGraphicBufferProducer>& producer) {
2566 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002567 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002568 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002569 creationArgs.isSecure = state.isSecure;
2570 creationArgs.displaySurface = dispSurface;
2571 creationArgs.hasWideColorGamut = false;
2572 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002573
Dominik Laskowski075d3172018-05-24 15:50:06 -07002574 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2575 creationArgs.isPrimary = isInternalDisplay;
2576
2577 if (useColorManagement && displayId) {
2578 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002579 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002580 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002581 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002582 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002583
Dominik Laskowski7e045462018-05-30 13:02:02 -07002584 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002585 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002586 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002587 }
tangrobin6753a022018-08-10 10:58:54 +08002588 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002589
Dominik Laskowski075d3172018-05-24 15:50:06 -07002590 if (displayId) {
2591 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002592 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002593 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002594 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002595
Lloyd Pique90c115d2018-09-18 21:39:42 -07002596 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002597 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002598 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002599
Lloyd Pique99d3da52018-01-22 17:48:03 -08002600 // Make sure that composition can never be stalled by a virtual display
2601 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002602 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002603 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002604 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2605 }
2606
Dominik Laskowski075d3172018-05-24 15:50:06 -07002607 creationArgs.displayInstallOrientation =
2608 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002609
Lloyd Pique99d3da52018-01-22 17:48:03 -08002610 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002611 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002612
Lloyd Pique90c115d2018-09-18 21:39:42 -07002613 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002614
2615 if (maxFrameBufferAcquiredBuffers >= 3) {
2616 nativeWindowSurface->preallocateBuffers();
2617 }
2618
2619 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002620 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002621 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002622 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002623 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002624 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002625 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2626 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002627 if (!state.isVirtual()) {
2628 LOG_ALWAYS_FATAL_IF(!displayId);
2629 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002630 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002631
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002632 display->setLayerStack(state.layerStack);
2633 display->setProjection(state.orientation, state.viewport, state.frame);
2634 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002635
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002636 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002637}
2638
Lloyd Pique347200f2017-12-14 17:00:15 -08002639void SurfaceFlinger::processDisplayChangesLocked() {
2640 // here we take advantage of Vector's copy-on-write semantics to
2641 // improve performance by skipping the transaction entirely when
2642 // know that the lists are identical
2643 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2644 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2645 if (!curr.isIdenticalTo(draw)) {
2646 mVisibleRegionsDirty = true;
2647 const size_t cc = curr.size();
2648 size_t dc = draw.size();
2649
2650 // find the displays that were removed
2651 // (ie: in drawing state but not in current state)
2652 // also handle displays that changed
2653 // (ie: displays that are in both lists)
2654 for (size_t i = 0; i < dc;) {
2655 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2656 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002657 // Save display IDs before disconnecting.
2658 const auto internalDisplayId = getInternalDisplayId();
2659 const auto externalDisplayId = getExternalDisplayId();
2660
Lloyd Pique347200f2017-12-14 17:00:15 -08002661 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002662 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002663 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002664 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002665 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002666 if (mUseScheduler) {
2667 mScheduler->hotplugReceived(mAppConnectionHandle,
2668 EventThread::DisplayType::Primary, false);
2669 } else {
2670 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2671 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002672 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002673 if (mUseScheduler) {
2674 mScheduler->hotplugReceived(mAppConnectionHandle,
2675 EventThread::DisplayType::External, false);
2676 } else {
2677 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2678 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002679 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002680 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002681 } else {
2682 // this display is in both lists. see if something changed.
2683 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002684 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002685 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2686 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2687 if (state_binder != draw_binder) {
2688 // changing the surface is like destroying and
2689 // recreating the DisplayDevice, so we just remove it
2690 // from the drawing state, so that it get re-added
2691 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002692 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002693 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002694 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002695 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002696 mDrawingState.displays.removeItemsAt(i);
2697 dc--;
2698 // at this point we must loop to the next item
2699 continue;
2700 }
2701
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002702 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002703 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002704 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002705 }
2706 if ((state.orientation != draw[i].orientation) ||
2707 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002708 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002709 }
2710 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002711 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002712 }
2713 }
2714 }
2715 ++i;
2716 }
2717
2718 // find displays that were added
2719 // (ie: in current state but not in drawing state)
2720 for (size_t i = 0; i < cc; i++) {
2721 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2722 const DisplayDeviceState& state(curr[i]);
2723
Lloyd Pique542307f2018-10-19 13:24:08 -07002724 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002725 sp<IGraphicBufferProducer> producer;
2726 sp<IGraphicBufferProducer> bqProducer;
2727 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002728 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002729
Dominik Laskowski075d3172018-05-24 15:50:06 -07002730 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002731 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002732 // Virtual displays without a surface are dormant:
2733 // they have external state (layer stack, projection,
2734 // etc.) but no internal state (i.e. a DisplayDevice).
2735 if (state.surface != nullptr) {
2736 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002737 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002738 int width = 0;
2739 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2740 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2741 int height = 0;
2742 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2743 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2744 int intFormat = 0;
2745 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2746 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002747 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002748
Dominik Laskowski075d3172018-05-24 15:50:06 -07002749 displayId =
2750 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002751 }
2752
2753 // TODO: Plumb requested format back up to consumer
2754
2755 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002756 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002757 bqProducer, bqConsumer,
2758 state.displayName);
2759
2760 dispSurface = vds;
2761 producer = vds;
2762 }
2763 } else {
2764 ALOGE_IF(state.surface != nullptr,
2765 "adding a supported display, but rendering "
2766 "surface is provided (%p), ignoring it",
2767 state.surface.get());
2768
Dominik Laskowski075d3172018-05-24 15:50:06 -07002769 displayId = state.displayId;
2770 LOG_ALWAYS_FATAL_IF(!displayId);
2771 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002772 producer = bqProducer;
2773 }
2774
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002775 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002776 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002777 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002778 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002779 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002780 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002781 LOG_ALWAYS_FATAL_IF(!displayId);
2782
2783 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002784 if (mUseScheduler) {
2785 mScheduler->hotplugReceived(mAppConnectionHandle,
2786 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002787 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002788 } else {
2789 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2790 true);
2791 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002792 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002793 if (mUseScheduler) {
2794 mScheduler->hotplugReceived(mAppConnectionHandle,
2795 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002796 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002797 } else {
2798 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2799 true);
2800 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002801 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002802 }
2803 }
2804 }
2805 }
2806 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002807
2808 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002809}
2810
Mathias Agopian87baae12012-07-31 12:38:26 -07002811void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002812{
Dan Stoza7dde5992015-05-22 09:51:44 -07002813 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002814 mCurrentState.traverseInZOrder([](Layer* layer) {
2815 layer->notifyAvailableFrames();
2816 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002817
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002818 /*
2819 * Traversal of the children
2820 * (perform the transaction for each of them if needed)
2821 */
2822
Robert Carr720e5062018-07-30 17:45:14 -07002823 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002824 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002825 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002826 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002827 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002828
2829 const uint32_t flags = layer->doTransaction(0);
2830 if (flags & Layer::eVisibleRegion)
2831 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002832
2833 if (flags & Layer::eInputInfoChanged) {
2834 inputChanged = true;
2835 }
Robert Carr2047fae2016-11-28 14:09:09 -08002836 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002837 }
2838
2839 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002840 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002841 */
2842
Mathias Agopiane57f2922012-08-09 16:29:12 -07002843 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002844 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002845 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002846 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002847
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002848 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002849 // The transform hint might have changed for some layers
2850 // (either because a display has changed, or because a layer
2851 // as changed).
2852 //
2853 // Walk through all the layers in currentLayers,
2854 // and update their transform hint.
2855 //
2856 // If a layer is visible only on a single display, then that
2857 // display is used to calculate the hint, otherwise we use the
2858 // default display.
2859 //
2860 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2861 // the hint is set before we acquire a buffer from the surface texture.
2862 //
2863 // NOTE: layer transactions have taken place already, so we use their
2864 // drawing state. However, SurfaceFlinger's own transaction has not
2865 // happened yet, so we must use the current state layer list
2866 // (soon to become the drawing state list).
2867 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002868 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002869 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002870 bool first = true;
2871 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002872 // NOTE: we rely on the fact that layers are sorted by
2873 // layerStack first (so we don't have to traverse the list
2874 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002875 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002876 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002877 currentlayerStack = layerStack;
2878 // figure out if this layerstack is mirrored
2879 // (more than one display) if so, pick the default display,
2880 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002881 hintDisplay = nullptr;
2882 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002883 if (display->getCompositionDisplay()
2884 ->belongsInOutput(layer->getLayerStack(),
2885 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002886 if (hintDisplay) {
2887 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002888 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002889 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002890 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002891 }
2892 }
2893 }
2894 }
Chet Haase91d25932013-04-11 15:24:55 -07002895
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002896 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002897 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2898 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002899
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002900 // could be null when this layer is using a layerStack
2901 // that is not visible on any display. Also can occur at
2902 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002903 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002904 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002905
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002906 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002907 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002908 if (hintDisplay) {
2909 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002910 }
Robert Carr2047fae2016-11-28 14:09:09 -08002911
2912 first = false;
2913 });
Mathias Agopian84300952012-11-21 16:02:13 -08002914 }
2915
2916
Mathias Agopian3559b072012-08-15 13:46:03 -07002917 /*
2918 * Perform our own transaction if needed
2919 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002920
2921 if (mLayersAdded) {
2922 mLayersAdded = false;
2923 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002924 mVisibleRegionsDirty = true;
2925 }
2926
2927 // some layers might have been removed, so
2928 // we need to update the regions they're exposing.
2929 if (mLayersRemoved) {
2930 mLayersRemoved = false;
2931 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002932 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002933 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002934 // this layer is not visible anymore
2935 // TODO: we could traverse the tree from front to back and
2936 // compute the actual visible region
2937 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002938 Region visibleReg;
2939 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002940 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002941 }
Robert Carr2047fae2016-11-28 14:09:09 -08002942 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002943 }
2944
2945 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002946
Vishnu Nairde19f852018-12-18 16:11:53 -08002947 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002948 updateInputWindows();
2949 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002950 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002951
Riley Andrews03414a12014-07-01 14:22:59 -07002952 updateCursorAsync();
2953}
2954
Robert Carr720e5062018-07-30 17:45:14 -07002955void SurfaceFlinger::updateInputWindows() {
2956 ATRACE_CALL();
2957
Vishnu Nairde19f852018-12-18 16:11:53 -08002958 if (mInputFlinger == nullptr) {
2959 return;
2960 }
2961
Robert Carr720e5062018-07-30 17:45:14 -07002962 Vector<InputWindowInfo> inputHandles;
2963
2964 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2965 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002966 // When calculating the screen bounds we ignore the transparent region since it may
2967 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002968 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002969 }
2970 });
2971 mInputFlinger->setInputWindows(inputHandles);
2972}
2973
chaviwfbe5d9c2018-12-26 12:23:37 -08002974void SurfaceFlinger::executeInputWindowCommands() {
2975 if (!mInputFlinger) {
2976 return;
2977 }
2978
2979 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2980 if (transferTouchFocusCommand.fromToken != nullptr &&
2981 transferTouchFocusCommand.toToken != nullptr &&
2982 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2983 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2984 transferTouchFocusCommand.toToken);
2985 }
2986 }
2987
2988 mInputWindowCommands.clear();
2989}
2990
Riley Andrews03414a12014-07-01 14:22:59 -07002991void SurfaceFlinger::updateCursorAsync()
2992{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002993 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002994 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002995 continue;
2996 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002997
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002998 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2999 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003000 }
3001 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003002}
3003
chaviw61626f22018-11-15 16:26:27 -08003004void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3005 if (layer->hasReadyFrame()) {
3006 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3007 if (layer->shouldPresentNow(expectedPresentTime)) {
3008 bool ignored = false;
3009 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
3010 }
3011 }
3012 layer->releasePendingBuffer(systemTime());
3013}
3014
Mathias Agopian4fec8732012-06-29 14:12:52 -07003015void SurfaceFlinger::commitTransaction()
3016{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003017 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003018 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003019 for (const auto& l : mLayersPendingRemoval) {
3020 recordBufferingStats(l->getName().string(),
3021 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003022
3023 // We need to release the HWC layers when the Layer is removed
3024 // from the current state otherwise the HWC layer just continues
3025 // showing at its last configured state until we eventually
3026 // abandon the buffer queue.
3027 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003028 l->destroyHwcLayersForAllDisplays();
3029 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003030 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003031 }
3032 mLayersPendingRemoval.clear();
3033 }
3034
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003035 // If this transaction is part of a window animation then the next frame
3036 // we composite should be considered an animation as well.
3037 mAnimCompositionPending = mAnimTransactionPending;
3038
Mathias Agopian4fec8732012-06-29 14:12:52 -07003039 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003040 // clear the "changed" flags in current state
3041 mCurrentState.colorMatrixChanged = false;
3042
Robert Carr1f0a16a2016-10-24 16:27:39 -07003043 mDrawingState.traverseInZOrder([](Layer* layer) {
3044 layer->commitChildList();
3045 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003046 mTransactionPending = false;
3047 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003048 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003049}
3050
Lloyd Pique32cbe282018-10-19 13:09:22 -07003051void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003052 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003053 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003054 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003055
Lloyd Pique32cbe282018-10-19 13:09:22 -07003056 auto display = displayDevice->getCompositionDisplay();
3057
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003058 Region aboveOpaqueLayers;
3059 Region aboveCoveredLayers;
3060 Region dirty;
3061
Mathias Agopian87baae12012-07-31 12:38:26 -07003062 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003063
Robert Carr2047fae2016-11-28 14:09:09 -08003064 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003065 // start with the whole surface at its current location
3066 const Layer::State& s(layer->getDrawingState());
3067
Jesse Hall01e29052013-02-19 16:13:35 -08003068 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003069 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003070 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003071 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003072
Mathias Agopianab028732010-03-16 16:41:46 -07003073 /*
3074 * opaqueRegion: area of a surface that is fully opaque.
3075 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003076 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003077
3078 /*
3079 * visibleRegion: area of a surface that is visible on screen
3080 * and not fully transparent. This is essentially the layer's
3081 * footprint minus the opaque regions above it.
3082 * Areas covered by a translucent surface are considered visible.
3083 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003084 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003085
3086 /*
3087 * coveredRegion: area of a surface that is covered by all
3088 * visible regions above it (which includes the translucent areas).
3089 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003090 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003091
Jesse Halla8026d22012-09-25 13:25:04 -07003092 /*
3093 * transparentRegion: area of a surface that is hinted to be completely
3094 * transparent. This is only used to tell when the layer has no visible
3095 * non-transparent regions and can be removed from the layer list. It
3096 * does not affect the visibleRegion of this layer or any layers
3097 * beneath it. The hint may not be correct if apps don't respect the
3098 * SurfaceView restrictions (which, sadly, some don't).
3099 */
3100 Region transparentRegion;
3101
Mathias Agopianab028732010-03-16 16:41:46 -07003102
3103 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003104 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003105 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003106 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003107
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003108 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003109 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003110 if (!visibleRegion.isEmpty()) {
3111 // Remove the transparent area from the visible region
3112 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003113 if (tr.preserveRects()) {
3114 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003115 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003116 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003117 // transformation too complex, can't do the
3118 // transparent region optimization.
3119 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003120 }
Mathias Agopianab028732010-03-16 16:41:46 -07003121 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003122
Mathias Agopianab028732010-03-16 16:41:46 -07003123 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003124 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003125 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003126 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003127 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003128 // the opaque region is the layer's footprint
3129 opaqueRegion = visibleRegion;
3130 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003131 }
3132 }
3133
Robert Carre5f4f692018-01-12 13:12:28 -08003134 if (visibleRegion.isEmpty()) {
3135 layer->clearVisibilityRegions();
3136 return;
3137 }
3138
Mathias Agopianab028732010-03-16 16:41:46 -07003139 // Clip the covered region to the visible region
3140 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3141
3142 // Update aboveCoveredLayers for next (lower) layer
3143 aboveCoveredLayers.orSelf(visibleRegion);
3144
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003145 // subtract the opaque region covered by the layers above us
3146 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003147
3148 // compute this layer's dirty region
3149 if (layer->contentDirty) {
3150 // we need to invalidate the whole region
3151 dirty = visibleRegion;
3152 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003153 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003154 layer->contentDirty = false;
3155 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003156 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003157 * the exposed region consists of two components:
3158 * 1) what's VISIBLE now and was COVERED before
3159 * 2) what's EXPOSED now less what was EXPOSED before
3160 *
3161 * note that (1) is conservative, we start with the whole
3162 * visible region but only keep what used to be covered by
3163 * something -- which mean it may have been exposed.
3164 *
3165 * (2) handles areas that were not covered by anything but got
3166 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003167 */
Mathias Agopianab028732010-03-16 16:41:46 -07003168 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003169 const Region oldVisibleRegion = layer->visibleRegion;
3170 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003171 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3172 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003173 }
3174 dirty.subtractSelf(aboveOpaqueLayers);
3175
3176 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003177 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003178
Mathias Agopianab028732010-03-16 16:41:46 -07003179 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003180 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003181
Jesse Halla8026d22012-09-25 13:25:04 -07003182 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003183 layer->setVisibleRegion(visibleRegion);
3184 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003185 layer->setVisibleNonTransparentRegion(
3186 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003187 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003188
Mathias Agopian87baae12012-07-31 12:38:26 -07003189 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003190}
3191
Chia-I Wuab0c3192017-08-01 11:29:00 -07003192void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003193 for (const auto& [token, displayDevice] : mDisplays) {
3194 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003195 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003196 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003197 }
3198 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003199}
3200
Dan Stoza6b9454d2014-11-07 16:00:59 -08003201bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003202{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003203 ALOGV("handlePageFlip");
3204
Brian Andersond6927fb2016-07-23 23:37:30 -07003205 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003206
Mathias Agopian4fec8732012-06-29 14:12:52 -07003207 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003208 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003209 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003210
3211 // Store the set of layers that need updates. This set must not change as
3212 // buffers are being latched, as this could result in a deadlock.
3213 // Example: Two producers share the same command stream and:
3214 // 1.) Layer 0 is latched
3215 // 2.) Layer 0 gets a new frame
3216 // 2.) Layer 1 gets a new frame
3217 // 3.) Layer 1 is latched.
3218 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3219 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003220 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003221 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003222 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003223 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3224 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003225 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003226 } else {
3227 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003228 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003229 } else {
3230 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003231 }
Robert Carr2047fae2016-11-28 14:09:09 -08003232 });
3233
Lloyd Piquef2c79392018-12-20 16:23:33 -08003234 if (!mLayersWithQueuedFrames.empty()) {
3235 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3236 // writes to Layer current state. See also b/119481871
3237 Mutex::Autolock lock(mStateLock);
3238
3239 for (auto& layer : mLayersWithQueuedFrames) {
3240 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3241 layer->useSurfaceDamage();
3242 invalidateLayerStack(layer, dirty);
3243 if (layer->isBufferLatched()) {
3244 newDataLatched = true;
3245 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003246 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003247 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003248
Alec Mouri86770e52018-09-24 22:40:58 +00003249 // Clear the renderengine fence here...
3250 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3251 // clear instead of sp::clear.
3252 getBE().flushFence = Fence::NO_FENCE;
3253
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003254 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003255
Vishnu Nairde19f852018-12-18 16:11:53 -08003256 if (visibleRegions) {
3257 // Update input window info if the layer receives its first buffer.
3258 updateInputWindows();
3259 }
3260
Dan Stoza6b9454d2014-11-07 16:00:59 -08003261 // If we will need to wake up at some time in the future to deal with a
3262 // queued frame that shouldn't be displayed during this vsync period, wake
3263 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003264 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003265 signalLayerUpdate();
3266 }
3267
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003268 // enter boot animation on first buffer latch
3269 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3270 ALOGI("Enter boot animation");
3271 mBootStage = BootStage::BOOTANIMATION;
3272 }
3273
Dan Stoza6b9454d2014-11-07 16:00:59 -08003274 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003275 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003276}
3277
Mathias Agopianad456f92011-01-13 17:53:01 -08003278void SurfaceFlinger::invalidateHwcGeometry()
3279{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003280 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003281}
3282
Lloyd Pique32cbe282018-10-19 13:09:22 -07003283void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003284 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003285 auto display = displayDevice->getCompositionDisplay();
3286
Dan Stoza71433162014-02-04 16:22:36 -08003287 // We only need to actually compose the display if:
3288 // 1) It is being handled by hardware composer, which may need this to
3289 // keep its virtual display state machine in sync, or
3290 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003291 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003292 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003293 return;
3294 }
3295
Dan Stoza9e56aa02015-11-02 13:00:03 -08003296 ALOGV("doDisplayComposition");
Lloyd Pique32cbe282018-10-19 13:09:22 -07003297 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003298
3299 // swap buffers (presentation)
Lloyd Pique31cb2942018-10-19 17:23:03 -07003300 display->getRenderSurface()->queueBuffer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003301}
3302
Lloyd Pique32cbe282018-10-19 13:09:22 -07003303bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003304 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003305
Lloyd Pique32cbe282018-10-19 13:09:22 -07003306 auto display = displayDevice->getCompositionDisplay();
3307 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003308 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003309
3310 const Region bounds(displayState.bounds);
3311 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003312 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003313 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003314
Peiyong Lind3788632018-09-18 16:01:31 -07003315 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003316 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003317
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003318 // Framebuffer will live in this scope for GPU composition.
3319 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
3320
Dan Stoza9e56aa02015-11-02 13:00:03 -08003321 if (hasClientComposition) {
3322 ALOGV("hasClientComposition");
3323
Lloyd Pique31cb2942018-10-19 17:23:03 -07003324 sp<GraphicBuffer> buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003325
3326 if (buf == nullptr) {
3327 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3328 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003329 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003330 return false;
3331 }
3332
3333 // Bind the framebuffer in this scope.
3334 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3335 buf->getNativeBuffer());
3336
3337 if (fbo->getStatus() != NO_ERROR) {
3338 ALOGW("Binding buffer for display [%s] failed with status: %d",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003339 displayDevice->getDisplayName().c_str(), fbo->getStatus());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003340 return false;
3341 }
3342
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003343 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003344 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003345 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003346 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003347 }
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003348 getRenderEngine().setOutputDataSpace(outputDataspace);
3349 getRenderEngine().setDisplayMaxLuminance(
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003350 profile->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003351
Lloyd Pique441d5042018-10-18 16:49:51 -07003352 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003353 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003354 getHwComposer()
3355 .hasDisplayCapability(displayId,
3356 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003357
Peiyong Lind3788632018-09-18 16:01:31 -07003358 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003359 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3360 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003361 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003362 }
3363
Lloyd Pique31cb2942018-10-19 17:23:03 -07003364 display->getRenderSurface()->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003365
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003366 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003367 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003368 // when using overlays, we assume a fully transparent framebuffer
3369 // NOTE: we could reduce how much we need to clear, for instance
3370 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003371 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003372 // We'll revisit later if needed.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003373 getRenderEngine().clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003374 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003375 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003376 // we're left with the letterbox region
3377 // (common case is that letterbox ends-up being empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003378 const Region letterbox = bounds.subtract(displayState.scissor);
Mathias Agopian766dc492012-10-30 18:08:06 -07003379
3380 // compute the area to clear
Lloyd Pique32cbe282018-10-19 13:09:22 -07003381 const Region region = displayState.undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003382
Mathias Agopianb9494d52012-04-18 02:28:45 -07003383 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003384 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003385 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003386 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003387 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003388 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003389
Lloyd Pique32cbe282018-10-19 13:09:22 -07003390 const Rect& bounds = displayState.bounds;
3391 const Rect& scissor = displayState.scissor;
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003392 if (scissor != bounds) {
3393 // scissor doesn't match the screen's dimensions, so we
3394 // need to clear everything outside of it and enable
3395 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003396
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003397 // enable scissor for this frame
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003398 getRenderEngine().setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003399 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003400 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003401
Mathias Agopian85d751c2012-08-29 16:59:24 -07003402 /*
3403 * and then, render the layers targeted at the framebuffer
3404 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003405
Dan Stoza9e56aa02015-11-02 13:00:03 -08003406 ALOGV("Rendering client layers");
Lloyd Pique32cbe282018-10-19 13:09:22 -07003407 const ui::Transform& displayTransform = displayState.transform;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003408 bool firstLayer = true;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003409 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003410 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003411 displayTransform.transform(layer->visibleRegion)));
3412 ALOGV("Layer: %s", layer->getName().string());
3413 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003414 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003415 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003416 case HWC2::Composition::Cursor:
3417 case HWC2::Composition::Device:
3418 case HWC2::Composition::Sideband:
3419 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003420 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003421 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003422 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003423 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003424 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003425 // never clear the very first layer since we're
3426 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003427 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003428 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003429 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003430 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003431 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003432 if (layer->hasColorTransform()) {
3433 mat4 tmpMatrix;
3434 if (applyColorMatrix) {
3435 tmpMatrix = mDrawingState.colorMatrix;
3436 }
3437 tmpMatrix *= layer->getColorTransform();
Peiyong Lind3788632018-09-18 16:01:31 -07003438 getRenderEngine().setColorTransform(tmpMatrix);
3439 } else {
3440 getRenderEngine().setColorTransform(colorMatrix);
3441 }
David Sodmanc1498e62018-09-12 14:36:26 -07003442 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003443 break;
3444 }
3445 default:
3446 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003447 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003448 } else {
3449 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003450 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003451 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003452 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003453
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003454 // Perform some cleanup steps if we used client composition.
3455 if (hasClientComposition) {
3456 getRenderEngine().setColorTransform(mat4());
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003457 getRenderEngine().disableScissor();
Lloyd Pique31cb2942018-10-19 17:23:03 -07003458 display->getRenderSurface()->finishBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003459 // Clear out error flags here so that we don't wait until next
3460 // composition to log.
3461 getRenderEngine().checkErrors();
3462 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003463 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003464}
3465
Chia-I Wu28e3a252018-09-07 12:05:02 -07003466void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003467 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003468 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003469}
3470
Dan Stoza7d89d062015-04-30 13:29:25 -07003471status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003472 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003473 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003474 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003475 const sp<Layer>& parent,
3476 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003477{
Dan Stoza7d89d062015-04-30 13:29:25 -07003478 // add this layer to the current state list
3479 {
3480 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003481 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003482 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3483 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003484 return NO_MEMORY;
3485 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003486 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003487 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003488 } else if (parent == nullptr) {
3489 lbc->onRemovedFromCurrentState();
3490 } else if (parent->isRemovedFromCurrentState()) {
3491 parent->addChild(lbc);
3492 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003493 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003494 parent->addChild(lbc);
3495 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003496
Yiwei Zhang243b3782018-05-15 17:40:04 -07003497 if (gbc != nullptr) {
3498 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3499 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3500 mMaxGraphicBufferProducerListSize,
3501 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3502 mGraphicBufferProducerList.size(),
3503 mMaxGraphicBufferProducerListSize, mNumLayers);
3504 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003505 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003506 }
3507
Mathias Agopian96f08192010-06-02 23:28:45 -07003508 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003509 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003510
Dan Stoza7d89d062015-04-30 13:29:25 -07003511 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003512}
3513
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003514uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003515 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003516}
3517
Mathias Agopian3f844832013-08-07 21:24:32 -07003518uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003519 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003520}
3521
Mathias Agopian3f844832013-08-07 21:24:32 -07003522uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003523 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003524}
3525
3526uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003527 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003528 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003529 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003530 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003531 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003532 }
3533 return old;
3534}
3535
Marissa Wall713b63f2018-10-17 15:42:43 -07003536bool SurfaceFlinger::flushTransactionQueues() {
3537 Mutex::Autolock _l(mStateLock);
3538 auto it = mTransactionQueues.begin();
3539 while (it != mTransactionQueues.end()) {
3540 auto& [applyToken, transactionQueue] = *it;
3541
3542 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003543 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3544 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003545 break;
3546 }
chaviw273171b2018-12-26 11:46:30 -08003547 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003548 transactionQueue.pop();
3549 }
3550
3551 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3552 }
3553 return mTransactionQueues.empty();
3554}
3555
chaviwca27f252018-02-06 16:46:39 -08003556bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3557 for (const ComposerState& state : states) {
3558 // Here we need to check that the interface we're given is indeed
3559 // one of our own. A malicious client could give us a nullptr
3560 // IInterface, or one of its own or even one of our own but a
3561 // different type. All these situations would cause us to crash.
3562 if (state.client == nullptr) {
3563 return true;
3564 }
3565
3566 sp<IBinder> binder = IInterface::asBinder(state.client);
3567 if (binder == nullptr) {
3568 return true;
3569 }
3570
3571 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3572 return true;
3573 }
3574 }
3575 return false;
3576}
3577
Marissa Wall17b4e452018-12-26 16:32:34 -08003578bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3579 const Vector<ComposerState>& states) {
3580 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3581 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3582 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3583 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3584 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3585 return false;
3586 }
3587
Marissa Wall713b63f2018-10-17 15:42:43 -07003588 for (const ComposerState& state : states) {
3589 const layer_state_t& s = state.state;
3590 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3591 continue;
3592 }
3593 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003594 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003595 }
3596 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003597 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003598}
3599
3600void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3601 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003602 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003603 const InputWindowCommands& inputWindowCommands,
3604 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003605 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003606 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003607
chaviwca27f252018-02-06 16:46:39 -08003608 if (containsAnyInvalidClientState(states)) {
3609 return;
3610 }
3611
Marissa Wall713b63f2018-10-17 15:42:43 -07003612 // If its TransactionQueue already has a pending TransactionState or if it is pending
3613 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003614 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3615 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003616 setTransactionFlags(eTransactionNeeded);
3617 return;
3618 }
3619
chaviw273171b2018-12-26 11:46:30 -08003620 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003621}
3622
3623void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003624 const Vector<DisplayState>& displays, uint32_t flags,
3625 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003626 uint32_t transactionFlags = 0;
3627
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003628 if (flags & eAnimation) {
3629 // For window updates that are part of an animation we must wait for
3630 // previous animation "frames" to be handled.
3631 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003632 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003633 if (CC_UNLIKELY(err != NO_ERROR)) {
3634 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003635 // caller after a few seconds.
3636 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3637 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003638 mAnimTransactionPending = false;
3639 break;
3640 }
3641 }
3642 }
3643
chaviwca27f252018-02-06 16:46:39 -08003644 for (const DisplayState& display : displays) {
3645 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003646 }
3647
Marissa Walle2ffb422018-10-12 11:33:52 -07003648 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003649 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003650 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003651 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003652 // If the state doesn't require a traversal and there are callbacks, send them now
3653 if (!(clientStateFlags & eTraversalNeeded)) {
3654 mTransactionCompletedThread.sendCallbacks();
3655 }
3656 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003657
chaviw273171b2018-12-26 11:46:30 -08003658 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3659
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003660 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3661 // anyway. This can be used as a flush mechanism for previous async transactions.
3662 // Empty animation transaction can be used to simulate back-pressure, so also force a
3663 // transaction for empty animation transactions.
3664 if (transactionFlags == 0 &&
3665 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003666 transactionFlags = eTransactionNeeded;
3667 }
3668
Mathias Agopian386aa982011-11-07 21:58:03 -08003669 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003670 if (mInterceptor->isEnabled()) {
3671 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003672 }
Irvel468051e2016-06-13 16:44:44 -07003673
Mathias Agopian386aa982011-11-07 21:58:03 -08003674 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003675 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3676 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003677 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003678
3679 // if this is a synchronous transaction, wait for it to take effect
3680 // before returning.
3681 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003682 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003683 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003684 if (flags & eAnimation) {
3685 mAnimTransactionPending = true;
3686 }
3687 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003688 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3689 if (CC_UNLIKELY(err != NO_ERROR)) {
3690 // just in case something goes wrong in SF, return to the
3691 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003692 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3693 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003694 break;
3695 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003696 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003697 }
3698}
3699
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003700uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3701 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3702 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003703
Mathias Agopiane57f2922012-08-09 16:29:12 -07003704 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003705 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3706
3707 const uint32_t what = s.what;
3708 if (what & DisplayState::eSurfaceChanged) {
3709 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3710 state.surface = s.surface;
3711 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003712 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003713 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003714 if (what & DisplayState::eLayerStackChanged) {
3715 if (state.layerStack != s.layerStack) {
3716 state.layerStack = s.layerStack;
3717 flags |= eDisplayTransactionNeeded;
3718 }
3719 }
3720 if (what & DisplayState::eDisplayProjectionChanged) {
3721 if (state.orientation != s.orientation) {
3722 state.orientation = s.orientation;
3723 flags |= eDisplayTransactionNeeded;
3724 }
3725 if (state.frame != s.frame) {
3726 state.frame = s.frame;
3727 flags |= eDisplayTransactionNeeded;
3728 }
3729 if (state.viewport != s.viewport) {
3730 state.viewport = s.viewport;
3731 flags |= eDisplayTransactionNeeded;
3732 }
3733 }
3734 if (what & DisplayState::eDisplaySizeChanged) {
3735 if (state.width != s.width) {
3736 state.width = s.width;
3737 flags |= eDisplayTransactionNeeded;
3738 }
3739 if (state.height != s.height) {
3740 state.height = s.height;
3741 flags |= eDisplayTransactionNeeded;
3742 }
3743 }
3744
Mathias Agopiane57f2922012-08-09 16:29:12 -07003745 return flags;
3746}
3747
Robert Carrd4ae7f32018-06-07 16:10:57 -07003748bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3749 IPCThreadState* ipc = IPCThreadState::self();
3750 const int pid = ipc->getCallingPid();
3751 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003752 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003753 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003754 return false;
3755 }
3756 return true;
3757}
3758
chaviwca27f252018-02-06 16:46:39 -08003759uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3760 const layer_state_t& s = composerState.state;
3761 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3762
Mathias Agopian13127d82013-03-05 17:47:11 -08003763 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003764 if (layer == nullptr) {
3765 return 0;
3766 }
3767
chaviw8b3871a2017-11-01 17:41:01 -07003768 uint32_t flags = 0;
3769
Garfield Tan8a3083e2018-12-03 13:21:07 -08003770 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003771 bool geometryAppliesWithResize =
3772 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003773
3774 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3775 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003776 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003777 layer->pushPendingState();
3778 }
3779
chaviw8b3871a2017-11-01 17:41:01 -07003780 if (what & layer_state_t::ePositionChanged) {
3781 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3782 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003783 }
chaviw8b3871a2017-11-01 17:41:01 -07003784 }
3785 if (what & layer_state_t::eLayerChanged) {
3786 // NOTE: index needs to be calculated before we update the state
3787 const auto& p = layer->getParent();
3788 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003789 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003790 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003791 mCurrentState.layersSortedByZ.removeAt(idx);
3792 mCurrentState.layersSortedByZ.add(layer);
3793 // we need traversal (state changed)
3794 // AND transaction (list changed)
3795 flags |= eTransactionNeeded|eTraversalNeeded;
3796 }
chaviw8b3871a2017-11-01 17:41:01 -07003797 } else {
3798 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003799 flags |= eTransactionNeeded|eTraversalNeeded;
3800 }
3801 }
chaviw8b3871a2017-11-01 17:41:01 -07003802 }
3803 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003804 // NOTE: index needs to be calculated before we update the state
3805 const auto& p = layer->getParent();
3806 if (p == nullptr) {
3807 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3808 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3809 mCurrentState.layersSortedByZ.removeAt(idx);
3810 mCurrentState.layersSortedByZ.add(layer);
3811 // we need traversal (state changed)
3812 // AND transaction (list changed)
3813 flags |= eTransactionNeeded|eTraversalNeeded;
3814 }
3815 } else {
3816 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3817 flags |= eTransactionNeeded|eTraversalNeeded;
3818 }
chaviw8b3871a2017-11-01 17:41:01 -07003819 }
3820 }
3821 if (what & layer_state_t::eSizeChanged) {
3822 if (layer->setSize(s.w, s.h)) {
3823 flags |= eTraversalNeeded;
3824 }
3825 }
3826 if (what & layer_state_t::eAlphaChanged) {
3827 if (layer->setAlpha(s.alpha))
3828 flags |= eTraversalNeeded;
3829 }
3830 if (what & layer_state_t::eColorChanged) {
3831 if (layer->setColor(s.color))
3832 flags |= eTraversalNeeded;
3833 }
Peiyong Lind3788632018-09-18 16:01:31 -07003834 if (what & layer_state_t::eColorTransformChanged) {
3835 if (layer->setColorTransform(s.colorTransform)) {
3836 flags |= eTraversalNeeded;
3837 }
3838 }
chaviw8b3871a2017-11-01 17:41:01 -07003839 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003840 // TODO: b/109894387
3841 //
3842 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3843 // rotation. To see the problem observe that if we have a square parent, and a child
3844 // of the same size, then we rotate the child 45 degrees around it's center, the child
3845 // must now be cropped to a non rectangular 8 sided region.
3846 //
3847 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3848 // private API, and the WindowManager only uses rotation in one case, which is on a top
3849 // level layer in which cropping is not an issue.
3850 //
3851 // However given that abuse of rotation matrices could lead to surfaces extending outside
3852 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3853 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3854 // transformations.
3855 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003856 flags |= eTraversalNeeded;
3857 }
3858 if (what & layer_state_t::eTransparentRegionChanged) {
3859 if (layer->setTransparentRegionHint(s.transparentRegion))
3860 flags |= eTraversalNeeded;
3861 }
3862 if (what & layer_state_t::eFlagsChanged) {
3863 if (layer->setFlags(s.flags, s.mask))
3864 flags |= eTraversalNeeded;
3865 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003866 if (what & layer_state_t::eCropChanged_legacy) {
3867 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003868 flags |= eTraversalNeeded;
3869 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003870 if (what & layer_state_t::eCornerRadiusChanged) {
3871 if (layer->setCornerRadius(s.cornerRadius))
3872 flags |= eTraversalNeeded;
3873 }
chaviw8b3871a2017-11-01 17:41:01 -07003874 if (what & layer_state_t::eLayerStackChanged) {
3875 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3876 // We only allow setting layer stacks for top level layers,
3877 // everything else inherits layer stack from its parent.
3878 if (layer->hasParent()) {
3879 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3880 layer->getName().string());
3881 } else if (idx < 0) {
3882 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3883 "that also does not appear in the top level layer list. Something"
3884 " has gone wrong.", layer->getName().string());
3885 } else if (layer->setLayerStack(s.layerStack)) {
3886 mCurrentState.layersSortedByZ.removeAt(idx);
3887 mCurrentState.layersSortedByZ.add(layer);
3888 // we need traversal (state changed)
3889 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003890 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003891 }
3892 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003893 if (what & layer_state_t::eDeferTransaction_legacy) {
3894 if (s.barrierHandle_legacy != nullptr) {
3895 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3896 } else if (s.barrierGbp_legacy != nullptr) {
3897 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003898 if (authenticateSurfaceTextureLocked(gbp)) {
3899 const auto& otherLayer =
3900 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003901 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003902 } else {
3903 ALOGE("Attempt to defer transaction to to an"
3904 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003905 }
3906 }
chaviw8b3871a2017-11-01 17:41:01 -07003907 // We don't trigger a traversal here because if no other state is
3908 // changed, we don't want this to cause any more work
3909 }
3910 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003911 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003912 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003913 if (!hadParent) {
3914 mCurrentState.layersSortedByZ.remove(layer);
3915 }
chaviw8b3871a2017-11-01 17:41:01 -07003916 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003917 }
chaviw8b3871a2017-11-01 17:41:01 -07003918 }
3919 if (what & layer_state_t::eReparentChildren) {
3920 if (layer->reparentChildren(s.reparentHandle)) {
3921 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003922 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003923 }
chaviw8b3871a2017-11-01 17:41:01 -07003924 if (what & layer_state_t::eDetachChildren) {
3925 layer->detachChildren();
3926 }
3927 if (what & layer_state_t::eOverrideScalingModeChanged) {
3928 layer->setOverrideScalingMode(s.overrideScalingMode);
3929 // We don't trigger a traversal here because if no other state is
3930 // changed, we don't want this to cause any more work
3931 }
Marissa Wall61c58622018-07-18 10:12:20 -07003932 if (what & layer_state_t::eTransformChanged) {
3933 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3934 }
3935 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3936 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3937 flags |= eTraversalNeeded;
3938 }
3939 if (what & layer_state_t::eCropChanged) {
3940 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3941 }
Marissa Wall861616d2018-10-22 12:52:23 -07003942 if (what & layer_state_t::eFrameChanged) {
3943 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3944 }
Marissa Wall61c58622018-07-18 10:12:20 -07003945 if (what & layer_state_t::eBufferChanged) {
3946 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3947 }
3948 if (what & layer_state_t::eAcquireFenceChanged) {
3949 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3950 }
3951 if (what & layer_state_t::eDataspaceChanged) {
3952 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3953 }
3954 if (what & layer_state_t::eHdrMetadataChanged) {
3955 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3956 }
3957 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3958 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3959 }
3960 if (what & layer_state_t::eApiChanged) {
3961 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3962 }
3963 if (what & layer_state_t::eSidebandStreamChanged) {
3964 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3965 }
Robert Carr720e5062018-07-30 17:45:14 -07003966 if (what & layer_state_t::eInputInfoChanged) {
3967 layer->setInputInfo(s.inputInfo);
3968 flags |= eTraversalNeeded;
3969 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003970 std::vector<sp<CallbackHandle>> callbackHandles;
3971 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3972 mTransactionCompletedThread.run();
3973 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3974 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3975 }
3976 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003977 if (what & layer_state_t::eCachedBufferChanged) {
3978 sp<GraphicBuffer> buffer =
3979 mBufferStateLayerCache.get(s.cachedBuffer.token, s.cachedBuffer.bufferId);
3980 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
3981 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003982 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3983 // Do not put anything that updates layer state or modifies flags after
3984 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003985 return flags;
3986}
3987
chaviw273171b2018-12-26 11:46:30 -08003988uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3989 uint32_t flags = 0;
3990 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3991 flags |= eTraversalNeeded;
3992 }
3993
3994 mInputWindowCommands.merge(inputWindowCommands);
3995 return flags;
3996}
3997
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003998status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003999 const String8& name,
4000 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004001 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07004002 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05004003 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004004{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004005 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004006 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004007 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004008 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004009 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004010
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004011 status_t result = NO_ERROR;
4012
4013 sp<Layer> layer;
4014
Cody Northropbc755282017-03-31 12:00:08 -06004015 String8 uniqueName = getUniqueLayerName(name);
4016
Mathias Agopian3165cc22012-08-08 19:42:09 -07004017 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004018 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004019 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4020 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004021
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004022 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004023 case ISurfaceComposerClient::eFXSurfaceBufferState:
4024 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4025 break;
chaviw13fdc492017-06-27 12:40:18 -07004026 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004027 // check if buffer size is set for color layer.
4028 if (w > 0 || h > 0) {
4029 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4030 int(w), int(h));
4031 return BAD_VALUE;
4032 }
4033
chaviw13fdc492017-06-27 12:40:18 -07004034 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004035 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004036 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004037 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004038 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004039 // check if buffer size is set for container layer.
4040 if (w > 0 || h > 0) {
4041 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4042 int(w), int(h));
4043 return BAD_VALUE;
4044 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004045 result = createContainerLayer(client,
4046 uniqueName, w, h, flags,
4047 handle, &layer);
4048 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004049 default:
4050 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004051 break;
4052 }
4053
Dan Stoza7d89d062015-04-30 13:29:25 -07004054 if (result != NO_ERROR) {
4055 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004056 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004057
Chia-I Wuab0c3192017-08-01 11:29:00 -07004058 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4059 // TODO b/64227542
4060 if (windowType == 441731) {
4061 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
4062 layer->setPrimaryDisplayOnly();
4063 }
4064
Albert Chaulk479c60c2017-01-27 14:21:34 -05004065 layer->setInfo(windowType, ownerUid);
4066
Robert Carrb89ea9d2018-12-10 13:01:14 -08004067 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4068 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4069 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004070 if (result != NO_ERROR) {
4071 return result;
4072 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004073 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004074
4075 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004076 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004077}
4078
Cody Northropbc755282017-03-31 12:00:08 -06004079String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4080{
4081 bool matchFound = true;
4082 uint32_t dupeCounter = 0;
4083
4084 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4085 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4086
Dan Stoza436ccf32018-06-21 12:10:12 -07004087 // Grab the state lock since we're accessing mCurrentState
4088 Mutex::Autolock lock(mStateLock);
4089
Cody Northropbc755282017-03-31 12:00:08 -06004090 // Loop over layers until we're sure there is no matching name
4091 while (matchFound) {
4092 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004093 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004094 if (layer->getName() == uniqueName) {
4095 matchFound = true;
4096 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4097 }
4098 });
4099 }
4100
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004101 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4102 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004103
4104 return uniqueName;
4105}
4106
Marissa Wallfd668622018-05-10 10:21:13 -07004107status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4108 uint32_t w, uint32_t h, uint32_t flags,
4109 PixelFormat& format, sp<IBinder>* handle,
4110 sp<IGraphicBufferProducer>* gbp,
4111 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004112 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004113 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004114 case PIXEL_FORMAT_TRANSPARENT:
4115 case PIXEL_FORMAT_TRANSLUCENT:
4116 format = PIXEL_FORMAT_RGBA_8888;
4117 break;
4118 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004119 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004120 break;
4121 }
4122
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004123 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004124 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004125 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004126 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004127 *handle = layer->getHandle();
4128 *gbp = layer->getProducer();
4129 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004130 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004131
Marissa Wallfd668622018-05-10 10:21:13 -07004132 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004133 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004134}
4135
Marissa Wall61c58622018-07-18 10:12:20 -07004136status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4137 uint32_t w, uint32_t h, uint32_t flags,
4138 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004139 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004140 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004141 *handle = layer->getHandle();
4142 *outLayer = layer;
4143
4144 return NO_ERROR;
4145}
4146
chaviw13fdc492017-06-27 12:40:18 -07004147status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004148 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004149 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004150{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004151 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004152 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004153 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004154}
4155
Robert Carr6b3f6c52018-08-13 13:05:17 -07004156status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4157 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4158 sp<IBinder>* handle, sp<Layer>* outLayer)
4159{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004160 *outLayer =
4161 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004162 *handle = (*outLayer)->getHandle();
4163 return NO_ERROR;
4164}
4165
4166
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004167void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004168 mLayersPendingRemoval.add(layer);
4169 mLayersRemoved = true;
4170 setTransactionFlags(eTransactionNeeded);
4171}
4172
Robert Carr695d5282018-12-18 15:27:58 -08004173void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004174{
Robert Carr2e102c92018-10-23 12:11:15 -07004175 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004176 // If a layer has a parent, we allow it to out-live it's handle
4177 // with the idea that the parent holds a reference and will eventually
4178 // be cleaned up. However no one cleans up the top-level so we do so
4179 // here.
4180 if (layer->getParent() == nullptr) {
4181 mCurrentState.layersSortedByZ.remove(layer);
4182 }
4183 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004184 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004185}
4186
Mathias Agopianb60314a2012-04-10 22:09:54 -07004187// ---------------------------------------------------------------------------
4188
Andy McFadden13a082e2012-08-24 10:16:42 -07004189void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004190 const auto display = getDefaultDisplayDeviceLocked();
4191 if (!display) return;
4192
4193 const sp<IBinder> token = display->getDisplayToken().promote();
4194 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004195
Jesse Hall01e29052013-02-19 16:13:35 -08004196 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004197 Vector<ComposerState> state;
4198 Vector<DisplayState> displays;
4199 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004200 d.what = DisplayState::eDisplayProjectionChanged |
4201 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004202 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004203 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004204 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004205 d.frame.makeInvalid();
4206 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004207 d.width = 0;
4208 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004209 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004210 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004211
Dominik Laskowskie9774092018-12-11 10:04:24 -08004212 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004213
Dominik Laskowski83b88212018-12-11 13:34:06 -08004214 const nsecs_t vsyncPeriod = getVsyncPeriod();
4215 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004216
Brian Andersond0010582017-03-07 13:20:31 -08004217 // Use phase of 0 since phase is not known.
4218 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004219 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004220 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004221}
4222
4223void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004224 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004225 postMessageAsync(
4226 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004227}
4228
Dominik Laskowskie9774092018-12-11 10:04:24 -08004229void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004230 if (display->isVirtual()) {
4231 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004232 return;
4233 }
4234
Dominik Laskowski075d3172018-05-24 15:50:06 -07004235 const auto displayId = display->getId();
4236 LOG_ALWAYS_FATAL_IF(!displayId);
4237
Dominik Laskowski34157762018-10-31 13:07:19 -07004238 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004239
4240 int currentMode = display->getPowerMode();
4241 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004242 return;
4243 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004244
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004245 display->setPowerMode(mode);
4246
Lloyd Pique4dccc412018-01-22 17:21:36 -08004247 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004248 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004249 }
4250
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004251 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004252 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004253 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004254 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004255 if (mUseScheduler) {
4256 mScheduler->onScreenAcquired(mAppConnectionHandle);
4257 } else {
4258 mEventThread->onScreenAcquired();
4259 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004260 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004261 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004262
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004263 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004264 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004265 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004266
4267 struct sched_param param = {0};
4268 param.sched_priority = 1;
4269 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4270 ALOGW("Couldn't set SCHED_FIFO on display on");
4271 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004272 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004273 // Turn off the display
4274 struct sched_param param = {0};
4275 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4276 ALOGW("Couldn't set SCHED_OTHER on display off");
4277 }
4278
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004279 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004280 if (mUseScheduler) {
4281 mScheduler->disableHardwareVsync(true);
4282 } else {
4283 disableHardwareVsync(true); // also cancels any in-progress resync
4284 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004285 if (mUseScheduler) {
4286 mScheduler->onScreenReleased(mAppConnectionHandle);
4287 } else {
4288 mEventThread->onScreenReleased();
4289 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004290 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004291
Dominik Laskowski075d3172018-05-24 15:50:06 -07004292 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004293 mVisibleRegionsDirty = true;
4294 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004295 } else if (mode == HWC_POWER_MODE_DOZE ||
4296 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004297 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004298 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004299 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004300 if (mUseScheduler) {
4301 mScheduler->onScreenAcquired(mAppConnectionHandle);
4302 } else {
4303 mEventThread->onScreenAcquired();
4304 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004305 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004306 }
4307 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4308 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004309 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004310 if (mUseScheduler) {
4311 mScheduler->disableHardwareVsync(true);
4312 } else {
4313 disableHardwareVsync(true); // also cancels any in-progress resync
4314 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004315 if (mUseScheduler) {
4316 mScheduler->onScreenReleased(mAppConnectionHandle);
4317 } else {
4318 mEventThread->onScreenReleased();
4319 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004320 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004321 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004322 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004323 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004324 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004325 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004326
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004327 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004328 mTimeStats->setPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004329 }
4330
Dominik Laskowski34157762018-10-31 13:07:19 -07004331 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004332}
4333
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004334void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004335 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004336 const auto display = getDisplayDevice(displayToken);
4337 if (!display) {
4338 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4339 displayToken.get());
4340 } else if (display->isVirtual()) {
4341 ALOGW("Attempt to set power mode %d for virtual display", mode);
4342 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004343 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004344 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004345 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004346}
4347
4348// ---------------------------------------------------------------------------
4349
Lloyd Pique755e3192018-01-31 16:46:15 -08004350status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4351 NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004352 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004353
Mathias Agopianbd115332013-04-18 16:41:04 -07004354 IPCThreadState* ipc = IPCThreadState::self();
4355 const int pid = ipc->getCallingPid();
4356 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004357
Mathias Agopianbd115332013-04-18 16:41:04 -07004358 if ((uid != AID_SHELL) &&
4359 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004360 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4361 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004362 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004363 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004364 // (this would indicate SF is stuck, but we want to be able to
4365 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004366 status_t err = mStateLock.timedLock(s2ns(1));
4367 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004368 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004369 StringAppendF(&result,
4370 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4371 "(no locks held)\n",
4372 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004373 }
4374
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004375 bool dumpAll = true;
4376 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004377 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004378
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004379 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004380 if ((index < numArgs) &&
4381 (args[index] == String16("--list"))) {
4382 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004383 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004384 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004385 }
4386
4387 if ((index < numArgs) &&
4388 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004389 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004390 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004391 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004392 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004393
4394 if ((index < numArgs) &&
4395 (args[index] == String16("--latency-clear"))) {
4396 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004397 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004398 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004399 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004400
4401 if ((index < numArgs) &&
4402 (args[index] == String16("--dispsync"))) {
4403 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004404 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004405 dumpAll = false;
4406 }
Dan Stozab90cf072015-03-05 11:05:59 -08004407
4408 if ((index < numArgs) &&
4409 (args[index] == String16("--static-screen"))) {
4410 index++;
4411 dumpStaticScreenStats(result);
4412 dumpAll = false;
4413 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004414
4415 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004416 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004417 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004418 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004419 dumpAll = false;
4420 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004421
4422 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4423 index++;
4424 dumpWideColorInfo(result);
4425 dumpAll = false;
4426 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004427
4428 if ((index < numArgs) &&
4429 (args[index] == String16("--enable-layer-stats"))) {
4430 index++;
4431 mLayerStats.enable();
4432 dumpAll = false;
4433 }
4434
4435 if ((index < numArgs) &&
4436 (args[index] == String16("--disable-layer-stats"))) {
4437 index++;
4438 mLayerStats.disable();
4439 dumpAll = false;
4440 }
4441
4442 if ((index < numArgs) &&
4443 (args[index] == String16("--clear-layer-stats"))) {
4444 index++;
4445 mLayerStats.clear();
4446 dumpAll = false;
4447 }
4448
4449 if ((index < numArgs) &&
4450 (args[index] == String16("--dump-layer-stats"))) {
4451 index++;
4452 mLayerStats.dump(result);
4453 dumpAll = false;
4454 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004455
4456 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004457 (args[index] == String16("--frame-composition"))) {
4458 index++;
4459 dumpFrameCompositionInfo(result);
4460 dumpAll = false;
4461 }
4462
4463 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004464 (args[index] == String16("--display-identification"))) {
4465 index++;
4466 dumpDisplayIdentificationData(result);
4467 dumpAll = false;
4468 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004469
4470 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4471 index++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004472 mTimeStats->parseArgs(asProto, args, index, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004473 dumpAll = false;
4474 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004475 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004476
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004477 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004478 if (asProto) {
4479 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4480 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4481 } else {
4482 dumpAllLocked(args, index, result);
4483 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004484 }
4485
Mathias Agopian9795c422009-08-26 16:36:26 -07004486 if (locked) {
4487 mStateLock.unlock();
4488 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004489 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004490 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004491 return NO_ERROR;
4492}
4493
Yiwei Zhang5434a782018-12-05 18:06:32 -08004494void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */, size_t& /* index */,
4495 std::string& result) const {
4496 mCurrentState.traverseInZOrder(
4497 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004498}
4499
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004500void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004501 std::string& result) const {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004502 String8 name;
4503 if (index < args.size()) {
4504 name = String8(args[index]);
4505 index++;
4506 }
4507
Dominik Laskowski83b88212018-12-11 13:34:06 -08004508 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004509
4510 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004511 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004512 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004513 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004514 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004515 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004516 }
Robert Carr2047fae2016-11-28 14:09:09 -08004517 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004518 }
4519}
4520
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004521void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004522 std::string& /* result */) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004523 String8 name;
4524 if (index < args.size()) {
4525 name = String8(args[index]);
4526 index++;
4527 }
4528
Robert Carr2047fae2016-11-28 14:09:09 -08004529 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004530 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004531 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004532 }
Robert Carr2047fae2016-11-28 14:09:09 -08004533 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004534
Svetoslavd85084b2014-03-20 10:28:31 -07004535 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004536}
4537
Jamie Gennis6547ff42013-07-16 20:12:42 -07004538// This should only be called from the main thread. Otherwise it would need
4539// the lock and should use mCurrentState rather than mDrawingState.
4540void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004541 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004542 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004543 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004544
4545 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4546}
4547
Yiwei Zhang5434a782018-12-05 18:06:32 -08004548void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004549 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004550
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004551 if (isLayerTripleBufferingDisabled())
4552 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004553
Yiwei Zhang5434a782018-12-05 18:06:32 -08004554 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4555 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4556 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4557 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4558 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4559 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004560 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004561}
4562
Yiwei Zhang5434a782018-12-05 18:06:32 -08004563void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4564 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004565 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4566 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004567 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004568 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004569 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004570 }
David Sodman4a36e932017-11-07 14:29:47 -08004571 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004572 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004573 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004574 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4575 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004576}
4577
Dan Stozae77c7662016-05-13 11:37:28 -07004578void SurfaceFlinger::recordBufferingStats(const char* layerName,
4579 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004580 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4581 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004582 for (const auto& segment : history) {
4583 if (!segment.usedThirdBuffer) {
4584 stats.twoBufferTime += segment.totalTime;
4585 }
4586 if (segment.occupancyAverage < 1.0f) {
4587 stats.doubleBufferedTime += segment.totalTime;
4588 } else if (segment.occupancyAverage < 2.0f) {
4589 stats.tripleBufferedTime += segment.totalTime;
4590 }
4591 ++stats.numSegments;
4592 stats.totalTime += segment.totalTime;
4593 }
4594}
4595
Yiwei Zhang5434a782018-12-05 18:06:32 -08004596void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4597 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004598
4599 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4600 const size_t count = currentLayers.size();
4601 for (size_t i=0 ; i<count ; i++) {
4602 currentLayers[i]->dumpFrameEvents(result);
4603 }
4604}
4605
Yiwei Zhang5434a782018-12-05 18:06:32 -08004606void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004607 result.append("Buffering stats:\n");
4608 result.append(" [Layer name] <Active time> <Two buffer> "
4609 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004610 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004611 typedef std::tuple<std::string, float, float, float> BufferTuple;
4612 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004613 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004614 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004615 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004616 if (stats.numSegments == 0) {
4617 continue;
4618 }
4619 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4620 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4621 stats.totalTime;
4622 float doubleBufferRatio = static_cast<float>(
4623 stats.doubleBufferedTime) / stats.totalTime;
4624 float tripleBufferRatio = static_cast<float>(
4625 stats.tripleBufferedTime) / stats.totalTime;
4626 sorted.insert({activeTime, {name, twoBufferRatio,
4627 doubleBufferRatio, tripleBufferRatio}});
4628 }
4629 for (const auto& sortedPair : sorted) {
4630 float activeTime = sortedPair.first;
4631 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004632 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4633 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004634 }
4635 result.append("\n");
4636}
4637
Yiwei Zhang5434a782018-12-05 18:06:32 -08004638void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004639 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004640 const auto displayId = display->getId();
4641 if (!displayId) {
4642 continue;
4643 }
4644 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004645 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004646 continue;
4647 }
4648
Yiwei Zhang5434a782018-12-05 18:06:32 -08004649 StringAppendF(&result,
4650 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4651 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004652 uint8_t port;
4653 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004654 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004655 result.append("no identification data\n");
4656 continue;
4657 }
4658
4659 if (!isEdid(data)) {
4660 result.append("unknown identification data: ");
4661 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004662 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004663 }
4664 result.append("\n");
4665 continue;
4666 }
4667
4668 const auto edid = parseEdid(data);
4669 if (!edid) {
4670 result.append("invalid EDID: ");
4671 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004672 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004673 }
4674 result.append("\n");
4675 continue;
4676 }
4677
Yiwei Zhang5434a782018-12-05 18:06:32 -08004678 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004679 result.append(edid->displayName.data(), edid->displayName.length());
4680 result.append("\"\n");
4681 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004682}
4683
Yiwei Zhang5434a782018-12-05 18:06:32 -08004684void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4685 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4686 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4687 StringAppendF(&result, "DisplayColorSetting: %s\n",
4688 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004689
4690 // TODO: print out if wide-color mode is active or not
4691
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004692 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004693 const auto displayId = display->getId();
4694 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004695 continue;
4696 }
4697
Yiwei Zhang5434a782018-12-05 18:06:32 -08004698 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004699 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004700 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004701 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004702 }
4703
Lloyd Pique32cbe282018-10-19 13:09:22 -07004704 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004705 StringAppendF(&result, " Current color mode: %s (%d)\n",
4706 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004707 }
4708 result.append("\n");
4709}
4710
Yiwei Zhang5434a782018-12-05 18:06:32 -08004711void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004712 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004713 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4714 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004715 continue;
4716 }
4717
Dominik Laskowski05275f12018-11-01 15:03:24 -07004718 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004719 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4720 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004721 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004722 compositionInfo.dump(result, nullptr);
4723 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004724 }
4725 }
David Sodman7e4ae112018-02-09 15:02:28 -08004726}
4727
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004728LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004729 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004730 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4731 const State& state = useDrawing ? mDrawingState : mCurrentState;
4732 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004733 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004734 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004735 });
4736
4737 return layersProto;
4738}
4739
Lloyd Pique32cbe282018-10-19 13:09:22 -07004740LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004741 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004742
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004743 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004744 resolution->set_w(displayDevice.getWidth());
4745 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004746
Lloyd Pique32cbe282018-10-19 13:09:22 -07004747 auto display = displayDevice.getCompositionDisplay();
4748 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004749
Lloyd Pique32cbe282018-10-19 13:09:22 -07004750 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4751 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4752 layersProto.set_global_transform(displayState.orientation);
4753
4754 const auto displayId = displayDevice.getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004755 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004756 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004757 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004758 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004759 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004760 }
4761 });
4762
4763 return layersProto;
4764}
4765
Mathias Agopian74d211a2013-04-22 16:55:35 +02004766void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004767 std::string& result) const {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004768 bool colorize = false;
4769 if (index < args.size()
4770 && (args[index] == String16("--color"))) {
4771 colorize = true;
4772 index++;
4773 }
4774
4775 Colorizer colorizer(colorize);
4776
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004777 // figure out if we're stuck somewhere
4778 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004779 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004780 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4781
4782 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004783 * Dump library configuration.
4784 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004785
4786 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004787 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004788 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004789 appendSfConfigString(result);
4790 appendUiConfigString(result);
4791 appendGuiConfigString(result);
4792 result.append("\n");
4793
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004794 result.append("\nDisplay identification data:\n");
4795 dumpDisplayIdentificationData(result);
4796
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004797 result.append("\nWide-Color information:\n");
4798 dumpWideColorInfo(result);
4799
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004800 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004801 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004802 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004803 result.append(SyncFeatures::getInstance().toString());
4804 result.append("\n");
4805
Andy McFadden41d67d72014-04-25 16:58:34 -07004806 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004807 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004808 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004809
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004810 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4811 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski83b88212018-12-11 13:34:06 -08004812 StringAppendF(&result,
4813 "app phase %" PRId64 " ns, "
4814 "sf phase %" PRId64 " ns, "
4815 "early app phase %" PRId64 " ns, "
4816 "early sf phase %" PRId64 " ns, "
4817 "early app gl phase %" PRId64 " ns, "
4818 "early sf gl phase %" PRId64 " ns, "
4819 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)\n",
4820 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, appEarlyOffset, sfEarlyOffset,
4821 appEarlyGlOffset, sfEarlyGlOffset, dispSyncPresentTimeOffset, getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004822
Dan Stozab90cf072015-03-05 11:05:59 -08004823 // Dump static screen stats
4824 result.append("\n");
4825 dumpStaticScreenStats(result);
4826 result.append("\n");
4827
Yiwei Zhang5434a782018-12-05 18:06:32 -08004828 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004829
Dan Stozae77c7662016-05-13 11:37:28 -07004830 dumpBufferingStats(result);
4831
Andy McFadden4803b742012-09-24 19:07:20 -07004832 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004833 * Dump the visible layer list
4834 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004835 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004836 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4837 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4838 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004839 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004840
Chia-I Wu2f884132018-09-13 15:17:58 -07004841 {
4842 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4843 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004844 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004845 result.append("\n");
4846 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004847
David Sodman7e4ae112018-02-09 15:02:28 -08004848 result.append("\nFrame-Composition information:\n");
4849 dumpFrameCompositionInfo(result);
4850 result.append("\n");
4851
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004852 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004853 * Dump Display state
4854 */
4855
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004856 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004857 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004858 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004859 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004860 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004861 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004862 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004863
4864 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004865 * Dump SurfaceFlinger global state
4866 */
4867
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004868 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004869 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004870 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004871
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004872 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004873
Dominik Laskowski075d3172018-05-24 15:50:06 -07004874 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004875 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4876 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004877 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4878 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004879 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004880 StringAppendF(&result,
4881 " transaction-flags : %08x\n"
4882 " gpu_to_cpu_unsupported : %d\n",
4883 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004884
Dominik Laskowski075d3172018-05-24 15:50:06 -07004885 if (const auto displayId = getInternalDisplayId();
4886 displayId && getHwComposer().isConnected(*displayId)) {
4887 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004888 StringAppendF(&result,
4889 " refresh-rate : %f fps\n"
4890 " x-dpi : %f\n"
4891 " y-dpi : %f\n",
4892 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4893 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004894 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004895
Yiwei Zhang5434a782018-12-05 18:06:32 -08004896 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004897
Yiwei Zhang5434a782018-12-05 18:06:32 -08004898 StringAppendF(&result, " use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004899 /*
4900 * VSYNC state
4901 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004902 if (mUseScheduler) {
4903 mScheduler->dump(mAppConnectionHandle, result);
4904 } else {
4905 mEventThread->dump(result);
4906 }
Dan Stozae22aec72016-08-01 13:20:59 -07004907 result.append("\n");
4908
4909 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004910 * Tracing state
4911 */
4912 mTracing.dump(result);
4913 result.append("\n");
4914
4915 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004916 * HWC layer minidump
4917 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004918 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004919 const auto displayId = display->getId();
4920 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004921 continue;
4922 }
4923
Yiwei Zhang5434a782018-12-05 18:06:32 -08004924 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004925 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004926 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004927 result.append("\n");
4928 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004929
4930 /*
4931 * Dump HWComposer state
4932 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004933 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004934 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004935 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004936 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004937 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004938 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004939
4940 /*
4941 * Dump gralloc state
4942 */
4943 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4944 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004945
4946 /*
4947 * Dump VrFlinger state if in use.
4948 */
4949 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4950 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004951 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004952 result.append("\n");
4953 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004954}
4955
Dominik Laskowski075d3172018-05-24 15:50:06 -07004956const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004957 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004958 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004959 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004960 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004961 }
4962 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004963
Dominik Laskowski34157762018-10-31 13:07:19 -07004964 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004965 static const Vector<sp<Layer>> empty;
4966 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004967}
4968
Keun young Park63f165f2012-08-31 10:53:36 -07004969bool SurfaceFlinger::startDdmConnection()
4970{
4971 void* libddmconnection_dso =
4972 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4973 if (!libddmconnection_dso) {
4974 return false;
4975 }
4976 void (*DdmConnection_start)(const char* name);
4977 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004978 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004979 if (!DdmConnection_start) {
4980 dlclose(libddmconnection_dso);
4981 return false;
4982 }
4983 (*DdmConnection_start)(getServiceName());
4984 return true;
4985}
4986
Chia-I Wu28f320b2018-05-03 11:02:56 -07004987void SurfaceFlinger::updateColorMatrixLocked() {
4988 mat4 colorMatrix;
4989 if (mGlobalSaturationFactor != 1.0f) {
4990 // Rec.709 luma coefficients
4991 float3 luminance{0.213f, 0.715f, 0.072f};
4992 luminance *= 1.0f - mGlobalSaturationFactor;
4993 mat4 saturationMatrix = mat4(
4994 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4995 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4996 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4997 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4998 );
4999 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
5000 } else {
5001 colorMatrix = mClientColorMatrix * mDaltonizer();
5002 }
5003
5004 if (mCurrentState.colorMatrix != colorMatrix) {
5005 mCurrentState.colorMatrix = colorMatrix;
5006 mCurrentState.colorMatrixChanged = true;
5007 setTransactionFlags(eTransactionNeeded);
5008 }
5009}
5010
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005011status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005012#pragma clang diagnostic push
5013#pragma clang diagnostic error "-Wswitch-enum"
5014 switch (static_cast<ISurfaceComposerTag>(code)) {
5015 // These methods should at minimum make sure that the client requested
5016 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005017 case BOOT_FINISHED:
5018 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005019 case CREATE_DISPLAY:
5020 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005021 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005022 case GET_ACTIVE_COLOR_MODE:
5023 case GET_ANIMATION_FRAME_STATS:
5024 case GET_HDR_CAPABILITIES:
5025 case SET_ACTIVE_CONFIG:
5026 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005027 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005028 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005029 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005030 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
5031 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005032 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5033 IPCThreadState* ipc = IPCThreadState::self();
5034 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5035 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005036 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005037 }
Robert Carr1db73f62016-12-21 12:58:51 -08005038 return OK;
5039 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005040 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005041 IPCThreadState* ipc = IPCThreadState::self();
5042 const int pid = ipc->getCallingPid();
5043 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005044 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5045 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005046 return PERMISSION_DENIED;
5047 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005048 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005049 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005050 // Used by apps to hook Choreographer to SurfaceFlinger.
5051 case CREATE_DISPLAY_EVENT_CONNECTION:
5052 // The following calls are currently used by clients that do not
5053 // request necessary permissions. However, they do not expose any secret
5054 // information, so it is OK to pass them.
5055 case AUTHENTICATE_SURFACE:
5056 case GET_ACTIVE_CONFIG:
5057 case GET_BUILT_IN_DISPLAY:
5058 case GET_DISPLAY_COLOR_MODES:
5059 case GET_DISPLAY_CONFIGS:
5060 case GET_DISPLAY_STATS:
5061 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5062 // Calling setTransactionState is safe, because you need to have been
5063 // granted a reference to Client* and Handle* to do anything with it.
5064 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005065 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005066 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005067 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005068 case GET_PROTECTED_CONTENT_SUPPORT:
5069 case CACHE_BUFFER:
5070 case UNCACHE_BUFFER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005071 return OK;
5072 }
5073 case CAPTURE_LAYERS:
5074 case CAPTURE_SCREEN: {
5075 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005076 IPCThreadState* ipc = IPCThreadState::self();
5077 const int pid = ipc->getCallingPid();
5078 const int uid = ipc->getCallingUid();
5079 if ((uid != AID_GRAPHICS) &&
5080 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5081 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5082 return PERMISSION_DENIED;
5083 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005084 return OK;
5085 }
5086 // The following codes are deprecated and should never be allowed to access SF.
5087 case CONNECT_DISPLAY_UNUSED:
5088 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5089 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5090 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005091 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005092 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005093
5094 // These codes are used for the IBinder protocol to either interrogate the recipient
5095 // side of the transaction for its canonical interface descriptor or to dump its state.
5096 // We let them pass by default.
5097 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5098 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5099 code == IBinder::SYSPROPS_TRANSACTION) {
5100 return OK;
5101 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005102 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005103 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005104 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005105 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5106 return OK;
5107 }
5108 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5109 return PERMISSION_DENIED;
5110#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005111}
5112
Ana Krulec13be8ad2018-08-21 02:43:56 +00005113status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5114 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005115 status_t credentialCheck = CheckTransactCodeCredentials(code);
5116 if (credentialCheck != OK) {
5117 return credentialCheck;
5118 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005119
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005120 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5121 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005122 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005123 IPCThreadState* ipc = IPCThreadState::self();
5124 const int uid = ipc->getCallingUid();
5125 if (CC_UNLIKELY(uid != AID_SYSTEM
5126 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005127 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005128 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005129 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005130 return PERMISSION_DENIED;
5131 }
5132 int n;
5133 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005134 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005135 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005136 return NO_ERROR;
5137 case 1002: // SHOW_UPDATES
5138 n = data.readInt32();
5139 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005140 invalidateHwcGeometry();
5141 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005142 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005143 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005144 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005145 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005146 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005147 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005148 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005149 setTransactionFlags(
5150 eTransactionNeeded|
5151 eDisplayTransactionNeeded|
5152 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005153 return NO_ERROR;
5154 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005155 case 1006:{ // send empty update
5156 signalRefresh();
5157 return NO_ERROR;
5158 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005159 case 1008: // toggle use of hw composer
5160 n = data.readInt32();
5161 mDebugDisableHWC = n ? 1 : 0;
5162 invalidateHwcGeometry();
5163 repaintEverything();
5164 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005165 case 1009: // toggle use of transform hint
5166 n = data.readInt32();
5167 mDebugDisableTransformHint = n ? 1 : 0;
5168 invalidateHwcGeometry();
5169 repaintEverything();
5170 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005171 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005172 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005173 reply->writeInt32(0);
5174 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005175 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005176 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005177 return NO_ERROR;
5178 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005179 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005180 if (!display) {
5181 return NAME_NOT_FOUND;
5182 }
5183
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005184 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005185 return NO_ERROR;
5186 }
5187 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005188 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005189 // daltonize
5190 n = data.readInt32();
5191 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005192 case 1:
5193 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5194 break;
5195 case 2:
5196 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5197 break;
5198 case 3:
5199 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5200 break;
5201 default:
5202 mDaltonizer.setType(ColorBlindnessType::None);
5203 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005204 }
5205 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005206 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005207 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005208 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005209 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005210
5211 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005212 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005213 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005214 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005215 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005216 // apply a color matrix
5217 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005218 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005219 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005220 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005221 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005222 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005223 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005224 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005225 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005226 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005227 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005228
5229 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5230 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005231 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005232 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5233 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5234 }
5235
Chia-I Wu28f320b2018-05-03 11:02:56 -07005236 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005237 return NO_ERROR;
5238 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005239 // This is an experimental interface
5240 // Needs to be shifted to proper binder interface when we productize
5241 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005242 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005243 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005244 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005245 return NO_ERROR;
5246 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005247 case 1017: {
5248 n = data.readInt32();
5249 mForceFullDamage = static_cast<bool>(n);
5250 return NO_ERROR;
5251 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005252 case 1018: { // Modify Choreographer's phase offset
5253 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005254 if (mUseScheduler) {
5255 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5256 } else {
5257 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5258 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005259 return NO_ERROR;
5260 }
5261 case 1019: { // Modify SurfaceFlinger's phase offset
5262 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005263 if (mUseScheduler) {
5264 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5265 } else {
5266 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5267 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005268 return NO_ERROR;
5269 }
Irvel468051e2016-06-13 16:44:44 -07005270 case 1020: { // Layer updates interceptor
5271 n = data.readInt32();
5272 if (n) {
5273 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005274 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005275 }
5276 else{
5277 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005278 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005279 }
5280 return NO_ERROR;
5281 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005282 case 1021: { // Disable HWC virtual displays
5283 n = data.readInt32();
5284 mUseHwcVirtualDisplays = !n;
5285 return NO_ERROR;
5286 }
Romain Guy0147a172017-06-01 13:53:56 -07005287 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005288 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005289 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005290
Chia-I Wu28f320b2018-05-03 11:02:56 -07005291 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005292 return NO_ERROR;
5293 }
Romain Guy54f154a2017-10-24 21:40:32 +01005294 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005295 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005296 invalidateHwcGeometry();
5297 repaintEverything();
5298 return NO_ERROR;
5299 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005300 // Deprecate, use 1030 to check whether the device is color managed.
5301 case 1024: {
5302 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005303 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005304 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005305 n = data.readInt32();
5306 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005307 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005308 mTracing.enable();
5309 doTracing("tracing.enable");
5310 reply->writeInt32(NO_ERROR);
5311 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005312 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005313 status_t err = mTracing.disable();
5314 reply->writeInt32(err);
5315 }
5316 return NO_ERROR;
5317 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005318 case 1026: { // Get layer tracing status
5319 reply->writeBool(mTracing.isEnabled());
5320 return NO_ERROR;
5321 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005322 // Is a DisplayColorSetting supported?
5323 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005324 const auto display = getDefaultDisplayDevice();
5325 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005326 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005327 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005328
5329 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5330 switch (setting) {
5331 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005332 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005333 break;
5334 case DisplayColorSetting::UNMANAGED:
5335 reply->writeBool(true);
5336 break;
5337 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005338 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005339 break;
5340 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005341 reply->writeBool(
5342 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005343 break;
5344 }
5345 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005346 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005347 // Is VrFlinger active?
5348 case 1028: {
5349 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005350 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005351 return NO_ERROR;
5352 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005353 // Is device color managed?
5354 case 1030: {
5355 reply->writeBool(useColorManagement);
5356 return NO_ERROR;
5357 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005358 // Override default composition data space
5359 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5360 // && adb shell stop zygote && adb shell start zygote
5361 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5362 // adb shell stop zygote && adb shell start zygote
5363 case 1031: {
5364 Mutex::Autolock _l(mStateLock);
5365 n = data.readInt32();
5366 if (n) {
5367 n = data.readInt32();
5368 if (n) {
5369 Dataspace dataspace = static_cast<Dataspace>(n);
5370 if (!validateCompositionDataspace(dataspace)) {
5371 return BAD_VALUE;
5372 }
5373 mDefaultCompositionDataspace = dataspace;
5374 }
5375 n = data.readInt32();
5376 if (n) {
5377 Dataspace dataspace = static_cast<Dataspace>(n);
5378 if (!validateCompositionDataspace(dataspace)) {
5379 return BAD_VALUE;
5380 }
5381 mWideColorGamutCompositionDataspace = dataspace;
5382 }
5383 } else {
5384 // restore composition data space.
5385 mDefaultCompositionDataspace = defaultCompositionDataspace;
5386 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5387 }
5388 return NO_ERROR;
5389 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005390 }
5391 }
5392 return err;
5393}
5394
Steven Thomas6d8110b2017-08-31 18:24:21 -07005395void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005396 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005397 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005398}
5399
Ana Krulec7d1d6832018-12-27 11:10:09 -08005400void SurfaceFlinger::repaintEverythingForHWC() {
5401 mRepaintEverything = true;
5402 mEventQueue->invalidateForHWC();
5403}
5404
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005405// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5406class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005407public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005408 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5409 ~WindowDisconnector() {
5410 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005411 }
5412
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005413private:
5414 ANativeWindow* mWindow;
5415 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005416};
5417
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005418status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005419 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5420 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005421 uint32_t reqWidth, uint32_t reqHeight,
5422 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005423 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005424 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005425
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005426 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005427
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005428 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5429
Chia-I Wu20261cb2018-08-23 12:55:44 -07005430 sp<DisplayDevice> display;
5431 {
5432 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005433
Chia-I Wu20261cb2018-08-23 12:55:44 -07005434 display = getDisplayDeviceLocked(displayToken);
5435 if (!display) return BAD_VALUE;
5436
Chia-I Wucb023152018-08-28 12:57:23 -07005437 // set the requested width/height to the logical display viewport size
5438 // by default
5439 if (reqWidth == 0 || reqHeight == 0) {
5440 reqWidth = uint32_t(display->getViewport().width());
5441 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005442 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005443 }
5444
Peiyong Lin0e003c92018-09-17 11:09:51 -07005445 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5446 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005447
5448 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005449 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005450 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5451 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005452}
5453
5454status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005455 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5456 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005457 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005458 ATRACE_CALL();
5459
5460 class LayerRenderArea : public RenderArea {
5461 public:
Robert Carr578038f2018-03-09 12:25:24 -08005462 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005463 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5464 bool childrenOnly)
5465 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005466 mLayer(layer),
5467 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005468 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005469 mFlinger(flinger),
5470 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005471 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005472 Rect getBounds() const override {
5473 const Layer::State& layerState(mLayer->getDrawingState());
5474 return mLayer->getBufferSize(layerState);
5475 }
Marissa Wall61c58622018-07-18 10:12:20 -07005476 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005477 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005478 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005479 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005480 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005481 }
chaviwa76b2712017-09-20 12:02:26 -07005482 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005483 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005484 Rect getSourceCrop() const override {
5485 if (mCrop.isEmpty()) {
5486 return getBounds();
5487 } else {
5488 return mCrop;
5489 }
5490 }
Robert Carr578038f2018-03-09 12:25:24 -08005491 class ReparentForDrawing {
5492 public:
5493 const sp<Layer>& oldParent;
5494 const sp<Layer>& newParent;
5495
5496 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5497 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005498 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005499 }
Robert Carr15eae092018-03-23 13:43:53 -07005500 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005501 };
5502
5503 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005504 const Rect sourceCrop = getSourceCrop();
5505 // no need to check rotation because there is none
5506 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5507 sourceCrop.height() != getReqHeight();
5508
Robert Carr578038f2018-03-09 12:25:24 -08005509 if (!mChildrenOnly) {
5510 mTransform = mLayer->getTransform().inverse();
5511 drawLayers();
5512 } else {
5513 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005514 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005515 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5516 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005517
5518 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5519 drawLayers();
5520 }
5521 }
chaviwa76b2712017-09-20 12:02:26 -07005522
chaviwa76b2712017-09-20 12:02:26 -07005523 private:
chaviw7206d492017-11-10 16:16:12 -08005524 const sp<Layer> mLayer;
5525 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005526
5527 // In the "childrenOnly" case we reparent the children to a screenshot
5528 // layer which has no properties set and which does not draw.
5529 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005530 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005531 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005532
5533 SurfaceFlinger* mFlinger;
5534 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005535 };
5536
5537 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5538 auto parent = layerHandle->owner.promote();
5539
Robert Carr2e102c92018-10-23 12:11:15 -07005540 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005541 ALOGE("captureLayers called with a removed parent");
5542 return NAME_NOT_FOUND;
5543 }
5544
Robert Carr578038f2018-03-09 12:25:24 -08005545 const int uid = IPCThreadState::self()->getCallingUid();
5546 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005547 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005548 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5549 return PERMISSION_DENIED;
5550 }
5551
chaviw7206d492017-11-10 16:16:12 -08005552 Rect crop(sourceCrop);
5553 if (sourceCrop.width() <= 0) {
5554 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005555 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005556 }
5557
5558 if (sourceCrop.height() <= 0) {
5559 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005560 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005561 }
5562
5563 int32_t reqWidth = crop.width() * frameScale;
5564 int32_t reqHeight = crop.height() * frameScale;
5565
Chia-I Wu20261cb2018-08-23 12:55:44 -07005566 // really small crop or frameScale
5567 if (reqWidth <= 0) {
5568 reqWidth = 1;
5569 }
5570 if (reqHeight <= 0) {
5571 reqHeight = 1;
5572 }
5573
Peiyong Lin0e003c92018-09-17 11:09:51 -07005574 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005575
Robert Carr578038f2018-03-09 12:25:24 -08005576 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005577 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5578 if (!layer->isVisible()) {
5579 return;
Robert Carr578038f2018-03-09 12:25:24 -08005580 } else if (childrenOnly && layer == parent.get()) {
5581 return;
chaviwa76b2712017-09-20 12:02:26 -07005582 }
5583 visitor(layer);
5584 });
5585 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005586 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005587}
5588
5589status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5590 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005591 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005592 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005593 bool useIdentityTransform) {
5594 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005595
Peiyong Lin0e003c92018-09-17 11:09:51 -07005596 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005597 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5598 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005599 *outBuffer =
5600 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5601 static_cast<android_pixel_format>(reqPixelFormat), 1,
5602 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005603
5604 // This mutex protects syncFd and captureResult for communication of the return values from the
5605 // main thread back to this Binder thread
5606 std::mutex captureMutex;
5607 std::condition_variable captureCondition;
5608 std::unique_lock<std::mutex> captureLock(captureMutex);
5609 int syncFd = -1;
5610 std::optional<status_t> captureResult;
5611
Robert Carr03480e22018-01-04 16:02:06 -08005612 const int uid = IPCThreadState::self()->getCallingUid();
5613 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5614
Dominik Laskowski8c001672018-05-30 16:52:06 -07005615 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005616 // If there is a refresh pending, bug out early and tell the binder thread to try again
5617 // after the refresh.
5618 if (mRefreshPending) {
5619 ATRACE_NAME("Skipping screenshot for now");
5620 std::unique_lock<std::mutex> captureLock(captureMutex);
5621 captureResult = std::make_optional<status_t>(EAGAIN);
5622 captureCondition.notify_one();
5623 return;
5624 }
5625
5626 status_t result = NO_ERROR;
5627 int fd = -1;
5628 {
5629 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005630 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005631 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5632 useIdentityTransform, forSystem, &fd);
5633 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005634 }
5635
5636 {
5637 std::unique_lock<std::mutex> captureLock(captureMutex);
5638 syncFd = fd;
5639 captureResult = std::make_optional<status_t>(result);
5640 captureCondition.notify_one();
5641 }
5642 });
5643
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005644 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005645 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005646 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005647 while (*captureResult == EAGAIN) {
5648 captureResult.reset();
5649 result = postMessageAsync(message);
5650 if (result != NO_ERROR) {
5651 return result;
5652 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005653 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005654 }
5655 result = *captureResult;
5656 }
5657
5658 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005659 sync_wait(syncFd, -1);
5660 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005661 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005662
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005663 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005664}
5665
chaviwa76b2712017-09-20 12:02:26 -07005666void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005667 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005668 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005669 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005670
Lloyd Pique144e1162017-12-20 16:44:52 -08005671 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005672
chaviwa76b2712017-09-20 12:02:26 -07005673 const auto reqWidth = renderArea.getReqWidth();
5674 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005675 const auto sourceCrop = renderArea.getSourceCrop();
5676 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005677
Peiyong Lin0e003c92018-09-17 11:09:51 -07005678 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005679 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005680
Mathias Agopian180f10d2013-04-10 22:55:41 -07005681 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005682 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005683
5684 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005685 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005686 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005687
chaviw50da5042018-04-09 13:49:37 -07005688 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005689 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005690 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005691
chaviwa76b2712017-09-20 12:02:26 -07005692 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005693 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005694 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005695 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005696 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005697}
5698
chaviwa76b2712017-09-20 12:02:26 -07005699status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5700 TraverseLayersFunction traverseLayers,
5701 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005702 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005703 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005704 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005705 ATRACE_CALL();
5706
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005707 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005708
5709 traverseLayers([&](Layer* layer) {
5710 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5711 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005712
Robert Carr03480e22018-01-04 16:02:06 -08005713 // We allow the system server to take screenshots of secure layers for
5714 // use in situations like the Screen-rotation animation and place
5715 // the impetus on WindowManager to not persist them.
5716 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005717 ALOGW("FB is protected: PERMISSION_DENIED");
5718 return PERMISSION_DENIED;
5719 }
Peiyong Linfb530cf2018-12-15 05:07:38 +00005720 auto& engine(getRenderEngine());
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005721
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005722 // this binds the given EGLImage as a framebuffer for the
5723 // duration of this scope.
Peiyong Linfb530cf2018-12-15 05:07:38 +00005724 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005725 if (bufferBond.getStatus() != NO_ERROR) {
5726 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005727 return INVALID_OPERATION;
5728 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005729
Dan Stozaabcda352017-06-01 14:37:39 -07005730 // this will in fact render into our dequeued buffer
5731 // via an FBO, which means we didn't have to create
5732 // an EGLSurface and therefore we're not
5733 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005734 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005735
Peiyong Linfb530cf2018-12-15 05:07:38 +00005736 base::unique_fd syncFd = engine.flush();
Alec Mouri492bc572018-09-11 21:40:04 +00005737 if (syncFd < 0) {
Peiyong Linfb530cf2018-12-15 05:07:38 +00005738 engine.finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005739 }
Alec Mouri492bc572018-09-11 21:40:04 +00005740 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005741
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005742 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005743}
5744
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005745// ---------------------------------------------------------------------------
5746
Dan Stoza412903f2017-04-27 13:42:17 -07005747void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5748 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005749}
5750
Dan Stoza412903f2017-04-27 13:42:17 -07005751void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5752 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005753}
5754
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005755void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005756 const LayerVector::Visitor& visitor) {
5757 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005758 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005759 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005760 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005761 continue;
5762 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005763 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005764 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005765 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005766 return;
5767 }
chaviwa76b2712017-09-20 12:02:26 -07005768 if (!layer->isVisible()) {
5769 return;
5770 }
5771 visitor(layer);
5772 });
5773 }
5774}
5775
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005776}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005777
Lloyd Pique074e8122018-07-26 12:57:23 -07005778
Mathias Agopian3f844832013-08-07 21:24:32 -07005779#if defined(__gl_h_)
5780#error "don't include gl/gl.h in this file"
5781#endif
5782
5783#if defined(__gl2_h_)
5784#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005785#endif