blob: 39cab0a3bb01ec9f93fdaf8950fb55572647945b [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>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080040#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070041#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070042#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070043#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080044#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080045#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080046#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070047#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070048#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070049#include <ui/ColorSpace.h>
50#include <ui/DebugUtils.h>
51#include <ui/DisplayInfo.h>
52#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070053#include <ui/GraphicBufferAllocator.h>
54#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070055#include <ui/UiConfig.h>
Ady Abraham8164d482019-01-11 14:47:59 -080056#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080057#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070058#include <utils/String16.h>
59#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070060#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080061#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070062#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Mathias Agopian921e6ac2012-07-23 23:11:29 -070064#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070065#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080066
Robert Carr578038f2018-03-09 12:25:24 -080067#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070068#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070069#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020070#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020072#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080073#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080074#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080075#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070077#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080078#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070079#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070080#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070082#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083
Steven Thomasb02664d2017-07-26 18:48:28 -070084#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070085#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070086#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070087#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070088#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070089#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070090#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070091#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070092#include "Scheduler/EventControlThread.h"
93#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070094#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070095#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070096#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080097#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070098
Mathias Agopianff2ed702013-09-01 21:36:12 -070099#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700100
David Sodman7e4ae112018-02-09 15:02:28 -0800101#include "android-base/stringprintf.h"
102
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900103#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800104#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700105#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800106#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900107#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900108
chaviw1d044282017-09-27 12:19:28 -0700109#include <layerproto/LayerProtoParser.h>
110
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800111namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700112
Jaesoo Lee43518572017-01-23 19:03:16 +0900113using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900114using namespace android::hardware::configstore::V1_0;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800115using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700116using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700117using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700118using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700119using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900120
Steven Thomasb02664d2017-07-26 18:48:28 -0700121namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700122
123#pragma clang diagnostic push
124#pragma clang diagnostic error "-Wswitch-enum"
125
126bool isWideColorMode(const ColorMode colorMode) {
127 switch (colorMode) {
128 case ColorMode::DISPLAY_P3:
129 case ColorMode::ADOBE_RGB:
130 case ColorMode::DCI_P3:
131 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700132 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700133 case ColorMode::BT2100_PQ:
134 case ColorMode::BT2100_HLG:
135 return true;
136 case ColorMode::NATIVE:
137 case ColorMode::STANDARD_BT601_625:
138 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
139 case ColorMode::STANDARD_BT601_525:
140 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
141 case ColorMode::STANDARD_BT709:
142 case ColorMode::SRGB:
143 return false;
144 }
145 return false;
146}
147
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700148ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
149 switch (rotation) {
150 case ISurfaceComposer::eRotateNone:
151 return ui::Transform::ROT_0;
152 case ISurfaceComposer::eRotate90:
153 return ui::Transform::ROT_90;
154 case ISurfaceComposer::eRotate180:
155 return ui::Transform::ROT_180;
156 case ISurfaceComposer::eRotate270:
157 return ui::Transform::ROT_270;
158 }
159 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
160 return ui::Transform::ROT_0;
161}
162
Peiyong Linfca547f2018-07-09 13:03:33 -0700163#pragma clang diagnostic pop
164
Steven Thomasb02664d2017-07-26 18:48:28 -0700165class ConditionalLock {
166public:
167 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
168 if (lock) {
169 mMutex.lock();
170 }
171 }
172 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
173private:
174 Mutex& mMutex;
175 bool mLocked;
176};
Peiyong Linfca547f2018-07-09 13:03:33 -0700177
Peiyong Lin9d846a52018-11-05 13:18:20 -0800178// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
179bool validateCompositionDataspace(Dataspace dataspace) {
180 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
181}
182
Steven Thomasb02664d2017-07-26 18:48:28 -0700183} // namespace anonymous
184
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800185// ---------------------------------------------------------------------------
186
Mathias Agopian99b49842011-06-27 16:05:52 -0700187const String16 sHardwareTest("android.permission.HARDWARE_TEST");
188const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
189const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
190const String16 sDump("android.permission.DUMP");
191
192// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800193int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
194int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700195int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700196bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800197uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800198bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800199bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800200int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600201bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700202int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700203bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700204bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700205Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
206ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
207Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
208ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700209
Kalle Raitaa099a242017-01-11 11:17:29 -0800210std::string getHwcServiceName() {
211 char value[PROPERTY_VALUE_MAX] = {};
212 property_get("debug.sf.hwc_service_name", value, "default");
213 ALOGI("Using HWComposer service: '%s'", value);
214 return std::string(value);
215}
216
217bool useTrebleTestingOverride() {
218 char value[PROPERTY_VALUE_MAX] = {};
219 property_get("debug.sf.treble_testing_override", value, "false");
220 ALOGI("Treble testing override: '%s'", value);
221 return std::string(value) == "true";
222}
223
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800224std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
225 switch(displayColorSetting) {
226 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700227 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800228 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700229 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800230 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700231 return std::string("Enhanced");
232 default:
233 return std::string("Unknown ") +
234 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800235 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800236}
237
David Sodmanbc815282017-11-05 18:57:52 -0800238SurfaceFlingerBE::SurfaceFlingerBE()
239 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800240 mFrameBuckets(),
241 mTotalTime(0),
242 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800243 mComposerSequenceId(0) {
244}
245
Lloyd Pique90c115d2018-09-18 21:39:42 -0700246SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
247 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800248 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700249 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700250 mTransactionPending(false),
251 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700252 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700253 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800254 mBootTime(systemTime()),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800255 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800256 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800257 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800258 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800259 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700260 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700261 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700262 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700263 mDebugInTransaction(0),
264 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700265 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800266 mTimeStats(factory.createTimeStats()),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700267 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700268 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800269 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800270 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800271 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700272 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700273 mMainThreadId(std::this_thread::get_id()),
274 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800275
Lloyd Pique90c115d2018-09-18 21:39:42 -0700276SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
277 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800278 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800279
280 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
281 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
282
283 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
284 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
285
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800286 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
287 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700289 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
290 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
291
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700292 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
293 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
294
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800295 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
296 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
297
Steven Thomas050b2c82017-03-06 11:45:16 -0800298 // Vr flinger is only enabled on Daydream ready devices.
299 useVrFlinger = getBool< ISurfaceFlingerConfigs,
300 &ISurfaceFlingerConfigs::useVrFlinger>(false);
301
Fabien Sanglard1971b632017-03-10 14:50:03 -0800302 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
303 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
304
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600305 hasWideColorDisplay =
306 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700307 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700308 getBool<V1_2::ISurfaceFlingerConfigs,
309 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
310
311 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
312 if (surfaceFlingerConfigsServiceV1_2) {
313 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
Peiyong Linc6780972018-10-28 15:24:08 -0700314 [&](auto tmpDefaultDataspace, auto tmpDefaultPixelFormat,
315 auto tmpWideColorGamutDataspace, auto tmpWideColorGamutPixelFormat) {
316 defaultCompositionDataspace = tmpDefaultDataspace;
317 defaultCompositionPixelFormat = tmpDefaultPixelFormat;
318 wideColorGamutCompositionDataspace = tmpWideColorGamutDataspace;
319 wideColorGamutCompositionPixelFormat = tmpWideColorGamutPixelFormat;
320 });
Peiyong Lin0256f722018-08-31 15:45:10 -0700321 }
Peiyong Lin9d846a52018-11-05 13:18:20 -0800322 mDefaultCompositionDataspace = defaultCompositionDataspace;
323 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600324
Peiyong Linb3839ad2018-09-05 15:37:19 -0700325 useContextPriority = getBool<ISurfaceFlingerConfigs,
326 &ISurfaceFlingerConfigs::useContextPriority>(true);
327
Iris Chang7501ed62018-04-30 14:45:42 +0800328 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700329 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
330 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800331 V1_1::DisplayOrientation::ORIENTATION_0);
332
333 switch (primaryDisplayOrientation) {
334 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700335 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800336 break;
337 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700338 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800339 break;
340 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700341 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800342 break;
343 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700344 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800345 break;
346 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700347 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800348
Lloyd Pique90c115d2018-09-18 21:39:42 -0700349 mPrimaryDispSync =
350 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
351 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700352
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800353 // debugging stuff...
354 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700355
Mathias Agopianb4b17302013-03-20 18:36:41 -0700356 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700357 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700358
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800359 property_get("debug.sf.showupdates", value, "0");
360 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700361
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700362 property_get("debug.sf.ddms", value, "0");
363 mDebugDDMS = atoi(value);
364 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700365 if (!startDdmConnection()) {
366 // start failed, and DDMS debugging not enabled
367 mDebugDDMS = 0;
368 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700369 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700370 ALOGI_IF(mDebugRegion, "showupdates enabled");
371 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700372
373 property_get("debug.sf.disable_backpressure", value, "0");
374 mPropagateBackpressure = !atoi(value);
375 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700376
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800377 property_get("debug.sf.enable_hwc_vds", value, "0");
378 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800379 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800380
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800381 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800382 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800383 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700384
Yiwei Zhang243b3782018-05-15 17:40:04 -0700385 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700386 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
387 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
388
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200389 property_get("debug.sf.early_phase_offset_ns", value, "-1");
390 const int earlySfOffsetNs = atoi(value);
391
392 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
393 const int earlyGlSfOffsetNs = atoi(value);
394
395 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
396 const int earlyAppOffsetNs = atoi(value);
397
398 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
399 const int earlyGlAppOffsetNs = atoi(value);
400
Ana Krulec98b5b242018-08-10 15:03:23 -0700401 property_get("debug.sf.use_scheduler", value, "0");
402 mUseScheduler = atoi(value);
403
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200404 const VSyncModulator::Offsets earlyOffsets =
405 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
406 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
407 const VSyncModulator::Offsets earlyGlOffsets =
408 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
409 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
410 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
411 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700412
Romain Guy11d63f42017-07-20 12:47:14 -0700413 // We should be reading 'persist.sys.sf.color_saturation' here
414 // but since /data may be encrypted, we need to wait until after vold
415 // comes online to attempt to read the property. The property is
416 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800417
418 if (useTrebleTestingOverride()) {
419 // Without the override SurfaceFlinger cannot connect to HIDL
420 // services that are not listed in the manifests. Considered
421 // deriving the setting from the set service name, but it
422 // would be brittle if the name that's not 'default' is used
423 // for production purposes later on.
424 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
425 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800426}
427
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800428void SurfaceFlinger::onFirstRef()
429{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800430 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800431}
432
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800433SurfaceFlinger::~SurfaceFlinger()
434{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800435}
436
Dan Stozac7014012014-02-14 15:03:43 -0800437void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800438{
439 // the window manager died on us. prepare its eulogy.
440
Andy McFadden13a082e2012-08-24 10:16:42 -0700441 // restore initial conditions (default device unblank, etc)
442 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800443
444 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700445 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800446}
447
Robert Carr1db73f62016-12-21 12:58:51 -0800448static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700449 status_t err = client->initCheck();
450 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800451 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800452 }
Robert Carr1db73f62016-12-21 12:58:51 -0800453 return nullptr;
454}
455
456sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
457 return initClient(new Client(this));
458}
459
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700460sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
461 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700462{
463 class DisplayToken : public BBinder {
464 sp<SurfaceFlinger> flinger;
465 virtual ~DisplayToken() {
466 // no more references, this display must be terminated
467 Mutex::Autolock _l(flinger->mStateLock);
468 flinger->mCurrentState.displays.removeItem(this);
469 flinger->setTransactionFlags(eDisplayTransactionNeeded);
470 }
471 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700472 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700473 : flinger(flinger) {
474 }
475 };
476
477 sp<BBinder> token = new DisplayToken(this);
478
479 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700480 // Display ID is assigned when virtual display is allocated by HWC.
481 DisplayDeviceState state;
482 state.isSecure = secure;
483 state.displayName = displayName;
484 mCurrentState.displays.add(token, state);
485 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700486 return token;
487}
488
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700489void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700490 Mutex::Autolock _l(mStateLock);
491
Dominik Laskowski075d3172018-05-24 15:50:06 -0700492 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
493 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700494 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700495 return;
496 }
497
Dominik Laskowski075d3172018-05-24 15:50:06 -0700498 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
499 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700500 ALOGE("destroyDisplay called for non-virtual display");
501 return;
502 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700503 mInterceptor->saveDisplayDeletion(state.sequenceId);
504 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700505 setTransactionFlags(eDisplayTransactionNeeded);
506}
507
Mathias Agopiane57f2922012-08-09 16:29:12 -0700508sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700509 std::optional<DisplayId> displayId;
510
511 if (id == HWC_DISPLAY_PRIMARY) {
512 displayId = getInternalDisplayId();
513 } else if (id == HWC_DISPLAY_EXTERNAL) {
514 displayId = getExternalDisplayId();
515 }
516
517 if (!displayId) {
518 ALOGE("%s: Invalid display %d", __FUNCTION__, id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800519 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700520 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700521
522 return getPhysicalDisplayToken(*displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700523}
524
Ady Abraham37965d42018-11-01 13:43:32 -0700525status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
526 if (!outGetColorManagement) {
527 return BAD_VALUE;
528 }
529 *outGetColorManagement = useColorManagement;
530 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700531}
532
Lloyd Pique441d5042018-10-18 16:49:51 -0700533HWComposer& SurfaceFlinger::getHwComposer() const {
534 return mCompositionEngine->getHwComposer();
535}
536
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700537renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
538 return mCompositionEngine->getRenderEngine();
539}
540
Lloyd Pique70d91362018-10-18 16:02:55 -0700541compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
542 return *mCompositionEngine.get();
543}
544
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800545void SurfaceFlinger::bootFinished()
546{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700547 if (mStartPropertySetThread->join() != NO_ERROR) {
548 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800549 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800550 const nsecs_t now = systemTime();
551 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000552 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700553
554 // wait patiently for the window manager death
555 const String16 name("window");
556 sp<IBinder> window(defaultServiceManager()->getService(name));
557 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700558 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700559 }
Robert Carr720e5062018-07-30 17:45:14 -0700560 sp<IBinder> input(defaultServiceManager()->getService(
561 String16("inputflinger")));
562 if (input == nullptr) {
563 ALOGE("Failed to link to input service");
564 } else {
565 mInputFlinger = interface_cast<IInputFlinger>(input);
566 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700567
Steven Thomas050b2c82017-03-06 11:45:16 -0800568 if (mVrFlinger) {
569 mVrFlinger->OnBootFinished();
570 }
571
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700572 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700573 // formerly we would just kill the process, but we now ask it to exit so it
574 // can choose where to stop the animation.
575 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700576
577 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
578 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
579 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700580
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800581 postMessageAsync(new LambdaMessage([this] {
582 readPersistentProperties();
583 mBootStage = BootStage::FINISHED;
584 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800585}
586
Dan Stoza436ccf32018-06-21 12:10:12 -0700587uint32_t SurfaceFlinger::getNewTexture() {
588 {
589 std::lock_guard lock(mTexturePoolMutex);
590 if (!mTexturePool.empty()) {
591 uint32_t name = mTexturePool.back();
592 mTexturePool.pop_back();
593 ATRACE_INT("TexturePoolSize", mTexturePool.size());
594 return name;
595 }
596
597 // The pool was too small, so increase it for the future
598 ++mTexturePoolSize;
599 }
600
601 // The pool was empty, so we need to get a new texture name directly using a
602 // blocking call to the main thread
603 uint32_t name = 0;
604 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
605 return name;
606}
607
Mathias Agopian3f844832013-08-07 21:24:32 -0700608void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700609 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700610}
611
Wei Wangf9b05ee2017-07-19 20:59:39 -0700612// Do not call property_set on main thread which will be blocked by init
613// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700614void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700615 ALOGI( "SurfaceFlinger's main thread ready to run. "
616 "Initializing graphics H/W...");
617
Thierry Strudel2924d012017-08-14 15:19:37 -0700618 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900619
Steven Thomasb02664d2017-07-26 18:48:28 -0700620 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800621
Dominik Laskowski83b88212018-12-11 13:34:06 -0800622 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -0800623
Steven Thomasb02664d2017-07-26 18:48:28 -0700624 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700625 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700626 mScheduler = getFactory().createScheduler([this](bool enabled) {
627 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
628 });
629
Ana Krulec98b5b242018-08-10 15:03:23 -0700630 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700631 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Dominik Laskowskif654d572018-12-20 11:03:06 -0800632 resyncCallback,
Ana Krulec98b5b242018-08-10 15:03:23 -0700633 impl::EventThread::InterceptVSyncsCallback());
634 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700635 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Dominik Laskowskif654d572018-12-20 11:03:06 -0800636 resyncCallback, [this](nsecs_t timestamp) {
Ana Krulec98b5b242018-08-10 15:03:23 -0700637 mInterceptor->saveVSyncEvent(timestamp);
638 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800639
Ana Krulec98b5b242018-08-10 15:03:23 -0700640 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700641 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
642 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700643 } else {
644 mEventThreadSource =
645 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
646 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
647 mEventThread =
648 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700649 impl::EventThread::InterceptVSyncsCallback(),
650 "appEventThread");
651 mSfEventThreadSource =
652 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
653 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
654
655 mSFEventThread =
656 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700657 [this](nsecs_t timestamp) {
658 mInterceptor->saveVSyncEvent(timestamp);
659 },
660 "sfEventThread");
Dominik Laskowskif654d572018-12-20 11:03:06 -0800661 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Ana Krulec98b5b242018-08-10 15:03:23 -0700662 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
663 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800664
Steven Thomasb02664d2017-07-26 18:48:28 -0700665 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700666 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700667 renderEngineFeature |= (useColorManagement ?
668 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700669 renderEngineFeature |= (useContextPriority ?
670 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700671
672 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700673 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700674 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700675 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700676
677 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
678 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700679 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
680 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800681 // Process any initial hotplug and resulting display changes.
682 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700683 const auto display = getDefaultDisplayDeviceLocked();
684 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700685 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700686 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800687
Steven Thomas050b2c82017-03-06 11:45:16 -0800688 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700689 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700690 // This callback is called from the vr flinger dispatch thread. We
691 // need to call signalTransaction(), which requires holding
692 // mStateLock when we're not on the main thread. Acquiring
693 // mStateLock from the vr flinger dispatch thread might trigger a
694 // deadlock in surface flinger (see b/66916578), so post a message
695 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700696 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700697 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
698 mVrFlingerRequestsDisplay = requestDisplay;
699 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700700 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800701 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700702 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
703 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700704 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700705 .value_or(0),
706 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800707 if (!mVrFlinger) {
708 ALOGE("Failed to start vrflinger");
709 }
710 }
711
Lloyd Pique90c115d2018-09-18 21:39:42 -0700712 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700713 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700714
Mathias Agopian92a979a2012-08-02 18:32:23 -0700715 // initialize our drawing state
716 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700717
Andy McFadden13a082e2012-08-24 10:16:42 -0700718 // set initial conditions (e.g. unblank default device)
719 initializeDisplays();
720
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700721 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700722
Wei Wangf9b05ee2017-07-19 20:59:39 -0700723 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700724
725 const bool presentFenceReliable =
726 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
727 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700728
729 if (mStartPropertySetThread->Start() != NO_ERROR) {
730 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800731 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800732
Ana Krulec7d1d6832018-12-27 11:10:09 -0800733 if (mUseScheduler) {
734 mScheduler->setExpiredIdleTimerCallback([this]() { setRefreshRateTo(60.f /* fps */); });
735 mScheduler->setResetIdleTimerCallback([this]() { setRefreshRateTo(90.f /* fps */); });
736 }
737
Dan Stoza9e56aa02015-11-02 13:00:03 -0800738 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700739}
740
Romain Guy11d63f42017-07-20 12:47:14 -0700741void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700742 Mutex::Autolock _l(mStateLock);
743
Romain Guy11d63f42017-07-20 12:47:14 -0700744 char value[PROPERTY_VALUE_MAX];
745
746 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800747 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700748 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800749 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100750
751 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700752 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700753}
754
Mathias Agopiana67e4182012-06-19 17:26:12 -0700755void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800756 // Start boot animation service by setting a property mailbox
757 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700758 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800759 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700760 if (mStartPropertySetThread->join() != NO_ERROR) {
761 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800762 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700763}
764
Mathias Agopian875d8e12013-06-07 15:35:48 -0700765size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700766 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700767}
768
Mathias Agopian875d8e12013-06-07 15:35:48 -0700769size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700770 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700771}
772
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800773// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800774
Jamie Gennis582270d2011-08-17 18:19:00 -0700775bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800776 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800777 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800778 return authenticateSurfaceTextureLocked(bufferProducer);
779}
780
781bool SurfaceFlinger::authenticateSurfaceTextureLocked(
782 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800783 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800784 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800785}
786
Brian Anderson6b376712017-04-04 10:51:39 -0700787status_t SurfaceFlinger::getSupportedFrameTimestamps(
788 std::vector<FrameEvent>* outSupported) const {
789 *outSupported = {
790 FrameEvent::REQUESTED_PRESENT,
791 FrameEvent::ACQUIRE,
792 FrameEvent::LATCH,
793 FrameEvent::FIRST_REFRESH_START,
794 FrameEvent::LAST_REFRESH_START,
795 FrameEvent::GPU_COMPOSITION_DONE,
796 FrameEvent::DEQUEUE_READY,
797 FrameEvent::RELEASE,
798 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700799 ConditionalLock _l(mStateLock,
800 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700801 if (!getHwComposer().hasCapability(
802 HWC2::Capability::PresentFenceIsNotReliable)) {
803 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
804 }
805 return NO_ERROR;
806}
807
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700808status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
809 Vector<DisplayInfo>* configs) {
810 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700811 return BAD_VALUE;
812 }
813
Dominik Laskowski075d3172018-05-24 15:50:06 -0700814 const auto displayId = getPhysicalDisplayId(displayToken);
815 if (!displayId) {
816 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700817 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700818
Mathias Agopian8b736f12012-08-13 17:54:26 -0700819 // TODO: Not sure if display density should handled by SF any longer
820 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700821 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700822 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700823 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800824 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700825 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700826 }
827 return density;
828 }
829 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700830 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700831 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700832 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700833 return getDensityFromProperty("ro.sf.lcd_density"); }
834 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700835
Dan Stoza7f7da322014-05-02 15:26:25 -0700836 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700837
Steven Thomas6d8110b2017-08-31 18:24:21 -0700838 ConditionalLock _l(mStateLock,
839 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700840 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700841 DisplayInfo info = DisplayInfo();
842
Dan Stoza9e56aa02015-11-02 13:00:03 -0800843 float xdpi = hwConfig->getDpiX();
844 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700845
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700846 info.w = hwConfig->getWidth();
847 info.h = hwConfig->getHeight();
848 // Default display viewport to display width and height
849 info.viewportW = info.w;
850 info.viewportH = info.h;
851
Dominik Laskowski075d3172018-05-24 15:50:06 -0700852 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700853 // The density of the device is provided by a build property
854 float density = Density::getBuildDensity() / 160.0f;
855 if (density == 0) {
856 // the build doesn't provide a density -- this is wrong!
857 // use xdpi instead
858 ALOGE("ro.sf.lcd_density must be defined as a build property");
859 density = xdpi / 160.0f;
860 }
861 if (Density::getEmuDensity()) {
862 // if "qemu.sf.lcd_density" is specified, it overrides everything
863 xdpi = ydpi = density = Density::getEmuDensity();
864 density /= 160.0f;
865 }
866 info.density = density;
867
868 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700869 const auto display = getDefaultDisplayDeviceLocked();
870 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700871
872 // This is for screenrecord
873 const Rect viewport = display->getViewport();
874 if (viewport.isValid()) {
875 info.viewportW = uint32_t(viewport.getWidth());
876 info.viewportH = uint32_t(viewport.getHeight());
877 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700878 } else {
879 // TODO: where should this value come from?
880 static const int TV_DENSITY = 213;
881 info.density = TV_DENSITY / 160.0f;
882 info.orientation = 0;
883 }
884
Dan Stoza7f7da322014-05-02 15:26:25 -0700885 info.xdpi = xdpi;
886 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800887 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900888 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800889
Andy McFadden91b2ca82014-06-13 14:04:23 -0700890 // This is how far in advance a buffer must be queued for
891 // presentation at a given time. If you want a buffer to appear
892 // on the screen at time N, you must submit the buffer before
893 // (N - presentationDeadline).
894 //
895 // Normally it's one full refresh period (to give SF a chance to
896 // latch the buffer), but this can be reduced by configuring a
897 // DispSync offset. Any additional delays introduced by the hardware
898 // composer or panel must be accounted for here.
899 //
900 // We add an additional 1ms to allow for processing time and
901 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800902 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800903 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700904
905 // All non-virtual displays are currently considered secure.
906 info.secure = true;
907
Dominik Laskowski075d3172018-05-24 15:50:06 -0700908 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700909 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800910 std::swap(info.w, info.h);
911 }
912
Michael Wright28f24d02016-07-12 13:30:53 -0700913 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700914 }
915
Dan Stoza7f7da322014-05-02 15:26:25 -0700916 return NO_ERROR;
917}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700918
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700919status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
920 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700921 return BAD_VALUE;
922 }
923
Ana Krulece588e312018-09-18 12:32:24 -0700924 if (mUseScheduler) {
925 mScheduler->getDisplayStatInfo(stats);
926 } else {
927 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
928 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
929 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700930 return NO_ERROR;
931}
932
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700933int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
934 const auto display = getDisplayDevice(displayToken);
935 if (!display) {
936 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800937 return BAD_VALUE;
938 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700939
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700940 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700941}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700942
Ana Krulec7d1d6832018-12-27 11:10:09 -0800943status_t SurfaceFlinger::setActiveConfigAsync(const sp<IBinder>& displayToken, int mode) {
944 ATRACE_NAME("setActiveConfigAsync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800945 postMessageAsync(new LambdaMessage(
946 [=]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800947 return NO_ERROR;
948}
949
950status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
951 ATRACE_NAME("setActiveConfigSync");
Dominik Laskowski83b88212018-12-11 13:34:06 -0800952 postMessageSync(new LambdaMessage(
953 [&]() NO_THREAD_SAFETY_ANALYSIS { setActiveConfigInternal(displayToken, mode); }));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800954 return NO_ERROR;
955}
956
957void SurfaceFlinger::setActiveConfigInternal(const sp<IBinder>& displayToken, int mode) {
958 Vector<DisplayInfo> configs;
959 getDisplayConfigs(displayToken, &configs);
960 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
961 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
962 return;
963 }
964
965 const auto display = getDisplayDevice(displayToken);
966 if (!display) {
967 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
968 displayToken.get());
969 return;
970 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700971 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800972 ALOGW("Attempt to set active config %d for virtual display", mode);
973 return;
974 }
975 int currentDisplayPowerMode = display->getPowerMode();
976 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
977 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700978 return;
979 }
980
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700981 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700982 if (mode == currentMode) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800983 // Don't update config if we are already running in the desired mode.
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700984 return;
985 }
986
Dominik Laskowski075d3172018-05-24 15:50:06 -0700987 const auto displayId = display->getId();
988 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700989
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700990 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700991 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700992
Ana Krulec7d1d6832018-12-27 11:10:09 -0800993 ATRACE_INT("ActiveConfigMode", mode);
Dominik Laskowski83b88212018-12-11 13:34:06 -0800994 resyncToHardwareVsync(true, getVsyncPeriod());
Mathias Agopianc666cae2012-07-25 18:56:13 -0700995}
Dominik Laskowski075d3172018-05-24 15:50:06 -0700996
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700997status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
998 Vector<ColorMode>* outColorModes) {
999 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001000 return BAD_VALUE;
1001 }
1002
Dominik Laskowski075d3172018-05-24 15:50:06 -07001003 const auto displayId = getPhysicalDisplayId(displayToken);
1004 if (!displayId) {
1005 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -07001006 }
1007
Peiyong Lina52f0292018-03-14 17:26:31 -07001008 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001009 {
1010 ConditionalLock _l(mStateLock,
1011 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001012 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001013 }
Michael Wright28f24d02016-07-12 13:30:53 -07001014 outColorModes->clear();
1015 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1016
1017 return NO_ERROR;
1018}
1019
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001020ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1021 if (const auto display = getDisplayDevice(displayToken)) {
1022 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001023 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001024 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001025}
1026
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001027void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1028 Dataspace dataSpace, RenderIntent renderIntent) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001029 if (display->isVirtual()) {
1030 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
1031 return;
1032 }
1033
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001034 ColorMode currentMode = display->getActiveColorMode();
1035 Dataspace currentDataSpace = display->getCompositionDataSpace();
1036 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001037
Peiyong Lin38e9a562018-04-10 16:24:20 -07001038 if (mode == currentMode && dataSpace == currentDataSpace &&
1039 renderIntent == currentRenderIntent) {
1040 return;
1041 }
1042
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001043 display->setActiveColorMode(mode);
1044 display->setCompositionDataSpace(dataSpace);
1045 display->setActiveRenderIntent(renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001046
Dominik Laskowski075d3172018-05-24 15:50:06 -07001047 const auto displayId = display->getId();
1048 LOG_ALWAYS_FATAL_IF(!displayId);
1049 getHwComposer().setActiveColorMode(*displayId, mode, renderIntent);
1050
Dominik Laskowski34157762018-10-31 13:07:19 -07001051 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), display=%s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001052 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
Dominik Laskowski34157762018-10-31 13:07:19 -07001053 renderIntent, to_string(*displayId).c_str());
Michael Wright28f24d02016-07-12 13:30:53 -07001054}
1055
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001056status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001057 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001058 Vector<ColorMode> modes;
1059 getDisplayColorModes(displayToken, &modes);
1060 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1061 if (mode < ColorMode::NATIVE || !exists) {
1062 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1063 decodeColorMode(mode).c_str(), mode, displayToken.get());
1064 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001065 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001066 const auto display = getDisplayDevice(displayToken);
1067 if (!display) {
1068 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1069 decodeColorMode(mode).c_str(), mode, displayToken.get());
1070 } else if (display->isVirtual()) {
1071 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1072 decodeColorMode(mode).c_str(), mode);
1073 } else {
1074 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1075 RenderIntent::COLORIMETRIC);
1076 }
1077 }));
1078
Michael Wright28f24d02016-07-12 13:30:53 -07001079 return NO_ERROR;
1080}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001081
Svetoslavd85084b2014-03-20 10:28:31 -07001082status_t SurfaceFlinger::clearAnimationFrameStats() {
1083 Mutex::Autolock _l(mStateLock);
1084 mAnimFrameTracker.clearStats();
1085 return NO_ERROR;
1086}
1087
1088status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1089 Mutex::Autolock _l(mStateLock);
1090 mAnimFrameTracker.getStats(outStats);
1091 return NO_ERROR;
1092}
1093
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001094status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1095 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001096 Mutex::Autolock _l(mStateLock);
1097
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001098 const auto display = getDisplayDeviceLocked(displayToken);
1099 if (!display) {
1100 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001101 return BAD_VALUE;
1102 }
1103
Peiyong Linfb069302018-04-25 14:34:31 -07001104 // At this point the DisplayDeivce should already be set up,
1105 // meaning the luminance information is already queried from
1106 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001107 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001108 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1109 capabilities.getDesiredMaxLuminance(),
1110 capabilities.getDesiredMaxAverageLuminance(),
1111 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001112
1113 return NO_ERROR;
1114}
1115
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001116status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1117 ui::PixelFormat* outFormat,
1118 ui::Dataspace* outDataspace,
1119 uint8_t* outComponentMask) const {
1120 if (!outFormat || !outDataspace || !outComponentMask) {
1121 return BAD_VALUE;
1122 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001123 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001124 if (!display || !display->getId()) {
1125 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1126 return BAD_VALUE;
1127 }
1128 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1129 outDataspace, outComponentMask);
1130}
1131
Kevin DuBois74e53772018-11-19 10:52:38 -08001132status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1133 bool enable, uint8_t componentMask,
1134 uint64_t maxFrames) const {
1135 const auto display = getDisplayDevice(displayToken);
1136 if (!display || !display->getId()) {
1137 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1138 return BAD_VALUE;
1139 }
1140
1141 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1142 componentMask, maxFrames);
1143}
1144
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001145status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1146 uint64_t maxFrames, uint64_t timestamp,
1147 DisplayedFrameStats* outStats) const {
1148 const auto display = getDisplayDevice(displayToken);
1149 if (!display || !display->getId()) {
1150 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1151 return BAD_VALUE;
1152 }
1153
1154 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1155 outStats);
1156}
1157
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001158status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1159 if (!outSupported) {
1160 return BAD_VALUE;
1161 }
1162 *outSupported = getRenderEngine().supportsProtectedContent();
1163 return NO_ERROR;
1164}
1165
Marissa Wallebc2c052019-01-16 19:16:55 -08001166status_t SurfaceFlinger::cacheBuffer(const sp<IBinder>& token, const sp<GraphicBuffer>& buffer,
1167 int32_t* outBufferId) {
1168 if (!outBufferId) {
1169 return BAD_VALUE;
1170 }
1171 *outBufferId = mBufferStateLayerCache.add(token, buffer);
1172 return NO_ERROR;
1173}
1174
1175status_t SurfaceFlinger::uncacheBuffer(const sp<IBinder>& token, int32_t bufferId) {
1176 mBufferStateLayerCache.release(token, bufferId);
1177 return NO_ERROR;
1178}
1179
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001180status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001181 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001182 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001183
Chia-I Wu90f669f2017-10-05 14:24:41 -07001184 if (mInjectVSyncs == enable) {
1185 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001186 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001187
Dominik Laskowski83b88212018-12-11 13:34:06 -08001188 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001189
Ana Krulec98b5b242018-08-10 15:03:23 -07001190 // TODO(akrulec): Part of the Injector should be refactored, so that it
1191 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001192 if (enable) {
1193 ALOGV("VSync Injections enabled");
1194 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001195 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001196 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001197 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001198 impl::EventThread::InterceptVSyncsCallback(),
1199 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001200 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001201 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001202 } else {
1203 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001204 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001205 }
1206
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001207 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001208 }));
1209
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001210 return NO_ERROR;
1211}
1212
1213status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001214 Mutex::Autolock _l(mStateLock);
1215
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001216 if (!mInjectVSyncs) {
1217 ALOGE("VSync Injections not enabled");
1218 return BAD_VALUE;
1219 }
1220 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1221 ALOGV("Injecting VSync inside SurfaceFlinger");
1222 mVSyncInjector->onInjectSyncEvent(when);
1223 }
1224 return NO_ERROR;
1225}
1226
Lloyd Pique755e3192018-01-31 16:46:15 -08001227status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1228 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001229 // Try to acquire a lock for 1s, fail gracefully
1230 const status_t err = mStateLock.timedLock(s2ns(1));
1231 const bool locked = (err == NO_ERROR);
1232 if (!locked) {
1233 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1234 return TIMED_OUT;
1235 }
1236
1237 outLayers->clear();
1238 mCurrentState.traverseInZOrder([&](Layer* layer) {
1239 outLayers->push_back(layer->getLayerDebugInfo());
1240 });
1241
1242 mStateLock.unlock();
1243 return NO_ERROR;
1244}
1245
Peiyong Linc6780972018-10-28 15:24:08 -07001246status_t SurfaceFlinger::getCompositionPreference(
1247 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1248 Dataspace* outWideColorGamutDataspace,
1249 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001250 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001251 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001252 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001253 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001254 return NO_ERROR;
1255}
1256
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001257// ----------------------------------------------------------------------------
1258
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001259sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1260 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001261 auto resyncCallback = makeResyncCallback([this] {
1262 Mutex::Autolock lock(mStateLock);
1263 return getVsyncPeriod();
1264 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001265
Ana Krulec98b5b242018-08-10 15:03:23 -07001266 if (mUseScheduler) {
1267 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001268 return mScheduler->createDisplayEventConnection(mSfConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001269 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001270 return mScheduler->createDisplayEventConnection(mAppConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001271 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001272 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001273 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001274 return mSFEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001275 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001276 return mEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001277 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001278 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001279}
1280
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001281// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001282
1283void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001284 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001285}
1286
1287void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001288 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001289}
1290
1291void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001292 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001293}
1294
1295void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001296 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001297 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001298}
1299
1300status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001301 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001302 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001303}
1304
1305status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001306 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001307 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001308 if (res == NO_ERROR) {
1309 msg->wait();
1310 }
1311 return res;
1312}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001313
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001314void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001315 do {
1316 waitForEvent();
1317 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001318}
1319
Dominik Laskowski83b88212018-12-11 13:34:06 -08001320nsecs_t SurfaceFlinger::getVsyncPeriod() const {
1321 const auto displayId = getInternalDisplayId();
1322 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1323 return 0;
1324 }
1325
1326 const auto config = getHwComposer().getActiveConfig(*displayId);
1327 return config ? config->getVsyncPeriod() : 0;
1328}
1329
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001330void SurfaceFlinger::enableHardwareVsync() {
1331 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001332 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001333 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001334 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001335 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001336 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001337}
1338
Dominik Laskowski83b88212018-12-11 13:34:06 -08001339void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001340 Mutex::Autolock _l(mHWVsyncLock);
1341
Jesse Hall948fe0c2013-10-14 12:56:09 -07001342 if (makeAvailable) {
1343 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001344 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1345 if (mUseScheduler) {
1346 mScheduler->makeHWSyncAvailable(true);
1347 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001348 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001349 // Hardware vsync is not currently available, so abort the resync
1350 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001351 return;
1352 }
1353
Dominik Laskowski83b88212018-12-11 13:34:06 -08001354 if (period <= 0) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001355 return;
1356 }
1357
Ana Krulece588e312018-09-18 12:32:24 -07001358 if (mUseScheduler) {
1359 mScheduler->setVsyncPeriod(period);
1360 } else {
1361 mPrimaryDispSync->reset();
1362 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001363
Ana Krulece588e312018-09-18 12:32:24 -07001364 if (!mPrimaryHWVsyncEnabled) {
1365 mPrimaryDispSync->beginResync();
1366 mEventControlThread->setVsyncEnabled(true);
1367 mPrimaryHWVsyncEnabled = true;
1368 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001369 }
1370}
1371
Jesse Hall948fe0c2013-10-14 12:56:09 -07001372void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001373 Mutex::Autolock _l(mHWVsyncLock);
1374 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001375 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001376 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001377 mPrimaryHWVsyncEnabled = false;
1378 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001379 if (makeUnavailable) {
1380 mHWVsyncAvailable = false;
1381 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001382}
1383
Dominik Laskowski83b88212018-12-11 13:34:06 -08001384void SurfaceFlinger::VsyncState::resync(const GetVsyncPeriod& getVsyncPeriod) {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001385 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001386
Dan Stoza57164302017-05-08 14:03:54 -07001387 const nsecs_t now = systemTime();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001388 const nsecs_t last = lastResyncTime.exchange(now);
1389
1390 if (now - last > kIgnoreDelay) {
1391 flinger.resyncToHardwareVsync(false, getVsyncPeriod());
Tim Murray4a4e4a22016-04-19 16:29:23 +00001392 }
1393}
1394
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001395void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1396 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001397 ATRACE_NAME("SF onVsync");
1398
Steven Thomas3cfac282017-02-06 12:29:30 -08001399 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001400 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001401 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001402 return;
1403 }
1404
Dominik Laskowski075d3172018-05-24 15:50:06 -07001405 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001406 return;
1407 }
1408
Dominik Laskowski075d3172018-05-24 15:50:06 -07001409 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001410 // For now, we don't do anything with external display vsyncs.
1411 return;
1412 }
1413
Ana Krulece588e312018-09-18 12:32:24 -07001414 if (mUseScheduler) {
1415 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001416 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001417 bool needsHwVsync = false;
1418 { // Scope for the lock
1419 Mutex::Autolock _l(mHWVsyncLock);
1420 if (mPrimaryHWVsyncEnabled) {
1421 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1422 }
1423 }
1424
1425 if (needsHwVsync) {
1426 enableHardwareVsync();
1427 } else {
1428 disableHardwareVsync(false);
1429 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001430 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001431}
1432
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001433void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001434 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1435 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001436}
1437
Ana Krulec7d1d6832018-12-27 11:10:09 -08001438void SurfaceFlinger::setRefreshRateTo(float newFps) {
1439 const auto displayId = getInternalDisplayId();
1440 if (!displayId || mBootStage != BootStage::FINISHED) {
1441 return;
1442 }
1443 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1444 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1445 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1446 // refresh cycle.
1447
1448 // Don't do any updating if the current fps is the same as the new one.
1449 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
1450 const nsecs_t currentVsyncPeriod = activeConfig->getVsyncPeriod();
1451 if (currentVsyncPeriod == 0) {
1452 return;
1453 }
1454 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1455 // floating numbers.
1456 const float currentFps = 1e9 / currentVsyncPeriod;
1457 if (std::abs(currentFps - newFps) <= 1) {
1458 return;
1459 }
1460
1461 auto configs = getHwComposer().getConfigs(*displayId);
1462 for (int i = 0; i < configs.size(); i++) {
1463 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1464 if (vsyncPeriod == 0) {
1465 continue;
1466 }
1467 const float fps = 1e9 / vsyncPeriod;
1468 // TODO(b/113612090): There should be a better way at determining which config
1469 // has the right refresh rate.
1470 if (std::abs(fps - newFps) <= 1) {
1471 const auto display = getBuiltInDisplay(HWC_DISPLAY_PRIMARY);
1472 if (!display) return;
1473 // This is posted in async function to avoid deadlock when getDisplayDevice
1474 // requires mStateLock.
1475 setActiveConfigAsync(display, i);
1476 ATRACE_INT("FPS", newFps);
1477 }
1478 }
1479}
1480
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001481void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001482 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001483 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001484 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001485
Lloyd Piqueba04e622017-12-14 17:11:26 -08001486 // Ignore events that do not have the right sequenceId.
1487 if (sequenceId != getBE().mComposerSequenceId) {
1488 return;
1489 }
1490
Steven Thomasb02664d2017-07-26 18:48:28 -07001491 // Only lock if we're not on the main thread. This function is normally
1492 // called on a hwbinder thread, but for the primary display it's called on
1493 // the main thread with the state lock already held, so don't attempt to
1494 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001495 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001496
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001497 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001498
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001499 if (std::this_thread::get_id() == mMainThreadId) {
1500 // Process all pending hot plug events immediately if we are on the main thread.
1501 processDisplayHotplugEventsLocked();
1502 }
1503
Lloyd Piqueba04e622017-12-14 17:11:26 -08001504 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001505}
1506
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001507void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001508 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001509 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001510 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001511 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001512 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001513}
1514
Dominik Laskowski075d3172018-05-24 15:50:06 -07001515void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001516 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001517 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001518 if (const auto displayId = getInternalDisplayId()) {
1519 getHwComposer().setVsyncEnabled(*displayId,
1520 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1521 }
Mathias Agopian86303202012-07-24 22:46:10 -07001522}
1523
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001524// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001525void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001526 if (mUseScheduler) {
1527 mScheduler->disableHardwareVsync(true);
1528 } else {
1529 disableHardwareVsync(true);
1530 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001531 // Clear the drawing state so that the logic inside of
1532 // handleTransactionLocked will fire. It will determine the delta between
1533 // mCurrentState and mDrawingState and re-apply all changes when we make the
1534 // transition.
1535 mDrawingState.displays.clear();
1536 mDisplays.clear();
1537}
1538
Steven Thomas050b2c82017-03-06 11:45:16 -08001539void SurfaceFlinger::updateVrFlinger() {
1540 if (!mVrFlinger)
1541 return;
1542 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001543 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001544 return;
1545 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001546
Lloyd Pique441d5042018-10-18 16:49:51 -07001547 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001548 ALOGE("Vr flinger is only supported for remote hardware composer"
1549 " service connections. Ignoring request to transition to vr"
1550 " flinger.");
1551 mVrFlingerRequestsDisplay = false;
1552 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001553 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001554
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001555 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001556
Steven Thomas0123ac62018-07-12 11:32:34 -07001557 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001558 LOG_ALWAYS_FATAL_IF(!display);
1559 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001560 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1561 // called below. Clear the reference now so we don't accidentally use it
1562 // later.
1563 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001564
Steven Thomasb02664d2017-07-26 18:48:28 -07001565 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001566 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001567 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001568
Steven Thomasb02664d2017-07-26 18:48:28 -07001569 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001570 // Delete the current instance before creating the new one
1571 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1572 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1573 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1574 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001575
Lloyd Pique441d5042018-10-18 16:49:51 -07001576 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001577 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001578
1579 if (vrFlingerRequestsDisplay) {
1580 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001581 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001582
1583 mVisibleRegionsDirty = true;
1584 invalidateHwcGeometry();
1585
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001586 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001587 display = getDefaultDisplayDeviceLocked();
1588 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001589 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001590
Steven Thomasb02664d2017-07-26 18:48:28 -07001591 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001592 const nsecs_t vsyncPeriod = getVsyncPeriod();
1593 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001594
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001595 // The present fences returned from vr_hwc are not an accurate
1596 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001597 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001598 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1599 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001600 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001601 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001602 !hasSyncFramework);
1603 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001604
Steven Thomasb02664d2017-07-26 18:48:28 -07001605 // Use phase of 0 since phase is not known.
1606 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001607 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001608 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001609
Dominik Laskowski83b88212018-12-11 13:34:06 -08001610 resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001611
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001612 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001613 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001614}
1615
Mathias Agopian4fec8732012-06-29 14:12:52 -07001616void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001617 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001618 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001619 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001620 if (mUseScheduler) {
1621 // This call is made each time SF wakes up and creates a new frame.
1622 mScheduler->incrementFrameCounter();
1623 }
Dan Stoza50182882016-07-08 12:02:20 -07001624 bool frameMissed = !mHadClientComposition &&
1625 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001626 (mPreviousPresentFence->getSignalTime() ==
1627 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001628 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001629 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001630 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001631 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001632 if (mPropagateBackpressure) {
1633 signalLayerUpdate();
1634 break;
1635 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001636 }
Dan Stoza50182882016-07-08 12:02:20 -07001637
Steven Thomas050b2c82017-03-06 11:45:16 -08001638 // Now that we're going to make it to the handleMessageTransaction()
1639 // call below it's safe to call updateVrFlinger(), which will
1640 // potentially trigger a display handoff.
1641 updateVrFlinger();
1642
Dan Stoza6b9454d2014-11-07 16:00:59 -08001643 bool refreshNeeded = handleMessageTransaction();
1644 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001645 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001646 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001647 // Signal a refresh if a transaction modified the window state,
1648 // a new buffer was latched, or if HWC has requested a full
1649 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001650 signalRefresh();
1651 }
1652 break;
1653 }
1654 case MessageQueue::REFRESH: {
1655 handleMessageRefresh();
1656 break;
1657 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001658 }
1659}
1660
Dan Stoza6b9454d2014-11-07 16:00:59 -08001661bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001662 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001663
1664 // Apply any ready transactions in the queues if there are still transactions that have not been
1665 // applied, wake up during the next vsync period and check again
1666 bool transactionNeeded = false;
1667 if (!flushTransactionQueues()) {
1668 transactionNeeded = true;
1669 }
1670
Mathias Agopian4fec8732012-06-29 14:12:52 -07001671 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001672 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001673 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001674
1675 if (transactionNeeded) {
1676 setTransactionFlags(eTransactionNeeded);
1677 }
1678
1679 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001680}
1681
Mathias Agopian4fec8732012-06-29 14:12:52 -07001682void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001683 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001684
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001685 mRefreshPending = false;
1686
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001687 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001688 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001689 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001690 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001691 for (const auto& [token, display] : mDisplays) {
1692 beginFrame(display);
1693 prepareFrame(display);
1694 doDebugFlashRegions(display, repaintEverything);
1695 doComposition(display, repaintEverything);
1696 }
1697
Adrian Roos1e1a1282017-11-01 19:05:31 +01001698 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001699 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001700
1701 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001702 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001703
Dan Stozabfbffeb2016-07-21 14:49:33 -07001704 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001705 for (const auto& [token, display] : mDisplays) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001706 mHadClientComposition =
1707 mHadClientComposition || getHwComposer().hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001708 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001709
Alec Mouri86770e52018-09-24 22:40:58 +00001710 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001711 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001712 if (mHadClientComposition) {
1713 base::unique_fd flushFence(getRenderEngine().flush());
1714 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1715 getBE().flushFence = new Fence(std::move(flushFence));
1716 } else {
1717 // Cleanup for hygiene.
1718 getBE().flushFence = Fence::NO_FENCE;
1719 }
1720 }
1721
Jorim Jaggi90535212018-05-23 23:44:06 +02001722 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001723
David Sodman7e4ae112018-02-09 15:02:28 -08001724 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001725 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001726 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001727 compositionInfo.hwc.hwcLayer = nullptr;
1728 }
David Sodmanba340492018-08-05 21:51:33 -07001729 }
David Sodman7e4ae112018-02-09 15:02:28 -08001730
1731 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001732}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001733
David Sodmanfa9b2af2017-12-24 13:28:59 -08001734
1735bool SurfaceFlinger::handleMessageInvalidate() {
1736 ATRACE_CALL();
1737 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001738}
1739
David Sodman79bba0e2018-08-05 18:07:49 -07001740void SurfaceFlinger::calculateWorkingSet() {
1741 ATRACE_CALL();
1742 ALOGV(__FUNCTION__);
1743
David Sodman79bba0e2018-08-05 18:07:49 -07001744 // build the h/w work list
1745 if (CC_UNLIKELY(mGeometryInvalid)) {
1746 mGeometryInvalid = false;
1747 for (const auto& [token, display] : mDisplays) {
1748 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001749 if (!displayId) {
1750 continue;
1751 }
David Sodman79bba0e2018-08-05 18:07:49 -07001752
Dominik Laskowski075d3172018-05-24 15:50:06 -07001753 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
1754 for (size_t i = 0; i < currentLayers.size(); i++) {
1755 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001756
Dominik Laskowski075d3172018-05-24 15:50:06 -07001757 if (!layer->hasHwcLayer(*displayId)) {
1758 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1759 layer->forceClientComposition(*displayId);
1760 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001761 }
1762 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001763
1764 layer->setGeometry(display, i);
1765 if (mDebugDisableHWC || mDebugRegion) {
1766 layer->forceClientComposition(*displayId);
1767 }
David Sodman79bba0e2018-08-05 18:07:49 -07001768 }
1769 }
1770 }
1771
1772 // Set the per-frame data
1773 for (const auto& [token, display] : mDisplays) {
1774 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001775 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001776 continue;
1777 }
1778
1779 if (mDrawingState.colorMatrixChanged) {
1780 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001781 status_t result =
1782 getHwComposer().setColorTransform(*displayId, mDrawingState.colorMatrix);
Dominik Laskowski34157762018-10-31 13:07:19 -07001783 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %s: %d",
1784 to_string(*displayId).c_str(), result);
David Sodman79bba0e2018-08-05 18:07:49 -07001785 }
1786 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1787 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001788 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001789 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1790 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1791 !display->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001792 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001793 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1794 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1795 !display->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001796 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001797 }
1798
Peiyong Lind3788632018-09-18 16:01:31 -07001799 // TODO(b/111562338) remove when composer 2.3 is shipped.
1800 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001801 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001802 }
1803
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001804 if (layer->getRoundedCornerState().radius > 0.0f) {
1805 layer->forceClientComposition(*displayId);
1806 }
1807
Dominik Laskowski075d3172018-05-24 15:50:06 -07001808 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001809 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001810 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001811 continue;
1812 }
1813
Dominik Laskowski075d3172018-05-24 15:50:06 -07001814 layer->setPerFrameData(*displayId, display->getTransform(), display->getViewport(),
1815 display->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001816 }
1817
Peiyong Lin13effd12018-07-24 17:01:47 -07001818 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001819 ColorMode colorMode;
1820 Dataspace dataSpace;
1821 RenderIntent renderIntent;
1822 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1823 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1824 }
1825 }
1826
1827 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001828
1829 for (const auto& [token, display] : mDisplays) {
1830 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001831 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001832 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001833
1834 if (displayId) {
1835 if (!layer->setHwcLayer(*displayId)) {
1836 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1837 }
1838 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001839 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001840
Dominik Laskowski05275f12018-11-01 15:03:24 -07001841 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001842 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1843 }
1844 }
David Sodman79bba0e2018-08-05 18:07:49 -07001845}
1846
David Sodmanfa9b2af2017-12-24 13:28:59 -08001847void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001848{
1849 // is debugging enabled
1850 if (CC_LIKELY(!mDebugRegion))
1851 return;
1852
David Sodmanfa9b2af2017-12-24 13:28:59 -08001853 if (display->isPoweredOn()) {
1854 // transform the dirty region into this screen's coordinate space
1855 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1856 if (!dirtyRegion.isEmpty()) {
1857 // redraw the whole screen
1858 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001859
David Sodmanfa9b2af2017-12-24 13:28:59 -08001860 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001861 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001862 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001863
Alec Mouri0a9c7b82018-11-16 13:05:25 -08001864 display->queueBuffer(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001865 }
1866 }
1867
David Sodmanfa9b2af2017-12-24 13:28:59 -08001868 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001869
1870 if (mDebugRegion > 1) {
1871 usleep(mDebugRegion * 1000);
1872 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001873
Dominik Laskowski05275f12018-11-01 15:03:24 -07001874 prepareFrame(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001875}
1876
Adrian Roos1e1a1282017-11-01 19:05:31 +01001877void SurfaceFlinger::doTracing(const char* where) {
1878 ATRACE_CALL();
1879 ATRACE_NAME(where);
1880 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001881 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001882 }
1883}
1884
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001885void SurfaceFlinger::logLayerStats() {
1886 ATRACE_CALL();
1887 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001888 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001889 if (display->isPrimary()) {
1890 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001891 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001892 }
1893 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001894
1895 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001896 }
1897}
1898
David Sodman2b406362017-12-15 13:33:47 -08001899void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001900{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001901 ATRACE_CALL();
1902 ALOGV("preComposition");
1903
David Sodman2b406362017-12-15 13:33:47 -08001904 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1905
Mathias Agopiancd60f992012-08-16 16:28:27 -07001906 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001907 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001908 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001909 needExtraInvalidate = true;
1910 }
Robert Carr2047fae2016-11-28 14:09:09 -08001911 });
1912
Mathias Agopiancd60f992012-08-16 16:28:27 -07001913 if (needExtraInvalidate) {
1914 signalLayerUpdate();
1915 }
1916}
1917
Ana Krulece588e312018-09-18 12:32:24 -07001918void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1919 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001920 // Update queue of past composite+present times and determine the
1921 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001922 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001923 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001924 while (!getBE().mCompositePresentTimes.empty()) {
1925 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001926 // Cached values should have been updated before calling this method,
1927 // which helps avoid duplicate syscalls.
1928 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1929 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1930 break;
1931 }
1932 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001933 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001934 }
1935
1936 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001937 while (getBE().mCompositePresentTimes.size() > 16) {
1938 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001939 }
1940
Ana Krulece588e312018-09-18 12:32:24 -07001941 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001942}
1943
Ana Krulece588e312018-09-18 12:32:24 -07001944void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1945 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001946 // Integer division and modulo round toward 0 not -inf, so we need to
1947 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001948 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1949 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1950 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001951
Brian Andersond0010582017-03-07 13:20:31 -08001952 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1953 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001954 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001955 }
1956
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001957 // Snap the latency to a value that removes scheduling jitter from the
1958 // composition and present times, which often have >1ms of jitter.
1959 // Reducing jitter is important if an app attempts to extrapolate
1960 // something (such as user input) to an accurate diasplay time.
1961 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1962 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001963 nsecs_t bias = stats.vsyncPeriod / 2;
1964 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1965 nsecs_t snappedCompositeToPresentLatency =
1966 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001967
David Sodman99974d22017-11-28 12:04:33 -08001968 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001969 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1970 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001971 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001972}
1973
Ady Abraham8164d482019-01-11 14:47:59 -08001974// debug patch for b/119477596 - add stack guards to catch stack
1975// corruptions and disable clang optimizations.
1976// The code below is temporary and planned to be removed once stack
1977// corruptions are found.
1978#pragma clang optimize off
1979class StackGuard {
1980public:
1981 StackGuard(const char* name, const char* func, int line) {
1982 guarders.reserve(MIN_CAPACITY);
1983 guarders.push_back({this, name, func, line});
1984 validate();
1985 }
1986 ~StackGuard() {
1987 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1988 if (i->guard == this) {
1989 guarders.erase(i);
1990 break;
1991 }
1992 }
1993 }
1994
1995 static void validate() {
1996 for (const auto& guard : guarders) {
1997 if (guard.guard->cookie != COOKIE_VALUE) {
1998 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1999 CallStack stack(LOG_TAG);
2000 abort();
2001 }
2002 }
2003 }
2004
2005private:
2006 uint64_t cookie = COOKIE_VALUE;
2007 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
2008 static constexpr size_t MIN_CAPACITY = 16;
2009
2010 struct GuarderElement {
2011 StackGuard* guard;
2012 const char* name;
2013 const char* func;
2014 int line;
2015 };
2016
2017 static std::vector<GuarderElement> guarders;
2018};
2019std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2020
2021#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2022
2023#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002024void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002025{
Ady Abraham8164d482019-01-11 14:47:59 -08002026 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002027 ATRACE_CALL();
2028 ALOGV("postComposition");
2029
Brian Anderson3546a3f2016-07-14 11:51:14 -07002030 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002031 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002032 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002033 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002034 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002035 }
Ady Abraham8164d482019-01-11 14:47:59 -08002036 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002037
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002038 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002039 const auto display = getDefaultDisplayDeviceLocked();
Ady Abraham8164d482019-01-11 14:47:59 -08002040 DEFINE_STACK_GUARD(display);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002041
David Sodman73beded2017-11-15 11:56:06 -08002042 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002043 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002044 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2045
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002046 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002047 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002048 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002049 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002050 } else {
2051 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2052 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002053
Ady Abraham8164d482019-01-11 14:47:59 -08002054 ASSERT_ON_STACK_GUARD();
2055
David Sodman73beded2017-11-15 11:56:06 -08002056 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002057 mPreviousPresentFence =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002058 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002059 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002060 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002061 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002062
Ana Krulece588e312018-09-18 12:32:24 -07002063 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002064 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002065 if (mUseScheduler) {
2066 mScheduler->getDisplayStatInfo(&stats);
2067 } else {
2068 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2069 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2070 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002071
Ady Abraham8164d482019-01-11 14:47:59 -08002072 ASSERT_ON_STACK_GUARD();
2073
David Sodman2b406362017-12-15 13:33:47 -08002074 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002075 // when we started doing work for this frame, but that should be okay
2076 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002077 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002078 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002079 DEFINE_STACK_GUARD(compositorTiming);
2080
Brian Andersond0010582017-03-07 13:20:31 -08002081 {
David Sodman99974d22017-11-28 12:04:33 -08002082 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002083 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002084 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002085
2086 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002087 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002088
Robert Carr2047fae2016-11-28 14:09:09 -08002089 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002090 bool frameLatched = layer->onPostComposition(display->getId(), glCompositionDoneFenceTime,
2091 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002092 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002093 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002094 recordBufferingStats(layer->getName().string(),
2095 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002096 }
Ady Abraham8164d482019-01-11 14:47:59 -08002097 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002098 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002099
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002100 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002101 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002102 if (mUseScheduler) {
2103 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002104 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002105 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002106 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2107 enableHardwareVsync();
2108 } else {
2109 disableHardwareVsync(false);
2110 }
Ady Abraham8164d482019-01-11 14:47:59 -08002111 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002112 }
2113 }
2114
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002115 if (!hasSyncFramework) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002116 if (display && getHwComposer().isConnected(*display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002117 if (mUseScheduler) {
2118 mScheduler->enableHardwareVsync();
2119 } else {
2120 enableHardwareVsync();
2121 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002122 }
2123 }
2124
Ady Abraham8164d482019-01-11 14:47:59 -08002125 ASSERT_ON_STACK_GUARD();
2126
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002127 if (mAnimCompositionPending) {
2128 mAnimCompositionPending = false;
2129
Brian Anderson4e606e32017-03-16 15:34:57 -07002130 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002131 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002132 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002133
2134 ASSERT_ON_STACK_GUARD();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002135 } else if (display && getHwComposer().isConnected(*display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002136 // The HWC doesn't support present fences, so use the refresh
2137 // timestamp instead.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002138 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002139 DEFINE_STACK_GUARD(presentTime);
2140
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002141 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002142 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002143 }
2144 mAnimFrameTracker.advanceFrame();
2145 }
Dan Stozab90cf072015-03-05 11:05:59 -08002146
Ady Abraham8164d482019-01-11 14:47:59 -08002147 ASSERT_ON_STACK_GUARD();
2148
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002149 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002150 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002151 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002152 }
2153
Ady Abraham8164d482019-01-11 14:47:59 -08002154 ASSERT_ON_STACK_GUARD();
2155
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002156 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002157
Ady Abraham8164d482019-01-11 14:47:59 -08002158 ASSERT_ON_STACK_GUARD();
2159
Dominik Laskowski075d3172018-05-24 15:50:06 -07002160 if (display && getHwComposer().isConnected(*display->getId()) && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002161 return;
2162 }
2163
2164 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002165 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002166 if (mHasPoweredOff) {
2167 mHasPoweredOff = false;
2168 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002169 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002170 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002171 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002172 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002173 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2174 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002175 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002176 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002177 }
David Sodman4a36e932017-11-07 14:29:47 -08002178 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002179
2180 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002181 }
David Sodman4a36e932017-11-07 14:29:47 -08002182 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002183 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002184
2185 {
2186 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002187 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002188 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002189 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002190 if (refillCount > 0) {
2191 const size_t offset = mTexturePool.size();
2192 mTexturePool.resize(mTexturePoolSize);
2193 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2194 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2195 }
Ady Abraham8164d482019-01-11 14:47:59 -08002196 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002197 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002198
Marissa Wallfda30bb2018-10-12 11:34:28 -07002199 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002200 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002201
2202 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002203}
Ady Abraham8164d482019-01-11 14:47:59 -08002204#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002205
2206void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002207 ATRACE_CALL();
2208 ALOGV("rebuildLayerStacks");
2209
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002210 // We need to clear these out now as these may be holding on to a
2211 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2212 // also holds a reference. When the set of visible layers is recomputed,
2213 // some layers may be destroyed if the only thing keeping them alive was
2214 // that list of visible layers associated with each display. The layer
2215 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2216 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2217 for (const auto& [token, display] : mDisplays) {
2218 getBE().mCompositionInfo[token].clear();
2219 }
2220
Mathias Agopiancd60f992012-08-16 16:28:27 -07002221 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002222 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002223 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002224 mVisibleRegionsDirty = false;
2225 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002226
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002227 for (const auto& pair : mDisplays) {
2228 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07002229 Region opaqueRegion;
2230 Region dirtyRegion;
2231 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002232 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07002233 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002234 const Rect bounds = display->getBounds();
2235 if (display->isPoweredOn()) {
2236 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002237
Jeff Sharkey76488112017-02-27 14:15:18 -07002238 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002239 bool hwcLayerDestroyed = false;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002240 const auto displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002241 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002242 Region drawRegion(tr.transform(
2243 layer->visibleNonTransparentRegion));
2244 drawRegion.andSelf(bounds);
2245 if (!drawRegion.isEmpty()) {
2246 layersSortedByZ.add(layer);
2247 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002248 // Clear out the HWC layer if this layer was
2249 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002250 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002251 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002252 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002253 // WM changes display->layerStack upon sleep/awake.
2254 // Here we make sure we delete the HWC layers even if
2255 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002256 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002257 }
2258
2259 // If a layer is not going to get a release fence because
2260 // it is invisible, but it is also going to release its
2261 // old buffer, add it to the list of layers needing
2262 // fences.
2263 if (hwcLayerDestroyed) {
2264 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2265 mLayersWithQueuedFrames.cend(), layer);
2266 if (found != mLayersWithQueuedFrames.cend()) {
2267 layersNeedingFences.add(layer);
2268 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002269 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002270 });
2271 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002272 display->setVisibleLayersSortedByZ(layersSortedByZ);
2273 display->setLayersNeedingFences(layersNeedingFences);
2274 display->undefinedRegion.set(bounds);
2275 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2276 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002277 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002278 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002279}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002280
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002281// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002282// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002283// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002284// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002285// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002286// The returned HDR data space is one of
2287// - Dataspace::UNKNOWN
2288// - Dataspace::BT2020_HLG
2289// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002290Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2291 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002292 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002293 *outHdrDataSpace = Dataspace::UNKNOWN;
2294
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002295 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002296 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002297 case Dataspace::V0_SCRGB:
2298 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002299 case Dataspace::BT2020:
2300 case Dataspace::BT2020_ITU:
2301 case Dataspace::BT2020_LINEAR:
2302 case Dataspace::DISPLAY_BT2020:
2303 bestDataSpace = Dataspace::DISPLAY_BT2020;
2304 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002305 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002306 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002307 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002308 case Dataspace::BT2020_PQ:
2309 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002310 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002311 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002312 case Dataspace::BT2020_HLG:
2313 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002314 // When there's mixed PQ content and HLG content, we set the HDR
2315 // data space to be BT2020_PQ and convert HLG to PQ.
2316 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2317 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002318 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002319 break;
2320 default:
2321 break;
2322 }
Romain Guy54f154a2017-10-24 21:40:32 +01002323 }
2324
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002325 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002326}
2327
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002328// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002329void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2330 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002331 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2332 *outMode = ColorMode::NATIVE;
2333 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002334 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002335 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002336 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002337
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002338 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002339 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002340
Peiyong Lindfde5112018-06-05 10:58:41 -07002341 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002342 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002343 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002344 if (isHdr) {
2345 bestDataSpace = hdrDataSpace;
2346 }
2347
Chia-I Wu0d711262018-05-21 15:19:35 -07002348 RenderIntent intent;
2349 switch (mDisplayColorSetting) {
2350 case DisplayColorSetting::MANAGED:
2351 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002352 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002353 break;
2354 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002355 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002356 break;
2357 default: // vendor display color setting
2358 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2359 break;
2360 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002361
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002362 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002363}
2364
David Sodmanfa9b2af2017-12-24 13:28:59 -08002365void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002366{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002367 bool dirty = !display->getDirtyRegion(false).isEmpty();
2368 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2369 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002370
David Sodmanfa9b2af2017-12-24 13:28:59 -08002371 // If nothing has changed (!dirty), don't recompose.
2372 // If something changed, but we don't currently have any visible layers,
2373 // and didn't when we last did a composition, then skip it this time.
2374 // The second rule does two things:
2375 // - When all layers are removed from a display, we'll emit one black
2376 // frame, then nothing more until we get new layers.
2377 // - When a display is created with a private layer stack, we won't
2378 // emit any black frames until a layer is added to the layer stack.
2379 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002380
Dominik Laskowski075d3172018-05-24 15:50:06 -07002381 const char flagPrefix[] = {'-', '+'};
2382 static_cast<void>(flagPrefix);
2383 ALOGV_IF(display->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2384 __FUNCTION__, mustRecompose ? "doing" : "skipping", display->getDebugName().c_str(),
2385 flagPrefix[dirty], flagPrefix[empty], flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002386
David Sodmanfa9b2af2017-12-24 13:28:59 -08002387 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002388
David Sodmanfa9b2af2017-12-24 13:28:59 -08002389 if (mustRecompose) {
2390 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002391 }
2392}
2393
David Sodmanfa9b2af2017-12-24 13:28:59 -08002394void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002395{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002396 if (!display->isPoweredOn()) {
2397 return;
David Sodman2b406362017-12-15 13:33:47 -08002398 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002399
Dominik Laskowski05275f12018-11-01 15:03:24 -07002400 status_t result = display->prepareFrame(getHwComposer(),
2401 getBE().mCompositionInfo[display->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002402 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
2403 display->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002404}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002405
David Sodmanfa9b2af2017-12-24 13:28:59 -08002406void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002407 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002408 ALOGV("doComposition");
2409
David Sodmanfa9b2af2017-12-24 13:28:59 -08002410 if (display->isPoweredOn()) {
2411 // transform the dirty region into this screen's coordinate space
2412 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002413
David Sodmanfa9b2af2017-12-24 13:28:59 -08002414 // repaint the framebuffer (if needed)
2415 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002416
David Sodmanfa9b2af2017-12-24 13:28:59 -08002417 display->dirtyRegion.clear();
2418 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002419 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002420 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002421}
2422
David Sodmanfa9b2af2017-12-24 13:28:59 -08002423void SurfaceFlinger::postFrame()
2424{
2425 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002426 const auto display = getDefaultDisplayDeviceLocked();
2427 if (display && getHwComposer().isConnected(*display->getId())) {
2428 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002429 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2430 logFrameStats();
2431 }
2432 }
2433}
2434
2435void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002436{
Mathias Agopian841cde52012-03-01 15:44:37 -08002437 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002438 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002439
David Sodmanfa9b2af2017-12-24 13:28:59 -08002440 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002441
David Sodmanfa9b2af2017-12-24 13:28:59 -08002442 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002443 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002444 if (displayId) {
2445 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002446 }
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002447 display->onPresentDisplayCompleted();
David Sodman15094112018-10-11 09:39:37 -07002448 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002449 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002450
Chia-I Wu7b549592017-11-15 09:14:57 -08002451 // The layer buffer from the previous frame (if any) is released
2452 // by HWC only when the release fence from this frame (if any) is
2453 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002454 if (displayId && layer->hasHwcLayer(*displayId)) {
2455 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2456 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002457 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002458
2459 // If the layer was client composited in the previous frame, we
2460 // need to merge with the previous client target acquire fence.
2461 // Since we do not track that, always merge with the current
2462 // client target acquire fence when it is available, even though
2463 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002464 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002465 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002466 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002467 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002468
David Sodman15094112018-10-11 09:39:37 -07002469 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002470 }
Chia-I Wu83806892017-11-16 10:50:20 -08002471
2472 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002473 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002474 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002475 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002476 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002477 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002478 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002479 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002480 }
2481 }
2482
Dominik Laskowski075d3172018-05-24 15:50:06 -07002483 if (displayId) {
2484 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002485 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002486 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002487}
2488
Mathias Agopian87baae12012-07-31 12:38:26 -07002489void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002490{
Mathias Agopian841cde52012-03-01 15:44:37 -08002491 ATRACE_CALL();
2492
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002493 // here we keep a copy of the drawing state (that is the state that's
2494 // going to be overwritten by handleTransactionLocked()) outside of
2495 // mStateLock so that the side-effects of the State assignment
2496 // don't happen with mStateLock held (which can cause deadlocks).
2497 State drawingState(mDrawingState);
2498
Mathias Agopianca4d3602011-05-19 15:38:14 -07002499 Mutex::Autolock _l(mStateLock);
2500 const nsecs_t now = systemTime();
2501 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002502
Mathias Agopianca4d3602011-05-19 15:38:14 -07002503 // Here we're guaranteed that some transaction flags are set
2504 // so we can call handleTransactionLocked() unconditionally.
2505 // We call getTransactionFlags(), which will also clear the flags,
2506 // with mStateLock held to guarantee that mCurrentState won't change
2507 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002508
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002509 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002510 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002511 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002512
Mathias Agopianca4d3602011-05-19 15:38:14 -07002513 mLastTransactionTime = systemTime() - now;
2514 mDebugInTransaction = 0;
2515 invalidateHwcGeometry();
2516 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002517}
2518
Lloyd Piqueba04e622017-12-14 17:11:26 -08002519void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2520 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002521 const std::optional<DisplayIdentificationInfo> info =
2522 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002523
Dominik Laskowski075d3172018-05-24 15:50:06 -07002524 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002525 continue;
2526 }
2527
Lloyd Piqueba04e622017-12-14 17:11:26 -08002528 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002529 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002530 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002531 mPhysicalDisplayTokens[info->id] = new BBinder();
2532 DisplayDeviceState state;
2533 state.displayId = info->id;
2534 state.isSecure = true; // All physical displays are currently considered secure.
2535 state.displayName = info->name;
2536 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2537 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002538 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002539 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002540 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002541
Dominik Laskowski075d3172018-05-24 15:50:06 -07002542 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2543 if (index >= 0) {
2544 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2545 mInterceptor->saveDisplayDeletion(state.sequenceId);
2546 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002547 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002548 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002549 }
2550
2551 processDisplayChangesLocked();
2552 }
2553
2554 mPendingHotplugEvents.clear();
2555}
2556
Lloyd Pique99d3da52018-01-22 17:48:03 -08002557sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002558 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
2559 const DisplayDeviceState& state, const sp<DisplaySurface>& dispSurface,
2560 const sp<IGraphicBufferProducer>& producer) {
2561 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002562 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002563 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002564 creationArgs.isSecure = state.isSecure;
2565 creationArgs.displaySurface = dispSurface;
2566 creationArgs.hasWideColorGamut = false;
2567 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002568
Dominik Laskowski075d3172018-05-24 15:50:06 -07002569 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2570 creationArgs.isPrimary = isInternalDisplay;
2571
2572 if (useColorManagement && displayId) {
2573 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002574 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002575 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002576 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002577 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002578
Dominik Laskowski7e045462018-05-30 13:02:02 -07002579 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002580 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002581 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002582 }
tangrobin6753a022018-08-10 10:58:54 +08002583 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002584
Dominik Laskowski075d3172018-05-24 15:50:06 -07002585 if (displayId) {
2586 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002587 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002588 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002589 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002590
Lloyd Pique90c115d2018-09-18 21:39:42 -07002591 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002592 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002593 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002594
Lloyd Pique99d3da52018-01-22 17:48:03 -08002595 // Make sure that composition can never be stalled by a virtual display
2596 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002597 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002598 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002599 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2600 }
2601
Dominik Laskowski075d3172018-05-24 15:50:06 -07002602 creationArgs.displayInstallOrientation =
2603 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002604
Lloyd Pique99d3da52018-01-22 17:48:03 -08002605 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002606 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002607
Lloyd Pique90c115d2018-09-18 21:39:42 -07002608 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002609
2610 if (maxFrameBufferAcquiredBuffers >= 3) {
2611 nativeWindowSurface->preallocateBuffers();
2612 }
2613
2614 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002615 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002616 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002617 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002618 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002619 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002620 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002621 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002622 if (!state.isVirtual()) {
2623 LOG_ALWAYS_FATAL_IF(!displayId);
2624 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002625 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002626
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002627 display->setLayerStack(state.layerStack);
2628 display->setProjection(state.orientation, state.viewport, state.frame);
2629 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002630
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002631 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002632}
2633
Lloyd Pique347200f2017-12-14 17:00:15 -08002634void SurfaceFlinger::processDisplayChangesLocked() {
2635 // here we take advantage of Vector's copy-on-write semantics to
2636 // improve performance by skipping the transaction entirely when
2637 // know that the lists are identical
2638 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2639 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2640 if (!curr.isIdenticalTo(draw)) {
2641 mVisibleRegionsDirty = true;
2642 const size_t cc = curr.size();
2643 size_t dc = draw.size();
2644
2645 // find the displays that were removed
2646 // (ie: in drawing state but not in current state)
2647 // also handle displays that changed
2648 // (ie: displays that are in both lists)
2649 for (size_t i = 0; i < dc;) {
2650 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2651 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002652 // Save display IDs before disconnecting.
2653 const auto internalDisplayId = getInternalDisplayId();
2654 const auto externalDisplayId = getExternalDisplayId();
2655
Lloyd Pique347200f2017-12-14 17:00:15 -08002656 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002657 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2658 display->disconnect(getHwComposer());
2659 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002660 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002661 if (mUseScheduler) {
2662 mScheduler->hotplugReceived(mAppConnectionHandle,
2663 EventThread::DisplayType::Primary, false);
2664 } else {
2665 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2666 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002667 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002668 if (mUseScheduler) {
2669 mScheduler->hotplugReceived(mAppConnectionHandle,
2670 EventThread::DisplayType::External, false);
2671 } else {
2672 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2673 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002674 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002675 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002676 } else {
2677 // this display is in both lists. see if something changed.
2678 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002679 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002680 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2681 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2682 if (state_binder != draw_binder) {
2683 // changing the surface is like destroying and
2684 // recreating the DisplayDevice, so we just remove it
2685 // from the drawing state, so that it get re-added
2686 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002687 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2688 display->disconnect(getHwComposer());
2689 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002690 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002691 mDrawingState.displays.removeItemsAt(i);
2692 dc--;
2693 // at this point we must loop to the next item
2694 continue;
2695 }
2696
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002697 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002698 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002699 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002700 }
2701 if ((state.orientation != draw[i].orientation) ||
2702 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002703 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002704 }
2705 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002706 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002707 }
2708 }
2709 }
2710 ++i;
2711 }
2712
2713 // find displays that were added
2714 // (ie: in current state but not in drawing state)
2715 for (size_t i = 0; i < cc; i++) {
2716 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2717 const DisplayDeviceState& state(curr[i]);
2718
2719 sp<DisplaySurface> dispSurface;
2720 sp<IGraphicBufferProducer> producer;
2721 sp<IGraphicBufferProducer> bqProducer;
2722 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002723 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002724
Dominik Laskowski075d3172018-05-24 15:50:06 -07002725 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002726 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002727 // Virtual displays without a surface are dormant:
2728 // they have external state (layer stack, projection,
2729 // etc.) but no internal state (i.e. a DisplayDevice).
2730 if (state.surface != nullptr) {
2731 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002732 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002733 int width = 0;
2734 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2735 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2736 int height = 0;
2737 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2738 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2739 int intFormat = 0;
2740 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2741 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002742 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002743
Dominik Laskowski075d3172018-05-24 15:50:06 -07002744 displayId =
2745 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002746 }
2747
2748 // TODO: Plumb requested format back up to consumer
2749
2750 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002751 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002752 bqProducer, bqConsumer,
2753 state.displayName);
2754
2755 dispSurface = vds;
2756 producer = vds;
2757 }
2758 } else {
2759 ALOGE_IF(state.surface != nullptr,
2760 "adding a supported display, but rendering "
2761 "surface is provided (%p), ignoring it",
2762 state.surface.get());
2763
Dominik Laskowski075d3172018-05-24 15:50:06 -07002764 displayId = state.displayId;
2765 LOG_ALWAYS_FATAL_IF(!displayId);
2766 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002767 producer = bqProducer;
2768 }
2769
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002770 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002771 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002772 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002773 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002774 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002775 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002776 LOG_ALWAYS_FATAL_IF(!displayId);
2777
2778 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002779 if (mUseScheduler) {
2780 mScheduler->hotplugReceived(mAppConnectionHandle,
2781 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002782 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002783 } else {
2784 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2785 true);
2786 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002787 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002788 if (mUseScheduler) {
2789 mScheduler->hotplugReceived(mAppConnectionHandle,
2790 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002791 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002792 } else {
2793 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2794 true);
2795 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002796 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002797 }
2798 }
2799 }
2800 }
2801 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002802
2803 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002804}
2805
Mathias Agopian87baae12012-07-31 12:38:26 -07002806void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002807{
Dan Stoza7dde5992015-05-22 09:51:44 -07002808 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002809 mCurrentState.traverseInZOrder([](Layer* layer) {
2810 layer->notifyAvailableFrames();
2811 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002812
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002813 /*
2814 * Traversal of the children
2815 * (perform the transaction for each of them if needed)
2816 */
2817
Robert Carr720e5062018-07-30 17:45:14 -07002818 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002819 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002820 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002821 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002822 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002823
2824 const uint32_t flags = layer->doTransaction(0);
2825 if (flags & Layer::eVisibleRegion)
2826 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002827
2828 if (flags & Layer::eInputInfoChanged) {
2829 inputChanged = true;
2830 }
Robert Carr2047fae2016-11-28 14:09:09 -08002831 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002832 }
2833
2834 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002835 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002836 */
2837
Mathias Agopiane57f2922012-08-09 16:29:12 -07002838 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002839 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002840 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002841 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002842
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002843 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002844 // The transform hint might have changed for some layers
2845 // (either because a display has changed, or because a layer
2846 // as changed).
2847 //
2848 // Walk through all the layers in currentLayers,
2849 // and update their transform hint.
2850 //
2851 // If a layer is visible only on a single display, then that
2852 // display is used to calculate the hint, otherwise we use the
2853 // default display.
2854 //
2855 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2856 // the hint is set before we acquire a buffer from the surface texture.
2857 //
2858 // NOTE: layer transactions have taken place already, so we use their
2859 // drawing state. However, SurfaceFlinger's own transaction has not
2860 // happened yet, so we must use the current state layer list
2861 // (soon to become the drawing state list).
2862 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002863 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002864 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002865 bool first = true;
2866 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002867 // NOTE: we rely on the fact that layers are sorted by
2868 // layerStack first (so we don't have to traverse the list
2869 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002870 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002871 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002872 currentlayerStack = layerStack;
2873 // figure out if this layerstack is mirrored
2874 // (more than one display) if so, pick the default display,
2875 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002876 hintDisplay = nullptr;
2877 for (const auto& [token, display] : mDisplays) {
2878 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2879 if (hintDisplay) {
2880 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002881 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002882 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002883 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002884 }
2885 }
2886 }
2887 }
Chet Haase91d25932013-04-11 15:24:55 -07002888
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002889 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002890 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2891 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002892
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002893 // could be null when this layer is using a layerStack
2894 // that is not visible on any display. Also can occur at
2895 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002896 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002897 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002898
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002899 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002900 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002901 if (hintDisplay) {
2902 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002903 }
Robert Carr2047fae2016-11-28 14:09:09 -08002904
2905 first = false;
2906 });
Mathias Agopian84300952012-11-21 16:02:13 -08002907 }
2908
2909
Mathias Agopian3559b072012-08-15 13:46:03 -07002910 /*
2911 * Perform our own transaction if needed
2912 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002913
2914 if (mLayersAdded) {
2915 mLayersAdded = false;
2916 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002917 mVisibleRegionsDirty = true;
2918 }
2919
2920 // some layers might have been removed, so
2921 // we need to update the regions they're exposing.
2922 if (mLayersRemoved) {
2923 mLayersRemoved = false;
2924 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002925 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002926 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002927 // this layer is not visible anymore
2928 // TODO: we could traverse the tree from front to back and
2929 // compute the actual visible region
2930 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002931 Region visibleReg;
2932 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002933 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002934 }
Robert Carr2047fae2016-11-28 14:09:09 -08002935 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002936 }
2937
2938 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002939
Vishnu Nairde19f852018-12-18 16:11:53 -08002940 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002941 updateInputWindows();
2942 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002943 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002944
Riley Andrews03414a12014-07-01 14:22:59 -07002945 updateCursorAsync();
2946}
2947
Robert Carr720e5062018-07-30 17:45:14 -07002948void SurfaceFlinger::updateInputWindows() {
2949 ATRACE_CALL();
2950
Vishnu Nairde19f852018-12-18 16:11:53 -08002951 if (mInputFlinger == nullptr) {
2952 return;
2953 }
2954
Robert Carr720e5062018-07-30 17:45:14 -07002955 Vector<InputWindowInfo> inputHandles;
2956
2957 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2958 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002959 // When calculating the screen bounds we ignore the transparent region since it may
2960 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002961 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002962 }
2963 });
2964 mInputFlinger->setInputWindows(inputHandles);
2965}
2966
chaviwfbe5d9c2018-12-26 12:23:37 -08002967void SurfaceFlinger::executeInputWindowCommands() {
2968 if (!mInputFlinger) {
2969 return;
2970 }
2971
2972 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2973 if (transferTouchFocusCommand.fromToken != nullptr &&
2974 transferTouchFocusCommand.toToken != nullptr &&
2975 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2976 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2977 transferTouchFocusCommand.toToken);
2978 }
2979 }
2980
2981 mInputWindowCommands.clear();
2982}
2983
Riley Andrews03414a12014-07-01 14:22:59 -07002984void SurfaceFlinger::updateCursorAsync()
2985{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002986 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002987 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002988 continue;
2989 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002990
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002991 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2992 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002993 }
2994 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002995}
2996
chaviw61626f22018-11-15 16:26:27 -08002997void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2998 if (layer->hasReadyFrame()) {
2999 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3000 if (layer->shouldPresentNow(expectedPresentTime)) {
3001 bool ignored = false;
3002 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
3003 }
3004 }
3005 layer->releasePendingBuffer(systemTime());
3006}
3007
Mathias Agopian4fec8732012-06-29 14:12:52 -07003008void SurfaceFlinger::commitTransaction()
3009{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003010 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003011 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003012 for (const auto& l : mLayersPendingRemoval) {
3013 recordBufferingStats(l->getName().string(),
3014 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003015
3016 // We need to release the HWC layers when the Layer is removed
3017 // from the current state otherwise the HWC layer just continues
3018 // showing at its last configured state until we eventually
3019 // abandon the buffer queue.
3020 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003021 l->destroyHwcLayersForAllDisplays();
3022 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003023 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003024 }
3025 mLayersPendingRemoval.clear();
3026 }
3027
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003028 // If this transaction is part of a window animation then the next frame
3029 // we composite should be considered an animation as well.
3030 mAnimCompositionPending = mAnimTransactionPending;
3031
Mathias Agopian4fec8732012-06-29 14:12:52 -07003032 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003033 // clear the "changed" flags in current state
3034 mCurrentState.colorMatrixChanged = false;
3035
Robert Carr1f0a16a2016-10-24 16:27:39 -07003036 mDrawingState.traverseInZOrder([](Layer* layer) {
3037 layer->commitChildList();
3038 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003039 mTransactionPending = false;
3040 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003041 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003042}
3043
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003044void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
3045 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003046 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003047 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003048
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003049 Region aboveOpaqueLayers;
3050 Region aboveCoveredLayers;
3051 Region dirty;
3052
Mathias Agopian87baae12012-07-31 12:38:26 -07003053 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003054
Robert Carr2047fae2016-11-28 14:09:09 -08003055 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003056 // start with the whole surface at its current location
3057 const Layer::State& s(layer->getDrawingState());
3058
Jesse Hall01e29052013-02-19 16:13:35 -08003059 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003060 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003061 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003062 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003063
Mathias Agopianab028732010-03-16 16:41:46 -07003064 /*
3065 * opaqueRegion: area of a surface that is fully opaque.
3066 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003067 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003068
3069 /*
3070 * visibleRegion: area of a surface that is visible on screen
3071 * and not fully transparent. This is essentially the layer's
3072 * footprint minus the opaque regions above it.
3073 * Areas covered by a translucent surface are considered visible.
3074 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003075 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003076
3077 /*
3078 * coveredRegion: area of a surface that is covered by all
3079 * visible regions above it (which includes the translucent areas).
3080 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003081 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003082
Jesse Halla8026d22012-09-25 13:25:04 -07003083 /*
3084 * transparentRegion: area of a surface that is hinted to be completely
3085 * transparent. This is only used to tell when the layer has no visible
3086 * non-transparent regions and can be removed from the layer list. It
3087 * does not affect the visibleRegion of this layer or any layers
3088 * beneath it. The hint may not be correct if apps don't respect the
3089 * SurfaceView restrictions (which, sadly, some don't).
3090 */
3091 Region transparentRegion;
3092
Mathias Agopianab028732010-03-16 16:41:46 -07003093
3094 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003095 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003096 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003097 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003098
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003099 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003100 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003101 if (!visibleRegion.isEmpty()) {
3102 // Remove the transparent area from the visible region
3103 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003104 if (tr.preserveRects()) {
3105 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003106 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003107 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003108 // transformation too complex, can't do the
3109 // transparent region optimization.
3110 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003111 }
Mathias Agopianab028732010-03-16 16:41:46 -07003112 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003113
Mathias Agopianab028732010-03-16 16:41:46 -07003114 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003115 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003116 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003117 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003118 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003119 // the opaque region is the layer's footprint
3120 opaqueRegion = visibleRegion;
3121 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003122 }
3123 }
3124
Robert Carre5f4f692018-01-12 13:12:28 -08003125 if (visibleRegion.isEmpty()) {
3126 layer->clearVisibilityRegions();
3127 return;
3128 }
3129
Mathias Agopianab028732010-03-16 16:41:46 -07003130 // Clip the covered region to the visible region
3131 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3132
3133 // Update aboveCoveredLayers for next (lower) layer
3134 aboveCoveredLayers.orSelf(visibleRegion);
3135
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003136 // subtract the opaque region covered by the layers above us
3137 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003138
3139 // compute this layer's dirty region
3140 if (layer->contentDirty) {
3141 // we need to invalidate the whole region
3142 dirty = visibleRegion;
3143 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003144 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003145 layer->contentDirty = false;
3146 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003147 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003148 * the exposed region consists of two components:
3149 * 1) what's VISIBLE now and was COVERED before
3150 * 2) what's EXPOSED now less what was EXPOSED before
3151 *
3152 * note that (1) is conservative, we start with the whole
3153 * visible region but only keep what used to be covered by
3154 * something -- which mean it may have been exposed.
3155 *
3156 * (2) handles areas that were not covered by anything but got
3157 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003158 */
Mathias Agopianab028732010-03-16 16:41:46 -07003159 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003160 const Region oldVisibleRegion = layer->visibleRegion;
3161 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003162 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3163 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003164 }
3165 dirty.subtractSelf(aboveOpaqueLayers);
3166
3167 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003168 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003169
Mathias Agopianab028732010-03-16 16:41:46 -07003170 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003171 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003172
Jesse Halla8026d22012-09-25 13:25:04 -07003173 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003174 layer->setVisibleRegion(visibleRegion);
3175 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003176 layer->setVisibleNonTransparentRegion(
3177 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003178 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003179
Mathias Agopian87baae12012-07-31 12:38:26 -07003180 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003181}
3182
Chia-I Wuab0c3192017-08-01 11:29:00 -07003183void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003184 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003185 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
3186 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003187 }
3188 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003189}
3190
Dan Stoza6b9454d2014-11-07 16:00:59 -08003191bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003192{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003193 ALOGV("handlePageFlip");
3194
Brian Andersond6927fb2016-07-23 23:37:30 -07003195 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003196
Mathias Agopian4fec8732012-06-29 14:12:52 -07003197 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003198 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003199 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003200
3201 // Store the set of layers that need updates. This set must not change as
3202 // buffers are being latched, as this could result in a deadlock.
3203 // Example: Two producers share the same command stream and:
3204 // 1.) Layer 0 is latched
3205 // 2.) Layer 0 gets a new frame
3206 // 2.) Layer 1 gets a new frame
3207 // 3.) Layer 1 is latched.
3208 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3209 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003210 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003211 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003212 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003213 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3214 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003215 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003216 } else {
3217 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003218 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003219 } else {
3220 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003221 }
Robert Carr2047fae2016-11-28 14:09:09 -08003222 });
3223
Lloyd Piquef2c79392018-12-20 16:23:33 -08003224 if (!mLayersWithQueuedFrames.empty()) {
3225 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3226 // writes to Layer current state. See also b/119481871
3227 Mutex::Autolock lock(mStateLock);
3228
3229 for (auto& layer : mLayersWithQueuedFrames) {
3230 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3231 layer->useSurfaceDamage();
3232 invalidateLayerStack(layer, dirty);
3233 if (layer->isBufferLatched()) {
3234 newDataLatched = true;
3235 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003236 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003237 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003238
Alec Mouri86770e52018-09-24 22:40:58 +00003239 // Clear the renderengine fence here...
3240 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3241 // clear instead of sp::clear.
3242 getBE().flushFence = Fence::NO_FENCE;
3243
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003244 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003245
Vishnu Nairde19f852018-12-18 16:11:53 -08003246 if (visibleRegions) {
3247 // Update input window info if the layer receives its first buffer.
3248 updateInputWindows();
3249 }
3250
Dan Stoza6b9454d2014-11-07 16:00:59 -08003251 // If we will need to wake up at some time in the future to deal with a
3252 // queued frame that shouldn't be displayed during this vsync period, wake
3253 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003254 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003255 signalLayerUpdate();
3256 }
3257
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003258 // enter boot animation on first buffer latch
3259 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3260 ALOGI("Enter boot animation");
3261 mBootStage = BootStage::BOOTANIMATION;
3262 }
3263
Dan Stoza6b9454d2014-11-07 16:00:59 -08003264 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003265 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003266}
3267
Mathias Agopianad456f92011-01-13 17:53:01 -08003268void SurfaceFlinger::invalidateHwcGeometry()
3269{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003270 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003271}
3272
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003273void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& display,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003274 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003275 // We only need to actually compose the display if:
3276 // 1) It is being handled by hardware composer, which may need this to
3277 // keep its virtual display state machine in sync, or
3278 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski34157762018-10-31 13:07:19 -07003279 if (!display->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003280 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003281 return;
3282 }
3283
Dan Stoza9e56aa02015-11-02 13:00:03 -08003284 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003285 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003286
3287 // swap buffers (presentation)
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003288 display->queueBuffer(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003289}
3290
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003291bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003292 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003293
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003294 const Region bounds(display->bounds());
3295 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003296 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07003297 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003298 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003299
Peiyong Lind3788632018-09-18 16:01:31 -07003300 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003301 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003302
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003303 // Framebuffer will live in this scope for GPU composition.
3304 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
3305
Dan Stoza9e56aa02015-11-02 13:00:03 -08003306 if (hasClientComposition) {
3307 ALOGV("hasClientComposition");
3308
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003309 sp<GraphicBuffer> buf = display->dequeueBuffer();
3310
3311 if (buf == nullptr) {
3312 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3313 "client composition for this frame",
3314 display->getDisplayName().c_str());
3315 return false;
3316 }
3317
3318 // Bind the framebuffer in this scope.
3319 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3320 buf->getNativeBuffer());
3321
3322 if (fbo->getStatus() != NO_ERROR) {
3323 ALOGW("Binding buffer for display [%s] failed with status: %d",
3324 display->getDisplayName().c_str(), fbo->getStatus());
3325 return false;
3326 }
3327
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003328 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003329 if (display->hasWideColorGamut()) {
3330 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003331 }
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003332 getRenderEngine().setOutputDataSpace(outputDataspace);
3333 getRenderEngine().setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003334 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003335
Lloyd Pique441d5042018-10-18 16:49:51 -07003336 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003337 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003338 getHwComposer()
3339 .hasDisplayCapability(displayId,
3340 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003341
Peiyong Lind3788632018-09-18 16:01:31 -07003342 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003343 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3344 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003345 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003346 }
3347
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003348 display->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003349
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003350 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003351 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003352 // when using overlays, we assume a fully transparent framebuffer
3353 // NOTE: we could reduce how much we need to clear, for instance
3354 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003355 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003356 // We'll revisit later if needed.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003357 getRenderEngine().clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003358 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003359 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003360 // we're left with the letterbox region
3361 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003362 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003363
3364 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003365 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003366
Mathias Agopianb9494d52012-04-18 02:28:45 -07003367 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003368 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003369 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003370 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003371 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003372 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003373
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003374 const Rect& bounds = display->getBounds();
3375 const Rect& scissor = display->getScissor();
3376 if (scissor != bounds) {
3377 // scissor doesn't match the screen's dimensions, so we
3378 // need to clear everything outside of it and enable
3379 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003380
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003381 // enable scissor for this frame
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003382 getRenderEngine().setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003383 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003384 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003385
Mathias Agopian85d751c2012-08-29 16:59:24 -07003386 /*
3387 * and then, render the layers targeted at the framebuffer
3388 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003389
Dan Stoza9e56aa02015-11-02 13:00:03 -08003390 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003391 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003392 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003393 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003394 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003395 displayTransform.transform(layer->visibleRegion)));
3396 ALOGV("Layer: %s", layer->getName().string());
3397 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003398 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003399 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003400 case HWC2::Composition::Cursor:
3401 case HWC2::Composition::Device:
3402 case HWC2::Composition::Sideband:
3403 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003404 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003405 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003406 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003407 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003408 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003409 // never clear the very first layer since we're
3410 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003411 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003412 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003413 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003414 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003415 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003416 if (layer->hasColorTransform()) {
3417 mat4 tmpMatrix;
3418 if (applyColorMatrix) {
3419 tmpMatrix = mDrawingState.colorMatrix;
3420 }
3421 tmpMatrix *= layer->getColorTransform();
Peiyong Lind3788632018-09-18 16:01:31 -07003422 getRenderEngine().setColorTransform(tmpMatrix);
3423 } else {
3424 getRenderEngine().setColorTransform(colorMatrix);
3425 }
David Sodmanc1498e62018-09-12 14:36:26 -07003426 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003427 break;
3428 }
3429 default:
3430 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003431 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003432 } else {
3433 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003434 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003435 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003436 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003437
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003438 // Perform some cleanup steps if we used client composition.
3439 if (hasClientComposition) {
3440 getRenderEngine().setColorTransform(mat4());
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003441 getRenderEngine().disableScissor();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003442 display->finishBuffer();
3443 // Clear out error flags here so that we don't wait until next
3444 // composition to log.
3445 getRenderEngine().checkErrors();
3446 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003447 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003448}
3449
Chia-I Wu28e3a252018-09-07 12:05:02 -07003450void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003451 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003452 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003453}
3454
Dan Stoza7d89d062015-04-30 13:29:25 -07003455status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003456 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003457 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003458 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003459 const sp<Layer>& parent,
3460 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003461{
Dan Stoza7d89d062015-04-30 13:29:25 -07003462 // add this layer to the current state list
3463 {
3464 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003465 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003466 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3467 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003468 return NO_MEMORY;
3469 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003470 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003471 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003472 } else if (parent == nullptr) {
3473 lbc->onRemovedFromCurrentState();
3474 } else if (parent->isRemovedFromCurrentState()) {
3475 parent->addChild(lbc);
3476 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003477 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003478 parent->addChild(lbc);
3479 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003480
Yiwei Zhang243b3782018-05-15 17:40:04 -07003481 if (gbc != nullptr) {
3482 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3483 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3484 mMaxGraphicBufferProducerListSize,
3485 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3486 mGraphicBufferProducerList.size(),
3487 mMaxGraphicBufferProducerListSize, mNumLayers);
3488 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003489 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003490 }
3491
Mathias Agopian96f08192010-06-02 23:28:45 -07003492 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003493 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003494
Dan Stoza7d89d062015-04-30 13:29:25 -07003495 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003496}
3497
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003498uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003499 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003500}
3501
Mathias Agopian3f844832013-08-07 21:24:32 -07003502uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003503 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003504}
3505
Mathias Agopian3f844832013-08-07 21:24:32 -07003506uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003507 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003508}
3509
3510uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003511 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003512 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003513 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003514 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003515 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003516 }
3517 return old;
3518}
3519
Marissa Wall713b63f2018-10-17 15:42:43 -07003520bool SurfaceFlinger::flushTransactionQueues() {
3521 Mutex::Autolock _l(mStateLock);
3522 auto it = mTransactionQueues.begin();
3523 while (it != mTransactionQueues.end()) {
3524 auto& [applyToken, transactionQueue] = *it;
3525
3526 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003527 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3528 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003529 break;
3530 }
chaviw273171b2018-12-26 11:46:30 -08003531 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003532 transactionQueue.pop();
3533 }
3534
3535 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3536 }
3537 return mTransactionQueues.empty();
3538}
3539
chaviwca27f252018-02-06 16:46:39 -08003540bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3541 for (const ComposerState& state : states) {
3542 // Here we need to check that the interface we're given is indeed
3543 // one of our own. A malicious client could give us a nullptr
3544 // IInterface, or one of its own or even one of our own but a
3545 // different type. All these situations would cause us to crash.
3546 if (state.client == nullptr) {
3547 return true;
3548 }
3549
3550 sp<IBinder> binder = IInterface::asBinder(state.client);
3551 if (binder == nullptr) {
3552 return true;
3553 }
3554
3555 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3556 return true;
3557 }
3558 }
3559 return false;
3560}
3561
Marissa Wall17b4e452018-12-26 16:32:34 -08003562bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3563 const Vector<ComposerState>& states) {
3564 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3565 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3566 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3567 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3568 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3569 return false;
3570 }
3571
Marissa Wall713b63f2018-10-17 15:42:43 -07003572 for (const ComposerState& state : states) {
3573 const layer_state_t& s = state.state;
3574 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3575 continue;
3576 }
3577 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003578 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003579 }
3580 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003581 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003582}
3583
3584void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3585 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003586 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003587 const InputWindowCommands& inputWindowCommands,
3588 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003589 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003590 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003591
chaviwca27f252018-02-06 16:46:39 -08003592 if (containsAnyInvalidClientState(states)) {
3593 return;
3594 }
3595
Marissa Wall713b63f2018-10-17 15:42:43 -07003596 // If its TransactionQueue already has a pending TransactionState or if it is pending
3597 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003598 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3599 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003600 setTransactionFlags(eTransactionNeeded);
3601 return;
3602 }
3603
chaviw273171b2018-12-26 11:46:30 -08003604 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003605}
3606
3607void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003608 const Vector<DisplayState>& displays, uint32_t flags,
3609 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003610 uint32_t transactionFlags = 0;
3611
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003612 if (flags & eAnimation) {
3613 // For window updates that are part of an animation we must wait for
3614 // previous animation "frames" to be handled.
3615 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003616 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003617 if (CC_UNLIKELY(err != NO_ERROR)) {
3618 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003619 // caller after a few seconds.
3620 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3621 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003622 mAnimTransactionPending = false;
3623 break;
3624 }
3625 }
3626 }
3627
chaviwca27f252018-02-06 16:46:39 -08003628 for (const DisplayState& display : displays) {
3629 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003630 }
3631
Marissa Walle2ffb422018-10-12 11:33:52 -07003632 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003633 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003634 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003635 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003636 // If the state doesn't require a traversal and there are callbacks, send them now
3637 if (!(clientStateFlags & eTraversalNeeded)) {
3638 mTransactionCompletedThread.sendCallbacks();
3639 }
3640 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003641
chaviw273171b2018-12-26 11:46:30 -08003642 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3643
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003644 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3645 // anyway. This can be used as a flush mechanism for previous async transactions.
3646 // Empty animation transaction can be used to simulate back-pressure, so also force a
3647 // transaction for empty animation transactions.
3648 if (transactionFlags == 0 &&
3649 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003650 transactionFlags = eTransactionNeeded;
3651 }
3652
Mathias Agopian386aa982011-11-07 21:58:03 -08003653 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003654 if (mInterceptor->isEnabled()) {
3655 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003656 }
Irvel468051e2016-06-13 16:44:44 -07003657
Mathias Agopian386aa982011-11-07 21:58:03 -08003658 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003659 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3660 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003661 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003662
3663 // if this is a synchronous transaction, wait for it to take effect
3664 // before returning.
3665 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003666 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003667 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003668 if (flags & eAnimation) {
3669 mAnimTransactionPending = true;
3670 }
3671 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003672 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3673 if (CC_UNLIKELY(err != NO_ERROR)) {
3674 // just in case something goes wrong in SF, return to the
3675 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003676 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3677 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003678 break;
3679 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003680 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003681 }
3682}
3683
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003684uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3685 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3686 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003687
Mathias Agopiane57f2922012-08-09 16:29:12 -07003688 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003689 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3690
3691 const uint32_t what = s.what;
3692 if (what & DisplayState::eSurfaceChanged) {
3693 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3694 state.surface = s.surface;
3695 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003696 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003697 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003698 if (what & DisplayState::eLayerStackChanged) {
3699 if (state.layerStack != s.layerStack) {
3700 state.layerStack = s.layerStack;
3701 flags |= eDisplayTransactionNeeded;
3702 }
3703 }
3704 if (what & DisplayState::eDisplayProjectionChanged) {
3705 if (state.orientation != s.orientation) {
3706 state.orientation = s.orientation;
3707 flags |= eDisplayTransactionNeeded;
3708 }
3709 if (state.frame != s.frame) {
3710 state.frame = s.frame;
3711 flags |= eDisplayTransactionNeeded;
3712 }
3713 if (state.viewport != s.viewport) {
3714 state.viewport = s.viewport;
3715 flags |= eDisplayTransactionNeeded;
3716 }
3717 }
3718 if (what & DisplayState::eDisplaySizeChanged) {
3719 if (state.width != s.width) {
3720 state.width = s.width;
3721 flags |= eDisplayTransactionNeeded;
3722 }
3723 if (state.height != s.height) {
3724 state.height = s.height;
3725 flags |= eDisplayTransactionNeeded;
3726 }
3727 }
3728
Mathias Agopiane57f2922012-08-09 16:29:12 -07003729 return flags;
3730}
3731
Robert Carrd4ae7f32018-06-07 16:10:57 -07003732bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3733 IPCThreadState* ipc = IPCThreadState::self();
3734 const int pid = ipc->getCallingPid();
3735 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003736 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003737 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003738 return false;
3739 }
3740 return true;
3741}
3742
chaviwca27f252018-02-06 16:46:39 -08003743uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3744 const layer_state_t& s = composerState.state;
3745 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3746
Mathias Agopian13127d82013-03-05 17:47:11 -08003747 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003748 if (layer == nullptr) {
3749 return 0;
3750 }
3751
chaviw8b3871a2017-11-01 17:41:01 -07003752 uint32_t flags = 0;
3753
Garfield Tan8a3083e2018-12-03 13:21:07 -08003754 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003755 bool geometryAppliesWithResize =
3756 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003757
3758 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3759 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003760 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003761 layer->pushPendingState();
3762 }
3763
chaviw8b3871a2017-11-01 17:41:01 -07003764 if (what & layer_state_t::ePositionChanged) {
3765 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3766 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003767 }
chaviw8b3871a2017-11-01 17:41:01 -07003768 }
3769 if (what & layer_state_t::eLayerChanged) {
3770 // NOTE: index needs to be calculated before we update the state
3771 const auto& p = layer->getParent();
3772 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003773 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003774 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003775 mCurrentState.layersSortedByZ.removeAt(idx);
3776 mCurrentState.layersSortedByZ.add(layer);
3777 // we need traversal (state changed)
3778 // AND transaction (list changed)
3779 flags |= eTransactionNeeded|eTraversalNeeded;
3780 }
chaviw8b3871a2017-11-01 17:41:01 -07003781 } else {
3782 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003783 flags |= eTransactionNeeded|eTraversalNeeded;
3784 }
3785 }
chaviw8b3871a2017-11-01 17:41:01 -07003786 }
3787 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003788 // NOTE: index needs to be calculated before we update the state
3789 const auto& p = layer->getParent();
3790 if (p == nullptr) {
3791 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3792 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3793 mCurrentState.layersSortedByZ.removeAt(idx);
3794 mCurrentState.layersSortedByZ.add(layer);
3795 // we need traversal (state changed)
3796 // AND transaction (list changed)
3797 flags |= eTransactionNeeded|eTraversalNeeded;
3798 }
3799 } else {
3800 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3801 flags |= eTransactionNeeded|eTraversalNeeded;
3802 }
chaviw8b3871a2017-11-01 17:41:01 -07003803 }
3804 }
3805 if (what & layer_state_t::eSizeChanged) {
3806 if (layer->setSize(s.w, s.h)) {
3807 flags |= eTraversalNeeded;
3808 }
3809 }
3810 if (what & layer_state_t::eAlphaChanged) {
3811 if (layer->setAlpha(s.alpha))
3812 flags |= eTraversalNeeded;
3813 }
3814 if (what & layer_state_t::eColorChanged) {
3815 if (layer->setColor(s.color))
3816 flags |= eTraversalNeeded;
3817 }
Peiyong Lind3788632018-09-18 16:01:31 -07003818 if (what & layer_state_t::eColorTransformChanged) {
3819 if (layer->setColorTransform(s.colorTransform)) {
3820 flags |= eTraversalNeeded;
3821 }
3822 }
chaviw8b3871a2017-11-01 17:41:01 -07003823 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003824 // TODO: b/109894387
3825 //
3826 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3827 // rotation. To see the problem observe that if we have a square parent, and a child
3828 // of the same size, then we rotate the child 45 degrees around it's center, the child
3829 // must now be cropped to a non rectangular 8 sided region.
3830 //
3831 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3832 // private API, and the WindowManager only uses rotation in one case, which is on a top
3833 // level layer in which cropping is not an issue.
3834 //
3835 // However given that abuse of rotation matrices could lead to surfaces extending outside
3836 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3837 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3838 // transformations.
3839 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003840 flags |= eTraversalNeeded;
3841 }
3842 if (what & layer_state_t::eTransparentRegionChanged) {
3843 if (layer->setTransparentRegionHint(s.transparentRegion))
3844 flags |= eTraversalNeeded;
3845 }
3846 if (what & layer_state_t::eFlagsChanged) {
3847 if (layer->setFlags(s.flags, s.mask))
3848 flags |= eTraversalNeeded;
3849 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003850 if (what & layer_state_t::eCropChanged_legacy) {
3851 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003852 flags |= eTraversalNeeded;
3853 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003854 if (what & layer_state_t::eCornerRadiusChanged) {
3855 if (layer->setCornerRadius(s.cornerRadius))
3856 flags |= eTraversalNeeded;
3857 }
chaviw8b3871a2017-11-01 17:41:01 -07003858 if (what & layer_state_t::eLayerStackChanged) {
3859 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3860 // We only allow setting layer stacks for top level layers,
3861 // everything else inherits layer stack from its parent.
3862 if (layer->hasParent()) {
3863 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3864 layer->getName().string());
3865 } else if (idx < 0) {
3866 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3867 "that also does not appear in the top level layer list. Something"
3868 " has gone wrong.", layer->getName().string());
3869 } else if (layer->setLayerStack(s.layerStack)) {
3870 mCurrentState.layersSortedByZ.removeAt(idx);
3871 mCurrentState.layersSortedByZ.add(layer);
3872 // we need traversal (state changed)
3873 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003874 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003875 }
3876 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003877 if (what & layer_state_t::eDeferTransaction_legacy) {
3878 if (s.barrierHandle_legacy != nullptr) {
3879 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3880 } else if (s.barrierGbp_legacy != nullptr) {
3881 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003882 if (authenticateSurfaceTextureLocked(gbp)) {
3883 const auto& otherLayer =
3884 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003885 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003886 } else {
3887 ALOGE("Attempt to defer transaction to to an"
3888 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003889 }
3890 }
chaviw8b3871a2017-11-01 17:41:01 -07003891 // We don't trigger a traversal here because if no other state is
3892 // changed, we don't want this to cause any more work
3893 }
3894 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003895 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003896 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003897 if (!hadParent) {
3898 mCurrentState.layersSortedByZ.remove(layer);
3899 }
chaviw8b3871a2017-11-01 17:41:01 -07003900 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003901 }
chaviw8b3871a2017-11-01 17:41:01 -07003902 }
3903 if (what & layer_state_t::eReparentChildren) {
3904 if (layer->reparentChildren(s.reparentHandle)) {
3905 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003906 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003907 }
chaviw8b3871a2017-11-01 17:41:01 -07003908 if (what & layer_state_t::eDetachChildren) {
3909 layer->detachChildren();
3910 }
3911 if (what & layer_state_t::eOverrideScalingModeChanged) {
3912 layer->setOverrideScalingMode(s.overrideScalingMode);
3913 // We don't trigger a traversal here because if no other state is
3914 // changed, we don't want this to cause any more work
3915 }
Marissa Wall61c58622018-07-18 10:12:20 -07003916 if (what & layer_state_t::eTransformChanged) {
3917 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3918 }
3919 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3920 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3921 flags |= eTraversalNeeded;
3922 }
3923 if (what & layer_state_t::eCropChanged) {
3924 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3925 }
Marissa Wall861616d2018-10-22 12:52:23 -07003926 if (what & layer_state_t::eFrameChanged) {
3927 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3928 }
Marissa Wall61c58622018-07-18 10:12:20 -07003929 if (what & layer_state_t::eBufferChanged) {
3930 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3931 }
3932 if (what & layer_state_t::eAcquireFenceChanged) {
3933 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3934 }
3935 if (what & layer_state_t::eDataspaceChanged) {
3936 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3937 }
3938 if (what & layer_state_t::eHdrMetadataChanged) {
3939 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3940 }
3941 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3942 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3943 }
3944 if (what & layer_state_t::eApiChanged) {
3945 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3946 }
3947 if (what & layer_state_t::eSidebandStreamChanged) {
3948 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3949 }
Robert Carr720e5062018-07-30 17:45:14 -07003950 if (what & layer_state_t::eInputInfoChanged) {
3951 layer->setInputInfo(s.inputInfo);
3952 flags |= eTraversalNeeded;
3953 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003954 std::vector<sp<CallbackHandle>> callbackHandles;
3955 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3956 mTransactionCompletedThread.run();
3957 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3958 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3959 }
3960 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003961 if (what & layer_state_t::eCachedBufferChanged) {
3962 sp<GraphicBuffer> buffer =
3963 mBufferStateLayerCache.get(s.cachedBuffer.token, s.cachedBuffer.bufferId);
3964 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
3965 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003966 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3967 // Do not put anything that updates layer state or modifies flags after
3968 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003969 return flags;
3970}
3971
chaviw273171b2018-12-26 11:46:30 -08003972uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3973 uint32_t flags = 0;
3974 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3975 flags |= eTraversalNeeded;
3976 }
3977
3978 mInputWindowCommands.merge(inputWindowCommands);
3979 return flags;
3980}
3981
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003982status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003983 const String8& name,
3984 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003985 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003986 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003987 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003988{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003989 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003990 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003991 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003992 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003993 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003994
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003995 status_t result = NO_ERROR;
3996
3997 sp<Layer> layer;
3998
Cody Northropbc755282017-03-31 12:00:08 -06003999 String8 uniqueName = getUniqueLayerName(name);
4000
Mathias Agopian3165cc22012-08-08 19:42:09 -07004001 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004002 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004003 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4004 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004005
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004006 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004007 case ISurfaceComposerClient::eFXSurfaceBufferState:
4008 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4009 break;
chaviw13fdc492017-06-27 12:40:18 -07004010 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004011 // check if buffer size is set for color layer.
4012 if (w > 0 || h > 0) {
4013 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4014 int(w), int(h));
4015 return BAD_VALUE;
4016 }
4017
chaviw13fdc492017-06-27 12:40:18 -07004018 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004019 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004020 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004021 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004022 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004023 // check if buffer size is set for container layer.
4024 if (w > 0 || h > 0) {
4025 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4026 int(w), int(h));
4027 return BAD_VALUE;
4028 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004029 result = createContainerLayer(client,
4030 uniqueName, w, h, flags,
4031 handle, &layer);
4032 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004033 default:
4034 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004035 break;
4036 }
4037
Dan Stoza7d89d062015-04-30 13:29:25 -07004038 if (result != NO_ERROR) {
4039 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004040 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004041
Chia-I Wuab0c3192017-08-01 11:29:00 -07004042 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4043 // TODO b/64227542
4044 if (windowType == 441731) {
4045 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
4046 layer->setPrimaryDisplayOnly();
4047 }
4048
Albert Chaulk479c60c2017-01-27 14:21:34 -05004049 layer->setInfo(windowType, ownerUid);
4050
Robert Carrb89ea9d2018-12-10 13:01:14 -08004051 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4052 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4053 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004054 if (result != NO_ERROR) {
4055 return result;
4056 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004057 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004058
4059 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004060 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004061}
4062
Cody Northropbc755282017-03-31 12:00:08 -06004063String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4064{
4065 bool matchFound = true;
4066 uint32_t dupeCounter = 0;
4067
4068 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4069 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4070
Dan Stoza436ccf32018-06-21 12:10:12 -07004071 // Grab the state lock since we're accessing mCurrentState
4072 Mutex::Autolock lock(mStateLock);
4073
Cody Northropbc755282017-03-31 12:00:08 -06004074 // Loop over layers until we're sure there is no matching name
4075 while (matchFound) {
4076 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004077 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004078 if (layer->getName() == uniqueName) {
4079 matchFound = true;
4080 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4081 }
4082 });
4083 }
4084
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004085 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4086 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004087
4088 return uniqueName;
4089}
4090
Marissa Wallfd668622018-05-10 10:21:13 -07004091status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4092 uint32_t w, uint32_t h, uint32_t flags,
4093 PixelFormat& format, sp<IBinder>* handle,
4094 sp<IGraphicBufferProducer>* gbp,
4095 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004096 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004097 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004098 case PIXEL_FORMAT_TRANSPARENT:
4099 case PIXEL_FORMAT_TRANSLUCENT:
4100 format = PIXEL_FORMAT_RGBA_8888;
4101 break;
4102 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004103 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004104 break;
4105 }
4106
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004107 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004108 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004109 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004110 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004111 *handle = layer->getHandle();
4112 *gbp = layer->getProducer();
4113 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004114 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004115
Marissa Wallfd668622018-05-10 10:21:13 -07004116 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004117 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004118}
4119
Marissa Wall61c58622018-07-18 10:12:20 -07004120status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4121 uint32_t w, uint32_t h, uint32_t flags,
4122 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004123 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004124 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004125 *handle = layer->getHandle();
4126 *outLayer = layer;
4127
4128 return NO_ERROR;
4129}
4130
chaviw13fdc492017-06-27 12:40:18 -07004131status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004132 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004133 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004134{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004135 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004136 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004137 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004138}
4139
Robert Carr6b3f6c52018-08-13 13:05:17 -07004140status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4141 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4142 sp<IBinder>* handle, sp<Layer>* outLayer)
4143{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004144 *outLayer =
4145 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004146 *handle = (*outLayer)->getHandle();
4147 return NO_ERROR;
4148}
4149
4150
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004151void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004152 mLayersPendingRemoval.add(layer);
4153 mLayersRemoved = true;
4154 setTransactionFlags(eTransactionNeeded);
4155}
4156
Robert Carr695d5282018-12-18 15:27:58 -08004157void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004158{
Robert Carr2e102c92018-10-23 12:11:15 -07004159 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004160 // If a layer has a parent, we allow it to out-live it's handle
4161 // with the idea that the parent holds a reference and will eventually
4162 // be cleaned up. However no one cleans up the top-level so we do so
4163 // here.
4164 if (layer->getParent() == nullptr) {
4165 mCurrentState.layersSortedByZ.remove(layer);
4166 }
4167 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004168 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004169}
4170
Mathias Agopianb60314a2012-04-10 22:09:54 -07004171// ---------------------------------------------------------------------------
4172
Andy McFadden13a082e2012-08-24 10:16:42 -07004173void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004174 const auto display = getDefaultDisplayDeviceLocked();
4175 if (!display) return;
4176
4177 const sp<IBinder> token = display->getDisplayToken().promote();
4178 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004179
Jesse Hall01e29052013-02-19 16:13:35 -08004180 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004181 Vector<ComposerState> state;
4182 Vector<DisplayState> displays;
4183 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004184 d.what = DisplayState::eDisplayProjectionChanged |
4185 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004186 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004187 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004188 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004189 d.frame.makeInvalid();
4190 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004191 d.width = 0;
4192 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004193 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004194 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004195
Dominik Laskowskie9774092018-12-11 10:04:24 -08004196 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004197
Dominik Laskowski83b88212018-12-11 13:34:06 -08004198 const nsecs_t vsyncPeriod = getVsyncPeriod();
4199 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004200
Brian Andersond0010582017-03-07 13:20:31 -08004201 // Use phase of 0 since phase is not known.
4202 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004203 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004204 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004205}
4206
4207void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004208 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004209 postMessageAsync(
4210 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004211}
4212
Dominik Laskowskie9774092018-12-11 10:04:24 -08004213void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004214 if (display->isVirtual()) {
4215 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004216 return;
4217 }
4218
Dominik Laskowski075d3172018-05-24 15:50:06 -07004219 const auto displayId = display->getId();
4220 LOG_ALWAYS_FATAL_IF(!displayId);
4221
Dominik Laskowski34157762018-10-31 13:07:19 -07004222 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004223
4224 int currentMode = display->getPowerMode();
4225 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004226 return;
4227 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004228
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004229 display->setPowerMode(mode);
4230
Lloyd Pique4dccc412018-01-22 17:21:36 -08004231 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004232 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004233 }
4234
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004235 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004236 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004237 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004238 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004239 if (mUseScheduler) {
4240 mScheduler->onScreenAcquired(mAppConnectionHandle);
4241 } else {
4242 mEventThread->onScreenAcquired();
4243 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004244 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004245 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004246
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004247 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004248 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004249 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004250
4251 struct sched_param param = {0};
4252 param.sched_priority = 1;
4253 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4254 ALOGW("Couldn't set SCHED_FIFO on display on");
4255 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004256 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004257 // Turn off the display
4258 struct sched_param param = {0};
4259 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4260 ALOGW("Couldn't set SCHED_OTHER on display off");
4261 }
4262
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004263 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004264 if (mUseScheduler) {
4265 mScheduler->disableHardwareVsync(true);
4266 } else {
4267 disableHardwareVsync(true); // also cancels any in-progress resync
4268 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004269 if (mUseScheduler) {
4270 mScheduler->onScreenReleased(mAppConnectionHandle);
4271 } else {
4272 mEventThread->onScreenReleased();
4273 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004274 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004275
Dominik Laskowski075d3172018-05-24 15:50:06 -07004276 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004277 mVisibleRegionsDirty = true;
4278 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004279 } else if (mode == HWC_POWER_MODE_DOZE ||
4280 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004281 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004282 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004283 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004284 if (mUseScheduler) {
4285 mScheduler->onScreenAcquired(mAppConnectionHandle);
4286 } else {
4287 mEventThread->onScreenAcquired();
4288 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004289 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004290 }
4291 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4292 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004293 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004294 if (mUseScheduler) {
4295 mScheduler->disableHardwareVsync(true);
4296 } else {
4297 disableHardwareVsync(true); // also cancels any in-progress resync
4298 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004299 if (mUseScheduler) {
4300 mScheduler->onScreenReleased(mAppConnectionHandle);
4301 } else {
4302 mEventThread->onScreenReleased();
4303 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004304 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004305 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004306 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004307 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004308 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004309 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004310
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004311 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004312 mTimeStats->setPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004313 }
4314
Dominik Laskowski34157762018-10-31 13:07:19 -07004315 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004316}
4317
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004318void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004319 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004320 const auto display = getDisplayDevice(displayToken);
4321 if (!display) {
4322 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4323 displayToken.get());
4324 } else if (display->isVirtual()) {
4325 ALOGW("Attempt to set power mode %d for virtual display", mode);
4326 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004327 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004328 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004329 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004330}
4331
4332// ---------------------------------------------------------------------------
4333
Lloyd Pique755e3192018-01-31 16:46:15 -08004334status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4335 NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004336 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004337
Mathias Agopianbd115332013-04-18 16:41:04 -07004338 IPCThreadState* ipc = IPCThreadState::self();
4339 const int pid = ipc->getCallingPid();
4340 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004341
Mathias Agopianbd115332013-04-18 16:41:04 -07004342 if ((uid != AID_SHELL) &&
4343 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004344 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4345 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004346 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004347 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004348 // (this would indicate SF is stuck, but we want to be able to
4349 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004350 status_t err = mStateLock.timedLock(s2ns(1));
4351 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004352 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004353 StringAppendF(&result,
4354 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4355 "(no locks held)\n",
4356 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004357 }
4358
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004359 bool dumpAll = true;
4360 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004361 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004362
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004363 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004364 if ((index < numArgs) &&
4365 (args[index] == String16("--list"))) {
4366 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004367 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004368 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004369 }
4370
4371 if ((index < numArgs) &&
4372 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004373 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004374 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004375 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004376 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004377
4378 if ((index < numArgs) &&
4379 (args[index] == String16("--latency-clear"))) {
4380 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004381 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004382 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004383 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004384
4385 if ((index < numArgs) &&
4386 (args[index] == String16("--dispsync"))) {
4387 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004388 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004389 dumpAll = false;
4390 }
Dan Stozab90cf072015-03-05 11:05:59 -08004391
4392 if ((index < numArgs) &&
4393 (args[index] == String16("--static-screen"))) {
4394 index++;
4395 dumpStaticScreenStats(result);
4396 dumpAll = false;
4397 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004398
4399 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004400 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004401 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004402 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004403 dumpAll = false;
4404 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004405
4406 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4407 index++;
4408 dumpWideColorInfo(result);
4409 dumpAll = false;
4410 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004411
4412 if ((index < numArgs) &&
4413 (args[index] == String16("--enable-layer-stats"))) {
4414 index++;
4415 mLayerStats.enable();
4416 dumpAll = false;
4417 }
4418
4419 if ((index < numArgs) &&
4420 (args[index] == String16("--disable-layer-stats"))) {
4421 index++;
4422 mLayerStats.disable();
4423 dumpAll = false;
4424 }
4425
4426 if ((index < numArgs) &&
4427 (args[index] == String16("--clear-layer-stats"))) {
4428 index++;
4429 mLayerStats.clear();
4430 dumpAll = false;
4431 }
4432
4433 if ((index < numArgs) &&
4434 (args[index] == String16("--dump-layer-stats"))) {
4435 index++;
4436 mLayerStats.dump(result);
4437 dumpAll = false;
4438 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004439
4440 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004441 (args[index] == String16("--frame-composition"))) {
4442 index++;
4443 dumpFrameCompositionInfo(result);
4444 dumpAll = false;
4445 }
4446
4447 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004448 (args[index] == String16("--display-identification"))) {
4449 index++;
4450 dumpDisplayIdentificationData(result);
4451 dumpAll = false;
4452 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004453
4454 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4455 index++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004456 mTimeStats->parseArgs(asProto, args, index, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004457 dumpAll = false;
4458 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004459 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004460
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004461 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004462 if (asProto) {
4463 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4464 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4465 } else {
4466 dumpAllLocked(args, index, result);
4467 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004468 }
4469
Mathias Agopian9795c422009-08-26 16:36:26 -07004470 if (locked) {
4471 mStateLock.unlock();
4472 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004473 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004474 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004475 return NO_ERROR;
4476}
4477
Yiwei Zhang5434a782018-12-05 18:06:32 -08004478void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */, size_t& /* index */,
4479 std::string& result) const {
4480 mCurrentState.traverseInZOrder(
4481 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004482}
4483
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004484void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004485 std::string& result) const {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004486 String8 name;
4487 if (index < args.size()) {
4488 name = String8(args[index]);
4489 index++;
4490 }
4491
Dominik Laskowski83b88212018-12-11 13:34:06 -08004492 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004493
4494 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004495 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004496 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004497 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004498 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004499 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004500 }
Robert Carr2047fae2016-11-28 14:09:09 -08004501 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004502 }
4503}
4504
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004505void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004506 std::string& /* result */) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004507 String8 name;
4508 if (index < args.size()) {
4509 name = String8(args[index]);
4510 index++;
4511 }
4512
Robert Carr2047fae2016-11-28 14:09:09 -08004513 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004514 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004515 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004516 }
Robert Carr2047fae2016-11-28 14:09:09 -08004517 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004518
Svetoslavd85084b2014-03-20 10:28:31 -07004519 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004520}
4521
Jamie Gennis6547ff42013-07-16 20:12:42 -07004522// This should only be called from the main thread. Otherwise it would need
4523// the lock and should use mCurrentState rather than mDrawingState.
4524void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004525 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004526 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004527 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004528
4529 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4530}
4531
Yiwei Zhang5434a782018-12-05 18:06:32 -08004532void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004533 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004534
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004535 if (isLayerTripleBufferingDisabled())
4536 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004537
Yiwei Zhang5434a782018-12-05 18:06:32 -08004538 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4539 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4540 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4541 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4542 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4543 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004544 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004545}
4546
Yiwei Zhang5434a782018-12-05 18:06:32 -08004547void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4548 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004549 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4550 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004551 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004552 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004553 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004554 }
David Sodman4a36e932017-11-07 14:29:47 -08004555 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004556 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004557 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004558 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4559 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004560}
4561
Dan Stozae77c7662016-05-13 11:37:28 -07004562void SurfaceFlinger::recordBufferingStats(const char* layerName,
4563 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004564 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4565 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004566 for (const auto& segment : history) {
4567 if (!segment.usedThirdBuffer) {
4568 stats.twoBufferTime += segment.totalTime;
4569 }
4570 if (segment.occupancyAverage < 1.0f) {
4571 stats.doubleBufferedTime += segment.totalTime;
4572 } else if (segment.occupancyAverage < 2.0f) {
4573 stats.tripleBufferedTime += segment.totalTime;
4574 }
4575 ++stats.numSegments;
4576 stats.totalTime += segment.totalTime;
4577 }
4578}
4579
Yiwei Zhang5434a782018-12-05 18:06:32 -08004580void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4581 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004582
4583 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4584 const size_t count = currentLayers.size();
4585 for (size_t i=0 ; i<count ; i++) {
4586 currentLayers[i]->dumpFrameEvents(result);
4587 }
4588}
4589
Yiwei Zhang5434a782018-12-05 18:06:32 -08004590void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004591 result.append("Buffering stats:\n");
4592 result.append(" [Layer name] <Active time> <Two buffer> "
4593 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004594 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004595 typedef std::tuple<std::string, float, float, float> BufferTuple;
4596 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004597 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004598 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004599 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004600 if (stats.numSegments == 0) {
4601 continue;
4602 }
4603 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4604 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4605 stats.totalTime;
4606 float doubleBufferRatio = static_cast<float>(
4607 stats.doubleBufferedTime) / stats.totalTime;
4608 float tripleBufferRatio = static_cast<float>(
4609 stats.tripleBufferedTime) / stats.totalTime;
4610 sorted.insert({activeTime, {name, twoBufferRatio,
4611 doubleBufferRatio, tripleBufferRatio}});
4612 }
4613 for (const auto& sortedPair : sorted) {
4614 float activeTime = sortedPair.first;
4615 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004616 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4617 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004618 }
4619 result.append("\n");
4620}
4621
Yiwei Zhang5434a782018-12-05 18:06:32 -08004622void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004623 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004624 const auto displayId = display->getId();
4625 if (!displayId) {
4626 continue;
4627 }
4628 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004629 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004630 continue;
4631 }
4632
Yiwei Zhang5434a782018-12-05 18:06:32 -08004633 StringAppendF(&result,
4634 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4635 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004636 uint8_t port;
4637 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004638 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004639 result.append("no identification data\n");
4640 continue;
4641 }
4642
4643 if (!isEdid(data)) {
4644 result.append("unknown identification data: ");
4645 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004646 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004647 }
4648 result.append("\n");
4649 continue;
4650 }
4651
4652 const auto edid = parseEdid(data);
4653 if (!edid) {
4654 result.append("invalid EDID: ");
4655 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004656 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004657 }
4658 result.append("\n");
4659 continue;
4660 }
4661
Yiwei Zhang5434a782018-12-05 18:06:32 -08004662 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004663 result.append(edid->displayName.data(), edid->displayName.length());
4664 result.append("\"\n");
4665 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004666}
4667
Yiwei Zhang5434a782018-12-05 18:06:32 -08004668void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4669 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4670 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4671 StringAppendF(&result, "DisplayColorSetting: %s\n",
4672 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004673
4674 // TODO: print out if wide-color mode is active or not
4675
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004676 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004677 const auto displayId = display->getId();
4678 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004679 continue;
4680 }
4681
Yiwei Zhang5434a782018-12-05 18:06:32 -08004682 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004683 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004684 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004685 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004686 }
4687
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004688 ColorMode currentMode = display->getActiveColorMode();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004689 StringAppendF(&result, " Current color mode: %s (%d)\n",
4690 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004691 }
4692 result.append("\n");
4693}
4694
Yiwei Zhang5434a782018-12-05 18:06:32 -08004695void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004696 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004697 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4698 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004699 continue;
4700 }
4701
Dominik Laskowski05275f12018-11-01 15:03:24 -07004702 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004703 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4704 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004705 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004706 compositionInfo.dump(result, nullptr);
4707 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004708 }
4709 }
David Sodman7e4ae112018-02-09 15:02:28 -08004710}
4711
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004712LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004713 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004714 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4715 const State& state = useDrawing ? mDrawingState : mCurrentState;
4716 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004717 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004718 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004719 });
4720
4721 return layersProto;
4722}
4723
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004724LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004725 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004726
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004727 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004728 resolution->set_w(display.getWidth());
4729 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004730
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004731 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4732 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4733 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004734
Dominik Laskowski075d3172018-05-24 15:50:06 -07004735 const auto displayId = display.getId();
4736 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004737 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004738 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004739 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004740 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004741 }
4742 });
4743
4744 return layersProto;
4745}
4746
Mathias Agopian74d211a2013-04-22 16:55:35 +02004747void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004748 std::string& result) const {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004749 bool colorize = false;
4750 if (index < args.size()
4751 && (args[index] == String16("--color"))) {
4752 colorize = true;
4753 index++;
4754 }
4755
4756 Colorizer colorizer(colorize);
4757
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004758 // figure out if we're stuck somewhere
4759 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004760 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004761 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4762
4763 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004764 * Dump library configuration.
4765 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004766
4767 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004768 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004769 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004770 appendSfConfigString(result);
4771 appendUiConfigString(result);
4772 appendGuiConfigString(result);
4773 result.append("\n");
4774
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004775 result.append("\nDisplay identification data:\n");
4776 dumpDisplayIdentificationData(result);
4777
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004778 result.append("\nWide-Color information:\n");
4779 dumpWideColorInfo(result);
4780
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004781 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004782 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004783 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004784 result.append(SyncFeatures::getInstance().toString());
4785 result.append("\n");
4786
Andy McFadden41d67d72014-04-25 16:58:34 -07004787 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004788 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004789 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004790
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004791 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4792 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski83b88212018-12-11 13:34:06 -08004793 StringAppendF(&result,
4794 "app phase %" PRId64 " ns, "
4795 "sf phase %" PRId64 " ns, "
4796 "early app phase %" PRId64 " ns, "
4797 "early sf phase %" PRId64 " ns, "
4798 "early app gl phase %" PRId64 " ns, "
4799 "early sf gl phase %" PRId64 " ns, "
4800 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)\n",
4801 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, appEarlyOffset, sfEarlyOffset,
4802 appEarlyGlOffset, sfEarlyGlOffset, dispSyncPresentTimeOffset, getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004803
Dan Stozab90cf072015-03-05 11:05:59 -08004804 // Dump static screen stats
4805 result.append("\n");
4806 dumpStaticScreenStats(result);
4807 result.append("\n");
4808
Yiwei Zhang5434a782018-12-05 18:06:32 -08004809 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004810
Dan Stozae77c7662016-05-13 11:37:28 -07004811 dumpBufferingStats(result);
4812
Andy McFadden4803b742012-09-24 19:07:20 -07004813 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004814 * Dump the visible layer list
4815 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004816 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004817 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4818 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4819 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004820 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004821
Chia-I Wu2f884132018-09-13 15:17:58 -07004822 {
4823 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4824 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004825 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004826 result.append("\n");
4827 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004828
David Sodman7e4ae112018-02-09 15:02:28 -08004829 result.append("\nFrame-Composition information:\n");
4830 dumpFrameCompositionInfo(result);
4831 result.append("\n");
4832
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004833 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004834 * Dump Display state
4835 */
4836
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004837 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004838 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004839 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004840 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004841 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004842 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004843 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004844
4845 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004846 * Dump SurfaceFlinger global state
4847 */
4848
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004849 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004850 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004851 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004852
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004853 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004854
Dominik Laskowski075d3172018-05-24 15:50:06 -07004855 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004856 display->undefinedRegion.dump(result, "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004857 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4858 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004859 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004860 StringAppendF(&result,
4861 " transaction-flags : %08x\n"
4862 " gpu_to_cpu_unsupported : %d\n",
4863 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004864
Dominik Laskowski075d3172018-05-24 15:50:06 -07004865 if (const auto displayId = getInternalDisplayId();
4866 displayId && getHwComposer().isConnected(*displayId)) {
4867 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004868 StringAppendF(&result,
4869 " refresh-rate : %f fps\n"
4870 " x-dpi : %f\n"
4871 " y-dpi : %f\n",
4872 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4873 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004874 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004875
Yiwei Zhang5434a782018-12-05 18:06:32 -08004876 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004877
Yiwei Zhang5434a782018-12-05 18:06:32 -08004878 StringAppendF(&result, " use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004879 /*
4880 * VSYNC state
4881 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004882 if (mUseScheduler) {
4883 mScheduler->dump(mAppConnectionHandle, result);
4884 } else {
4885 mEventThread->dump(result);
4886 }
Dan Stozae22aec72016-08-01 13:20:59 -07004887 result.append("\n");
4888
4889 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004890 * Tracing state
4891 */
4892 mTracing.dump(result);
4893 result.append("\n");
4894
4895 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004896 * HWC layer minidump
4897 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004898 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004899 const auto displayId = display->getId();
4900 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004901 continue;
4902 }
4903
Yiwei Zhang5434a782018-12-05 18:06:32 -08004904 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004905 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004906 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004907 result.append("\n");
4908 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004909
4910 /*
4911 * Dump HWComposer state
4912 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004913 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004914 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004915 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004916 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004917 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004918 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004919
4920 /*
4921 * Dump gralloc state
4922 */
4923 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4924 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004925
4926 /*
4927 * Dump VrFlinger state if in use.
4928 */
4929 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4930 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004931 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004932 result.append("\n");
4933 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004934}
4935
Dominik Laskowski075d3172018-05-24 15:50:06 -07004936const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004937 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004938 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004939 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004940 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004941 }
4942 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004943
Dominik Laskowski34157762018-10-31 13:07:19 -07004944 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004945 static const Vector<sp<Layer>> empty;
4946 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004947}
4948
Keun young Park63f165f2012-08-31 10:53:36 -07004949bool SurfaceFlinger::startDdmConnection()
4950{
4951 void* libddmconnection_dso =
4952 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4953 if (!libddmconnection_dso) {
4954 return false;
4955 }
4956 void (*DdmConnection_start)(const char* name);
4957 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004958 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004959 if (!DdmConnection_start) {
4960 dlclose(libddmconnection_dso);
4961 return false;
4962 }
4963 (*DdmConnection_start)(getServiceName());
4964 return true;
4965}
4966
Chia-I Wu28f320b2018-05-03 11:02:56 -07004967void SurfaceFlinger::updateColorMatrixLocked() {
4968 mat4 colorMatrix;
4969 if (mGlobalSaturationFactor != 1.0f) {
4970 // Rec.709 luma coefficients
4971 float3 luminance{0.213f, 0.715f, 0.072f};
4972 luminance *= 1.0f - mGlobalSaturationFactor;
4973 mat4 saturationMatrix = mat4(
4974 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4975 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4976 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4977 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4978 );
4979 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4980 } else {
4981 colorMatrix = mClientColorMatrix * mDaltonizer();
4982 }
4983
4984 if (mCurrentState.colorMatrix != colorMatrix) {
4985 mCurrentState.colorMatrix = colorMatrix;
4986 mCurrentState.colorMatrixChanged = true;
4987 setTransactionFlags(eTransactionNeeded);
4988 }
4989}
4990
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004991status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004992#pragma clang diagnostic push
4993#pragma clang diagnostic error "-Wswitch-enum"
4994 switch (static_cast<ISurfaceComposerTag>(code)) {
4995 // These methods should at minimum make sure that the client requested
4996 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004997 case BOOT_FINISHED:
4998 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004999 case CREATE_DISPLAY:
5000 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005001 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005002 case GET_ACTIVE_COLOR_MODE:
5003 case GET_ANIMATION_FRAME_STATS:
5004 case GET_HDR_CAPABILITIES:
5005 case SET_ACTIVE_CONFIG:
5006 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005007 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005008 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005009 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005010 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
5011 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005012 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5013 IPCThreadState* ipc = IPCThreadState::self();
5014 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5015 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005016 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005017 }
Robert Carr1db73f62016-12-21 12:58:51 -08005018 return OK;
5019 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005020 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005021 IPCThreadState* ipc = IPCThreadState::self();
5022 const int pid = ipc->getCallingPid();
5023 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005024 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5025 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005026 return PERMISSION_DENIED;
5027 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005028 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005029 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005030 // Used by apps to hook Choreographer to SurfaceFlinger.
5031 case CREATE_DISPLAY_EVENT_CONNECTION:
5032 // The following calls are currently used by clients that do not
5033 // request necessary permissions. However, they do not expose any secret
5034 // information, so it is OK to pass them.
5035 case AUTHENTICATE_SURFACE:
5036 case GET_ACTIVE_CONFIG:
5037 case GET_BUILT_IN_DISPLAY:
5038 case GET_DISPLAY_COLOR_MODES:
5039 case GET_DISPLAY_CONFIGS:
5040 case GET_DISPLAY_STATS:
5041 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5042 // Calling setTransactionState is safe, because you need to have been
5043 // granted a reference to Client* and Handle* to do anything with it.
5044 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005045 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005046 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005047 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005048 case GET_PROTECTED_CONTENT_SUPPORT:
5049 case CACHE_BUFFER:
5050 case UNCACHE_BUFFER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005051 return OK;
5052 }
5053 case CAPTURE_LAYERS:
5054 case CAPTURE_SCREEN: {
5055 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005056 IPCThreadState* ipc = IPCThreadState::self();
5057 const int pid = ipc->getCallingPid();
5058 const int uid = ipc->getCallingUid();
5059 if ((uid != AID_GRAPHICS) &&
5060 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5061 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5062 return PERMISSION_DENIED;
5063 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005064 return OK;
5065 }
5066 // The following codes are deprecated and should never be allowed to access SF.
5067 case CONNECT_DISPLAY_UNUSED:
5068 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5069 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5070 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005071 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005072 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005073
5074 // These codes are used for the IBinder protocol to either interrogate the recipient
5075 // side of the transaction for its canonical interface descriptor or to dump its state.
5076 // We let them pass by default.
5077 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5078 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5079 code == IBinder::SYSPROPS_TRANSACTION) {
5080 return OK;
5081 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005082 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005083 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005084 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005085 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5086 return OK;
5087 }
5088 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5089 return PERMISSION_DENIED;
5090#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005091}
5092
Ana Krulec13be8ad2018-08-21 02:43:56 +00005093status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5094 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005095 status_t credentialCheck = CheckTransactCodeCredentials(code);
5096 if (credentialCheck != OK) {
5097 return credentialCheck;
5098 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005099
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005100 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5101 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005102 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005103 IPCThreadState* ipc = IPCThreadState::self();
5104 const int uid = ipc->getCallingUid();
5105 if (CC_UNLIKELY(uid != AID_SYSTEM
5106 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005107 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005108 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005109 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005110 return PERMISSION_DENIED;
5111 }
5112 int n;
5113 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005114 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005115 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005116 return NO_ERROR;
5117 case 1002: // SHOW_UPDATES
5118 n = data.readInt32();
5119 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005120 invalidateHwcGeometry();
5121 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005122 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005123 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005124 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005125 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005126 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005127 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005128 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005129 setTransactionFlags(
5130 eTransactionNeeded|
5131 eDisplayTransactionNeeded|
5132 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005133 return NO_ERROR;
5134 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005135 case 1006:{ // send empty update
5136 signalRefresh();
5137 return NO_ERROR;
5138 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005139 case 1008: // toggle use of hw composer
5140 n = data.readInt32();
5141 mDebugDisableHWC = n ? 1 : 0;
5142 invalidateHwcGeometry();
5143 repaintEverything();
5144 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005145 case 1009: // toggle use of transform hint
5146 n = data.readInt32();
5147 mDebugDisableTransformHint = n ? 1 : 0;
5148 invalidateHwcGeometry();
5149 repaintEverything();
5150 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005151 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005152 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005153 reply->writeInt32(0);
5154 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005155 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005156 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005157 return NO_ERROR;
5158 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005159 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005160 if (!display) {
5161 return NAME_NOT_FOUND;
5162 }
5163
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005164 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005165 return NO_ERROR;
5166 }
5167 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005168 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005169 // daltonize
5170 n = data.readInt32();
5171 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005172 case 1:
5173 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5174 break;
5175 case 2:
5176 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5177 break;
5178 case 3:
5179 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5180 break;
5181 default:
5182 mDaltonizer.setType(ColorBlindnessType::None);
5183 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005184 }
5185 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005186 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005187 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005188 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005189 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005190
5191 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005192 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005193 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005194 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005195 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005196 // apply a color matrix
5197 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005198 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005199 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005200 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005201 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005202 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005203 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005204 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005205 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005206 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005207 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005208
5209 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5210 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005211 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005212 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5213 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5214 }
5215
Chia-I Wu28f320b2018-05-03 11:02:56 -07005216 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005217 return NO_ERROR;
5218 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005219 // This is an experimental interface
5220 // Needs to be shifted to proper binder interface when we productize
5221 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005222 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005223 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005224 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005225 return NO_ERROR;
5226 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005227 case 1017: {
5228 n = data.readInt32();
5229 mForceFullDamage = static_cast<bool>(n);
5230 return NO_ERROR;
5231 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005232 case 1018: { // Modify Choreographer's phase offset
5233 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005234 if (mUseScheduler) {
5235 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5236 } else {
5237 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5238 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005239 return NO_ERROR;
5240 }
5241 case 1019: { // Modify SurfaceFlinger's phase offset
5242 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005243 if (mUseScheduler) {
5244 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5245 } else {
5246 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5247 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005248 return NO_ERROR;
5249 }
Irvel468051e2016-06-13 16:44:44 -07005250 case 1020: { // Layer updates interceptor
5251 n = data.readInt32();
5252 if (n) {
5253 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005254 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005255 }
5256 else{
5257 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005258 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005259 }
5260 return NO_ERROR;
5261 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005262 case 1021: { // Disable HWC virtual displays
5263 n = data.readInt32();
5264 mUseHwcVirtualDisplays = !n;
5265 return NO_ERROR;
5266 }
Romain Guy0147a172017-06-01 13:53:56 -07005267 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005268 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005269 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005270
Chia-I Wu28f320b2018-05-03 11:02:56 -07005271 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005272 return NO_ERROR;
5273 }
Romain Guy54f154a2017-10-24 21:40:32 +01005274 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005275 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005276 invalidateHwcGeometry();
5277 repaintEverything();
5278 return NO_ERROR;
5279 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005280 // Deprecate, use 1030 to check whether the device is color managed.
5281 case 1024: {
5282 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005283 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005284 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005285 n = data.readInt32();
5286 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005287 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005288 mTracing.enable();
5289 doTracing("tracing.enable");
5290 reply->writeInt32(NO_ERROR);
5291 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005292 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005293 status_t err = mTracing.disable();
5294 reply->writeInt32(err);
5295 }
5296 return NO_ERROR;
5297 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005298 case 1026: { // Get layer tracing status
5299 reply->writeBool(mTracing.isEnabled());
5300 return NO_ERROR;
5301 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005302 // Is a DisplayColorSetting supported?
5303 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005304 const auto display = getDefaultDisplayDevice();
5305 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005306 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005307 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005308
5309 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5310 switch (setting) {
5311 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005312 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005313 break;
5314 case DisplayColorSetting::UNMANAGED:
5315 reply->writeBool(true);
5316 break;
5317 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005318 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005319 break;
5320 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005321 reply->writeBool(
5322 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005323 break;
5324 }
5325 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005326 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005327 // Is VrFlinger active?
5328 case 1028: {
5329 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005330 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005331 return NO_ERROR;
5332 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005333 // Is device color managed?
5334 case 1030: {
5335 reply->writeBool(useColorManagement);
5336 return NO_ERROR;
5337 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005338 // Override default composition data space
5339 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5340 // && adb shell stop zygote && adb shell start zygote
5341 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5342 // adb shell stop zygote && adb shell start zygote
5343 case 1031: {
5344 Mutex::Autolock _l(mStateLock);
5345 n = data.readInt32();
5346 if (n) {
5347 n = data.readInt32();
5348 if (n) {
5349 Dataspace dataspace = static_cast<Dataspace>(n);
5350 if (!validateCompositionDataspace(dataspace)) {
5351 return BAD_VALUE;
5352 }
5353 mDefaultCompositionDataspace = dataspace;
5354 }
5355 n = data.readInt32();
5356 if (n) {
5357 Dataspace dataspace = static_cast<Dataspace>(n);
5358 if (!validateCompositionDataspace(dataspace)) {
5359 return BAD_VALUE;
5360 }
5361 mWideColorGamutCompositionDataspace = dataspace;
5362 }
5363 } else {
5364 // restore composition data space.
5365 mDefaultCompositionDataspace = defaultCompositionDataspace;
5366 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5367 }
5368 return NO_ERROR;
5369 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005370 }
5371 }
5372 return err;
5373}
5374
Steven Thomas6d8110b2017-08-31 18:24:21 -07005375void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005376 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005377 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005378}
5379
Ana Krulec7d1d6832018-12-27 11:10:09 -08005380void SurfaceFlinger::repaintEverythingForHWC() {
5381 mRepaintEverything = true;
5382 mEventQueue->invalidateForHWC();
5383}
5384
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005385// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5386class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005387public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005388 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5389 ~WindowDisconnector() {
5390 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005391 }
5392
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005393private:
5394 ANativeWindow* mWindow;
5395 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005396};
5397
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005398status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005399 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5400 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005401 uint32_t reqWidth, uint32_t reqHeight,
5402 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005403 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005404 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005405
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005406 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005407
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005408 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5409
Chia-I Wu20261cb2018-08-23 12:55:44 -07005410 sp<DisplayDevice> display;
5411 {
5412 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005413
Chia-I Wu20261cb2018-08-23 12:55:44 -07005414 display = getDisplayDeviceLocked(displayToken);
5415 if (!display) return BAD_VALUE;
5416
Chia-I Wucb023152018-08-28 12:57:23 -07005417 // set the requested width/height to the logical display viewport size
5418 // by default
5419 if (reqWidth == 0 || reqHeight == 0) {
5420 reqWidth = uint32_t(display->getViewport().width());
5421 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005422 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005423 }
5424
Peiyong Lin0e003c92018-09-17 11:09:51 -07005425 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5426 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005427
5428 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005429 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005430 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5431 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005432}
5433
5434status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005435 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5436 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005437 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005438 ATRACE_CALL();
5439
5440 class LayerRenderArea : public RenderArea {
5441 public:
Robert Carr578038f2018-03-09 12:25:24 -08005442 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005443 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5444 bool childrenOnly)
5445 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005446 mLayer(layer),
5447 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005448 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005449 mFlinger(flinger),
5450 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005451 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005452 Rect getBounds() const override {
5453 const Layer::State& layerState(mLayer->getDrawingState());
5454 return mLayer->getBufferSize(layerState);
5455 }
Marissa Wall61c58622018-07-18 10:12:20 -07005456 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005457 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005458 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005459 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005460 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005461 }
chaviwa76b2712017-09-20 12:02:26 -07005462 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005463 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005464 Rect getSourceCrop() const override {
5465 if (mCrop.isEmpty()) {
5466 return getBounds();
5467 } else {
5468 return mCrop;
5469 }
5470 }
Robert Carr578038f2018-03-09 12:25:24 -08005471 class ReparentForDrawing {
5472 public:
5473 const sp<Layer>& oldParent;
5474 const sp<Layer>& newParent;
5475
5476 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5477 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005478 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005479 }
Robert Carr15eae092018-03-23 13:43:53 -07005480 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005481 };
5482
5483 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005484 const Rect sourceCrop = getSourceCrop();
5485 // no need to check rotation because there is none
5486 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5487 sourceCrop.height() != getReqHeight();
5488
Robert Carr578038f2018-03-09 12:25:24 -08005489 if (!mChildrenOnly) {
5490 mTransform = mLayer->getTransform().inverse();
5491 drawLayers();
5492 } else {
5493 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005494 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005495 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5496 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005497
5498 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5499 drawLayers();
5500 }
5501 }
chaviwa76b2712017-09-20 12:02:26 -07005502
chaviwa76b2712017-09-20 12:02:26 -07005503 private:
chaviw7206d492017-11-10 16:16:12 -08005504 const sp<Layer> mLayer;
5505 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005506
5507 // In the "childrenOnly" case we reparent the children to a screenshot
5508 // layer which has no properties set and which does not draw.
5509 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005510 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005511 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005512
5513 SurfaceFlinger* mFlinger;
5514 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005515 };
5516
5517 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5518 auto parent = layerHandle->owner.promote();
5519
Robert Carr2e102c92018-10-23 12:11:15 -07005520 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005521 ALOGE("captureLayers called with a removed parent");
5522 return NAME_NOT_FOUND;
5523 }
5524
Robert Carr578038f2018-03-09 12:25:24 -08005525 const int uid = IPCThreadState::self()->getCallingUid();
5526 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005527 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005528 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5529 return PERMISSION_DENIED;
5530 }
5531
chaviw7206d492017-11-10 16:16:12 -08005532 Rect crop(sourceCrop);
5533 if (sourceCrop.width() <= 0) {
5534 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005535 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005536 }
5537
5538 if (sourceCrop.height() <= 0) {
5539 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005540 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005541 }
5542
5543 int32_t reqWidth = crop.width() * frameScale;
5544 int32_t reqHeight = crop.height() * frameScale;
5545
Chia-I Wu20261cb2018-08-23 12:55:44 -07005546 // really small crop or frameScale
5547 if (reqWidth <= 0) {
5548 reqWidth = 1;
5549 }
5550 if (reqHeight <= 0) {
5551 reqHeight = 1;
5552 }
5553
Peiyong Lin0e003c92018-09-17 11:09:51 -07005554 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005555
Robert Carr578038f2018-03-09 12:25:24 -08005556 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005557 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5558 if (!layer->isVisible()) {
5559 return;
Robert Carr578038f2018-03-09 12:25:24 -08005560 } else if (childrenOnly && layer == parent.get()) {
5561 return;
chaviwa76b2712017-09-20 12:02:26 -07005562 }
5563 visitor(layer);
5564 });
5565 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005566 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005567}
5568
5569status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5570 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005571 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005572 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005573 bool useIdentityTransform) {
5574 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005575
Peiyong Lin0e003c92018-09-17 11:09:51 -07005576 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005577 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5578 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005579 *outBuffer =
5580 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5581 static_cast<android_pixel_format>(reqPixelFormat), 1,
5582 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005583
5584 // This mutex protects syncFd and captureResult for communication of the return values from the
5585 // main thread back to this Binder thread
5586 std::mutex captureMutex;
5587 std::condition_variable captureCondition;
5588 std::unique_lock<std::mutex> captureLock(captureMutex);
5589 int syncFd = -1;
5590 std::optional<status_t> captureResult;
5591
Robert Carr03480e22018-01-04 16:02:06 -08005592 const int uid = IPCThreadState::self()->getCallingUid();
5593 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5594
Dominik Laskowski8c001672018-05-30 16:52:06 -07005595 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005596 // If there is a refresh pending, bug out early and tell the binder thread to try again
5597 // after the refresh.
5598 if (mRefreshPending) {
5599 ATRACE_NAME("Skipping screenshot for now");
5600 std::unique_lock<std::mutex> captureLock(captureMutex);
5601 captureResult = std::make_optional<status_t>(EAGAIN);
5602 captureCondition.notify_one();
5603 return;
5604 }
5605
5606 status_t result = NO_ERROR;
5607 int fd = -1;
5608 {
5609 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005610 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005611 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5612 useIdentityTransform, forSystem, &fd);
5613 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005614 }
5615
5616 {
5617 std::unique_lock<std::mutex> captureLock(captureMutex);
5618 syncFd = fd;
5619 captureResult = std::make_optional<status_t>(result);
5620 captureCondition.notify_one();
5621 }
5622 });
5623
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005624 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005625 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005626 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005627 while (*captureResult == EAGAIN) {
5628 captureResult.reset();
5629 result = postMessageAsync(message);
5630 if (result != NO_ERROR) {
5631 return result;
5632 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005633 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005634 }
5635 result = *captureResult;
5636 }
5637
5638 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005639 sync_wait(syncFd, -1);
5640 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005641 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005642
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005643 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005644}
5645
chaviwa76b2712017-09-20 12:02:26 -07005646void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005647 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005648 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005649 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005650
Lloyd Pique144e1162017-12-20 16:44:52 -08005651 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005652
chaviwa76b2712017-09-20 12:02:26 -07005653 const auto reqWidth = renderArea.getReqWidth();
5654 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005655 const auto sourceCrop = renderArea.getSourceCrop();
5656 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005657
Peiyong Lin0e003c92018-09-17 11:09:51 -07005658 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005659 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005660
Mathias Agopian180f10d2013-04-10 22:55:41 -07005661 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005662 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005663
5664 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005665 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005666 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005667
chaviw50da5042018-04-09 13:49:37 -07005668 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005669 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005670 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005671
chaviwa76b2712017-09-20 12:02:26 -07005672 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005673 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005674 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005675 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005676 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005677}
5678
chaviwa76b2712017-09-20 12:02:26 -07005679status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5680 TraverseLayersFunction traverseLayers,
5681 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005682 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005683 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005684 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005685 ATRACE_CALL();
5686
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005687 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005688
5689 traverseLayers([&](Layer* layer) {
5690 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5691 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005692
Robert Carr03480e22018-01-04 16:02:06 -08005693 // We allow the system server to take screenshots of secure layers for
5694 // use in situations like the Screen-rotation animation and place
5695 // the impetus on WindowManager to not persist them.
5696 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005697 ALOGW("FB is protected: PERMISSION_DENIED");
5698 return PERMISSION_DENIED;
5699 }
Peiyong Linfb530cf2018-12-15 05:07:38 +00005700 auto& engine(getRenderEngine());
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005701
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005702 // this binds the given EGLImage as a framebuffer for the
5703 // duration of this scope.
Peiyong Linfb530cf2018-12-15 05:07:38 +00005704 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005705 if (bufferBond.getStatus() != NO_ERROR) {
5706 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005707 return INVALID_OPERATION;
5708 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005709
Dan Stozaabcda352017-06-01 14:37:39 -07005710 // this will in fact render into our dequeued buffer
5711 // via an FBO, which means we didn't have to create
5712 // an EGLSurface and therefore we're not
5713 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005714 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005715
Peiyong Linfb530cf2018-12-15 05:07:38 +00005716 base::unique_fd syncFd = engine.flush();
Alec Mouri492bc572018-09-11 21:40:04 +00005717 if (syncFd < 0) {
Peiyong Linfb530cf2018-12-15 05:07:38 +00005718 engine.finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005719 }
Alec Mouri492bc572018-09-11 21:40:04 +00005720 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005721
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005722 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005723}
5724
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005725// ---------------------------------------------------------------------------
5726
Dan Stoza412903f2017-04-27 13:42:17 -07005727void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5728 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005729}
5730
Dan Stoza412903f2017-04-27 13:42:17 -07005731void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5732 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005733}
5734
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005735void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005736 const LayerVector::Visitor& visitor) {
5737 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005738 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005739 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005740 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005741 continue;
5742 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005743 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005744 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005745 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005746 return;
5747 }
chaviwa76b2712017-09-20 12:02:26 -07005748 if (!layer->isVisible()) {
5749 return;
5750 }
5751 visitor(layer);
5752 });
5753 }
5754}
5755
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005756}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005757
Lloyd Pique074e8122018-07-26 12:57:23 -07005758
Mathias Agopian3f844832013-08-07 21:24:32 -07005759#if defined(__gl_h_)
5760#error "don't include gl/gl.h in this file"
5761#endif
5762
5763#if defined(__gl2_h_)
5764#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005765#endif