blob: 1af111232049c3d714946bd32532adad49d33e46 [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
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001166status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001167 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001168 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001169
Chia-I Wu90f669f2017-10-05 14:24:41 -07001170 if (mInjectVSyncs == enable) {
1171 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001172 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001173
Dominik Laskowski83b88212018-12-11 13:34:06 -08001174 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001175
Ana Krulec98b5b242018-08-10 15:03:23 -07001176 // TODO(akrulec): Part of the Injector should be refactored, so that it
1177 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001178 if (enable) {
1179 ALOGV("VSync Injections enabled");
1180 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001181 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001182 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001183 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001184 impl::EventThread::InterceptVSyncsCallback(),
1185 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001186 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001187 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001188 } else {
1189 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001190 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001191 }
1192
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001193 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001194 }));
1195
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001196 return NO_ERROR;
1197}
1198
1199status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001200 Mutex::Autolock _l(mStateLock);
1201
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001202 if (!mInjectVSyncs) {
1203 ALOGE("VSync Injections not enabled");
1204 return BAD_VALUE;
1205 }
1206 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1207 ALOGV("Injecting VSync inside SurfaceFlinger");
1208 mVSyncInjector->onInjectSyncEvent(when);
1209 }
1210 return NO_ERROR;
1211}
1212
Lloyd Pique755e3192018-01-31 16:46:15 -08001213status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1214 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001215 // Try to acquire a lock for 1s, fail gracefully
1216 const status_t err = mStateLock.timedLock(s2ns(1));
1217 const bool locked = (err == NO_ERROR);
1218 if (!locked) {
1219 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1220 return TIMED_OUT;
1221 }
1222
1223 outLayers->clear();
1224 mCurrentState.traverseInZOrder([&](Layer* layer) {
1225 outLayers->push_back(layer->getLayerDebugInfo());
1226 });
1227
1228 mStateLock.unlock();
1229 return NO_ERROR;
1230}
1231
Peiyong Linc6780972018-10-28 15:24:08 -07001232status_t SurfaceFlinger::getCompositionPreference(
1233 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1234 Dataspace* outWideColorGamutDataspace,
1235 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001236 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001237 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001238 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001239 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001240 return NO_ERROR;
1241}
1242
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001243// ----------------------------------------------------------------------------
1244
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001245sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1246 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001247 auto resyncCallback = makeResyncCallback([this] {
1248 Mutex::Autolock lock(mStateLock);
1249 return getVsyncPeriod();
1250 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001251
Ana Krulec98b5b242018-08-10 15:03:23 -07001252 if (mUseScheduler) {
1253 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001254 return mScheduler->createDisplayEventConnection(mSfConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001255 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001256 return mScheduler->createDisplayEventConnection(mAppConnectionHandle, resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001257 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001258 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001259 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001260 return mSFEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001261 } else {
Dominik Laskowskif654d572018-12-20 11:03:06 -08001262 return mEventThread->createEventConnection(resyncCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -07001263 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001264 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001265}
1266
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001267// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001268
1269void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001270 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001271}
1272
1273void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001274 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001275}
1276
1277void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001278 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001279}
1280
1281void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001282 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001283 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001284}
1285
1286status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001287 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001288 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001289}
1290
1291status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001292 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001293 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001294 if (res == NO_ERROR) {
1295 msg->wait();
1296 }
1297 return res;
1298}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001299
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001300void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001301 do {
1302 waitForEvent();
1303 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001304}
1305
Dominik Laskowski83b88212018-12-11 13:34:06 -08001306nsecs_t SurfaceFlinger::getVsyncPeriod() const {
1307 const auto displayId = getInternalDisplayId();
1308 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1309 return 0;
1310 }
1311
1312 const auto config = getHwComposer().getActiveConfig(*displayId);
1313 return config ? config->getVsyncPeriod() : 0;
1314}
1315
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001316void SurfaceFlinger::enableHardwareVsync() {
1317 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001318 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001319 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001320 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001321 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001322 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001323}
1324
Dominik Laskowski83b88212018-12-11 13:34:06 -08001325void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001326 Mutex::Autolock _l(mHWVsyncLock);
1327
Jesse Hall948fe0c2013-10-14 12:56:09 -07001328 if (makeAvailable) {
1329 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001330 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1331 if (mUseScheduler) {
1332 mScheduler->makeHWSyncAvailable(true);
1333 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001334 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001335 // Hardware vsync is not currently available, so abort the resync
1336 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001337 return;
1338 }
1339
Dominik Laskowski83b88212018-12-11 13:34:06 -08001340 if (period <= 0) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001341 return;
1342 }
1343
Ana Krulece588e312018-09-18 12:32:24 -07001344 if (mUseScheduler) {
1345 mScheduler->setVsyncPeriod(period);
1346 } else {
1347 mPrimaryDispSync->reset();
1348 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001349
Ana Krulece588e312018-09-18 12:32:24 -07001350 if (!mPrimaryHWVsyncEnabled) {
1351 mPrimaryDispSync->beginResync();
1352 mEventControlThread->setVsyncEnabled(true);
1353 mPrimaryHWVsyncEnabled = true;
1354 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001355 }
1356}
1357
Jesse Hall948fe0c2013-10-14 12:56:09 -07001358void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001359 Mutex::Autolock _l(mHWVsyncLock);
1360 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001361 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001362 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001363 mPrimaryHWVsyncEnabled = false;
1364 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001365 if (makeUnavailable) {
1366 mHWVsyncAvailable = false;
1367 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001368}
1369
Dominik Laskowski83b88212018-12-11 13:34:06 -08001370void SurfaceFlinger::VsyncState::resync(const GetVsyncPeriod& getVsyncPeriod) {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001371 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001372
Dan Stoza57164302017-05-08 14:03:54 -07001373 const nsecs_t now = systemTime();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001374 const nsecs_t last = lastResyncTime.exchange(now);
1375
1376 if (now - last > kIgnoreDelay) {
1377 flinger.resyncToHardwareVsync(false, getVsyncPeriod());
Tim Murray4a4e4a22016-04-19 16:29:23 +00001378 }
1379}
1380
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001381void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1382 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001383 ATRACE_NAME("SF onVsync");
1384
Steven Thomas3cfac282017-02-06 12:29:30 -08001385 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001386 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001387 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001388 return;
1389 }
1390
Dominik Laskowski075d3172018-05-24 15:50:06 -07001391 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001392 return;
1393 }
1394
Dominik Laskowski075d3172018-05-24 15:50:06 -07001395 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001396 // For now, we don't do anything with external display vsyncs.
1397 return;
1398 }
1399
Ana Krulece588e312018-09-18 12:32:24 -07001400 if (mUseScheduler) {
1401 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001402 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001403 bool needsHwVsync = false;
1404 { // Scope for the lock
1405 Mutex::Autolock _l(mHWVsyncLock);
1406 if (mPrimaryHWVsyncEnabled) {
1407 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1408 }
1409 }
1410
1411 if (needsHwVsync) {
1412 enableHardwareVsync();
1413 } else {
1414 disableHardwareVsync(false);
1415 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001416 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001417}
1418
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001419void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001420 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1421 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001422}
1423
Ana Krulec7d1d6832018-12-27 11:10:09 -08001424void SurfaceFlinger::setRefreshRateTo(float newFps) {
1425 const auto displayId = getInternalDisplayId();
1426 if (!displayId || mBootStage != BootStage::FINISHED) {
1427 return;
1428 }
1429 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1430 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1431 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1432 // refresh cycle.
1433
1434 // Don't do any updating if the current fps is the same as the new one.
1435 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
1436 const nsecs_t currentVsyncPeriod = activeConfig->getVsyncPeriod();
1437 if (currentVsyncPeriod == 0) {
1438 return;
1439 }
1440 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1441 // floating numbers.
1442 const float currentFps = 1e9 / currentVsyncPeriod;
1443 if (std::abs(currentFps - newFps) <= 1) {
1444 return;
1445 }
1446
1447 auto configs = getHwComposer().getConfigs(*displayId);
1448 for (int i = 0; i < configs.size(); i++) {
1449 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1450 if (vsyncPeriod == 0) {
1451 continue;
1452 }
1453 const float fps = 1e9 / vsyncPeriod;
1454 // TODO(b/113612090): There should be a better way at determining which config
1455 // has the right refresh rate.
1456 if (std::abs(fps - newFps) <= 1) {
1457 const auto display = getBuiltInDisplay(HWC_DISPLAY_PRIMARY);
1458 if (!display) return;
1459 // This is posted in async function to avoid deadlock when getDisplayDevice
1460 // requires mStateLock.
1461 setActiveConfigAsync(display, i);
1462 ATRACE_INT("FPS", newFps);
1463 }
1464 }
1465}
1466
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001467void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001468 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001469 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001470 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001471
Lloyd Piqueba04e622017-12-14 17:11:26 -08001472 // Ignore events that do not have the right sequenceId.
1473 if (sequenceId != getBE().mComposerSequenceId) {
1474 return;
1475 }
1476
Steven Thomasb02664d2017-07-26 18:48:28 -07001477 // Only lock if we're not on the main thread. This function is normally
1478 // called on a hwbinder thread, but for the primary display it's called on
1479 // the main thread with the state lock already held, so don't attempt to
1480 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001481 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001482
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001483 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001484
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001485 if (std::this_thread::get_id() == mMainThreadId) {
1486 // Process all pending hot plug events immediately if we are on the main thread.
1487 processDisplayHotplugEventsLocked();
1488 }
1489
Lloyd Piqueba04e622017-12-14 17:11:26 -08001490 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001491}
1492
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001493void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001494 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001495 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001496 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001497 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001498 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001499}
1500
Dominik Laskowski075d3172018-05-24 15:50:06 -07001501void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001502 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001503 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001504 if (const auto displayId = getInternalDisplayId()) {
1505 getHwComposer().setVsyncEnabled(*displayId,
1506 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1507 }
Mathias Agopian86303202012-07-24 22:46:10 -07001508}
1509
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001510// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001511void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001512 if (mUseScheduler) {
1513 mScheduler->disableHardwareVsync(true);
1514 } else {
1515 disableHardwareVsync(true);
1516 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001517 // Clear the drawing state so that the logic inside of
1518 // handleTransactionLocked will fire. It will determine the delta between
1519 // mCurrentState and mDrawingState and re-apply all changes when we make the
1520 // transition.
1521 mDrawingState.displays.clear();
1522 mDisplays.clear();
1523}
1524
Steven Thomas050b2c82017-03-06 11:45:16 -08001525void SurfaceFlinger::updateVrFlinger() {
1526 if (!mVrFlinger)
1527 return;
1528 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001529 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001530 return;
1531 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001532
Lloyd Pique441d5042018-10-18 16:49:51 -07001533 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001534 ALOGE("Vr flinger is only supported for remote hardware composer"
1535 " service connections. Ignoring request to transition to vr"
1536 " flinger.");
1537 mVrFlingerRequestsDisplay = false;
1538 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001539 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001540
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001541 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001542
Steven Thomas0123ac62018-07-12 11:32:34 -07001543 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001544 LOG_ALWAYS_FATAL_IF(!display);
1545 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001546 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1547 // called below. Clear the reference now so we don't accidentally use it
1548 // later.
1549 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001550
Steven Thomasb02664d2017-07-26 18:48:28 -07001551 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001552 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001553 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001554
Steven Thomasb02664d2017-07-26 18:48:28 -07001555 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001556 // Delete the current instance before creating the new one
1557 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1558 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1559 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1560 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001561
Lloyd Pique441d5042018-10-18 16:49:51 -07001562 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001563 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001564
1565 if (vrFlingerRequestsDisplay) {
1566 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001567 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001568
1569 mVisibleRegionsDirty = true;
1570 invalidateHwcGeometry();
1571
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001572 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001573 display = getDefaultDisplayDeviceLocked();
1574 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001575 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001576
Steven Thomasb02664d2017-07-26 18:48:28 -07001577 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001578 const nsecs_t vsyncPeriod = getVsyncPeriod();
1579 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001580
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001581 // The present fences returned from vr_hwc are not an accurate
1582 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001583 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001584 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1585 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001586 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001587 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001588 !hasSyncFramework);
1589 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001590
Steven Thomasb02664d2017-07-26 18:48:28 -07001591 // Use phase of 0 since phase is not known.
1592 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001593 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001594 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001595
Dominik Laskowski83b88212018-12-11 13:34:06 -08001596 resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001597
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001598 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001599 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001600}
1601
Mathias Agopian4fec8732012-06-29 14:12:52 -07001602void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001603 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001604 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001605 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001606 if (mUseScheduler) {
1607 // This call is made each time SF wakes up and creates a new frame.
1608 mScheduler->incrementFrameCounter();
1609 }
Dan Stoza50182882016-07-08 12:02:20 -07001610 bool frameMissed = !mHadClientComposition &&
1611 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001612 (mPreviousPresentFence->getSignalTime() ==
1613 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001614 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001615 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001616 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001617 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001618 if (mPropagateBackpressure) {
1619 signalLayerUpdate();
1620 break;
1621 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001622 }
Dan Stoza50182882016-07-08 12:02:20 -07001623
Steven Thomas050b2c82017-03-06 11:45:16 -08001624 // Now that we're going to make it to the handleMessageTransaction()
1625 // call below it's safe to call updateVrFlinger(), which will
1626 // potentially trigger a display handoff.
1627 updateVrFlinger();
1628
Dan Stoza6b9454d2014-11-07 16:00:59 -08001629 bool refreshNeeded = handleMessageTransaction();
1630 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001631 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001632 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001633 // Signal a refresh if a transaction modified the window state,
1634 // a new buffer was latched, or if HWC has requested a full
1635 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001636 signalRefresh();
1637 }
1638 break;
1639 }
1640 case MessageQueue::REFRESH: {
1641 handleMessageRefresh();
1642 break;
1643 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001644 }
1645}
1646
Dan Stoza6b9454d2014-11-07 16:00:59 -08001647bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001648 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001649
1650 // Apply any ready transactions in the queues if there are still transactions that have not been
1651 // applied, wake up during the next vsync period and check again
1652 bool transactionNeeded = false;
1653 if (!flushTransactionQueues()) {
1654 transactionNeeded = true;
1655 }
1656
Mathias Agopian4fec8732012-06-29 14:12:52 -07001657 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001658 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001659 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001660
1661 if (transactionNeeded) {
1662 setTransactionFlags(eTransactionNeeded);
1663 }
1664
1665 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001666}
1667
Mathias Agopian4fec8732012-06-29 14:12:52 -07001668void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001669 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001670
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001671 mRefreshPending = false;
1672
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001673 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001674 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001675 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001676 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001677 for (const auto& [token, display] : mDisplays) {
1678 beginFrame(display);
1679 prepareFrame(display);
1680 doDebugFlashRegions(display, repaintEverything);
1681 doComposition(display, repaintEverything);
1682 }
1683
Adrian Roos1e1a1282017-11-01 19:05:31 +01001684 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001685 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001686
1687 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001688 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001689
Dan Stozabfbffeb2016-07-21 14:49:33 -07001690 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001691 for (const auto& [token, display] : mDisplays) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001692 mHadClientComposition =
1693 mHadClientComposition || getHwComposer().hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001694 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001695
Alec Mouri86770e52018-09-24 22:40:58 +00001696 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001697 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001698 if (mHadClientComposition) {
1699 base::unique_fd flushFence(getRenderEngine().flush());
1700 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1701 getBE().flushFence = new Fence(std::move(flushFence));
1702 } else {
1703 // Cleanup for hygiene.
1704 getBE().flushFence = Fence::NO_FENCE;
1705 }
1706 }
1707
Jorim Jaggi90535212018-05-23 23:44:06 +02001708 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001709
David Sodman7e4ae112018-02-09 15:02:28 -08001710 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001711 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001712 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001713 compositionInfo.hwc.hwcLayer = nullptr;
1714 }
David Sodmanba340492018-08-05 21:51:33 -07001715 }
David Sodman7e4ae112018-02-09 15:02:28 -08001716
1717 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001718}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001719
David Sodmanfa9b2af2017-12-24 13:28:59 -08001720
1721bool SurfaceFlinger::handleMessageInvalidate() {
1722 ATRACE_CALL();
1723 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001724}
1725
David Sodman79bba0e2018-08-05 18:07:49 -07001726void SurfaceFlinger::calculateWorkingSet() {
1727 ATRACE_CALL();
1728 ALOGV(__FUNCTION__);
1729
David Sodman79bba0e2018-08-05 18:07:49 -07001730 // build the h/w work list
1731 if (CC_UNLIKELY(mGeometryInvalid)) {
1732 mGeometryInvalid = false;
1733 for (const auto& [token, display] : mDisplays) {
1734 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001735 if (!displayId) {
1736 continue;
1737 }
David Sodman79bba0e2018-08-05 18:07:49 -07001738
Dominik Laskowski075d3172018-05-24 15:50:06 -07001739 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
1740 for (size_t i = 0; i < currentLayers.size(); i++) {
1741 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001742
Dominik Laskowski075d3172018-05-24 15:50:06 -07001743 if (!layer->hasHwcLayer(*displayId)) {
1744 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1745 layer->forceClientComposition(*displayId);
1746 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001747 }
1748 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001749
1750 layer->setGeometry(display, i);
1751 if (mDebugDisableHWC || mDebugRegion) {
1752 layer->forceClientComposition(*displayId);
1753 }
David Sodman79bba0e2018-08-05 18:07:49 -07001754 }
1755 }
1756 }
1757
1758 // Set the per-frame data
1759 for (const auto& [token, display] : mDisplays) {
1760 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001761 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001762 continue;
1763 }
1764
1765 if (mDrawingState.colorMatrixChanged) {
1766 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001767 status_t result =
1768 getHwComposer().setColorTransform(*displayId, mDrawingState.colorMatrix);
Dominik Laskowski34157762018-10-31 13:07:19 -07001769 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %s: %d",
1770 to_string(*displayId).c_str(), result);
David Sodman79bba0e2018-08-05 18:07:49 -07001771 }
1772 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1773 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001774 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001775 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1776 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1777 !display->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001778 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001779 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1780 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1781 !display->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001782 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001783 }
1784
Peiyong Lind3788632018-09-18 16:01:31 -07001785 // TODO(b/111562338) remove when composer 2.3 is shipped.
1786 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001787 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001788 }
1789
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001790 if (layer->getRoundedCornerState().radius > 0.0f) {
1791 layer->forceClientComposition(*displayId);
1792 }
1793
Dominik Laskowski075d3172018-05-24 15:50:06 -07001794 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001795 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001796 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001797 continue;
1798 }
1799
Dominik Laskowski075d3172018-05-24 15:50:06 -07001800 layer->setPerFrameData(*displayId, display->getTransform(), display->getViewport(),
1801 display->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001802 }
1803
Peiyong Lin13effd12018-07-24 17:01:47 -07001804 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001805 ColorMode colorMode;
1806 Dataspace dataSpace;
1807 RenderIntent renderIntent;
1808 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1809 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1810 }
1811 }
1812
1813 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001814
1815 for (const auto& [token, display] : mDisplays) {
1816 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001817 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001818 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001819
1820 if (displayId) {
1821 if (!layer->setHwcLayer(*displayId)) {
1822 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1823 }
1824 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001825 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001826
Dominik Laskowski05275f12018-11-01 15:03:24 -07001827 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001828 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1829 }
1830 }
David Sodman79bba0e2018-08-05 18:07:49 -07001831}
1832
David Sodmanfa9b2af2017-12-24 13:28:59 -08001833void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001834{
1835 // is debugging enabled
1836 if (CC_LIKELY(!mDebugRegion))
1837 return;
1838
David Sodmanfa9b2af2017-12-24 13:28:59 -08001839 if (display->isPoweredOn()) {
1840 // transform the dirty region into this screen's coordinate space
1841 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1842 if (!dirtyRegion.isEmpty()) {
1843 // redraw the whole screen
1844 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001845
David Sodmanfa9b2af2017-12-24 13:28:59 -08001846 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001847 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001848 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001849
Alec Mouri0a9c7b82018-11-16 13:05:25 -08001850 display->queueBuffer(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001851 }
1852 }
1853
David Sodmanfa9b2af2017-12-24 13:28:59 -08001854 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001855
1856 if (mDebugRegion > 1) {
1857 usleep(mDebugRegion * 1000);
1858 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001859
Dominik Laskowski05275f12018-11-01 15:03:24 -07001860 prepareFrame(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001861}
1862
Adrian Roos1e1a1282017-11-01 19:05:31 +01001863void SurfaceFlinger::doTracing(const char* where) {
1864 ATRACE_CALL();
1865 ATRACE_NAME(where);
1866 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001867 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001868 }
1869}
1870
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001871void SurfaceFlinger::logLayerStats() {
1872 ATRACE_CALL();
1873 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001874 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001875 if (display->isPrimary()) {
1876 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001877 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001878 }
1879 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001880
1881 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001882 }
1883}
1884
David Sodman2b406362017-12-15 13:33:47 -08001885void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001886{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001887 ATRACE_CALL();
1888 ALOGV("preComposition");
1889
David Sodman2b406362017-12-15 13:33:47 -08001890 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1891
Mathias Agopiancd60f992012-08-16 16:28:27 -07001892 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001893 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001894 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001895 needExtraInvalidate = true;
1896 }
Robert Carr2047fae2016-11-28 14:09:09 -08001897 });
1898
Mathias Agopiancd60f992012-08-16 16:28:27 -07001899 if (needExtraInvalidate) {
1900 signalLayerUpdate();
1901 }
1902}
1903
Ana Krulece588e312018-09-18 12:32:24 -07001904void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1905 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001906 // Update queue of past composite+present times and determine the
1907 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001908 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001909 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001910 while (!getBE().mCompositePresentTimes.empty()) {
1911 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001912 // Cached values should have been updated before calling this method,
1913 // which helps avoid duplicate syscalls.
1914 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1915 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1916 break;
1917 }
1918 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001919 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001920 }
1921
1922 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001923 while (getBE().mCompositePresentTimes.size() > 16) {
1924 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001925 }
1926
Ana Krulece588e312018-09-18 12:32:24 -07001927 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001928}
1929
Ana Krulece588e312018-09-18 12:32:24 -07001930void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1931 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001932 // Integer division and modulo round toward 0 not -inf, so we need to
1933 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001934 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1935 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1936 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001937
Brian Andersond0010582017-03-07 13:20:31 -08001938 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1939 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001940 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001941 }
1942
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001943 // Snap the latency to a value that removes scheduling jitter from the
1944 // composition and present times, which often have >1ms of jitter.
1945 // Reducing jitter is important if an app attempts to extrapolate
1946 // something (such as user input) to an accurate diasplay time.
1947 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1948 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001949 nsecs_t bias = stats.vsyncPeriod / 2;
1950 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1951 nsecs_t snappedCompositeToPresentLatency =
1952 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001953
David Sodman99974d22017-11-28 12:04:33 -08001954 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001955 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1956 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001957 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001958}
1959
Ady Abraham8164d482019-01-11 14:47:59 -08001960// debug patch for b/119477596 - add stack guards to catch stack
1961// corruptions and disable clang optimizations.
1962// The code below is temporary and planned to be removed once stack
1963// corruptions are found.
1964#pragma clang optimize off
1965class StackGuard {
1966public:
1967 StackGuard(const char* name, const char* func, int line) {
1968 guarders.reserve(MIN_CAPACITY);
1969 guarders.push_back({this, name, func, line});
1970 validate();
1971 }
1972 ~StackGuard() {
1973 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1974 if (i->guard == this) {
1975 guarders.erase(i);
1976 break;
1977 }
1978 }
1979 }
1980
1981 static void validate() {
1982 for (const auto& guard : guarders) {
1983 if (guard.guard->cookie != COOKIE_VALUE) {
1984 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1985 CallStack stack(LOG_TAG);
1986 abort();
1987 }
1988 }
1989 }
1990
1991private:
1992 uint64_t cookie = COOKIE_VALUE;
1993 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
1994 static constexpr size_t MIN_CAPACITY = 16;
1995
1996 struct GuarderElement {
1997 StackGuard* guard;
1998 const char* name;
1999 const char* func;
2000 int line;
2001 };
2002
2003 static std::vector<GuarderElement> guarders;
2004};
2005std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2006
2007#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2008
2009#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002010void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002011{
Ady Abraham8164d482019-01-11 14:47:59 -08002012 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002013 ATRACE_CALL();
2014 ALOGV("postComposition");
2015
Brian Anderson3546a3f2016-07-14 11:51:14 -07002016 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002017 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002018 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002019 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002020 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002021 }
Ady Abraham8164d482019-01-11 14:47:59 -08002022 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002023
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002024 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002025 const auto display = getDefaultDisplayDeviceLocked();
Ady Abraham8164d482019-01-11 14:47:59 -08002026 DEFINE_STACK_GUARD(display);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002027
David Sodman73beded2017-11-15 11:56:06 -08002028 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002029 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002030 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2031
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002032 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002033 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002034 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002035 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002036 } else {
2037 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2038 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002039
Ady Abraham8164d482019-01-11 14:47:59 -08002040 ASSERT_ON_STACK_GUARD();
2041
David Sodman73beded2017-11-15 11:56:06 -08002042 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002043 mPreviousPresentFence =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002044 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002045 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002046 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002047 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002048
Ana Krulece588e312018-09-18 12:32:24 -07002049 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002050 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002051 if (mUseScheduler) {
2052 mScheduler->getDisplayStatInfo(&stats);
2053 } else {
2054 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2055 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2056 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002057
Ady Abraham8164d482019-01-11 14:47:59 -08002058 ASSERT_ON_STACK_GUARD();
2059
David Sodman2b406362017-12-15 13:33:47 -08002060 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002061 // when we started doing work for this frame, but that should be okay
2062 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002063 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002064 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002065 DEFINE_STACK_GUARD(compositorTiming);
2066
Brian Andersond0010582017-03-07 13:20:31 -08002067 {
David Sodman99974d22017-11-28 12:04:33 -08002068 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002069 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002070 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002071
2072 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002073 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002074
Robert Carr2047fae2016-11-28 14:09:09 -08002075 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002076 bool frameLatched = layer->onPostComposition(display->getId(), glCompositionDoneFenceTime,
2077 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002078 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002079 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002080 recordBufferingStats(layer->getName().string(),
2081 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002082 }
Ady Abraham8164d482019-01-11 14:47:59 -08002083 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002084 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002085
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002086 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002087 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002088 if (mUseScheduler) {
2089 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002090 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002091 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002092 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2093 enableHardwareVsync();
2094 } else {
2095 disableHardwareVsync(false);
2096 }
Ady Abraham8164d482019-01-11 14:47:59 -08002097 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002098 }
2099 }
2100
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002101 if (!hasSyncFramework) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002102 if (display && getHwComposer().isConnected(*display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002103 if (mUseScheduler) {
2104 mScheduler->enableHardwareVsync();
2105 } else {
2106 enableHardwareVsync();
2107 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002108 }
2109 }
2110
Ady Abraham8164d482019-01-11 14:47:59 -08002111 ASSERT_ON_STACK_GUARD();
2112
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002113 if (mAnimCompositionPending) {
2114 mAnimCompositionPending = false;
2115
Brian Anderson4e606e32017-03-16 15:34:57 -07002116 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002117 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002118 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002119
2120 ASSERT_ON_STACK_GUARD();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002121 } else if (display && getHwComposer().isConnected(*display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002122 // The HWC doesn't support present fences, so use the refresh
2123 // timestamp instead.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002124 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002125 DEFINE_STACK_GUARD(presentTime);
2126
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002127 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002128 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002129 }
2130 mAnimFrameTracker.advanceFrame();
2131 }
Dan Stozab90cf072015-03-05 11:05:59 -08002132
Ady Abraham8164d482019-01-11 14:47:59 -08002133 ASSERT_ON_STACK_GUARD();
2134
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002135 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002136 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002137 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002138 }
2139
Ady Abraham8164d482019-01-11 14:47:59 -08002140 ASSERT_ON_STACK_GUARD();
2141
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002142 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002143
Ady Abraham8164d482019-01-11 14:47:59 -08002144 ASSERT_ON_STACK_GUARD();
2145
Dominik Laskowski075d3172018-05-24 15:50:06 -07002146 if (display && getHwComposer().isConnected(*display->getId()) && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002147 return;
2148 }
2149
2150 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002151 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002152 if (mHasPoweredOff) {
2153 mHasPoweredOff = false;
2154 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002155 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002156 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002157 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002158 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002159 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2160 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002161 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002162 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002163 }
David Sodman4a36e932017-11-07 14:29:47 -08002164 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002165
2166 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002167 }
David Sodman4a36e932017-11-07 14:29:47 -08002168 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002169 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002170
2171 {
2172 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002173 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002174 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002175 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002176 if (refillCount > 0) {
2177 const size_t offset = mTexturePool.size();
2178 mTexturePool.resize(mTexturePoolSize);
2179 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2180 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2181 }
Ady Abraham8164d482019-01-11 14:47:59 -08002182 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002183 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002184
Marissa Wallfda30bb2018-10-12 11:34:28 -07002185 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002186 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002187
2188 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002189}
Ady Abraham8164d482019-01-11 14:47:59 -08002190#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002191
2192void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002193 ATRACE_CALL();
2194 ALOGV("rebuildLayerStacks");
2195
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002196 // We need to clear these out now as these may be holding on to a
2197 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2198 // also holds a reference. When the set of visible layers is recomputed,
2199 // some layers may be destroyed if the only thing keeping them alive was
2200 // that list of visible layers associated with each display. The layer
2201 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2202 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2203 for (const auto& [token, display] : mDisplays) {
2204 getBE().mCompositionInfo[token].clear();
2205 }
2206
Mathias Agopiancd60f992012-08-16 16:28:27 -07002207 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002208 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002209 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002210 mVisibleRegionsDirty = false;
2211 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002212
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002213 for (const auto& pair : mDisplays) {
2214 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07002215 Region opaqueRegion;
2216 Region dirtyRegion;
2217 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002218 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07002219 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002220 const Rect bounds = display->getBounds();
2221 if (display->isPoweredOn()) {
2222 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002223
Jeff Sharkey76488112017-02-27 14:15:18 -07002224 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002225 bool hwcLayerDestroyed = false;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002226 const auto displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002227 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002228 Region drawRegion(tr.transform(
2229 layer->visibleNonTransparentRegion));
2230 drawRegion.andSelf(bounds);
2231 if (!drawRegion.isEmpty()) {
2232 layersSortedByZ.add(layer);
2233 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002234 // Clear out the HWC layer if this layer was
2235 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002236 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002237 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002238 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002239 // WM changes display->layerStack upon sleep/awake.
2240 // Here we make sure we delete the HWC layers even if
2241 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002242 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002243 }
2244
2245 // If a layer is not going to get a release fence because
2246 // it is invisible, but it is also going to release its
2247 // old buffer, add it to the list of layers needing
2248 // fences.
2249 if (hwcLayerDestroyed) {
2250 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2251 mLayersWithQueuedFrames.cend(), layer);
2252 if (found != mLayersWithQueuedFrames.cend()) {
2253 layersNeedingFences.add(layer);
2254 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002255 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002256 });
2257 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002258 display->setVisibleLayersSortedByZ(layersSortedByZ);
2259 display->setLayersNeedingFences(layersNeedingFences);
2260 display->undefinedRegion.set(bounds);
2261 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2262 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002263 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002264 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002265}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002266
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002267// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002268// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002269// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002270// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002271// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002272// The returned HDR data space is one of
2273// - Dataspace::UNKNOWN
2274// - Dataspace::BT2020_HLG
2275// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002276Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2277 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002278 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002279 *outHdrDataSpace = Dataspace::UNKNOWN;
2280
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002281 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002282 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002283 case Dataspace::V0_SCRGB:
2284 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002285 case Dataspace::BT2020:
2286 case Dataspace::BT2020_ITU:
2287 case Dataspace::BT2020_LINEAR:
2288 case Dataspace::DISPLAY_BT2020:
2289 bestDataSpace = Dataspace::DISPLAY_BT2020;
2290 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002291 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002292 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002293 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002294 case Dataspace::BT2020_PQ:
2295 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002296 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002297 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002298 case Dataspace::BT2020_HLG:
2299 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002300 // When there's mixed PQ content and HLG content, we set the HDR
2301 // data space to be BT2020_PQ and convert HLG to PQ.
2302 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2303 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002304 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002305 break;
2306 default:
2307 break;
2308 }
Romain Guy54f154a2017-10-24 21:40:32 +01002309 }
2310
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002311 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002312}
2313
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002314// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002315void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2316 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002317 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2318 *outMode = ColorMode::NATIVE;
2319 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002320 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002321 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002322 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002323
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002324 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002325 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002326
Peiyong Lindfde5112018-06-05 10:58:41 -07002327 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002328 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002329 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002330 if (isHdr) {
2331 bestDataSpace = hdrDataSpace;
2332 }
2333
Chia-I Wu0d711262018-05-21 15:19:35 -07002334 RenderIntent intent;
2335 switch (mDisplayColorSetting) {
2336 case DisplayColorSetting::MANAGED:
2337 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002338 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002339 break;
2340 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002341 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002342 break;
2343 default: // vendor display color setting
2344 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2345 break;
2346 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002347
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002348 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002349}
2350
David Sodmanfa9b2af2017-12-24 13:28:59 -08002351void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002352{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002353 bool dirty = !display->getDirtyRegion(false).isEmpty();
2354 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2355 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002356
David Sodmanfa9b2af2017-12-24 13:28:59 -08002357 // If nothing has changed (!dirty), don't recompose.
2358 // If something changed, but we don't currently have any visible layers,
2359 // and didn't when we last did a composition, then skip it this time.
2360 // The second rule does two things:
2361 // - When all layers are removed from a display, we'll emit one black
2362 // frame, then nothing more until we get new layers.
2363 // - When a display is created with a private layer stack, we won't
2364 // emit any black frames until a layer is added to the layer stack.
2365 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002366
Dominik Laskowski075d3172018-05-24 15:50:06 -07002367 const char flagPrefix[] = {'-', '+'};
2368 static_cast<void>(flagPrefix);
2369 ALOGV_IF(display->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2370 __FUNCTION__, mustRecompose ? "doing" : "skipping", display->getDebugName().c_str(),
2371 flagPrefix[dirty], flagPrefix[empty], flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002372
David Sodmanfa9b2af2017-12-24 13:28:59 -08002373 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002374
David Sodmanfa9b2af2017-12-24 13:28:59 -08002375 if (mustRecompose) {
2376 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002377 }
2378}
2379
David Sodmanfa9b2af2017-12-24 13:28:59 -08002380void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002381{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002382 if (!display->isPoweredOn()) {
2383 return;
David Sodman2b406362017-12-15 13:33:47 -08002384 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002385
Dominik Laskowski05275f12018-11-01 15:03:24 -07002386 status_t result = display->prepareFrame(getHwComposer(),
2387 getBE().mCompositionInfo[display->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002388 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
2389 display->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002390}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002391
David Sodmanfa9b2af2017-12-24 13:28:59 -08002392void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002393 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002394 ALOGV("doComposition");
2395
David Sodmanfa9b2af2017-12-24 13:28:59 -08002396 if (display->isPoweredOn()) {
2397 // transform the dirty region into this screen's coordinate space
2398 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002399
David Sodmanfa9b2af2017-12-24 13:28:59 -08002400 // repaint the framebuffer (if needed)
2401 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002402
David Sodmanfa9b2af2017-12-24 13:28:59 -08002403 display->dirtyRegion.clear();
2404 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002405 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002406 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002407}
2408
David Sodmanfa9b2af2017-12-24 13:28:59 -08002409void SurfaceFlinger::postFrame()
2410{
2411 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002412 const auto display = getDefaultDisplayDeviceLocked();
2413 if (display && getHwComposer().isConnected(*display->getId())) {
2414 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002415 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2416 logFrameStats();
2417 }
2418 }
2419}
2420
2421void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002422{
Mathias Agopian841cde52012-03-01 15:44:37 -08002423 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002424 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002425
David Sodmanfa9b2af2017-12-24 13:28:59 -08002426 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002427
David Sodmanfa9b2af2017-12-24 13:28:59 -08002428 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002429 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002430 if (displayId) {
2431 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002432 }
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002433 display->onPresentDisplayCompleted();
David Sodman15094112018-10-11 09:39:37 -07002434 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002435 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002436
Chia-I Wu7b549592017-11-15 09:14:57 -08002437 // The layer buffer from the previous frame (if any) is released
2438 // by HWC only when the release fence from this frame (if any) is
2439 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002440 if (displayId && layer->hasHwcLayer(*displayId)) {
2441 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2442 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002443 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002444
2445 // If the layer was client composited in the previous frame, we
2446 // need to merge with the previous client target acquire fence.
2447 // Since we do not track that, always merge with the current
2448 // client target acquire fence when it is available, even though
2449 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002450 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002451 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002452 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002453 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002454
David Sodman15094112018-10-11 09:39:37 -07002455 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002456 }
Chia-I Wu83806892017-11-16 10:50:20 -08002457
2458 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002459 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002460 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002461 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002462 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002463 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002464 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002465 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002466 }
2467 }
2468
Dominik Laskowski075d3172018-05-24 15:50:06 -07002469 if (displayId) {
2470 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002471 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002472 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002473}
2474
Mathias Agopian87baae12012-07-31 12:38:26 -07002475void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002476{
Mathias Agopian841cde52012-03-01 15:44:37 -08002477 ATRACE_CALL();
2478
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002479 // here we keep a copy of the drawing state (that is the state that's
2480 // going to be overwritten by handleTransactionLocked()) outside of
2481 // mStateLock so that the side-effects of the State assignment
2482 // don't happen with mStateLock held (which can cause deadlocks).
2483 State drawingState(mDrawingState);
2484
Mathias Agopianca4d3602011-05-19 15:38:14 -07002485 Mutex::Autolock _l(mStateLock);
2486 const nsecs_t now = systemTime();
2487 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002488
Mathias Agopianca4d3602011-05-19 15:38:14 -07002489 // Here we're guaranteed that some transaction flags are set
2490 // so we can call handleTransactionLocked() unconditionally.
2491 // We call getTransactionFlags(), which will also clear the flags,
2492 // with mStateLock held to guarantee that mCurrentState won't change
2493 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002494
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002495 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002496 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002497 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002498
Mathias Agopianca4d3602011-05-19 15:38:14 -07002499 mLastTransactionTime = systemTime() - now;
2500 mDebugInTransaction = 0;
2501 invalidateHwcGeometry();
2502 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002503}
2504
Lloyd Piqueba04e622017-12-14 17:11:26 -08002505void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2506 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002507 const std::optional<DisplayIdentificationInfo> info =
2508 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002509
Dominik Laskowski075d3172018-05-24 15:50:06 -07002510 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002511 continue;
2512 }
2513
Lloyd Piqueba04e622017-12-14 17:11:26 -08002514 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002515 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002516 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002517 mPhysicalDisplayTokens[info->id] = new BBinder();
2518 DisplayDeviceState state;
2519 state.displayId = info->id;
2520 state.isSecure = true; // All physical displays are currently considered secure.
2521 state.displayName = info->name;
2522 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2523 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002524 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002525 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002526 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002527
Dominik Laskowski075d3172018-05-24 15:50:06 -07002528 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2529 if (index >= 0) {
2530 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2531 mInterceptor->saveDisplayDeletion(state.sequenceId);
2532 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002533 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002534 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002535 }
2536
2537 processDisplayChangesLocked();
2538 }
2539
2540 mPendingHotplugEvents.clear();
2541}
2542
Lloyd Pique99d3da52018-01-22 17:48:03 -08002543sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002544 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
2545 const DisplayDeviceState& state, const sp<DisplaySurface>& dispSurface,
2546 const sp<IGraphicBufferProducer>& producer) {
2547 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002548 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002549 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002550 creationArgs.isSecure = state.isSecure;
2551 creationArgs.displaySurface = dispSurface;
2552 creationArgs.hasWideColorGamut = false;
2553 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002554
Dominik Laskowski075d3172018-05-24 15:50:06 -07002555 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2556 creationArgs.isPrimary = isInternalDisplay;
2557
2558 if (useColorManagement && displayId) {
2559 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002560 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002561 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002562 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002563 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002564
Dominik Laskowski7e045462018-05-30 13:02:02 -07002565 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002566 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002567 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002568 }
tangrobin6753a022018-08-10 10:58:54 +08002569 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002570
Dominik Laskowski075d3172018-05-24 15:50:06 -07002571 if (displayId) {
2572 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002573 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002574 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002575 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002576
Lloyd Pique90c115d2018-09-18 21:39:42 -07002577 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002578 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002579 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002580
Lloyd Pique99d3da52018-01-22 17:48:03 -08002581 // Make sure that composition can never be stalled by a virtual display
2582 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002583 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002584 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002585 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2586 }
2587
Dominik Laskowski075d3172018-05-24 15:50:06 -07002588 creationArgs.displayInstallOrientation =
2589 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002590
Lloyd Pique99d3da52018-01-22 17:48:03 -08002591 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002592 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002593
Lloyd Pique90c115d2018-09-18 21:39:42 -07002594 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002595
2596 if (maxFrameBufferAcquiredBuffers >= 3) {
2597 nativeWindowSurface->preallocateBuffers();
2598 }
2599
2600 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002601 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002602 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002603 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002604 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002605 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002606 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002607 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002608 if (!state.isVirtual()) {
2609 LOG_ALWAYS_FATAL_IF(!displayId);
2610 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002611 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002612
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002613 display->setLayerStack(state.layerStack);
2614 display->setProjection(state.orientation, state.viewport, state.frame);
2615 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002616
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002617 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002618}
2619
Lloyd Pique347200f2017-12-14 17:00:15 -08002620void SurfaceFlinger::processDisplayChangesLocked() {
2621 // here we take advantage of Vector's copy-on-write semantics to
2622 // improve performance by skipping the transaction entirely when
2623 // know that the lists are identical
2624 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2625 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2626 if (!curr.isIdenticalTo(draw)) {
2627 mVisibleRegionsDirty = true;
2628 const size_t cc = curr.size();
2629 size_t dc = draw.size();
2630
2631 // find the displays that were removed
2632 // (ie: in drawing state but not in current state)
2633 // also handle displays that changed
2634 // (ie: displays that are in both lists)
2635 for (size_t i = 0; i < dc;) {
2636 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2637 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002638 // Save display IDs before disconnecting.
2639 const auto internalDisplayId = getInternalDisplayId();
2640 const auto externalDisplayId = getExternalDisplayId();
2641
Lloyd Pique347200f2017-12-14 17:00:15 -08002642 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002643 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2644 display->disconnect(getHwComposer());
2645 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002646 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002647 if (mUseScheduler) {
2648 mScheduler->hotplugReceived(mAppConnectionHandle,
2649 EventThread::DisplayType::Primary, false);
2650 } else {
2651 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2652 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002653 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002654 if (mUseScheduler) {
2655 mScheduler->hotplugReceived(mAppConnectionHandle,
2656 EventThread::DisplayType::External, false);
2657 } else {
2658 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2659 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002660 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002661 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002662 } else {
2663 // this display is in both lists. see if something changed.
2664 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002665 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002666 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2667 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2668 if (state_binder != draw_binder) {
2669 // changing the surface is like destroying and
2670 // recreating the DisplayDevice, so we just remove it
2671 // from the drawing state, so that it get re-added
2672 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002673 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2674 display->disconnect(getHwComposer());
2675 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002676 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002677 mDrawingState.displays.removeItemsAt(i);
2678 dc--;
2679 // at this point we must loop to the next item
2680 continue;
2681 }
2682
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002683 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002684 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002685 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002686 }
2687 if ((state.orientation != draw[i].orientation) ||
2688 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002689 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002690 }
2691 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002692 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002693 }
2694 }
2695 }
2696 ++i;
2697 }
2698
2699 // find displays that were added
2700 // (ie: in current state but not in drawing state)
2701 for (size_t i = 0; i < cc; i++) {
2702 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2703 const DisplayDeviceState& state(curr[i]);
2704
2705 sp<DisplaySurface> dispSurface;
2706 sp<IGraphicBufferProducer> producer;
2707 sp<IGraphicBufferProducer> bqProducer;
2708 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002709 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002710
Dominik Laskowski075d3172018-05-24 15:50:06 -07002711 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002712 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002713 // Virtual displays without a surface are dormant:
2714 // they have external state (layer stack, projection,
2715 // etc.) but no internal state (i.e. a DisplayDevice).
2716 if (state.surface != nullptr) {
2717 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002718 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002719 int width = 0;
2720 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2721 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2722 int height = 0;
2723 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2724 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2725 int intFormat = 0;
2726 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2727 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002728 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002729
Dominik Laskowski075d3172018-05-24 15:50:06 -07002730 displayId =
2731 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002732 }
2733
2734 // TODO: Plumb requested format back up to consumer
2735
2736 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002737 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002738 bqProducer, bqConsumer,
2739 state.displayName);
2740
2741 dispSurface = vds;
2742 producer = vds;
2743 }
2744 } else {
2745 ALOGE_IF(state.surface != nullptr,
2746 "adding a supported display, but rendering "
2747 "surface is provided (%p), ignoring it",
2748 state.surface.get());
2749
Dominik Laskowski075d3172018-05-24 15:50:06 -07002750 displayId = state.displayId;
2751 LOG_ALWAYS_FATAL_IF(!displayId);
2752 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002753 producer = bqProducer;
2754 }
2755
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002756 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002757 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002758 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002759 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002760 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002761 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002762 LOG_ALWAYS_FATAL_IF(!displayId);
2763
2764 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002765 if (mUseScheduler) {
2766 mScheduler->hotplugReceived(mAppConnectionHandle,
2767 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002768 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002769 } else {
2770 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2771 true);
2772 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002773 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002774 if (mUseScheduler) {
2775 mScheduler->hotplugReceived(mAppConnectionHandle,
2776 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002777 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002778 } else {
2779 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2780 true);
2781 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002782 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002783 }
2784 }
2785 }
2786 }
2787 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002788
2789 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002790}
2791
Mathias Agopian87baae12012-07-31 12:38:26 -07002792void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002793{
Dan Stoza7dde5992015-05-22 09:51:44 -07002794 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002795 mCurrentState.traverseInZOrder([](Layer* layer) {
2796 layer->notifyAvailableFrames();
2797 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002798
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002799 /*
2800 * Traversal of the children
2801 * (perform the transaction for each of them if needed)
2802 */
2803
Robert Carr720e5062018-07-30 17:45:14 -07002804 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002805 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002806 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002807 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002808 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002809
2810 const uint32_t flags = layer->doTransaction(0);
2811 if (flags & Layer::eVisibleRegion)
2812 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002813
2814 if (flags & Layer::eInputInfoChanged) {
2815 inputChanged = true;
2816 }
Robert Carr2047fae2016-11-28 14:09:09 -08002817 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002818 }
2819
2820 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002821 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002822 */
2823
Mathias Agopiane57f2922012-08-09 16:29:12 -07002824 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002825 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002826 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002827 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002828
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002829 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002830 // The transform hint might have changed for some layers
2831 // (either because a display has changed, or because a layer
2832 // as changed).
2833 //
2834 // Walk through all the layers in currentLayers,
2835 // and update their transform hint.
2836 //
2837 // If a layer is visible only on a single display, then that
2838 // display is used to calculate the hint, otherwise we use the
2839 // default display.
2840 //
2841 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2842 // the hint is set before we acquire a buffer from the surface texture.
2843 //
2844 // NOTE: layer transactions have taken place already, so we use their
2845 // drawing state. However, SurfaceFlinger's own transaction has not
2846 // happened yet, so we must use the current state layer list
2847 // (soon to become the drawing state list).
2848 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002849 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002850 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002851 bool first = true;
2852 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002853 // NOTE: we rely on the fact that layers are sorted by
2854 // layerStack first (so we don't have to traverse the list
2855 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002856 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002857 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002858 currentlayerStack = layerStack;
2859 // figure out if this layerstack is mirrored
2860 // (more than one display) if so, pick the default display,
2861 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002862 hintDisplay = nullptr;
2863 for (const auto& [token, display] : mDisplays) {
2864 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2865 if (hintDisplay) {
2866 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002867 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002868 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002869 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002870 }
2871 }
2872 }
2873 }
Chet Haase91d25932013-04-11 15:24:55 -07002874
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002875 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002876 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2877 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002878
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002879 // could be null when this layer is using a layerStack
2880 // that is not visible on any display. Also can occur at
2881 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002882 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002883 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002884
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002885 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002886 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002887 if (hintDisplay) {
2888 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002889 }
Robert Carr2047fae2016-11-28 14:09:09 -08002890
2891 first = false;
2892 });
Mathias Agopian84300952012-11-21 16:02:13 -08002893 }
2894
2895
Mathias Agopian3559b072012-08-15 13:46:03 -07002896 /*
2897 * Perform our own transaction if needed
2898 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002899
2900 if (mLayersAdded) {
2901 mLayersAdded = false;
2902 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002903 mVisibleRegionsDirty = true;
2904 }
2905
2906 // some layers might have been removed, so
2907 // we need to update the regions they're exposing.
2908 if (mLayersRemoved) {
2909 mLayersRemoved = false;
2910 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002911 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002912 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002913 // this layer is not visible anymore
2914 // TODO: we could traverse the tree from front to back and
2915 // compute the actual visible region
2916 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002917 Region visibleReg;
2918 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002919 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002920 }
Robert Carr2047fae2016-11-28 14:09:09 -08002921 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002922 }
2923
2924 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002925
Vishnu Nairde19f852018-12-18 16:11:53 -08002926 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002927 updateInputWindows();
2928 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002929 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002930
Riley Andrews03414a12014-07-01 14:22:59 -07002931 updateCursorAsync();
2932}
2933
Robert Carr720e5062018-07-30 17:45:14 -07002934void SurfaceFlinger::updateInputWindows() {
2935 ATRACE_CALL();
2936
Vishnu Nairde19f852018-12-18 16:11:53 -08002937 if (mInputFlinger == nullptr) {
2938 return;
2939 }
2940
Robert Carr720e5062018-07-30 17:45:14 -07002941 Vector<InputWindowInfo> inputHandles;
2942
2943 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2944 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002945 // When calculating the screen bounds we ignore the transparent region since it may
2946 // result in an unwanted offset.
2947 inputHandles.add(layer->fillInputInfo(
2948 layer->computeScreenBounds(false /* reduceTransparentRegion */)));
Robert Carr720e5062018-07-30 17:45:14 -07002949 }
2950 });
2951 mInputFlinger->setInputWindows(inputHandles);
2952}
2953
chaviwfbe5d9c2018-12-26 12:23:37 -08002954void SurfaceFlinger::executeInputWindowCommands() {
2955 if (!mInputFlinger) {
2956 return;
2957 }
2958
2959 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2960 if (transferTouchFocusCommand.fromToken != nullptr &&
2961 transferTouchFocusCommand.toToken != nullptr &&
2962 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2963 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2964 transferTouchFocusCommand.toToken);
2965 }
2966 }
2967
2968 mInputWindowCommands.clear();
2969}
2970
Riley Andrews03414a12014-07-01 14:22:59 -07002971void SurfaceFlinger::updateCursorAsync()
2972{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002973 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002974 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002975 continue;
2976 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002977
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002978 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2979 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002980 }
2981 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002982}
2983
chaviw61626f22018-11-15 16:26:27 -08002984void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2985 if (layer->hasReadyFrame()) {
2986 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2987 if (layer->shouldPresentNow(expectedPresentTime)) {
2988 bool ignored = false;
2989 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
2990 }
2991 }
2992 layer->releasePendingBuffer(systemTime());
2993}
2994
Mathias Agopian4fec8732012-06-29 14:12:52 -07002995void SurfaceFlinger::commitTransaction()
2996{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002997 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002998 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002999 for (const auto& l : mLayersPendingRemoval) {
3000 recordBufferingStats(l->getName().string(),
3001 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003002
3003 // We need to release the HWC layers when the Layer is removed
3004 // from the current state otherwise the HWC layer just continues
3005 // showing at its last configured state until we eventually
3006 // abandon the buffer queue.
3007 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003008 l->destroyHwcLayersForAllDisplays();
3009 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003010 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003011 }
3012 mLayersPendingRemoval.clear();
3013 }
3014
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003015 // If this transaction is part of a window animation then the next frame
3016 // we composite should be considered an animation as well.
3017 mAnimCompositionPending = mAnimTransactionPending;
3018
Mathias Agopian4fec8732012-06-29 14:12:52 -07003019 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003020 // clear the "changed" flags in current state
3021 mCurrentState.colorMatrixChanged = false;
3022
Robert Carr1f0a16a2016-10-24 16:27:39 -07003023 mDrawingState.traverseInZOrder([](Layer* layer) {
3024 layer->commitChildList();
3025 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003026 mTransactionPending = false;
3027 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003028 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003029}
3030
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003031void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
3032 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003033 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003034 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003035
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003036 Region aboveOpaqueLayers;
3037 Region aboveCoveredLayers;
3038 Region dirty;
3039
Mathias Agopian87baae12012-07-31 12:38:26 -07003040 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003041
Robert Carr2047fae2016-11-28 14:09:09 -08003042 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003043 // start with the whole surface at its current location
3044 const Layer::State& s(layer->getDrawingState());
3045
Jesse Hall01e29052013-02-19 16:13:35 -08003046 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003047 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003048 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003049 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003050
Mathias Agopianab028732010-03-16 16:41:46 -07003051 /*
3052 * opaqueRegion: area of a surface that is fully opaque.
3053 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003054 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003055
3056 /*
3057 * visibleRegion: area of a surface that is visible on screen
3058 * and not fully transparent. This is essentially the layer's
3059 * footprint minus the opaque regions above it.
3060 * Areas covered by a translucent surface are considered visible.
3061 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003062 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003063
3064 /*
3065 * coveredRegion: area of a surface that is covered by all
3066 * visible regions above it (which includes the translucent areas).
3067 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003068 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003069
Jesse Halla8026d22012-09-25 13:25:04 -07003070 /*
3071 * transparentRegion: area of a surface that is hinted to be completely
3072 * transparent. This is only used to tell when the layer has no visible
3073 * non-transparent regions and can be removed from the layer list. It
3074 * does not affect the visibleRegion of this layer or any layers
3075 * beneath it. The hint may not be correct if apps don't respect the
3076 * SurfaceView restrictions (which, sadly, some don't).
3077 */
3078 Region transparentRegion;
3079
Mathias Agopianab028732010-03-16 16:41:46 -07003080
3081 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003082 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003083 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003084 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003085
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003086 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003087 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003088 if (!visibleRegion.isEmpty()) {
3089 // Remove the transparent area from the visible region
3090 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003091 if (tr.preserveRects()) {
3092 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003093 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003094 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003095 // transformation too complex, can't do the
3096 // transparent region optimization.
3097 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003098 }
Mathias Agopianab028732010-03-16 16:41:46 -07003099 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003100
Mathias Agopianab028732010-03-16 16:41:46 -07003101 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003102 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003103 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003104 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003105 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003106 // the opaque region is the layer's footprint
3107 opaqueRegion = visibleRegion;
3108 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003109 }
3110 }
3111
Robert Carre5f4f692018-01-12 13:12:28 -08003112 if (visibleRegion.isEmpty()) {
3113 layer->clearVisibilityRegions();
3114 return;
3115 }
3116
Mathias Agopianab028732010-03-16 16:41:46 -07003117 // Clip the covered region to the visible region
3118 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3119
3120 // Update aboveCoveredLayers for next (lower) layer
3121 aboveCoveredLayers.orSelf(visibleRegion);
3122
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003123 // subtract the opaque region covered by the layers above us
3124 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003125
3126 // compute this layer's dirty region
3127 if (layer->contentDirty) {
3128 // we need to invalidate the whole region
3129 dirty = visibleRegion;
3130 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003131 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003132 layer->contentDirty = false;
3133 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003134 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003135 * the exposed region consists of two components:
3136 * 1) what's VISIBLE now and was COVERED before
3137 * 2) what's EXPOSED now less what was EXPOSED before
3138 *
3139 * note that (1) is conservative, we start with the whole
3140 * visible region but only keep what used to be covered by
3141 * something -- which mean it may have been exposed.
3142 *
3143 * (2) handles areas that were not covered by anything but got
3144 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003145 */
Mathias Agopianab028732010-03-16 16:41:46 -07003146 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003147 const Region oldVisibleRegion = layer->visibleRegion;
3148 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003149 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3150 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003151 }
3152 dirty.subtractSelf(aboveOpaqueLayers);
3153
3154 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003155 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003156
Mathias Agopianab028732010-03-16 16:41:46 -07003157 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003158 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003159
Jesse Halla8026d22012-09-25 13:25:04 -07003160 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003161 layer->setVisibleRegion(visibleRegion);
3162 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003163 layer->setVisibleNonTransparentRegion(
3164 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003165 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003166
Mathias Agopian87baae12012-07-31 12:38:26 -07003167 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003168}
3169
Chia-I Wuab0c3192017-08-01 11:29:00 -07003170void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003171 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003172 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
3173 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003174 }
3175 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003176}
3177
Dan Stoza6b9454d2014-11-07 16:00:59 -08003178bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003179{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003180 ALOGV("handlePageFlip");
3181
Brian Andersond6927fb2016-07-23 23:37:30 -07003182 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003183
Mathias Agopian4fec8732012-06-29 14:12:52 -07003184 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003185 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003186 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003187
3188 // Store the set of layers that need updates. This set must not change as
3189 // buffers are being latched, as this could result in a deadlock.
3190 // Example: Two producers share the same command stream and:
3191 // 1.) Layer 0 is latched
3192 // 2.) Layer 0 gets a new frame
3193 // 2.) Layer 1 gets a new frame
3194 // 3.) Layer 1 is latched.
3195 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3196 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003197 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003198 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003199 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003200 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3201 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003202 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003203 } else {
3204 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003205 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003206 } else {
3207 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003208 }
Robert Carr2047fae2016-11-28 14:09:09 -08003209 });
3210
Lloyd Piquef2c79392018-12-20 16:23:33 -08003211 if (!mLayersWithQueuedFrames.empty()) {
3212 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3213 // writes to Layer current state. See also b/119481871
3214 Mutex::Autolock lock(mStateLock);
3215
3216 for (auto& layer : mLayersWithQueuedFrames) {
3217 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3218 layer->useSurfaceDamage();
3219 invalidateLayerStack(layer, dirty);
3220 if (layer->isBufferLatched()) {
3221 newDataLatched = true;
3222 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003223 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003224 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003225
Alec Mouri86770e52018-09-24 22:40:58 +00003226 // Clear the renderengine fence here...
3227 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3228 // clear instead of sp::clear.
3229 getBE().flushFence = Fence::NO_FENCE;
3230
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003231 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003232
Vishnu Nairde19f852018-12-18 16:11:53 -08003233 if (visibleRegions) {
3234 // Update input window info if the layer receives its first buffer.
3235 updateInputWindows();
3236 }
3237
Dan Stoza6b9454d2014-11-07 16:00:59 -08003238 // If we will need to wake up at some time in the future to deal with a
3239 // queued frame that shouldn't be displayed during this vsync period, wake
3240 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003241 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003242 signalLayerUpdate();
3243 }
3244
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003245 // enter boot animation on first buffer latch
3246 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3247 ALOGI("Enter boot animation");
3248 mBootStage = BootStage::BOOTANIMATION;
3249 }
3250
Dan Stoza6b9454d2014-11-07 16:00:59 -08003251 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003252 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003253}
3254
Mathias Agopianad456f92011-01-13 17:53:01 -08003255void SurfaceFlinger::invalidateHwcGeometry()
3256{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003257 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003258}
3259
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003260void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& display,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003261 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003262 // We only need to actually compose the display if:
3263 // 1) It is being handled by hardware composer, which may need this to
3264 // keep its virtual display state machine in sync, or
3265 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski34157762018-10-31 13:07:19 -07003266 if (!display->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003267 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003268 return;
3269 }
3270
Dan Stoza9e56aa02015-11-02 13:00:03 -08003271 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003272 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003273
3274 // swap buffers (presentation)
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003275 display->queueBuffer(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003276}
3277
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003278bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003279 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003280
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003281 const Region bounds(display->bounds());
3282 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003283 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07003284 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003285 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003286
Peiyong Lind3788632018-09-18 16:01:31 -07003287 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003288 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003289
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003290 // Framebuffer will live in this scope for GPU composition.
3291 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
3292
Dan Stoza9e56aa02015-11-02 13:00:03 -08003293 if (hasClientComposition) {
3294 ALOGV("hasClientComposition");
3295
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003296 sp<GraphicBuffer> buf = display->dequeueBuffer();
3297
3298 if (buf == nullptr) {
3299 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3300 "client composition for this frame",
3301 display->getDisplayName().c_str());
3302 return false;
3303 }
3304
3305 // Bind the framebuffer in this scope.
3306 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3307 buf->getNativeBuffer());
3308
3309 if (fbo->getStatus() != NO_ERROR) {
3310 ALOGW("Binding buffer for display [%s] failed with status: %d",
3311 display->getDisplayName().c_str(), fbo->getStatus());
3312 return false;
3313 }
3314
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003315 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003316 if (display->hasWideColorGamut()) {
3317 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003318 }
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003319 getRenderEngine().setOutputDataSpace(outputDataspace);
3320 getRenderEngine().setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003321 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003322
Lloyd Pique441d5042018-10-18 16:49:51 -07003323 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003324 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003325 getHwComposer()
3326 .hasDisplayCapability(displayId,
3327 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003328
Peiyong Lind3788632018-09-18 16:01:31 -07003329 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003330 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3331 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003332 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003333 }
3334
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003335 display->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003336
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003337 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003338 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003339 // when using overlays, we assume a fully transparent framebuffer
3340 // NOTE: we could reduce how much we need to clear, for instance
3341 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003342 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003343 // We'll revisit later if needed.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003344 getRenderEngine().clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003345 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003346 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003347 // we're left with the letterbox region
3348 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003349 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003350
3351 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003352 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003353
Mathias Agopianb9494d52012-04-18 02:28:45 -07003354 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003355 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003356 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003357 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003358 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003359 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003360
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003361 const Rect& bounds = display->getBounds();
3362 const Rect& scissor = display->getScissor();
3363 if (scissor != bounds) {
3364 // scissor doesn't match the screen's dimensions, so we
3365 // need to clear everything outside of it and enable
3366 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003367
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003368 // enable scissor for this frame
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003369 getRenderEngine().setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003370 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003371 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003372
Mathias Agopian85d751c2012-08-29 16:59:24 -07003373 /*
3374 * and then, render the layers targeted at the framebuffer
3375 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003376
Dan Stoza9e56aa02015-11-02 13:00:03 -08003377 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003378 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003379 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003380 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003381 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003382 displayTransform.transform(layer->visibleRegion)));
3383 ALOGV("Layer: %s", layer->getName().string());
3384 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003385 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003386 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003387 case HWC2::Composition::Cursor:
3388 case HWC2::Composition::Device:
3389 case HWC2::Composition::Sideband:
3390 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003391 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003392 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003393 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003394 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003395 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003396 // never clear the very first layer since we're
3397 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003398 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003399 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003400 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003401 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003402 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003403 if (layer->hasColorTransform()) {
3404 mat4 tmpMatrix;
3405 if (applyColorMatrix) {
3406 tmpMatrix = mDrawingState.colorMatrix;
3407 }
3408 tmpMatrix *= layer->getColorTransform();
Peiyong Lind3788632018-09-18 16:01:31 -07003409 getRenderEngine().setColorTransform(tmpMatrix);
3410 } else {
3411 getRenderEngine().setColorTransform(colorMatrix);
3412 }
David Sodmanc1498e62018-09-12 14:36:26 -07003413 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003414 break;
3415 }
3416 default:
3417 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003418 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003419 } else {
3420 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003421 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003422 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003423 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003424
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003425 // Perform some cleanup steps if we used client composition.
3426 if (hasClientComposition) {
3427 getRenderEngine().setColorTransform(mat4());
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003428 getRenderEngine().disableScissor();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003429 display->finishBuffer();
3430 // Clear out error flags here so that we don't wait until next
3431 // composition to log.
3432 getRenderEngine().checkErrors();
3433 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003434 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003435}
3436
Chia-I Wu28e3a252018-09-07 12:05:02 -07003437void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003438 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003439 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003440}
3441
Dan Stoza7d89d062015-04-30 13:29:25 -07003442status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003443 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003444 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003445 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003446 const sp<Layer>& parent,
3447 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003448{
Dan Stoza7d89d062015-04-30 13:29:25 -07003449 // add this layer to the current state list
3450 {
3451 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003452 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003453 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3454 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003455 return NO_MEMORY;
3456 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003457 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003458 mCurrentState.layersSortedByZ.add(lbc);
Robert Carrb89ea9d2018-12-10 13:01:14 -08003459 } else if (parent == nullptr || parent->isRemovedFromCurrentState()) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003460 ALOGE("addClientLayer called with a removed parent");
chaviw61626f22018-11-15 16:26:27 -08003461 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003462 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003463 parent->addChild(lbc);
3464 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003465
Yiwei Zhang243b3782018-05-15 17:40:04 -07003466 if (gbc != nullptr) {
3467 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3468 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3469 mMaxGraphicBufferProducerListSize,
3470 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3471 mGraphicBufferProducerList.size(),
3472 mMaxGraphicBufferProducerListSize, mNumLayers);
3473 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003474 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003475 }
3476
Mathias Agopian96f08192010-06-02 23:28:45 -07003477 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003478 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003479
Dan Stoza7d89d062015-04-30 13:29:25 -07003480 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003481}
3482
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003483uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003484 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003485}
3486
Mathias Agopian3f844832013-08-07 21:24:32 -07003487uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003488 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003489}
3490
Mathias Agopian3f844832013-08-07 21:24:32 -07003491uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003492 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003493}
3494
3495uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003496 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003497 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003498 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003499 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003500 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003501 }
3502 return old;
3503}
3504
Marissa Wall713b63f2018-10-17 15:42:43 -07003505bool SurfaceFlinger::flushTransactionQueues() {
3506 Mutex::Autolock _l(mStateLock);
3507 auto it = mTransactionQueues.begin();
3508 while (it != mTransactionQueues.end()) {
3509 auto& [applyToken, transactionQueue] = *it;
3510
3511 while (!transactionQueue.empty()) {
3512 const auto& [states, displays, flags] = transactionQueue.front();
3513 if (composerStateContainsUnsignaledFences(states)) {
3514 break;
3515 }
chaviw273171b2018-12-26 11:46:30 -08003516 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003517 transactionQueue.pop();
3518 }
3519
3520 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3521 }
3522 return mTransactionQueues.empty();
3523}
3524
chaviwca27f252018-02-06 16:46:39 -08003525bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3526 for (const ComposerState& state : states) {
3527 // Here we need to check that the interface we're given is indeed
3528 // one of our own. A malicious client could give us a nullptr
3529 // IInterface, or one of its own or even one of our own but a
3530 // different type. All these situations would cause us to crash.
3531 if (state.client == nullptr) {
3532 return true;
3533 }
3534
3535 sp<IBinder> binder = IInterface::asBinder(state.client);
3536 if (binder == nullptr) {
3537 return true;
3538 }
3539
3540 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3541 return true;
3542 }
3543 }
3544 return false;
3545}
3546
Marissa Wall713b63f2018-10-17 15:42:43 -07003547bool SurfaceFlinger::composerStateContainsUnsignaledFences(const Vector<ComposerState>& states) {
3548 for (const ComposerState& state : states) {
3549 const layer_state_t& s = state.state;
3550 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3551 continue;
3552 }
3553 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
3554 return true;
3555 }
3556 }
3557 return false;
3558}
3559
3560void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3561 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003562 const sp<IBinder>& applyToken,
3563 const InputWindowCommands& inputWindowCommands) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003564 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003565 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003566
chaviwca27f252018-02-06 16:46:39 -08003567 if (containsAnyInvalidClientState(states)) {
3568 return;
3569 }
3570
Marissa Wall713b63f2018-10-17 15:42:43 -07003571 // If its TransactionQueue already has a pending TransactionState or if it is pending
3572 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
3573 composerStateContainsUnsignaledFences(states)) {
3574 mTransactionQueues[applyToken].emplace(states, displays, flags);
3575 setTransactionFlags(eTransactionNeeded);
3576 return;
3577 }
3578
chaviw273171b2018-12-26 11:46:30 -08003579 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003580}
3581
3582void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003583 const Vector<DisplayState>& displays, uint32_t flags,
3584 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003585 uint32_t transactionFlags = 0;
3586
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003587 if (flags & eAnimation) {
3588 // For window updates that are part of an animation we must wait for
3589 // previous animation "frames" to be handled.
3590 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003591 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003592 if (CC_UNLIKELY(err != NO_ERROR)) {
3593 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003594 // caller after a few seconds.
3595 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3596 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003597 mAnimTransactionPending = false;
3598 break;
3599 }
3600 }
3601 }
3602
chaviwca27f252018-02-06 16:46:39 -08003603 for (const DisplayState& display : displays) {
3604 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003605 }
3606
Marissa Walle2ffb422018-10-12 11:33:52 -07003607 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003608 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003609 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003610 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003611 // If the state doesn't require a traversal and there are callbacks, send them now
3612 if (!(clientStateFlags & eTraversalNeeded)) {
3613 mTransactionCompletedThread.sendCallbacks();
3614 }
3615 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003616
chaviw273171b2018-12-26 11:46:30 -08003617 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3618
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003619 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3620 // anyway. This can be used as a flush mechanism for previous async transactions.
3621 // Empty animation transaction can be used to simulate back-pressure, so also force a
3622 // transaction for empty animation transactions.
3623 if (transactionFlags == 0 &&
3624 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003625 transactionFlags = eTransactionNeeded;
3626 }
3627
Mathias Agopian386aa982011-11-07 21:58:03 -08003628 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003629 if (mInterceptor->isEnabled()) {
3630 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003631 }
Irvel468051e2016-06-13 16:44:44 -07003632
Mathias Agopian386aa982011-11-07 21:58:03 -08003633 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003634 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3635 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003636 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003637
3638 // if this is a synchronous transaction, wait for it to take effect
3639 // before returning.
3640 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003641 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003642 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003643 if (flags & eAnimation) {
3644 mAnimTransactionPending = true;
3645 }
3646 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003647 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3648 if (CC_UNLIKELY(err != NO_ERROR)) {
3649 // just in case something goes wrong in SF, return to the
3650 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003651 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3652 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003653 break;
3654 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003655 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003656 }
3657}
3658
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003659uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3660 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3661 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003662
Mathias Agopiane57f2922012-08-09 16:29:12 -07003663 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003664 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3665
3666 const uint32_t what = s.what;
3667 if (what & DisplayState::eSurfaceChanged) {
3668 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3669 state.surface = s.surface;
3670 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003671 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003672 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003673 if (what & DisplayState::eLayerStackChanged) {
3674 if (state.layerStack != s.layerStack) {
3675 state.layerStack = s.layerStack;
3676 flags |= eDisplayTransactionNeeded;
3677 }
3678 }
3679 if (what & DisplayState::eDisplayProjectionChanged) {
3680 if (state.orientation != s.orientation) {
3681 state.orientation = s.orientation;
3682 flags |= eDisplayTransactionNeeded;
3683 }
3684 if (state.frame != s.frame) {
3685 state.frame = s.frame;
3686 flags |= eDisplayTransactionNeeded;
3687 }
3688 if (state.viewport != s.viewport) {
3689 state.viewport = s.viewport;
3690 flags |= eDisplayTransactionNeeded;
3691 }
3692 }
3693 if (what & DisplayState::eDisplaySizeChanged) {
3694 if (state.width != s.width) {
3695 state.width = s.width;
3696 flags |= eDisplayTransactionNeeded;
3697 }
3698 if (state.height != s.height) {
3699 state.height = s.height;
3700 flags |= eDisplayTransactionNeeded;
3701 }
3702 }
3703
Mathias Agopiane57f2922012-08-09 16:29:12 -07003704 return flags;
3705}
3706
Robert Carrd4ae7f32018-06-07 16:10:57 -07003707bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3708 IPCThreadState* ipc = IPCThreadState::self();
3709 const int pid = ipc->getCallingPid();
3710 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003711 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003712 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003713 return false;
3714 }
3715 return true;
3716}
3717
chaviwca27f252018-02-06 16:46:39 -08003718uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3719 const layer_state_t& s = composerState.state;
3720 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3721
Mathias Agopian13127d82013-03-05 17:47:11 -08003722 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003723 if (layer == nullptr) {
3724 return 0;
3725 }
3726
chaviw8b3871a2017-11-01 17:41:01 -07003727 uint32_t flags = 0;
3728
Garfield Tan8a3083e2018-12-03 13:21:07 -08003729 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003730 bool geometryAppliesWithResize =
3731 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003732
3733 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3734 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003735 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003736 layer->pushPendingState();
3737 }
3738
chaviw8b3871a2017-11-01 17:41:01 -07003739 if (what & layer_state_t::ePositionChanged) {
3740 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3741 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003742 }
chaviw8b3871a2017-11-01 17:41:01 -07003743 }
3744 if (what & layer_state_t::eLayerChanged) {
3745 // NOTE: index needs to be calculated before we update the state
3746 const auto& p = layer->getParent();
3747 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003748 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003749 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003750 mCurrentState.layersSortedByZ.removeAt(idx);
3751 mCurrentState.layersSortedByZ.add(layer);
3752 // we need traversal (state changed)
3753 // AND transaction (list changed)
3754 flags |= eTransactionNeeded|eTraversalNeeded;
3755 }
chaviw8b3871a2017-11-01 17:41:01 -07003756 } else {
3757 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003758 flags |= eTransactionNeeded|eTraversalNeeded;
3759 }
3760 }
chaviw8b3871a2017-11-01 17:41:01 -07003761 }
3762 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003763 // NOTE: index needs to be calculated before we update the state
3764 const auto& p = layer->getParent();
3765 if (p == nullptr) {
3766 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3767 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3768 mCurrentState.layersSortedByZ.removeAt(idx);
3769 mCurrentState.layersSortedByZ.add(layer);
3770 // we need traversal (state changed)
3771 // AND transaction (list changed)
3772 flags |= eTransactionNeeded|eTraversalNeeded;
3773 }
3774 } else {
3775 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3776 flags |= eTransactionNeeded|eTraversalNeeded;
3777 }
chaviw8b3871a2017-11-01 17:41:01 -07003778 }
3779 }
3780 if (what & layer_state_t::eSizeChanged) {
3781 if (layer->setSize(s.w, s.h)) {
3782 flags |= eTraversalNeeded;
3783 }
3784 }
3785 if (what & layer_state_t::eAlphaChanged) {
3786 if (layer->setAlpha(s.alpha))
3787 flags |= eTraversalNeeded;
3788 }
3789 if (what & layer_state_t::eColorChanged) {
3790 if (layer->setColor(s.color))
3791 flags |= eTraversalNeeded;
3792 }
Peiyong Lind3788632018-09-18 16:01:31 -07003793 if (what & layer_state_t::eColorTransformChanged) {
3794 if (layer->setColorTransform(s.colorTransform)) {
3795 flags |= eTraversalNeeded;
3796 }
3797 }
chaviw8b3871a2017-11-01 17:41:01 -07003798 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003799 // TODO: b/109894387
3800 //
3801 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3802 // rotation. To see the problem observe that if we have a square parent, and a child
3803 // of the same size, then we rotate the child 45 degrees around it's center, the child
3804 // must now be cropped to a non rectangular 8 sided region.
3805 //
3806 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3807 // private API, and the WindowManager only uses rotation in one case, which is on a top
3808 // level layer in which cropping is not an issue.
3809 //
3810 // However given that abuse of rotation matrices could lead to surfaces extending outside
3811 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3812 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3813 // transformations.
3814 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003815 flags |= eTraversalNeeded;
3816 }
3817 if (what & layer_state_t::eTransparentRegionChanged) {
3818 if (layer->setTransparentRegionHint(s.transparentRegion))
3819 flags |= eTraversalNeeded;
3820 }
3821 if (what & layer_state_t::eFlagsChanged) {
3822 if (layer->setFlags(s.flags, s.mask))
3823 flags |= eTraversalNeeded;
3824 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003825 if (what & layer_state_t::eCropChanged_legacy) {
3826 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003827 flags |= eTraversalNeeded;
3828 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003829 if (what & layer_state_t::eCornerRadiusChanged) {
3830 if (layer->setCornerRadius(s.cornerRadius))
3831 flags |= eTraversalNeeded;
3832 }
chaviw8b3871a2017-11-01 17:41:01 -07003833 if (what & layer_state_t::eLayerStackChanged) {
3834 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3835 // We only allow setting layer stacks for top level layers,
3836 // everything else inherits layer stack from its parent.
3837 if (layer->hasParent()) {
3838 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3839 layer->getName().string());
3840 } else if (idx < 0) {
3841 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3842 "that also does not appear in the top level layer list. Something"
3843 " has gone wrong.", layer->getName().string());
3844 } else if (layer->setLayerStack(s.layerStack)) {
3845 mCurrentState.layersSortedByZ.removeAt(idx);
3846 mCurrentState.layersSortedByZ.add(layer);
3847 // we need traversal (state changed)
3848 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003849 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003850 }
3851 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003852 if (what & layer_state_t::eDeferTransaction_legacy) {
3853 if (s.barrierHandle_legacy != nullptr) {
3854 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3855 } else if (s.barrierGbp_legacy != nullptr) {
3856 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003857 if (authenticateSurfaceTextureLocked(gbp)) {
3858 const auto& otherLayer =
3859 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003860 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003861 } else {
3862 ALOGE("Attempt to defer transaction to to an"
3863 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003864 }
3865 }
chaviw8b3871a2017-11-01 17:41:01 -07003866 // We don't trigger a traversal here because if no other state is
3867 // changed, we don't want this to cause any more work
3868 }
3869 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003870 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003871 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003872 if (!hadParent) {
3873 mCurrentState.layersSortedByZ.remove(layer);
3874 }
chaviw8b3871a2017-11-01 17:41:01 -07003875 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003876 }
chaviw8b3871a2017-11-01 17:41:01 -07003877 }
3878 if (what & layer_state_t::eReparentChildren) {
3879 if (layer->reparentChildren(s.reparentHandle)) {
3880 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003881 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003882 }
chaviw8b3871a2017-11-01 17:41:01 -07003883 if (what & layer_state_t::eDetachChildren) {
3884 layer->detachChildren();
3885 }
3886 if (what & layer_state_t::eOverrideScalingModeChanged) {
3887 layer->setOverrideScalingMode(s.overrideScalingMode);
3888 // We don't trigger a traversal here because if no other state is
3889 // changed, we don't want this to cause any more work
3890 }
Marissa Wall61c58622018-07-18 10:12:20 -07003891 if (what & layer_state_t::eTransformChanged) {
3892 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3893 }
3894 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3895 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3896 flags |= eTraversalNeeded;
3897 }
3898 if (what & layer_state_t::eCropChanged) {
3899 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3900 }
Marissa Wall861616d2018-10-22 12:52:23 -07003901 if (what & layer_state_t::eFrameChanged) {
3902 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3903 }
Marissa Wall61c58622018-07-18 10:12:20 -07003904 if (what & layer_state_t::eBufferChanged) {
3905 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3906 }
3907 if (what & layer_state_t::eAcquireFenceChanged) {
3908 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3909 }
3910 if (what & layer_state_t::eDataspaceChanged) {
3911 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3912 }
3913 if (what & layer_state_t::eHdrMetadataChanged) {
3914 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3915 }
3916 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3917 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3918 }
3919 if (what & layer_state_t::eApiChanged) {
3920 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3921 }
3922 if (what & layer_state_t::eSidebandStreamChanged) {
3923 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3924 }
Robert Carr720e5062018-07-30 17:45:14 -07003925 if (what & layer_state_t::eInputInfoChanged) {
3926 layer->setInputInfo(s.inputInfo);
3927 flags |= eTraversalNeeded;
3928 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003929 std::vector<sp<CallbackHandle>> callbackHandles;
3930 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3931 mTransactionCompletedThread.run();
3932 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3933 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3934 }
3935 }
3936 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3937 // Do not put anything that updates layer state or modifies flags after
3938 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003939 return flags;
3940}
3941
chaviw273171b2018-12-26 11:46:30 -08003942uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3943 uint32_t flags = 0;
3944 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3945 flags |= eTraversalNeeded;
3946 }
3947
3948 mInputWindowCommands.merge(inputWindowCommands);
3949 return flags;
3950}
3951
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003952status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003953 const String8& name,
3954 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003955 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003956 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003957 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003958{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003959 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003960 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003961 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003962 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003963 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003964
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003965 status_t result = NO_ERROR;
3966
3967 sp<Layer> layer;
3968
Cody Northropbc755282017-03-31 12:00:08 -06003969 String8 uniqueName = getUniqueLayerName(name);
3970
Mathias Agopian3165cc22012-08-08 19:42:09 -07003971 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003972 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003973 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3974 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003975
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003976 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003977 case ISurfaceComposerClient::eFXSurfaceBufferState:
3978 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3979 break;
chaviw13fdc492017-06-27 12:40:18 -07003980 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003981 // check if buffer size is set for color layer.
3982 if (w > 0 || h > 0) {
3983 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3984 int(w), int(h));
3985 return BAD_VALUE;
3986 }
3987
chaviw13fdc492017-06-27 12:40:18 -07003988 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003989 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003990 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003991 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003992 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003993 // check if buffer size is set for container layer.
3994 if (w > 0 || h > 0) {
3995 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3996 int(w), int(h));
3997 return BAD_VALUE;
3998 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07003999 result = createContainerLayer(client,
4000 uniqueName, w, h, flags,
4001 handle, &layer);
4002 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004003 default:
4004 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004005 break;
4006 }
4007
Dan Stoza7d89d062015-04-30 13:29:25 -07004008 if (result != NO_ERROR) {
4009 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004010 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004011
Chia-I Wuab0c3192017-08-01 11:29:00 -07004012 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4013 // TODO b/64227542
4014 if (windowType == 441731) {
4015 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
4016 layer->setPrimaryDisplayOnly();
4017 }
4018
Albert Chaulk479c60c2017-01-27 14:21:34 -05004019 layer->setInfo(windowType, ownerUid);
4020
Robert Carrb89ea9d2018-12-10 13:01:14 -08004021 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4022 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4023 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004024 if (result != NO_ERROR) {
4025 return result;
4026 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004027 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004028
4029 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004030 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004031}
4032
Cody Northropbc755282017-03-31 12:00:08 -06004033String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4034{
4035 bool matchFound = true;
4036 uint32_t dupeCounter = 0;
4037
4038 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4039 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4040
Dan Stoza436ccf32018-06-21 12:10:12 -07004041 // Grab the state lock since we're accessing mCurrentState
4042 Mutex::Autolock lock(mStateLock);
4043
Cody Northropbc755282017-03-31 12:00:08 -06004044 // Loop over layers until we're sure there is no matching name
4045 while (matchFound) {
4046 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004047 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004048 if (layer->getName() == uniqueName) {
4049 matchFound = true;
4050 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4051 }
4052 });
4053 }
4054
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004055 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4056 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004057
4058 return uniqueName;
4059}
4060
Marissa Wallfd668622018-05-10 10:21:13 -07004061status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4062 uint32_t w, uint32_t h, uint32_t flags,
4063 PixelFormat& format, sp<IBinder>* handle,
4064 sp<IGraphicBufferProducer>* gbp,
4065 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004066 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004067 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004068 case PIXEL_FORMAT_TRANSPARENT:
4069 case PIXEL_FORMAT_TRANSLUCENT:
4070 format = PIXEL_FORMAT_RGBA_8888;
4071 break;
4072 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004073 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004074 break;
4075 }
4076
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004077 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004078 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004079 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004080 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004081 *handle = layer->getHandle();
4082 *gbp = layer->getProducer();
4083 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004084 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004085
Marissa Wallfd668622018-05-10 10:21:13 -07004086 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004087 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004088}
4089
Marissa Wall61c58622018-07-18 10:12:20 -07004090status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4091 uint32_t w, uint32_t h, uint32_t flags,
4092 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004093 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004094 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004095 *handle = layer->getHandle();
4096 *outLayer = layer;
4097
4098 return NO_ERROR;
4099}
4100
chaviw13fdc492017-06-27 12:40:18 -07004101status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004102 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004103 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004104{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004105 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004106 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004107 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004108}
4109
Robert Carr6b3f6c52018-08-13 13:05:17 -07004110status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4111 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4112 sp<IBinder>* handle, sp<Layer>* outLayer)
4113{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004114 *outLayer =
4115 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004116 *handle = (*outLayer)->getHandle();
4117 return NO_ERROR;
4118}
4119
4120
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004121void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004122 mLayersPendingRemoval.add(layer);
4123 mLayersRemoved = true;
4124 setTransactionFlags(eTransactionNeeded);
4125}
4126
Robert Carr695d5282018-12-18 15:27:58 -08004127void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004128{
Robert Carr2e102c92018-10-23 12:11:15 -07004129 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004130 // If a layer has a parent, we allow it to out-live it's handle
4131 // with the idea that the parent holds a reference and will eventually
4132 // be cleaned up. However no one cleans up the top-level so we do so
4133 // here.
4134 if (layer->getParent() == nullptr) {
4135 mCurrentState.layersSortedByZ.remove(layer);
4136 }
4137 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004138 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004139}
4140
Mathias Agopianb60314a2012-04-10 22:09:54 -07004141// ---------------------------------------------------------------------------
4142
Andy McFadden13a082e2012-08-24 10:16:42 -07004143void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004144 const auto display = getDefaultDisplayDeviceLocked();
4145 if (!display) return;
4146
4147 const sp<IBinder> token = display->getDisplayToken().promote();
4148 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004149
Jesse Hall01e29052013-02-19 16:13:35 -08004150 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004151 Vector<ComposerState> state;
4152 Vector<DisplayState> displays;
4153 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004154 d.what = DisplayState::eDisplayProjectionChanged |
4155 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004156 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004157 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004158 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004159 d.frame.makeInvalid();
4160 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004161 d.width = 0;
4162 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004163 displays.add(d);
chaviw273171b2018-12-26 11:46:30 -08004164 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004165
Dominik Laskowskie9774092018-12-11 10:04:24 -08004166 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004167
Dominik Laskowski83b88212018-12-11 13:34:06 -08004168 const nsecs_t vsyncPeriod = getVsyncPeriod();
4169 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004170
Brian Andersond0010582017-03-07 13:20:31 -08004171 // Use phase of 0 since phase is not known.
4172 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004173 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004174 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004175}
4176
4177void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004178 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004179 postMessageAsync(
4180 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004181}
4182
Dominik Laskowskie9774092018-12-11 10:04:24 -08004183void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004184 if (display->isVirtual()) {
4185 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004186 return;
4187 }
4188
Dominik Laskowski075d3172018-05-24 15:50:06 -07004189 const auto displayId = display->getId();
4190 LOG_ALWAYS_FATAL_IF(!displayId);
4191
Dominik Laskowski34157762018-10-31 13:07:19 -07004192 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004193
4194 int currentMode = display->getPowerMode();
4195 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004196 return;
4197 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004198
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004199 display->setPowerMode(mode);
4200
Lloyd Pique4dccc412018-01-22 17:21:36 -08004201 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004202 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004203 }
4204
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004205 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004206 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004207 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004208 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004209 if (mUseScheduler) {
4210 mScheduler->onScreenAcquired(mAppConnectionHandle);
4211 } else {
4212 mEventThread->onScreenAcquired();
4213 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004214 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004215 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004216
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004217 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004218 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004219 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004220
4221 struct sched_param param = {0};
4222 param.sched_priority = 1;
4223 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4224 ALOGW("Couldn't set SCHED_FIFO on display on");
4225 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004226 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004227 // Turn off the display
4228 struct sched_param param = {0};
4229 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4230 ALOGW("Couldn't set SCHED_OTHER on display off");
4231 }
4232
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004233 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004234 if (mUseScheduler) {
4235 mScheduler->disableHardwareVsync(true);
4236 } else {
4237 disableHardwareVsync(true); // also cancels any in-progress resync
4238 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004239 if (mUseScheduler) {
4240 mScheduler->onScreenReleased(mAppConnectionHandle);
4241 } else {
4242 mEventThread->onScreenReleased();
4243 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004244 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004245
Dominik Laskowski075d3172018-05-24 15:50:06 -07004246 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004247 mVisibleRegionsDirty = true;
4248 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004249 } else if (mode == HWC_POWER_MODE_DOZE ||
4250 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004251 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004252 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004253 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004254 if (mUseScheduler) {
4255 mScheduler->onScreenAcquired(mAppConnectionHandle);
4256 } else {
4257 mEventThread->onScreenAcquired();
4258 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004259 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004260 }
4261 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4262 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004263 if (display->isPrimary()) {
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 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004274 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004275 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004276 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004277 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004278 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004279 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004280
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004281 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004282 mTimeStats->setPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004283 }
4284
Dominik Laskowski34157762018-10-31 13:07:19 -07004285 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004286}
4287
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004288void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004289 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004290 const auto display = getDisplayDevice(displayToken);
4291 if (!display) {
4292 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4293 displayToken.get());
4294 } else if (display->isVirtual()) {
4295 ALOGW("Attempt to set power mode %d for virtual display", mode);
4296 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004297 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004298 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004299 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004300}
4301
4302// ---------------------------------------------------------------------------
4303
Lloyd Pique755e3192018-01-31 16:46:15 -08004304status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4305 NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004306 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004307
Mathias Agopianbd115332013-04-18 16:41:04 -07004308 IPCThreadState* ipc = IPCThreadState::self();
4309 const int pid = ipc->getCallingPid();
4310 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004311
Mathias Agopianbd115332013-04-18 16:41:04 -07004312 if ((uid != AID_SHELL) &&
4313 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004314 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4315 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004316 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004317 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004318 // (this would indicate SF is stuck, but we want to be able to
4319 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004320 status_t err = mStateLock.timedLock(s2ns(1));
4321 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004322 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004323 StringAppendF(&result,
4324 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4325 "(no locks held)\n",
4326 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004327 }
4328
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004329 bool dumpAll = true;
4330 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004331 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004332
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004333 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004334 if ((index < numArgs) &&
4335 (args[index] == String16("--list"))) {
4336 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004337 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004338 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004339 }
4340
4341 if ((index < numArgs) &&
4342 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004343 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004344 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004345 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004346 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004347
4348 if ((index < numArgs) &&
4349 (args[index] == String16("--latency-clear"))) {
4350 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004351 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004352 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004353 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004354
4355 if ((index < numArgs) &&
4356 (args[index] == String16("--dispsync"))) {
4357 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004358 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004359 dumpAll = false;
4360 }
Dan Stozab90cf072015-03-05 11:05:59 -08004361
4362 if ((index < numArgs) &&
4363 (args[index] == String16("--static-screen"))) {
4364 index++;
4365 dumpStaticScreenStats(result);
4366 dumpAll = false;
4367 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004368
4369 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004370 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004371 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004372 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004373 dumpAll = false;
4374 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004375
4376 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4377 index++;
4378 dumpWideColorInfo(result);
4379 dumpAll = false;
4380 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004381
4382 if ((index < numArgs) &&
4383 (args[index] == String16("--enable-layer-stats"))) {
4384 index++;
4385 mLayerStats.enable();
4386 dumpAll = false;
4387 }
4388
4389 if ((index < numArgs) &&
4390 (args[index] == String16("--disable-layer-stats"))) {
4391 index++;
4392 mLayerStats.disable();
4393 dumpAll = false;
4394 }
4395
4396 if ((index < numArgs) &&
4397 (args[index] == String16("--clear-layer-stats"))) {
4398 index++;
4399 mLayerStats.clear();
4400 dumpAll = false;
4401 }
4402
4403 if ((index < numArgs) &&
4404 (args[index] == String16("--dump-layer-stats"))) {
4405 index++;
4406 mLayerStats.dump(result);
4407 dumpAll = false;
4408 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004409
4410 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004411 (args[index] == String16("--frame-composition"))) {
4412 index++;
4413 dumpFrameCompositionInfo(result);
4414 dumpAll = false;
4415 }
4416
4417 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004418 (args[index] == String16("--display-identification"))) {
4419 index++;
4420 dumpDisplayIdentificationData(result);
4421 dumpAll = false;
4422 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004423
4424 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4425 index++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004426 mTimeStats->parseArgs(asProto, args, index, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004427 dumpAll = false;
4428 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004429 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004430
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004431 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004432 if (asProto) {
4433 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4434 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4435 } else {
4436 dumpAllLocked(args, index, result);
4437 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004438 }
4439
Mathias Agopian9795c422009-08-26 16:36:26 -07004440 if (locked) {
4441 mStateLock.unlock();
4442 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004443 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004444 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004445 return NO_ERROR;
4446}
4447
Yiwei Zhang5434a782018-12-05 18:06:32 -08004448void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */, size_t& /* index */,
4449 std::string& result) const {
4450 mCurrentState.traverseInZOrder(
4451 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004452}
4453
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004454void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004455 std::string& result) const {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004456 String8 name;
4457 if (index < args.size()) {
4458 name = String8(args[index]);
4459 index++;
4460 }
4461
Dominik Laskowski83b88212018-12-11 13:34:06 -08004462 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004463
4464 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004465 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004466 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004467 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004468 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004469 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004470 }
Robert Carr2047fae2016-11-28 14:09:09 -08004471 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004472 }
4473}
4474
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004475void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004476 std::string& /* result */) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004477 String8 name;
4478 if (index < args.size()) {
4479 name = String8(args[index]);
4480 index++;
4481 }
4482
Robert Carr2047fae2016-11-28 14:09:09 -08004483 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004484 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004485 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004486 }
Robert Carr2047fae2016-11-28 14:09:09 -08004487 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004488
Svetoslavd85084b2014-03-20 10:28:31 -07004489 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004490}
4491
Jamie Gennis6547ff42013-07-16 20:12:42 -07004492// This should only be called from the main thread. Otherwise it would need
4493// the lock and should use mCurrentState rather than mDrawingState.
4494void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004495 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004496 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004497 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004498
4499 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4500}
4501
Yiwei Zhang5434a782018-12-05 18:06:32 -08004502void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004503 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004504
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004505 if (isLayerTripleBufferingDisabled())
4506 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004507
Yiwei Zhang5434a782018-12-05 18:06:32 -08004508 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4509 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4510 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4511 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4512 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4513 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004514 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004515}
4516
Yiwei Zhang5434a782018-12-05 18:06:32 -08004517void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4518 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004519 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4520 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004521 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004522 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004523 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004524 }
David Sodman4a36e932017-11-07 14:29:47 -08004525 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004526 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004527 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004528 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4529 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004530}
4531
Dan Stozae77c7662016-05-13 11:37:28 -07004532void SurfaceFlinger::recordBufferingStats(const char* layerName,
4533 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004534 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4535 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004536 for (const auto& segment : history) {
4537 if (!segment.usedThirdBuffer) {
4538 stats.twoBufferTime += segment.totalTime;
4539 }
4540 if (segment.occupancyAverage < 1.0f) {
4541 stats.doubleBufferedTime += segment.totalTime;
4542 } else if (segment.occupancyAverage < 2.0f) {
4543 stats.tripleBufferedTime += segment.totalTime;
4544 }
4545 ++stats.numSegments;
4546 stats.totalTime += segment.totalTime;
4547 }
4548}
4549
Yiwei Zhang5434a782018-12-05 18:06:32 -08004550void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4551 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004552
4553 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4554 const size_t count = currentLayers.size();
4555 for (size_t i=0 ; i<count ; i++) {
4556 currentLayers[i]->dumpFrameEvents(result);
4557 }
4558}
4559
Yiwei Zhang5434a782018-12-05 18:06:32 -08004560void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004561 result.append("Buffering stats:\n");
4562 result.append(" [Layer name] <Active time> <Two buffer> "
4563 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004564 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004565 typedef std::tuple<std::string, float, float, float> BufferTuple;
4566 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004567 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004568 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004569 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004570 if (stats.numSegments == 0) {
4571 continue;
4572 }
4573 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4574 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4575 stats.totalTime;
4576 float doubleBufferRatio = static_cast<float>(
4577 stats.doubleBufferedTime) / stats.totalTime;
4578 float tripleBufferRatio = static_cast<float>(
4579 stats.tripleBufferedTime) / stats.totalTime;
4580 sorted.insert({activeTime, {name, twoBufferRatio,
4581 doubleBufferRatio, tripleBufferRatio}});
4582 }
4583 for (const auto& sortedPair : sorted) {
4584 float activeTime = sortedPair.first;
4585 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004586 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4587 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004588 }
4589 result.append("\n");
4590}
4591
Yiwei Zhang5434a782018-12-05 18:06:32 -08004592void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004593 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004594 const auto displayId = display->getId();
4595 if (!displayId) {
4596 continue;
4597 }
4598 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004599 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004600 continue;
4601 }
4602
Yiwei Zhang5434a782018-12-05 18:06:32 -08004603 StringAppendF(&result,
4604 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4605 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004606 uint8_t port;
4607 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004608 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004609 result.append("no identification data\n");
4610 continue;
4611 }
4612
4613 if (!isEdid(data)) {
4614 result.append("unknown identification data: ");
4615 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004616 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004617 }
4618 result.append("\n");
4619 continue;
4620 }
4621
4622 const auto edid = parseEdid(data);
4623 if (!edid) {
4624 result.append("invalid EDID: ");
4625 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004626 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004627 }
4628 result.append("\n");
4629 continue;
4630 }
4631
Yiwei Zhang5434a782018-12-05 18:06:32 -08004632 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004633 result.append(edid->displayName.data(), edid->displayName.length());
4634 result.append("\"\n");
4635 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004636}
4637
Yiwei Zhang5434a782018-12-05 18:06:32 -08004638void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4639 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4640 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4641 StringAppendF(&result, "DisplayColorSetting: %s\n",
4642 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004643
4644 // TODO: print out if wide-color mode is active or not
4645
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004646 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004647 const auto displayId = display->getId();
4648 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004649 continue;
4650 }
4651
Yiwei Zhang5434a782018-12-05 18:06:32 -08004652 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004653 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004654 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004655 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004656 }
4657
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004658 ColorMode currentMode = display->getActiveColorMode();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004659 StringAppendF(&result, " Current color mode: %s (%d)\n",
4660 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004661 }
4662 result.append("\n");
4663}
4664
Yiwei Zhang5434a782018-12-05 18:06:32 -08004665void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004666 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004667 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4668 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004669 continue;
4670 }
4671
Dominik Laskowski05275f12018-11-01 15:03:24 -07004672 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004673 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4674 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004675 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004676 compositionInfo.dump(result, nullptr);
4677 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004678 }
4679 }
David Sodman7e4ae112018-02-09 15:02:28 -08004680}
4681
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004682LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004683 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004684 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4685 const State& state = useDrawing ? mDrawingState : mCurrentState;
4686 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004687 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004688 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004689 });
4690
4691 return layersProto;
4692}
4693
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004694LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004695 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004696
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004697 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004698 resolution->set_w(display.getWidth());
4699 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004700
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004701 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4702 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4703 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004704
Dominik Laskowski075d3172018-05-24 15:50:06 -07004705 const auto displayId = display.getId();
4706 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004707 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004708 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004709 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004710 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004711 }
4712 });
4713
4714 return layersProto;
4715}
4716
Mathias Agopian74d211a2013-04-22 16:55:35 +02004717void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004718 std::string& result) const {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004719 bool colorize = false;
4720 if (index < args.size()
4721 && (args[index] == String16("--color"))) {
4722 colorize = true;
4723 index++;
4724 }
4725
4726 Colorizer colorizer(colorize);
4727
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004728 // figure out if we're stuck somewhere
4729 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004730 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004731 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4732
4733 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004734 * Dump library configuration.
4735 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004736
4737 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004738 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004739 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004740 appendSfConfigString(result);
4741 appendUiConfigString(result);
4742 appendGuiConfigString(result);
4743 result.append("\n");
4744
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004745 result.append("\nDisplay identification data:\n");
4746 dumpDisplayIdentificationData(result);
4747
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004748 result.append("\nWide-Color information:\n");
4749 dumpWideColorInfo(result);
4750
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004751 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004752 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004753 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004754 result.append(SyncFeatures::getInstance().toString());
4755 result.append("\n");
4756
Andy McFadden41d67d72014-04-25 16:58:34 -07004757 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004758 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004759 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004760
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004761 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4762 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski83b88212018-12-11 13:34:06 -08004763 StringAppendF(&result,
4764 "app phase %" PRId64 " ns, "
4765 "sf phase %" PRId64 " ns, "
4766 "early app phase %" PRId64 " ns, "
4767 "early sf phase %" PRId64 " ns, "
4768 "early app gl phase %" PRId64 " ns, "
4769 "early sf gl phase %" PRId64 " ns, "
4770 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)\n",
4771 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, appEarlyOffset, sfEarlyOffset,
4772 appEarlyGlOffset, sfEarlyGlOffset, dispSyncPresentTimeOffset, getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004773
Dan Stozab90cf072015-03-05 11:05:59 -08004774 // Dump static screen stats
4775 result.append("\n");
4776 dumpStaticScreenStats(result);
4777 result.append("\n");
4778
Yiwei Zhang5434a782018-12-05 18:06:32 -08004779 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004780
Dan Stozae77c7662016-05-13 11:37:28 -07004781 dumpBufferingStats(result);
4782
Andy McFadden4803b742012-09-24 19:07:20 -07004783 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004784 * Dump the visible layer list
4785 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004786 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004787 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4788 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4789 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004790 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004791
Chia-I Wu2f884132018-09-13 15:17:58 -07004792 {
4793 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4794 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004795 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004796 result.append("\n");
4797 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004798
David Sodman7e4ae112018-02-09 15:02:28 -08004799 result.append("\nFrame-Composition information:\n");
4800 dumpFrameCompositionInfo(result);
4801 result.append("\n");
4802
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004803 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004804 * Dump Display state
4805 */
4806
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004807 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004808 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004809 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004810 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004811 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004812 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004813 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004814
4815 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004816 * Dump SurfaceFlinger global state
4817 */
4818
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004819 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004820 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004821 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004822
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004823 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004824
Dominik Laskowski075d3172018-05-24 15:50:06 -07004825 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004826 display->undefinedRegion.dump(result, "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004827 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4828 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004829 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004830 StringAppendF(&result,
4831 " transaction-flags : %08x\n"
4832 " gpu_to_cpu_unsupported : %d\n",
4833 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004834
Dominik Laskowski075d3172018-05-24 15:50:06 -07004835 if (const auto displayId = getInternalDisplayId();
4836 displayId && getHwComposer().isConnected(*displayId)) {
4837 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004838 StringAppendF(&result,
4839 " refresh-rate : %f fps\n"
4840 " x-dpi : %f\n"
4841 " y-dpi : %f\n",
4842 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4843 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004844 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004845
Yiwei Zhang5434a782018-12-05 18:06:32 -08004846 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004847
Yiwei Zhang5434a782018-12-05 18:06:32 -08004848 StringAppendF(&result, " use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004849 /*
4850 * VSYNC state
4851 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004852 if (mUseScheduler) {
4853 mScheduler->dump(mAppConnectionHandle, result);
4854 } else {
4855 mEventThread->dump(result);
4856 }
Dan Stozae22aec72016-08-01 13:20:59 -07004857 result.append("\n");
4858
4859 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004860 * Tracing state
4861 */
4862 mTracing.dump(result);
4863 result.append("\n");
4864
4865 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004866 * HWC layer minidump
4867 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004868 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004869 const auto displayId = display->getId();
4870 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004871 continue;
4872 }
4873
Yiwei Zhang5434a782018-12-05 18:06:32 -08004874 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004875 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004876 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004877 result.append("\n");
4878 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004879
4880 /*
4881 * Dump HWComposer state
4882 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004883 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004884 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004885 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004886 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004887 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004888 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004889
4890 /*
4891 * Dump gralloc state
4892 */
4893 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4894 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004895
4896 /*
4897 * Dump VrFlinger state if in use.
4898 */
4899 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4900 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004901 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004902 result.append("\n");
4903 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004904}
4905
Dominik Laskowski075d3172018-05-24 15:50:06 -07004906const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004907 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004908 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004909 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004910 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004911 }
4912 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004913
Dominik Laskowski34157762018-10-31 13:07:19 -07004914 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004915 static const Vector<sp<Layer>> empty;
4916 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004917}
4918
Keun young Park63f165f2012-08-31 10:53:36 -07004919bool SurfaceFlinger::startDdmConnection()
4920{
4921 void* libddmconnection_dso =
4922 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4923 if (!libddmconnection_dso) {
4924 return false;
4925 }
4926 void (*DdmConnection_start)(const char* name);
4927 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004928 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004929 if (!DdmConnection_start) {
4930 dlclose(libddmconnection_dso);
4931 return false;
4932 }
4933 (*DdmConnection_start)(getServiceName());
4934 return true;
4935}
4936
Chia-I Wu28f320b2018-05-03 11:02:56 -07004937void SurfaceFlinger::updateColorMatrixLocked() {
4938 mat4 colorMatrix;
4939 if (mGlobalSaturationFactor != 1.0f) {
4940 // Rec.709 luma coefficients
4941 float3 luminance{0.213f, 0.715f, 0.072f};
4942 luminance *= 1.0f - mGlobalSaturationFactor;
4943 mat4 saturationMatrix = mat4(
4944 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4945 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4946 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4947 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4948 );
4949 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4950 } else {
4951 colorMatrix = mClientColorMatrix * mDaltonizer();
4952 }
4953
4954 if (mCurrentState.colorMatrix != colorMatrix) {
4955 mCurrentState.colorMatrix = colorMatrix;
4956 mCurrentState.colorMatrixChanged = true;
4957 setTransactionFlags(eTransactionNeeded);
4958 }
4959}
4960
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004961status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004962#pragma clang diagnostic push
4963#pragma clang diagnostic error "-Wswitch-enum"
4964 switch (static_cast<ISurfaceComposerTag>(code)) {
4965 // These methods should at minimum make sure that the client requested
4966 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004967 case BOOT_FINISHED:
4968 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004969 case CREATE_DISPLAY:
4970 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004971 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004972 case GET_ACTIVE_COLOR_MODE:
4973 case GET_ANIMATION_FRAME_STATS:
4974 case GET_HDR_CAPABILITIES:
4975 case SET_ACTIVE_CONFIG:
4976 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004977 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004978 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004979 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004980 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4981 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004982 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4983 IPCThreadState* ipc = IPCThreadState::self();
4984 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4985 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004986 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004987 }
Robert Carr1db73f62016-12-21 12:58:51 -08004988 return OK;
4989 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004990 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004991 IPCThreadState* ipc = IPCThreadState::self();
4992 const int pid = ipc->getCallingPid();
4993 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004994 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4995 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004996 return PERMISSION_DENIED;
4997 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004998 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004999 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005000 // Used by apps to hook Choreographer to SurfaceFlinger.
5001 case CREATE_DISPLAY_EVENT_CONNECTION:
5002 // The following calls are currently used by clients that do not
5003 // request necessary permissions. However, they do not expose any secret
5004 // information, so it is OK to pass them.
5005 case AUTHENTICATE_SURFACE:
5006 case GET_ACTIVE_CONFIG:
5007 case GET_BUILT_IN_DISPLAY:
5008 case GET_DISPLAY_COLOR_MODES:
5009 case GET_DISPLAY_CONFIGS:
5010 case GET_DISPLAY_STATS:
5011 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5012 // Calling setTransactionState is safe, because you need to have been
5013 // granted a reference to Client* and Handle* to do anything with it.
5014 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005015 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005016 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005017 case GET_COMPOSITION_PREFERENCE:
5018 case GET_PROTECTED_CONTENT_SUPPORT: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005019 return OK;
5020 }
5021 case CAPTURE_LAYERS:
5022 case CAPTURE_SCREEN: {
5023 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005024 IPCThreadState* ipc = IPCThreadState::self();
5025 const int pid = ipc->getCallingPid();
5026 const int uid = ipc->getCallingUid();
5027 if ((uid != AID_GRAPHICS) &&
5028 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5029 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5030 return PERMISSION_DENIED;
5031 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005032 return OK;
5033 }
5034 // The following codes are deprecated and should never be allowed to access SF.
5035 case CONNECT_DISPLAY_UNUSED:
5036 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5037 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5038 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005039 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005040 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005041
5042 // These codes are used for the IBinder protocol to either interrogate the recipient
5043 // side of the transaction for its canonical interface descriptor or to dump its state.
5044 // We let them pass by default.
5045 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5046 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5047 code == IBinder::SYSPROPS_TRANSACTION) {
5048 return OK;
5049 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005050 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005051 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005052 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005053 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5054 return OK;
5055 }
5056 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5057 return PERMISSION_DENIED;
5058#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005059}
5060
Ana Krulec13be8ad2018-08-21 02:43:56 +00005061status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5062 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005063 status_t credentialCheck = CheckTransactCodeCredentials(code);
5064 if (credentialCheck != OK) {
5065 return credentialCheck;
5066 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005067
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005068 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5069 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005070 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005071 IPCThreadState* ipc = IPCThreadState::self();
5072 const int uid = ipc->getCallingUid();
5073 if (CC_UNLIKELY(uid != AID_SYSTEM
5074 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005075 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005076 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005077 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005078 return PERMISSION_DENIED;
5079 }
5080 int n;
5081 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005082 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005083 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005084 return NO_ERROR;
5085 case 1002: // SHOW_UPDATES
5086 n = data.readInt32();
5087 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005088 invalidateHwcGeometry();
5089 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005090 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005091 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005092 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005093 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005094 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005095 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005096 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005097 setTransactionFlags(
5098 eTransactionNeeded|
5099 eDisplayTransactionNeeded|
5100 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005101 return NO_ERROR;
5102 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005103 case 1006:{ // send empty update
5104 signalRefresh();
5105 return NO_ERROR;
5106 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005107 case 1008: // toggle use of hw composer
5108 n = data.readInt32();
5109 mDebugDisableHWC = n ? 1 : 0;
5110 invalidateHwcGeometry();
5111 repaintEverything();
5112 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005113 case 1009: // toggle use of transform hint
5114 n = data.readInt32();
5115 mDebugDisableTransformHint = n ? 1 : 0;
5116 invalidateHwcGeometry();
5117 repaintEverything();
5118 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005119 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005120 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005121 reply->writeInt32(0);
5122 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005123 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005124 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005125 return NO_ERROR;
5126 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005127 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005128 if (!display) {
5129 return NAME_NOT_FOUND;
5130 }
5131
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005132 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005133 return NO_ERROR;
5134 }
5135 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005136 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005137 // daltonize
5138 n = data.readInt32();
5139 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005140 case 1:
5141 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5142 break;
5143 case 2:
5144 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5145 break;
5146 case 3:
5147 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5148 break;
5149 default:
5150 mDaltonizer.setType(ColorBlindnessType::None);
5151 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005152 }
5153 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005154 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005155 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005156 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005157 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005158
5159 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005160 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005161 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005162 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005163 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005164 // apply a color matrix
5165 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005166 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005167 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005168 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005169 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005170 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005171 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005172 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005173 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005174 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005175 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005176
5177 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5178 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005179 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005180 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5181 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5182 }
5183
Chia-I Wu28f320b2018-05-03 11:02:56 -07005184 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005185 return NO_ERROR;
5186 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005187 // This is an experimental interface
5188 // Needs to be shifted to proper binder interface when we productize
5189 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005190 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005191 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005192 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005193 return NO_ERROR;
5194 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005195 case 1017: {
5196 n = data.readInt32();
5197 mForceFullDamage = static_cast<bool>(n);
5198 return NO_ERROR;
5199 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005200 case 1018: { // Modify Choreographer's phase offset
5201 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005202 if (mUseScheduler) {
5203 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5204 } else {
5205 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5206 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005207 return NO_ERROR;
5208 }
5209 case 1019: { // Modify SurfaceFlinger's phase offset
5210 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005211 if (mUseScheduler) {
5212 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5213 } else {
5214 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5215 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005216 return NO_ERROR;
5217 }
Irvel468051e2016-06-13 16:44:44 -07005218 case 1020: { // Layer updates interceptor
5219 n = data.readInt32();
5220 if (n) {
5221 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005222 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005223 }
5224 else{
5225 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005226 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005227 }
5228 return NO_ERROR;
5229 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005230 case 1021: { // Disable HWC virtual displays
5231 n = data.readInt32();
5232 mUseHwcVirtualDisplays = !n;
5233 return NO_ERROR;
5234 }
Romain Guy0147a172017-06-01 13:53:56 -07005235 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005236 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005237 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005238
Chia-I Wu28f320b2018-05-03 11:02:56 -07005239 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005240 return NO_ERROR;
5241 }
Romain Guy54f154a2017-10-24 21:40:32 +01005242 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005243 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005244 invalidateHwcGeometry();
5245 repaintEverything();
5246 return NO_ERROR;
5247 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005248 // Deprecate, use 1030 to check whether the device is color managed.
5249 case 1024: {
5250 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005251 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005252 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005253 n = data.readInt32();
5254 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005255 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005256 mTracing.enable();
5257 doTracing("tracing.enable");
5258 reply->writeInt32(NO_ERROR);
5259 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005260 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005261 status_t err = mTracing.disable();
5262 reply->writeInt32(err);
5263 }
5264 return NO_ERROR;
5265 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005266 case 1026: { // Get layer tracing status
5267 reply->writeBool(mTracing.isEnabled());
5268 return NO_ERROR;
5269 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005270 // Is a DisplayColorSetting supported?
5271 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005272 const auto display = getDefaultDisplayDevice();
5273 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005274 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005275 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005276
5277 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5278 switch (setting) {
5279 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005280 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005281 break;
5282 case DisplayColorSetting::UNMANAGED:
5283 reply->writeBool(true);
5284 break;
5285 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005286 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005287 break;
5288 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005289 reply->writeBool(
5290 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005291 break;
5292 }
5293 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005294 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005295 // Is VrFlinger active?
5296 case 1028: {
5297 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005298 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005299 return NO_ERROR;
5300 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005301 // Is device color managed?
5302 case 1030: {
5303 reply->writeBool(useColorManagement);
5304 return NO_ERROR;
5305 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005306 // Override default composition data space
5307 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5308 // && adb shell stop zygote && adb shell start zygote
5309 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5310 // adb shell stop zygote && adb shell start zygote
5311 case 1031: {
5312 Mutex::Autolock _l(mStateLock);
5313 n = data.readInt32();
5314 if (n) {
5315 n = data.readInt32();
5316 if (n) {
5317 Dataspace dataspace = static_cast<Dataspace>(n);
5318 if (!validateCompositionDataspace(dataspace)) {
5319 return BAD_VALUE;
5320 }
5321 mDefaultCompositionDataspace = dataspace;
5322 }
5323 n = data.readInt32();
5324 if (n) {
5325 Dataspace dataspace = static_cast<Dataspace>(n);
5326 if (!validateCompositionDataspace(dataspace)) {
5327 return BAD_VALUE;
5328 }
5329 mWideColorGamutCompositionDataspace = dataspace;
5330 }
5331 } else {
5332 // restore composition data space.
5333 mDefaultCompositionDataspace = defaultCompositionDataspace;
5334 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5335 }
5336 return NO_ERROR;
5337 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005338 }
5339 }
5340 return err;
5341}
5342
Steven Thomas6d8110b2017-08-31 18:24:21 -07005343void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005344 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005345 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005346}
5347
Ana Krulec7d1d6832018-12-27 11:10:09 -08005348void SurfaceFlinger::repaintEverythingForHWC() {
5349 mRepaintEverything = true;
5350 mEventQueue->invalidateForHWC();
5351}
5352
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005353// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5354class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005355public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005356 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5357 ~WindowDisconnector() {
5358 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005359 }
5360
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005361private:
5362 ANativeWindow* mWindow;
5363 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005364};
5365
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005366status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005367 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5368 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005369 uint32_t reqWidth, uint32_t reqHeight,
5370 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005371 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005372 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005373
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005374 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005375
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005376 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5377
Chia-I Wu20261cb2018-08-23 12:55:44 -07005378 sp<DisplayDevice> display;
5379 {
5380 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005381
Chia-I Wu20261cb2018-08-23 12:55:44 -07005382 display = getDisplayDeviceLocked(displayToken);
5383 if (!display) return BAD_VALUE;
5384
Chia-I Wucb023152018-08-28 12:57:23 -07005385 // set the requested width/height to the logical display viewport size
5386 // by default
5387 if (reqWidth == 0 || reqHeight == 0) {
5388 reqWidth = uint32_t(display->getViewport().width());
5389 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005390 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005391 }
5392
Peiyong Lin0e003c92018-09-17 11:09:51 -07005393 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5394 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005395
5396 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005397 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005398 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5399 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005400}
5401
5402status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005403 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5404 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005405 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005406 ATRACE_CALL();
5407
5408 class LayerRenderArea : public RenderArea {
5409 public:
Robert Carr578038f2018-03-09 12:25:24 -08005410 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005411 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5412 bool childrenOnly)
5413 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005414 mLayer(layer),
5415 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005416 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005417 mFlinger(flinger),
5418 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005419 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005420 Rect getBounds() const override {
5421 const Layer::State& layerState(mLayer->getDrawingState());
5422 return mLayer->getBufferSize(layerState);
5423 }
Marissa Wall61c58622018-07-18 10:12:20 -07005424 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005425 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005426 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005427 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005428 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005429 }
chaviwa76b2712017-09-20 12:02:26 -07005430 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005431 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005432 Rect getSourceCrop() const override {
5433 if (mCrop.isEmpty()) {
5434 return getBounds();
5435 } else {
5436 return mCrop;
5437 }
5438 }
Robert Carr578038f2018-03-09 12:25:24 -08005439 class ReparentForDrawing {
5440 public:
5441 const sp<Layer>& oldParent;
5442 const sp<Layer>& newParent;
5443
5444 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5445 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005446 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005447 }
Robert Carr15eae092018-03-23 13:43:53 -07005448 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005449 };
5450
5451 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005452 const Rect sourceCrop = getSourceCrop();
5453 // no need to check rotation because there is none
5454 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5455 sourceCrop.height() != getReqHeight();
5456
Robert Carr578038f2018-03-09 12:25:24 -08005457 if (!mChildrenOnly) {
5458 mTransform = mLayer->getTransform().inverse();
5459 drawLayers();
5460 } else {
5461 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005462 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005463 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5464 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005465
5466 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5467 drawLayers();
5468 }
5469 }
chaviwa76b2712017-09-20 12:02:26 -07005470
chaviwa76b2712017-09-20 12:02:26 -07005471 private:
chaviw7206d492017-11-10 16:16:12 -08005472 const sp<Layer> mLayer;
5473 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005474
5475 // In the "childrenOnly" case we reparent the children to a screenshot
5476 // layer which has no properties set and which does not draw.
5477 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005478 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005479 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005480
5481 SurfaceFlinger* mFlinger;
5482 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005483 };
5484
5485 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5486 auto parent = layerHandle->owner.promote();
5487
Robert Carr2e102c92018-10-23 12:11:15 -07005488 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005489 ALOGE("captureLayers called with a removed parent");
5490 return NAME_NOT_FOUND;
5491 }
5492
Robert Carr578038f2018-03-09 12:25:24 -08005493 const int uid = IPCThreadState::self()->getCallingUid();
5494 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005495 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005496 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5497 return PERMISSION_DENIED;
5498 }
5499
chaviw7206d492017-11-10 16:16:12 -08005500 Rect crop(sourceCrop);
5501 if (sourceCrop.width() <= 0) {
5502 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005503 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005504 }
5505
5506 if (sourceCrop.height() <= 0) {
5507 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005508 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005509 }
5510
5511 int32_t reqWidth = crop.width() * frameScale;
5512 int32_t reqHeight = crop.height() * frameScale;
5513
Chia-I Wu20261cb2018-08-23 12:55:44 -07005514 // really small crop or frameScale
5515 if (reqWidth <= 0) {
5516 reqWidth = 1;
5517 }
5518 if (reqHeight <= 0) {
5519 reqHeight = 1;
5520 }
5521
Peiyong Lin0e003c92018-09-17 11:09:51 -07005522 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005523
Robert Carr578038f2018-03-09 12:25:24 -08005524 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005525 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5526 if (!layer->isVisible()) {
5527 return;
Robert Carr578038f2018-03-09 12:25:24 -08005528 } else if (childrenOnly && layer == parent.get()) {
5529 return;
chaviwa76b2712017-09-20 12:02:26 -07005530 }
5531 visitor(layer);
5532 });
5533 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005534 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005535}
5536
5537status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5538 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005539 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005540 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005541 bool useIdentityTransform) {
5542 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005543
Peiyong Lin0e003c92018-09-17 11:09:51 -07005544 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005545 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5546 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005547 *outBuffer =
5548 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5549 static_cast<android_pixel_format>(reqPixelFormat), 1,
5550 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005551
5552 // This mutex protects syncFd and captureResult for communication of the return values from the
5553 // main thread back to this Binder thread
5554 std::mutex captureMutex;
5555 std::condition_variable captureCondition;
5556 std::unique_lock<std::mutex> captureLock(captureMutex);
5557 int syncFd = -1;
5558 std::optional<status_t> captureResult;
5559
Robert Carr03480e22018-01-04 16:02:06 -08005560 const int uid = IPCThreadState::self()->getCallingUid();
5561 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5562
Dominik Laskowski8c001672018-05-30 16:52:06 -07005563 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005564 // If there is a refresh pending, bug out early and tell the binder thread to try again
5565 // after the refresh.
5566 if (mRefreshPending) {
5567 ATRACE_NAME("Skipping screenshot for now");
5568 std::unique_lock<std::mutex> captureLock(captureMutex);
5569 captureResult = std::make_optional<status_t>(EAGAIN);
5570 captureCondition.notify_one();
5571 return;
5572 }
5573
5574 status_t result = NO_ERROR;
5575 int fd = -1;
5576 {
5577 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005578 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005579 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5580 useIdentityTransform, forSystem, &fd);
5581 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005582 }
5583
5584 {
5585 std::unique_lock<std::mutex> captureLock(captureMutex);
5586 syncFd = fd;
5587 captureResult = std::make_optional<status_t>(result);
5588 captureCondition.notify_one();
5589 }
5590 });
5591
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005592 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005593 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005594 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005595 while (*captureResult == EAGAIN) {
5596 captureResult.reset();
5597 result = postMessageAsync(message);
5598 if (result != NO_ERROR) {
5599 return result;
5600 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005601 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005602 }
5603 result = *captureResult;
5604 }
5605
5606 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005607 sync_wait(syncFd, -1);
5608 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005609 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005610
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005611 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005612}
5613
chaviwa76b2712017-09-20 12:02:26 -07005614void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005615 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005616 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005617 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005618
Lloyd Pique144e1162017-12-20 16:44:52 -08005619 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005620
chaviwa76b2712017-09-20 12:02:26 -07005621 const auto reqWidth = renderArea.getReqWidth();
5622 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005623 const auto sourceCrop = renderArea.getSourceCrop();
5624 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005625
Peiyong Lin0e003c92018-09-17 11:09:51 -07005626 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005627 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005628
Mathias Agopian180f10d2013-04-10 22:55:41 -07005629 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005630 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005631
5632 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005633 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005634 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005635
chaviw50da5042018-04-09 13:49:37 -07005636 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005637 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005638 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005639
chaviwa76b2712017-09-20 12:02:26 -07005640 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005641 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005642 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005643 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005644 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005645}
5646
chaviwa76b2712017-09-20 12:02:26 -07005647status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5648 TraverseLayersFunction traverseLayers,
5649 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005650 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005651 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005652 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005653 ATRACE_CALL();
5654
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005655 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005656
5657 traverseLayers([&](Layer* layer) {
5658 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5659 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005660
Robert Carr03480e22018-01-04 16:02:06 -08005661 // We allow the system server to take screenshots of secure layers for
5662 // use in situations like the Screen-rotation animation and place
5663 // the impetus on WindowManager to not persist them.
5664 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005665 ALOGW("FB is protected: PERMISSION_DENIED");
5666 return PERMISSION_DENIED;
5667 }
Peiyong Linfb530cf2018-12-15 05:07:38 +00005668 auto& engine(getRenderEngine());
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005669
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005670 // this binds the given EGLImage as a framebuffer for the
5671 // duration of this scope.
Peiyong Linfb530cf2018-12-15 05:07:38 +00005672 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005673 if (bufferBond.getStatus() != NO_ERROR) {
5674 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005675 return INVALID_OPERATION;
5676 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005677
Dan Stozaabcda352017-06-01 14:37:39 -07005678 // this will in fact render into our dequeued buffer
5679 // via an FBO, which means we didn't have to create
5680 // an EGLSurface and therefore we're not
5681 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005682 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005683
Peiyong Linfb530cf2018-12-15 05:07:38 +00005684 base::unique_fd syncFd = engine.flush();
Alec Mouri492bc572018-09-11 21:40:04 +00005685 if (syncFd < 0) {
Peiyong Linfb530cf2018-12-15 05:07:38 +00005686 engine.finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005687 }
Alec Mouri492bc572018-09-11 21:40:04 +00005688 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005689
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005690 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005691}
5692
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005693// ---------------------------------------------------------------------------
5694
Dan Stoza412903f2017-04-27 13:42:17 -07005695void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5696 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005697}
5698
Dan Stoza412903f2017-04-27 13:42:17 -07005699void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5700 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005701}
5702
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005703void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005704 const LayerVector::Visitor& visitor) {
5705 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005706 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005707 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005708 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005709 continue;
5710 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005711 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005712 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005713 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005714 return;
5715 }
chaviwa76b2712017-09-20 12:02:26 -07005716 if (!layer->isVisible()) {
5717 return;
5718 }
5719 visitor(layer);
5720 });
5721 }
5722}
5723
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005724}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005725
Lloyd Pique074e8122018-07-26 12:57:23 -07005726
Mathias Agopian3f844832013-08-07 21:24:32 -07005727#if defined(__gl_h_)
5728#error "don't include gl/gl.h in this file"
5729#endif
5730
5731#if defined(__gl2_h_)
5732#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005733#endif