blob: 137d91bf2b165bd13efa5fc46c2d38726113f44e [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
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Chia-I Wud49d6692018-06-27 07:17:41 +080040#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070050#include <renderengine/RenderEngine.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070051#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Robert Carr578038f2018-03-09 12:25:24 -080065#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070066#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070067#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020070#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080072#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080073#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070077#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070078#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070080#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081
Steven Thomasb02664d2017-07-26 18:48:28 -070082#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070083#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070084#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070085#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070086#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070087#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070088#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070089#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070090#include "Scheduler/EventControlThread.h"
91#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070092#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070093#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070094#include "Scheduler/Scheduler.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070095
Mathias Agopianff2ed702013-09-01 21:36:12 -070096#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070097
David Sodman7e4ae112018-02-09 15:02:28 -080098#include "android-base/stringprintf.h"
99
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900100#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800101#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700102#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800103#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900104#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900105
chaviw1d044282017-09-27 12:19:28 -0700106#include <layerproto/LayerProtoParser.h>
107
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800108namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700109
Jaesoo Lee43518572017-01-23 19:03:16 +0900110using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900111using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700112using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700113using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700114using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700115using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900116
Steven Thomasb02664d2017-07-26 18:48:28 -0700117namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700118
119#pragma clang diagnostic push
120#pragma clang diagnostic error "-Wswitch-enum"
121
122bool isWideColorMode(const ColorMode colorMode) {
123 switch (colorMode) {
124 case ColorMode::DISPLAY_P3:
125 case ColorMode::ADOBE_RGB:
126 case ColorMode::DCI_P3:
127 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700128 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700129 case ColorMode::BT2100_PQ:
130 case ColorMode::BT2100_HLG:
131 return true;
132 case ColorMode::NATIVE:
133 case ColorMode::STANDARD_BT601_625:
134 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
135 case ColorMode::STANDARD_BT601_525:
136 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
137 case ColorMode::STANDARD_BT709:
138 case ColorMode::SRGB:
139 return false;
140 }
141 return false;
142}
143
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700144ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
145 switch (rotation) {
146 case ISurfaceComposer::eRotateNone:
147 return ui::Transform::ROT_0;
148 case ISurfaceComposer::eRotate90:
149 return ui::Transform::ROT_90;
150 case ISurfaceComposer::eRotate180:
151 return ui::Transform::ROT_180;
152 case ISurfaceComposer::eRotate270:
153 return ui::Transform::ROT_270;
154 }
155 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
156 return ui::Transform::ROT_0;
157}
158
Peiyong Linfca547f2018-07-09 13:03:33 -0700159#pragma clang diagnostic pop
160
Steven Thomasb02664d2017-07-26 18:48:28 -0700161class ConditionalLock {
162public:
163 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
164 if (lock) {
165 mMutex.lock();
166 }
167 }
168 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
169private:
170 Mutex& mMutex;
171 bool mLocked;
172};
Peiyong Linfca547f2018-07-09 13:03:33 -0700173
Steven Thomasb02664d2017-07-26 18:48:28 -0700174} // namespace anonymous
175
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800176// ---------------------------------------------------------------------------
177
Mathias Agopian99b49842011-06-27 16:05:52 -0700178const String16 sHardwareTest("android.permission.HARDWARE_TEST");
179const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
180const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
181const String16 sDump("android.permission.DUMP");
182
183// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800184int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
185int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700186int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700187bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800188uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800189bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800190bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800191int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800192// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600193bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700194int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700195bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700196bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700197Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
198ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
199Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
200ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700201
Kalle Raitaa099a242017-01-11 11:17:29 -0800202std::string getHwcServiceName() {
203 char value[PROPERTY_VALUE_MAX] = {};
204 property_get("debug.sf.hwc_service_name", value, "default");
205 ALOGI("Using HWComposer service: '%s'", value);
206 return std::string(value);
207}
208
209bool useTrebleTestingOverride() {
210 char value[PROPERTY_VALUE_MAX] = {};
211 property_get("debug.sf.treble_testing_override", value, "false");
212 ALOGI("Treble testing override: '%s'", value);
213 return std::string(value) == "true";
214}
215
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800216std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
217 switch(displayColorSetting) {
218 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700219 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800220 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700221 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800222 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700223 return std::string("Enhanced");
224 default:
225 return std::string("Unknown ") +
226 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800227 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800228}
229
David Sodmanbc815282017-11-05 18:57:52 -0800230SurfaceFlingerBE::SurfaceFlingerBE()
231 : mHwcServiceName(getHwcServiceName()),
232 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800233 mFrameBuckets(),
234 mTotalTime(0),
235 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800236 mComposerSequenceId(0) {
237}
238
Lloyd Pique90c115d2018-09-18 21:39:42 -0700239SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
240 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800241 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700242 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700243 mTransactionPending(false),
244 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700245 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700246 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800247 mBootTime(systemTime()),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800248 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800249 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800250 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800251 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800252 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700253 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700254 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700255 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700256 mDebugInTransaction(0),
257 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700258 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700259 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700260 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800261 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800262 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800263 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700264 mVrFlingerRequestsDisplay(false),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700265 mMainThreadId(std::this_thread::get_id()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800266
Lloyd Pique90c115d2018-09-18 21:39:42 -0700267SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
268 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800269 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800270
271 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
272 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
273
274 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
275 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
276
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800277 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
278 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800279
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700280 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
281 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
282
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700283 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
284 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
285
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800286 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
287 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
288
Steven Thomas050b2c82017-03-06 11:45:16 -0800289 // Vr flinger is only enabled on Daydream ready devices.
290 useVrFlinger = getBool< ISurfaceFlingerConfigs,
291 &ISurfaceFlingerConfigs::useVrFlinger>(false);
292
Fabien Sanglard1971b632017-03-10 14:50:03 -0800293 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
294 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
295
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600296 hasWideColorDisplay =
297 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700298 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700299 getBool<V1_2::ISurfaceFlingerConfigs,
300 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
301
302 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
303 if (surfaceFlingerConfigsServiceV1_2) {
304 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
Peiyong Linc6780972018-10-28 15:24:08 -0700305 [&](auto tmpDefaultDataspace, auto tmpDefaultPixelFormat,
306 auto tmpWideColorGamutDataspace, auto tmpWideColorGamutPixelFormat) {
307 defaultCompositionDataspace = tmpDefaultDataspace;
308 defaultCompositionPixelFormat = tmpDefaultPixelFormat;
309 wideColorGamutCompositionDataspace = tmpWideColorGamutDataspace;
310 wideColorGamutCompositionPixelFormat = tmpWideColorGamutPixelFormat;
311 });
Peiyong Lin0256f722018-08-31 15:45:10 -0700312 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600313
Peiyong Linb3839ad2018-09-05 15:37:19 -0700314 useContextPriority = getBool<ISurfaceFlingerConfigs,
315 &ISurfaceFlingerConfigs::useContextPriority>(true);
316
Iris Chang7501ed62018-04-30 14:45:42 +0800317 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700318 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
319 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800320 V1_1::DisplayOrientation::ORIENTATION_0);
321
322 switch (primaryDisplayOrientation) {
323 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700324 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800325 break;
326 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700327 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800328 break;
329 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700330 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800331 break;
332 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700333 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800334 break;
335 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700336 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800337
Lloyd Pique90c115d2018-09-18 21:39:42 -0700338 mPrimaryDispSync =
339 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
340 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700341
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800342 // debugging stuff...
343 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700344
Mathias Agopianb4b17302013-03-20 18:36:41 -0700345 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700346 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700347
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800348 property_get("debug.sf.showupdates", value, "0");
349 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700350
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700351 property_get("debug.sf.ddms", value, "0");
352 mDebugDDMS = atoi(value);
353 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700354 if (!startDdmConnection()) {
355 // start failed, and DDMS debugging not enabled
356 mDebugDDMS = 0;
357 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700358 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700359 ALOGI_IF(mDebugRegion, "showupdates enabled");
360 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700361
362 property_get("debug.sf.disable_backpressure", value, "0");
363 mPropagateBackpressure = !atoi(value);
364 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700365
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800366 property_get("debug.sf.enable_hwc_vds", value, "0");
367 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800368 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800369
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800370 property_get("ro.sf.disable_triple_buffer", value, "1");
371 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800372 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700373
Yiwei Zhang243b3782018-05-15 17:40:04 -0700374 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700375 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
376 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
377
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200378 property_get("debug.sf.early_phase_offset_ns", value, "-1");
379 const int earlySfOffsetNs = atoi(value);
380
381 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
382 const int earlyGlSfOffsetNs = atoi(value);
383
384 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
385 const int earlyAppOffsetNs = atoi(value);
386
387 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
388 const int earlyGlAppOffsetNs = atoi(value);
389
Ana Krulec98b5b242018-08-10 15:03:23 -0700390 property_get("debug.sf.use_scheduler", value, "0");
391 mUseScheduler = atoi(value);
392
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200393 const VSyncModulator::Offsets earlyOffsets =
394 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
395 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
396 const VSyncModulator::Offsets earlyGlOffsets =
397 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
398 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
399 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
400 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700401
Romain Guy11d63f42017-07-20 12:47:14 -0700402 // We should be reading 'persist.sys.sf.color_saturation' here
403 // but since /data may be encrypted, we need to wait until after vold
404 // comes online to attempt to read the property. The property is
405 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800406
407 if (useTrebleTestingOverride()) {
408 // Without the override SurfaceFlinger cannot connect to HIDL
409 // services that are not listed in the manifests. Considered
410 // deriving the setting from the set service name, but it
411 // would be brittle if the name that's not 'default' is used
412 // for production purposes later on.
413 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
414 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800415}
416
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800417void SurfaceFlinger::onFirstRef()
418{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800419 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800420}
421
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800422SurfaceFlinger::~SurfaceFlinger()
423{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800424}
425
Dan Stozac7014012014-02-14 15:03:43 -0800426void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800427{
428 // the window manager died on us. prepare its eulogy.
429
Andy McFadden13a082e2012-08-24 10:16:42 -0700430 // restore initial conditions (default device unblank, etc)
431 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800432
433 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700434 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800435}
436
Robert Carr1db73f62016-12-21 12:58:51 -0800437static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700438 status_t err = client->initCheck();
439 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800440 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800441 }
Robert Carr1db73f62016-12-21 12:58:51 -0800442 return nullptr;
443}
444
445sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
446 return initClient(new Client(this));
447}
448
449sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
450 const sp<IGraphicBufferProducer>& gbp) {
451 if (authenticateSurfaceTexture(gbp) == false) {
452 return nullptr;
453 }
454 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
455 if (layer == nullptr) {
456 return nullptr;
457 }
458
459 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800460}
461
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700462sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
463 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700464{
465 class DisplayToken : public BBinder {
466 sp<SurfaceFlinger> flinger;
467 virtual ~DisplayToken() {
468 // no more references, this display must be terminated
469 Mutex::Autolock _l(flinger->mStateLock);
470 flinger->mCurrentState.displays.removeItem(this);
471 flinger->setTransactionFlags(eDisplayTransactionNeeded);
472 }
473 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700474 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700475 : flinger(flinger) {
476 }
477 };
478
479 sp<BBinder> token = new DisplayToken(this);
480
481 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700482 // Display ID is assigned when virtual display is allocated by HWC.
483 DisplayDeviceState state;
484 state.isSecure = secure;
485 state.displayName = displayName;
486 mCurrentState.displays.add(token, state);
487 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700488 return token;
489}
490
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700491void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700492 Mutex::Autolock _l(mStateLock);
493
Dominik Laskowski075d3172018-05-24 15:50:06 -0700494 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
495 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700496 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700497 return;
498 }
499
Dominik Laskowski075d3172018-05-24 15:50:06 -0700500 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
501 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700502 ALOGE("destroyDisplay called for non-virtual display");
503 return;
504 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700505 mInterceptor->saveDisplayDeletion(state.sequenceId);
506 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700507 setTransactionFlags(eDisplayTransactionNeeded);
508}
509
Mathias Agopiane57f2922012-08-09 16:29:12 -0700510sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700511 std::optional<DisplayId> displayId;
512
513 if (id == HWC_DISPLAY_PRIMARY) {
514 displayId = getInternalDisplayId();
515 } else if (id == HWC_DISPLAY_EXTERNAL) {
516 displayId = getExternalDisplayId();
517 }
518
519 if (!displayId) {
520 ALOGE("%s: Invalid display %d", __FUNCTION__, id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800521 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700522 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700523
524 return getPhysicalDisplayToken(*displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700525}
526
Ady Abraham37965d42018-11-01 13:43:32 -0700527status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
528 if (!outGetColorManagement) {
529 return BAD_VALUE;
530 }
531 *outGetColorManagement = useColorManagement;
532 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700533}
534
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800535void SurfaceFlinger::bootFinished()
536{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700537 if (mStartPropertySetThread->join() != NO_ERROR) {
538 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800539 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800540 const nsecs_t now = systemTime();
541 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000542 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700543
544 // wait patiently for the window manager death
545 const String16 name("window");
546 sp<IBinder> window(defaultServiceManager()->getService(name));
547 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700548 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700549 }
550
Steven Thomas050b2c82017-03-06 11:45:16 -0800551 if (mVrFlinger) {
552 mVrFlinger->OnBootFinished();
553 }
554
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700555 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700556 // formerly we would just kill the process, but we now ask it to exit so it
557 // can choose where to stop the animation.
558 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700559
560 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
561 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
562 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700563
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800564 postMessageAsync(new LambdaMessage([this] {
565 readPersistentProperties();
566 mBootStage = BootStage::FINISHED;
567 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800568}
569
Dan Stoza436ccf32018-06-21 12:10:12 -0700570uint32_t SurfaceFlinger::getNewTexture() {
571 {
572 std::lock_guard lock(mTexturePoolMutex);
573 if (!mTexturePool.empty()) {
574 uint32_t name = mTexturePool.back();
575 mTexturePool.pop_back();
576 ATRACE_INT("TexturePoolSize", mTexturePool.size());
577 return name;
578 }
579
580 // The pool was too small, so increase it for the future
581 ++mTexturePoolSize;
582 }
583
584 // The pool was empty, so we need to get a new texture name directly using a
585 // blocking call to the main thread
586 uint32_t name = 0;
587 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
588 return name;
589}
590
Mathias Agopian3f844832013-08-07 21:24:32 -0700591void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700592 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700593}
594
Wei Wangf9b05ee2017-07-19 20:59:39 -0700595// Do not call property_set on main thread which will be blocked by init
596// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700597void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700598 ALOGI( "SurfaceFlinger's main thread ready to run. "
599 "Initializing graphics H/W...");
600
Thierry Strudel2924d012017-08-14 15:19:37 -0700601 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900602
Steven Thomasb02664d2017-07-26 18:48:28 -0700603 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800604
Steven Thomasb02664d2017-07-26 18:48:28 -0700605 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700606 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700607 mScheduler = getFactory().createScheduler([this](bool enabled) {
608 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
609 });
610
Ana Krulec98b5b242018-08-10 15:03:23 -0700611 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700612 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700613 [this] { resyncWithRateLimit(); },
614 impl::EventThread::InterceptVSyncsCallback());
615 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700616 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700617 [this] { resyncWithRateLimit(); },
618 [this](nsecs_t timestamp) {
619 mInterceptor->saveVSyncEvent(timestamp);
620 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800621
Ana Krulec98b5b242018-08-10 15:03:23 -0700622 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700623 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
624 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700625 } else {
626 mEventThreadSource =
627 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
628 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
629 mEventThread =
630 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
631 [this] { resyncWithRateLimit(); },
632 impl::EventThread::InterceptVSyncsCallback(),
633 "appEventThread");
634 mSfEventThreadSource =
635 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
636 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
637
638 mSFEventThread =
639 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
640 [this] { resyncWithRateLimit(); },
641 [this](nsecs_t timestamp) {
642 mInterceptor->saveVSyncEvent(timestamp);
643 },
644 "sfEventThread");
645 mEventQueue->setEventThread(mSFEventThread.get());
646 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
647 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800648
Steven Thomasb02664d2017-07-26 18:48:28 -0700649 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700650 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700651 renderEngineFeature |= (useColorManagement ?
652 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700653 renderEngineFeature |= (useContextPriority ?
654 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700655
656 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
657 getBE().mRenderEngine =
Peiyong Linc6780972018-10-28 15:24:08 -0700658 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
659 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800660 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700661
662 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
663 "Starting with vr flinger active is not currently supported.");
Lloyd Pique90c115d2018-09-18 21:39:42 -0700664 getBE().mHwc = getFactory().createHWComposer(getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -0700665 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800666 // Process any initial hotplug and resulting display changes.
667 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700668 const auto display = getDefaultDisplayDeviceLocked();
669 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700670 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700671 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800672
Lloyd Piquefcd86612017-12-14 17:15:36 -0800673 // make the default display GLContext current so that we can create textures
674 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700675 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800676
Steven Thomas050b2c82017-03-06 11:45:16 -0800677 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700678 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700679 // This callback is called from the vr flinger dispatch thread. We
680 // need to call signalTransaction(), which requires holding
681 // mStateLock when we're not on the main thread. Acquiring
682 // mStateLock from the vr flinger dispatch thread might trigger a
683 // deadlock in surface flinger (see b/66916578), so post a message
684 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700685 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700686 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
687 mVrFlingerRequestsDisplay = requestDisplay;
688 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700689 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800690 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700691 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
692 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700693 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700694 .value_or(0),
695 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800696 if (!mVrFlinger) {
697 ALOGE("Failed to start vrflinger");
698 }
699 }
700
Lloyd Pique90c115d2018-09-18 21:39:42 -0700701 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700702 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700703
Mathias Agopian92a979a2012-08-02 18:32:23 -0700704 // initialize our drawing state
705 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700706
Andy McFadden13a082e2012-08-24 10:16:42 -0700707 // set initial conditions (e.g. unblank default device)
708 initializeDisplays();
709
David Sodmanbc815282017-11-05 18:57:52 -0800710 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700711
Wei Wangf9b05ee2017-07-19 20:59:39 -0700712 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700713
714 const bool presentFenceReliable =
715 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
716 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700717
718 if (mStartPropertySetThread->Start() != NO_ERROR) {
719 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800720 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800721
Chia-I Wud49d6692018-06-27 07:17:41 +0800722 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
723 // is used to saturate legacy sRGB content. However, to make sure the same color under
724 // Display P3 will be saturated to the same color, we intentionally break the API spec
725 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
726 // such saturation matrix on Display P3 is understood fully, the API should always return
727 // identify matrix.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700728 mEnhancedSaturationMatrix =
729 getHwComposer().getDataspaceSaturationMatrix(*display->getId(), Dataspace::SRGB_LINEAR);
Chia-I Wud49d6692018-06-27 07:17:41 +0800730
731 // we will apply this on Display P3.
732 if (mEnhancedSaturationMatrix != mat4()) {
733 ColorSpace srgb(ColorSpace::sRGB());
734 ColorSpace displayP3(ColorSpace::DisplayP3());
735 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
736 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
737 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
738 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800739
Dan Stoza9e56aa02015-11-02 13:00:03 -0800740 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700741}
742
Romain Guy11d63f42017-07-20 12:47:14 -0700743void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700744 Mutex::Autolock _l(mStateLock);
745
Romain Guy11d63f42017-07-20 12:47:14 -0700746 char value[PROPERTY_VALUE_MAX];
747
748 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800749 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700750 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800751 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100752
753 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700754 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700755}
756
Mathias Agopiana67e4182012-06-19 17:26:12 -0700757void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800758 // Start boot animation service by setting a property mailbox
759 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700760 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800761 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700762 if (mStartPropertySetThread->join() != NO_ERROR) {
763 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800764 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700765}
766
Mathias Agopian875d8e12013-06-07 15:35:48 -0700767size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800768 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700769}
770
Mathias Agopian875d8e12013-06-07 15:35:48 -0700771size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800772 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700773}
774
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800775// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800776
Jamie Gennis582270d2011-08-17 18:19:00 -0700777bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800778 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800779 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800780 return authenticateSurfaceTextureLocked(bufferProducer);
781}
782
783bool SurfaceFlinger::authenticateSurfaceTextureLocked(
784 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800785 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800786 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800787}
788
Brian Anderson6b376712017-04-04 10:51:39 -0700789status_t SurfaceFlinger::getSupportedFrameTimestamps(
790 std::vector<FrameEvent>* outSupported) const {
791 *outSupported = {
792 FrameEvent::REQUESTED_PRESENT,
793 FrameEvent::ACQUIRE,
794 FrameEvent::LATCH,
795 FrameEvent::FIRST_REFRESH_START,
796 FrameEvent::LAST_REFRESH_START,
797 FrameEvent::GPU_COMPOSITION_DONE,
798 FrameEvent::DEQUEUE_READY,
799 FrameEvent::RELEASE,
800 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700801 ConditionalLock _l(mStateLock,
802 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700803 if (!getHwComposer().hasCapability(
804 HWC2::Capability::PresentFenceIsNotReliable)) {
805 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
806 }
807 return NO_ERROR;
808}
809
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700810status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
811 Vector<DisplayInfo>* configs) {
812 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700813 return BAD_VALUE;
814 }
815
Dominik Laskowski075d3172018-05-24 15:50:06 -0700816 const auto displayId = getPhysicalDisplayId(displayToken);
817 if (!displayId) {
818 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700819 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700820
Mathias Agopian8b736f12012-08-13 17:54:26 -0700821 // TODO: Not sure if display density should handled by SF any longer
822 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700823 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700824 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700825 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800826 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700827 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700828 }
829 return density;
830 }
831 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700832 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700833 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700834 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700835 return getDensityFromProperty("ro.sf.lcd_density"); }
836 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700837
Dan Stoza7f7da322014-05-02 15:26:25 -0700838 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700839
Steven Thomas6d8110b2017-08-31 18:24:21 -0700840 ConditionalLock _l(mStateLock,
841 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700842 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700843 DisplayInfo info = DisplayInfo();
844
Dan Stoza9e56aa02015-11-02 13:00:03 -0800845 float xdpi = hwConfig->getDpiX();
846 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700847
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700848 info.w = hwConfig->getWidth();
849 info.h = hwConfig->getHeight();
850 // Default display viewport to display width and height
851 info.viewportW = info.w;
852 info.viewportH = info.h;
853
Dominik Laskowski075d3172018-05-24 15:50:06 -0700854 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700855 // The density of the device is provided by a build property
856 float density = Density::getBuildDensity() / 160.0f;
857 if (density == 0) {
858 // the build doesn't provide a density -- this is wrong!
859 // use xdpi instead
860 ALOGE("ro.sf.lcd_density must be defined as a build property");
861 density = xdpi / 160.0f;
862 }
863 if (Density::getEmuDensity()) {
864 // if "qemu.sf.lcd_density" is specified, it overrides everything
865 xdpi = ydpi = density = Density::getEmuDensity();
866 density /= 160.0f;
867 }
868 info.density = density;
869
870 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700871 const auto display = getDefaultDisplayDeviceLocked();
872 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700873
874 // This is for screenrecord
875 const Rect viewport = display->getViewport();
876 if (viewport.isValid()) {
877 info.viewportW = uint32_t(viewport.getWidth());
878 info.viewportH = uint32_t(viewport.getHeight());
879 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700880 } else {
881 // TODO: where should this value come from?
882 static const int TV_DENSITY = 213;
883 info.density = TV_DENSITY / 160.0f;
884 info.orientation = 0;
885 }
886
Dan Stoza7f7da322014-05-02 15:26:25 -0700887 info.xdpi = xdpi;
888 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800889 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900890 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800891
Andy McFadden91b2ca82014-06-13 14:04:23 -0700892 // This is how far in advance a buffer must be queued for
893 // presentation at a given time. If you want a buffer to appear
894 // on the screen at time N, you must submit the buffer before
895 // (N - presentationDeadline).
896 //
897 // Normally it's one full refresh period (to give SF a chance to
898 // latch the buffer), but this can be reduced by configuring a
899 // DispSync offset. Any additional delays introduced by the hardware
900 // composer or panel must be accounted for here.
901 //
902 // We add an additional 1ms to allow for processing time and
903 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800904 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800905 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700906
907 // All non-virtual displays are currently considered secure.
908 info.secure = true;
909
Dominik Laskowski075d3172018-05-24 15:50:06 -0700910 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700911 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800912 std::swap(info.w, info.h);
913 }
914
Michael Wright28f24d02016-07-12 13:30:53 -0700915 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700916 }
917
Dan Stoza7f7da322014-05-02 15:26:25 -0700918 return NO_ERROR;
919}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700920
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700921status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
922 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700923 return BAD_VALUE;
924 }
925
Ana Krulece588e312018-09-18 12:32:24 -0700926 if (mUseScheduler) {
927 mScheduler->getDisplayStatInfo(stats);
928 } else {
929 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
930 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
931 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700932 return NO_ERROR;
933}
934
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700935int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
936 const auto display = getDisplayDevice(displayToken);
937 if (!display) {
938 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800939 return BAD_VALUE;
940 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700941
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700942 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700943}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700944
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700945void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700946 if (display->isVirtual()) {
947 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
948 return;
949 }
950
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700951 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700952 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700953 return;
954 }
955
Dominik Laskowski075d3172018-05-24 15:50:06 -0700956 const auto displayId = display->getId();
957 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700958
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700959 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700960 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700961}
962
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700963status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700964 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700965 Vector<DisplayInfo> configs;
966 getDisplayConfigs(displayToken, &configs);
967 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
968 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
969 configs.size());
970 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700971 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700972 const auto display = getDisplayDevice(displayToken);
973 if (!display) {
974 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
975 displayToken.get());
976 } else if (display->isVirtual()) {
977 ALOGW("Attempt to set active config %d for virtual display", mode);
978 } else {
979 setActiveConfigInternal(display, mode);
980 }
981 }));
982
Mathias Agopian888c8222012-08-04 21:10:38 -0700983 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700984}
Dominik Laskowski075d3172018-05-24 15:50:06 -0700985
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700986status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
987 Vector<ColorMode>* outColorModes) {
988 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700989 return BAD_VALUE;
990 }
991
Dominik Laskowski075d3172018-05-24 15:50:06 -0700992 const auto displayId = getPhysicalDisplayId(displayToken);
993 if (!displayId) {
994 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -0700995 }
996
Peiyong Lina52f0292018-03-14 17:26:31 -0700997 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700998 {
999 ConditionalLock _l(mStateLock,
1000 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001001 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001002 }
Michael Wright28f24d02016-07-12 13:30:53 -07001003 outColorModes->clear();
1004 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1005
1006 return NO_ERROR;
1007}
1008
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001009ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1010 if (const auto display = getDisplayDevice(displayToken)) {
1011 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001012 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001013 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001014}
1015
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001016void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1017 Dataspace dataSpace, RenderIntent renderIntent) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001018 if (display->isVirtual()) {
1019 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
1020 return;
1021 }
1022
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001023 ColorMode currentMode = display->getActiveColorMode();
1024 Dataspace currentDataSpace = display->getCompositionDataSpace();
1025 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001026
Peiyong Lin38e9a562018-04-10 16:24:20 -07001027 if (mode == currentMode && dataSpace == currentDataSpace &&
1028 renderIntent == currentRenderIntent) {
1029 return;
1030 }
1031
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001032 display->setActiveColorMode(mode);
1033 display->setCompositionDataSpace(dataSpace);
1034 display->setActiveRenderIntent(renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001035
Dominik Laskowski075d3172018-05-24 15:50:06 -07001036 const auto displayId = display->getId();
1037 LOG_ALWAYS_FATAL_IF(!displayId);
1038 getHwComposer().setActiveColorMode(*displayId, mode, renderIntent);
1039
1040 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), display=%" PRIu64,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001041 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
Dominik Laskowski075d3172018-05-24 15:50:06 -07001042 renderIntent, *displayId);
Michael Wright28f24d02016-07-12 13:30:53 -07001043}
1044
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001045status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001046 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001047 Vector<ColorMode> modes;
1048 getDisplayColorModes(displayToken, &modes);
1049 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1050 if (mode < ColorMode::NATIVE || !exists) {
1051 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1052 decodeColorMode(mode).c_str(), mode, displayToken.get());
1053 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001054 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001055 const auto display = getDisplayDevice(displayToken);
1056 if (!display) {
1057 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1058 decodeColorMode(mode).c_str(), mode, displayToken.get());
1059 } else if (display->isVirtual()) {
1060 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1061 decodeColorMode(mode).c_str(), mode);
1062 } else {
1063 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1064 RenderIntent::COLORIMETRIC);
1065 }
1066 }));
1067
Michael Wright28f24d02016-07-12 13:30:53 -07001068 return NO_ERROR;
1069}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001070
Svetoslavd85084b2014-03-20 10:28:31 -07001071status_t SurfaceFlinger::clearAnimationFrameStats() {
1072 Mutex::Autolock _l(mStateLock);
1073 mAnimFrameTracker.clearStats();
1074 return NO_ERROR;
1075}
1076
1077status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1078 Mutex::Autolock _l(mStateLock);
1079 mAnimFrameTracker.getStats(outStats);
1080 return NO_ERROR;
1081}
1082
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001083status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1084 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001085 Mutex::Autolock _l(mStateLock);
1086
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001087 const auto display = getDisplayDeviceLocked(displayToken);
1088 if (!display) {
1089 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001090 return BAD_VALUE;
1091 }
1092
Peiyong Linfb069302018-04-25 14:34:31 -07001093 // At this point the DisplayDeivce should already be set up,
1094 // meaning the luminance information is already queried from
1095 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001096 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001097 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1098 capabilities.getDesiredMaxLuminance(),
1099 capabilities.getDesiredMaxAverageLuminance(),
1100 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001101
1102 return NO_ERROR;
1103}
1104
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001105status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001106 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001107 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001108
Chia-I Wu90f669f2017-10-05 14:24:41 -07001109 if (mInjectVSyncs == enable) {
1110 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001111 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001112
Ana Krulec98b5b242018-08-10 15:03:23 -07001113 // TODO(akrulec): Part of the Injector should be refactored, so that it
1114 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001115 if (enable) {
1116 ALOGV("VSync Injections enabled");
1117 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001118 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001119 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001120 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001121 impl::EventThread::InterceptVSyncsCallback(),
1122 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001123 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001124 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001125 } else {
1126 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001127 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001128 }
1129
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001130 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001131 }));
1132
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001133 return NO_ERROR;
1134}
1135
1136status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001137 Mutex::Autolock _l(mStateLock);
1138
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001139 if (!mInjectVSyncs) {
1140 ALOGE("VSync Injections not enabled");
1141 return BAD_VALUE;
1142 }
1143 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1144 ALOGV("Injecting VSync inside SurfaceFlinger");
1145 mVSyncInjector->onInjectSyncEvent(when);
1146 }
1147 return NO_ERROR;
1148}
1149
Lloyd Pique755e3192018-01-31 16:46:15 -08001150status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1151 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001152 // Try to acquire a lock for 1s, fail gracefully
1153 const status_t err = mStateLock.timedLock(s2ns(1));
1154 const bool locked = (err == NO_ERROR);
1155 if (!locked) {
1156 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1157 return TIMED_OUT;
1158 }
1159
1160 outLayers->clear();
1161 mCurrentState.traverseInZOrder([&](Layer* layer) {
1162 outLayers->push_back(layer->getLayerDebugInfo());
1163 });
1164
1165 mStateLock.unlock();
1166 return NO_ERROR;
1167}
1168
Peiyong Linc6780972018-10-28 15:24:08 -07001169status_t SurfaceFlinger::getCompositionPreference(
1170 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1171 Dataspace* outWideColorGamutDataspace,
1172 ui::PixelFormat* outWideColorGamutPixelFormat) const {
1173 *outDataspace = defaultCompositionDataspace;
1174 *outPixelFormat = defaultCompositionPixelFormat;
1175 *outWideColorGamutDataspace = wideColorGamutCompositionDataspace;
1176 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001177 return NO_ERROR;
1178}
1179
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001180// ----------------------------------------------------------------------------
1181
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001182sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1183 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001184 if (mUseScheduler) {
1185 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1186 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1187 } else {
1188 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1189 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001190 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001191 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1192 return mSFEventThread->createEventConnection();
1193 } else {
1194 return mEventThread->createEventConnection();
1195 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001196 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001197}
1198
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001199// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001200
1201void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001202 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001203}
1204
1205void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001206 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001207}
1208
1209void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001210 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001211}
1212
1213void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001214 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001215 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001216}
1217
1218status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001219 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001220 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001221}
1222
1223status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001224 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001225 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001226 if (res == NO_ERROR) {
1227 msg->wait();
1228 }
1229 return res;
1230}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001231
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001232void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001233 do {
1234 waitForEvent();
1235 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001236}
1237
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001238void SurfaceFlinger::enableHardwareVsync() {
1239 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001240 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001241 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001242 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001243 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001244 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001245}
1246
Jesse Hall948fe0c2013-10-14 12:56:09 -07001247void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001248 Mutex::Autolock _l(mHWVsyncLock);
1249
Jesse Hall948fe0c2013-10-14 12:56:09 -07001250 if (makeAvailable) {
1251 mHWVsyncAvailable = true;
1252 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001253 // Hardware vsync is not currently available, so abort the resync
1254 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001255 return;
1256 }
1257
Dominik Laskowski075d3172018-05-24 15:50:06 -07001258 const auto displayId = getInternalDisplayId();
1259 if (!displayId || !getHwComposer().isConnected(*displayId)) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001260 return;
1261 }
1262
Dominik Laskowski075d3172018-05-24 15:50:06 -07001263 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001264 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001265
Ana Krulece588e312018-09-18 12:32:24 -07001266 if (mUseScheduler) {
1267 mScheduler->setVsyncPeriod(period);
1268 } else {
1269 mPrimaryDispSync->reset();
1270 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001271
Ana Krulece588e312018-09-18 12:32:24 -07001272 if (!mPrimaryHWVsyncEnabled) {
1273 mPrimaryDispSync->beginResync();
1274 mEventControlThread->setVsyncEnabled(true);
1275 mPrimaryHWVsyncEnabled = true;
1276 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001277 }
1278}
1279
Jesse Hall948fe0c2013-10-14 12:56:09 -07001280void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001281 Mutex::Autolock _l(mHWVsyncLock);
1282 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001283 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001284 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001285 mPrimaryHWVsyncEnabled = false;
1286 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001287 if (makeUnavailable) {
1288 mHWVsyncAvailable = false;
1289 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001290}
1291
Tim Murray4a4e4a22016-04-19 16:29:23 +00001292void SurfaceFlinger::resyncWithRateLimit() {
1293 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001294
1295 // No explicit locking is needed here since EventThread holds a lock while calling this method
1296 static nsecs_t sLastResyncAttempted = 0;
1297 const nsecs_t now = systemTime();
1298 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001299 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001300 }
Dan Stoza57164302017-05-08 14:03:54 -07001301 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001302}
1303
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001304void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1305 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001306 ATRACE_NAME("SF onVsync");
1307
Steven Thomas3cfac282017-02-06 12:29:30 -08001308 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001309 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001310 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001311 return;
1312 }
1313
Dominik Laskowski075d3172018-05-24 15:50:06 -07001314 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001315 return;
1316 }
1317
Dominik Laskowski075d3172018-05-24 15:50:06 -07001318 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001319 // For now, we don't do anything with external display vsyncs.
1320 return;
1321 }
1322
Ana Krulece588e312018-09-18 12:32:24 -07001323 if (mUseScheduler) {
1324 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001325 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001326 bool needsHwVsync = false;
1327 { // Scope for the lock
1328 Mutex::Autolock _l(mHWVsyncLock);
1329 if (mPrimaryHWVsyncEnabled) {
1330 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1331 }
1332 }
1333
1334 if (needsHwVsync) {
1335 enableHardwareVsync();
1336 } else {
1337 disableHardwareVsync(false);
1338 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001339 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001340}
1341
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001342void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001343 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1344 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001345}
1346
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001347void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001348 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001349 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001350 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001351
Lloyd Piqueba04e622017-12-14 17:11:26 -08001352 // Ignore events that do not have the right sequenceId.
1353 if (sequenceId != getBE().mComposerSequenceId) {
1354 return;
1355 }
1356
Steven Thomasb02664d2017-07-26 18:48:28 -07001357 // Only lock if we're not on the main thread. This function is normally
1358 // called on a hwbinder thread, but for the primary display it's called on
1359 // the main thread with the state lock already held, so don't attempt to
1360 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001361 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001362
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001363 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001364
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001365 if (std::this_thread::get_id() == mMainThreadId) {
1366 // Process all pending hot plug events immediately if we are on the main thread.
1367 processDisplayHotplugEventsLocked();
1368 }
1369
Lloyd Piqueba04e622017-12-14 17:11:26 -08001370 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001371}
1372
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001373void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001374 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001375 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001376 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001377 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001378 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001379}
1380
Dominik Laskowski075d3172018-05-24 15:50:06 -07001381void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001382 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001383 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001384 if (const auto displayId = getInternalDisplayId()) {
1385 getHwComposer().setVsyncEnabled(*displayId,
1386 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1387 }
Mathias Agopian86303202012-07-24 22:46:10 -07001388}
1389
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001390// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001391void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001392 if (mUseScheduler) {
1393 mScheduler->disableHardwareVsync(true);
1394 } else {
1395 disableHardwareVsync(true);
1396 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001397 // Clear the drawing state so that the logic inside of
1398 // handleTransactionLocked will fire. It will determine the delta between
1399 // mCurrentState and mDrawingState and re-apply all changes when we make the
1400 // transition.
1401 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001402 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001403 mDisplays.clear();
1404}
1405
Steven Thomas050b2c82017-03-06 11:45:16 -08001406void SurfaceFlinger::updateVrFlinger() {
1407 if (!mVrFlinger)
1408 return;
1409 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001410 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001411 return;
1412 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001413
David Sodman105b7dc2017-11-04 20:28:14 -07001414 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001415 ALOGE("Vr flinger is only supported for remote hardware composer"
1416 " service connections. Ignoring request to transition to vr"
1417 " flinger.");
1418 mVrFlingerRequestsDisplay = false;
1419 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001420 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001421
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001422 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001423
Steven Thomas0123ac62018-07-12 11:32:34 -07001424 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001425 LOG_ALWAYS_FATAL_IF(!display);
1426 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001427 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1428 // called below. Clear the reference now so we don't accidentally use it
1429 // later.
1430 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001431
Steven Thomasb02664d2017-07-26 18:48:28 -07001432 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001433 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001434 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001435
Steven Thomasb02664d2017-07-26 18:48:28 -07001436 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001437 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Pique90c115d2018-09-18 21:39:42 -07001438 getBE().mHwc = getFactory().createHWComposer(
1439 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -07001440 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001441
David Sodman105b7dc2017-11-04 20:28:14 -07001442 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1443 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001444
1445 if (vrFlingerRequestsDisplay) {
1446 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001447 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001448
1449 mVisibleRegionsDirty = true;
1450 invalidateHwcGeometry();
1451
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001452 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001453 display = getDefaultDisplayDeviceLocked();
1454 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001455 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001456
Steven Thomasb02664d2017-07-26 18:48:28 -07001457 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski075d3172018-05-24 15:50:06 -07001458 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001459 const nsecs_t period = activeConfig->getVsyncPeriod();
1460 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001461
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001462 // The present fences returned from vr_hwc are not an accurate
1463 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001464 if (mUseScheduler) {
1465 mScheduler->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() || !hasSyncFramework);
1466 } else {
1467 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1468 !hasSyncFramework);
1469 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001470
Steven Thomasb02664d2017-07-26 18:48:28 -07001471 // Use phase of 0 since phase is not known.
1472 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001473 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1474 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001475
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001476 resyncToHardwareVsync(false);
1477
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001478 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001479 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001480}
1481
Mathias Agopian4fec8732012-06-29 14:12:52 -07001482void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001483 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001484 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001485 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001486 bool frameMissed = !mHadClientComposition &&
1487 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001488 (mPreviousPresentFence->getSignalTime() ==
1489 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001490 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001491 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001492 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001493 mTimeStats.incrementMissedFrames();
1494 if (mPropagateBackpressure) {
1495 signalLayerUpdate();
1496 break;
1497 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001498 }
Dan Stoza50182882016-07-08 12:02:20 -07001499
Steven Thomas050b2c82017-03-06 11:45:16 -08001500 // Now that we're going to make it to the handleMessageTransaction()
1501 // call below it's safe to call updateVrFlinger(), which will
1502 // potentially trigger a display handoff.
1503 updateVrFlinger();
1504
Dan Stoza6b9454d2014-11-07 16:00:59 -08001505 bool refreshNeeded = handleMessageTransaction();
1506 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001507 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001508 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001509 // Signal a refresh if a transaction modified the window state,
1510 // a new buffer was latched, or if HWC has requested a full
1511 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001512 signalRefresh();
1513 }
1514 break;
1515 }
1516 case MessageQueue::REFRESH: {
1517 handleMessageRefresh();
1518 break;
1519 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001520 }
1521}
1522
Dan Stoza6b9454d2014-11-07 16:00:59 -08001523bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001524 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001525 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001526 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001527 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001528 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001529 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001530}
1531
Mathias Agopian4fec8732012-06-29 14:12:52 -07001532void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001533 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001534
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001535 mRefreshPending = false;
1536
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001537 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001538 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001539 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001540 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001541 for (const auto& [token, display] : mDisplays) {
1542 beginFrame(display);
1543 prepareFrame(display);
1544 doDebugFlashRegions(display, repaintEverything);
1545 doComposition(display, repaintEverything);
1546 }
1547
Adrian Roos1e1a1282017-11-01 19:05:31 +01001548 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001549 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001550
1551 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001552 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001553
Dan Stozabfbffeb2016-07-21 14:49:33 -07001554 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001555 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001556 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001557 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001558 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001559
Alec Mouri86770e52018-09-24 22:40:58 +00001560 // Setup RenderEngine sync fences if native sync is supported.
1561 if (getBE().mRenderEngine->useNativeFenceSync()) {
1562 if (mHadClientComposition) {
1563 base::unique_fd flushFence(getRenderEngine().flush());
1564 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1565 getBE().flushFence = new Fence(std::move(flushFence));
1566 } else {
1567 // Cleanup for hygiene.
1568 getBE().flushFence = Fence::NO_FENCE;
1569 }
1570 }
1571
Jorim Jaggi90535212018-05-23 23:44:06 +02001572 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001573
David Sodman7e4ae112018-02-09 15:02:28 -08001574 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001575 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001576 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001577 compositionInfo.hwc.hwcLayer = nullptr;
1578 }
David Sodmanba340492018-08-05 21:51:33 -07001579 }
David Sodman7e4ae112018-02-09 15:02:28 -08001580
1581 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001582}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001583
David Sodmanfa9b2af2017-12-24 13:28:59 -08001584
1585bool SurfaceFlinger::handleMessageInvalidate() {
1586 ATRACE_CALL();
1587 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001588}
1589
David Sodman79bba0e2018-08-05 18:07:49 -07001590void SurfaceFlinger::calculateWorkingSet() {
1591 ATRACE_CALL();
1592 ALOGV(__FUNCTION__);
1593
David Sodman79bba0e2018-08-05 18:07:49 -07001594 // build the h/w work list
1595 if (CC_UNLIKELY(mGeometryInvalid)) {
1596 mGeometryInvalid = false;
1597 for (const auto& [token, display] : mDisplays) {
1598 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001599 if (!displayId) {
1600 continue;
1601 }
David Sodman79bba0e2018-08-05 18:07:49 -07001602
Dominik Laskowski075d3172018-05-24 15:50:06 -07001603 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
1604 for (size_t i = 0; i < currentLayers.size(); i++) {
1605 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001606
Dominik Laskowski075d3172018-05-24 15:50:06 -07001607 if (!layer->hasHwcLayer(*displayId)) {
1608 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1609 layer->forceClientComposition(*displayId);
1610 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001611 }
1612 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001613
1614 layer->setGeometry(display, i);
1615 if (mDebugDisableHWC || mDebugRegion) {
1616 layer->forceClientComposition(*displayId);
1617 }
David Sodman79bba0e2018-08-05 18:07:49 -07001618 }
1619 }
1620 }
1621
1622 // Set the per-frame data
1623 for (const auto& [token, display] : mDisplays) {
1624 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001625 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001626 continue;
1627 }
1628
1629 if (mDrawingState.colorMatrixChanged) {
1630 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001631 status_t result =
1632 getHwComposer().setColorTransform(*displayId, mDrawingState.colorMatrix);
1633 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %" PRIu64 ": %d",
1634 *displayId, result);
David Sodman79bba0e2018-08-05 18:07:49 -07001635 }
1636 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1637 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001638 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001639 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1640 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1641 !display->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001642 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001643 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1644 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1645 !display->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001646 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001647 }
1648
Peiyong Lind3788632018-09-18 16:01:31 -07001649 // TODO(b/111562338) remove when composer 2.3 is shipped.
1650 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001651 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001652 }
1653
Dominik Laskowski075d3172018-05-24 15:50:06 -07001654 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001655 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001656 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001657 continue;
1658 }
1659
Dominik Laskowski075d3172018-05-24 15:50:06 -07001660 layer->setPerFrameData(*displayId, display->getTransform(), display->getViewport(),
1661 display->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001662 }
1663
Peiyong Lin13effd12018-07-24 17:01:47 -07001664 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001665 ColorMode colorMode;
1666 Dataspace dataSpace;
1667 RenderIntent renderIntent;
1668 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1669 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1670 }
1671 }
1672
1673 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001674
1675 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001676 getBE().mCompositionInfo[token].clear();
1677
David Sodmanba340492018-08-05 21:51:33 -07001678 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001679 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001680 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001681
1682 if (displayId) {
1683 if (!layer->setHwcLayer(*displayId)) {
1684 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1685 }
1686 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001687 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001688
Dominik Laskowski05275f12018-11-01 15:03:24 -07001689 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001690 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1691 }
1692 }
David Sodman79bba0e2018-08-05 18:07:49 -07001693}
1694
David Sodmanfa9b2af2017-12-24 13:28:59 -08001695void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001696{
1697 // is debugging enabled
1698 if (CC_LIKELY(!mDebugRegion))
1699 return;
1700
David Sodmanfa9b2af2017-12-24 13:28:59 -08001701 if (display->isPoweredOn()) {
1702 // transform the dirty region into this screen's coordinate space
1703 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1704 if (!dirtyRegion.isEmpty()) {
1705 // redraw the whole screen
1706 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001707
David Sodmanfa9b2af2017-12-24 13:28:59 -08001708 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001709 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001710 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001711
David Sodmanfa9b2af2017-12-24 13:28:59 -08001712 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001713 }
1714 }
1715
David Sodmanfa9b2af2017-12-24 13:28:59 -08001716 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001717
1718 if (mDebugRegion > 1) {
1719 usleep(mDebugRegion * 1000);
1720 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001721
Dominik Laskowski05275f12018-11-01 15:03:24 -07001722 prepareFrame(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001723}
1724
Adrian Roos1e1a1282017-11-01 19:05:31 +01001725void SurfaceFlinger::doTracing(const char* where) {
1726 ATRACE_CALL();
1727 ATRACE_NAME(where);
1728 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001729 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001730 }
1731}
1732
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001733void SurfaceFlinger::logLayerStats() {
1734 ATRACE_CALL();
1735 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001736 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001737 if (display->isPrimary()) {
1738 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001739 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001740 }
1741 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001742
1743 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001744 }
1745}
1746
David Sodman2b406362017-12-15 13:33:47 -08001747void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001748{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001749 ATRACE_CALL();
1750 ALOGV("preComposition");
1751
David Sodman2b406362017-12-15 13:33:47 -08001752 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1753
Mathias Agopiancd60f992012-08-16 16:28:27 -07001754 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001755 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001756 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001757 needExtraInvalidate = true;
1758 }
Robert Carr2047fae2016-11-28 14:09:09 -08001759 });
1760
Mathias Agopiancd60f992012-08-16 16:28:27 -07001761 if (needExtraInvalidate) {
1762 signalLayerUpdate();
1763 }
1764}
1765
Ana Krulece588e312018-09-18 12:32:24 -07001766void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1767 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001768 // Update queue of past composite+present times and determine the
1769 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001770 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001771 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001772 while (!getBE().mCompositePresentTimes.empty()) {
1773 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001774 // Cached values should have been updated before calling this method,
1775 // which helps avoid duplicate syscalls.
1776 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1777 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1778 break;
1779 }
1780 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001781 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001782 }
1783
1784 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001785 while (getBE().mCompositePresentTimes.size() > 16) {
1786 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001787 }
1788
Ana Krulece588e312018-09-18 12:32:24 -07001789 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001790}
1791
Ana Krulece588e312018-09-18 12:32:24 -07001792void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1793 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001794 // Integer division and modulo round toward 0 not -inf, so we need to
1795 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001796 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1797 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1798 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001799
Brian Andersond0010582017-03-07 13:20:31 -08001800 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1801 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001802 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001803 }
1804
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001805 // Snap the latency to a value that removes scheduling jitter from the
1806 // composition and present times, which often have >1ms of jitter.
1807 // Reducing jitter is important if an app attempts to extrapolate
1808 // something (such as user input) to an accurate diasplay time.
1809 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1810 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001811 nsecs_t bias = stats.vsyncPeriod / 2;
1812 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1813 nsecs_t snappedCompositeToPresentLatency =
1814 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001815
David Sodman99974d22017-11-28 12:04:33 -08001816 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001817 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1818 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001819 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001820}
1821
David Sodman2b406362017-12-15 13:33:47 -08001822void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001823{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001824 ATRACE_CALL();
1825 ALOGV("postComposition");
1826
Brian Anderson3546a3f2016-07-14 11:51:14 -07001827 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001828 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001829 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001830 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001831 }
1832
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001833 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001834 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001835
David Sodman73beded2017-11-15 11:56:06 -08001836 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001837 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001838 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001839 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001840 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001841 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001842 } else {
1843 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1844 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001845
David Sodman73beded2017-11-15 11:56:06 -08001846 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001847 mPreviousPresentFence =
Dominik Laskowski075d3172018-05-24 15:50:06 -07001848 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001849 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001850 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001851
Ana Krulece588e312018-09-18 12:32:24 -07001852 DisplayStatInfo stats;
1853 if (mUseScheduler) {
1854 mScheduler->getDisplayStatInfo(&stats);
1855 } else {
1856 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1857 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
1858 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001859
David Sodman2b406362017-12-15 13:33:47 -08001860 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001861 // when we started doing work for this frame, but that should be okay
1862 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07001863 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001864 CompositorTiming compositorTiming;
1865 {
David Sodman99974d22017-11-28 12:04:33 -08001866 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1867 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001868 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001869
Robert Carr2047fae2016-11-28 14:09:09 -08001870 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001871 bool frameLatched = layer->onPostComposition(display->getId(), glCompositionDoneFenceTime,
1872 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001873 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001874 recordBufferingStats(layer->getName().string(),
1875 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001876 }
Robert Carr2047fae2016-11-28 14:09:09 -08001877 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001878
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001879 if (presentFenceTime->isValid()) {
Ana Krulece588e312018-09-18 12:32:24 -07001880 if (mUseScheduler) {
1881 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001882 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001883 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
1884 enableHardwareVsync();
1885 } else {
1886 disableHardwareVsync(false);
1887 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001888 }
1889 }
1890
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001891 if (!hasSyncFramework) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001892 if (display && getHwComposer().isConnected(*display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07001893 if (mUseScheduler) {
1894 mScheduler->enableHardwareVsync();
1895 } else {
1896 enableHardwareVsync();
1897 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001898 }
1899 }
1900
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001901 if (mAnimCompositionPending) {
1902 mAnimCompositionPending = false;
1903
Brian Anderson4e606e32017-03-16 15:34:57 -07001904 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001905 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001906 std::move(presentFenceTime));
Dominik Laskowski075d3172018-05-24 15:50:06 -07001907 } else if (display && getHwComposer().isConnected(*display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001908 // The HWC doesn't support present fences, so use the refresh
1909 // timestamp instead.
Dominik Laskowski075d3172018-05-24 15:50:06 -07001910 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001911 mAnimFrameTracker.setActualPresentTime(presentTime);
1912 }
1913 mAnimFrameTracker.advanceFrame();
1914 }
Dan Stozab90cf072015-03-05 11:05:59 -08001915
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001916 mTimeStats.incrementTotalFrames();
1917 if (mHadClientComposition) {
1918 mTimeStats.incrementClientCompositionFrames();
1919 }
1920
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001921 mTimeStats.setPresentFenceGlobal(presentFenceTime);
1922
Dominik Laskowski075d3172018-05-24 15:50:06 -07001923 if (display && getHwComposer().isConnected(*display->getId()) && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08001924 return;
1925 }
1926
1927 nsecs_t currentTime = systemTime();
1928 if (mHasPoweredOff) {
1929 mHasPoweredOff = false;
1930 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001931 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001932 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001933 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1934 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001935 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001936 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001937 }
David Sodman4a36e932017-11-07 14:29:47 -08001938 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001939 }
David Sodman4a36e932017-11-07 14:29:47 -08001940 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001941
1942 {
1943 std::lock_guard lock(mTexturePoolMutex);
1944 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1945 if (refillCount > 0) {
1946 const size_t offset = mTexturePool.size();
1947 mTexturePool.resize(mTexturePoolSize);
1948 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1949 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1950 }
1951 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001952}
1953
1954void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001955 ATRACE_CALL();
1956 ALOGV("rebuildLayerStacks");
1957
Mathias Agopiancd60f992012-08-16 16:28:27 -07001958 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001959 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001960 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001961 mVisibleRegionsDirty = false;
1962 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001963
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001964 for (const auto& pair : mDisplays) {
1965 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001966 Region opaqueRegion;
1967 Region dirtyRegion;
1968 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001969 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001970 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001971 const Rect bounds = display->getBounds();
1972 if (display->isPoweredOn()) {
1973 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001974
Jeff Sharkey76488112017-02-27 14:15:18 -07001975 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001976 bool hwcLayerDestroyed = false;
Dominik Laskowski075d3172018-05-24 15:50:06 -07001977 const auto displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001978 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001979 Region drawRegion(tr.transform(
1980 layer->visibleNonTransparentRegion));
1981 drawRegion.andSelf(bounds);
1982 if (!drawRegion.isEmpty()) {
1983 layersSortedByZ.add(layer);
1984 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001985 // Clear out the HWC layer if this layer was
1986 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07001987 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07001988 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001989 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001990 // WM changes display->layerStack upon sleep/awake.
1991 // Here we make sure we delete the HWC layers even if
1992 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07001993 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08001994 }
1995
1996 // If a layer is not going to get a release fence because
1997 // it is invisible, but it is also going to release its
1998 // old buffer, add it to the list of layers needing
1999 // fences.
2000 if (hwcLayerDestroyed) {
2001 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2002 mLayersWithQueuedFrames.cend(), layer);
2003 if (found != mLayersWithQueuedFrames.cend()) {
2004 layersNeedingFences.add(layer);
2005 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002006 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002007 });
2008 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002009 display->setVisibleLayersSortedByZ(layersSortedByZ);
2010 display->setLayersNeedingFences(layersNeedingFences);
2011 display->undefinedRegion.set(bounds);
2012 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2013 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002014 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002015 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002016}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002017
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002018// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002019// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002020// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002021// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002022// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002023// The returned HDR data space is one of
2024// - Dataspace::UNKNOWN
2025// - Dataspace::BT2020_HLG
2026// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002027Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2028 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07002029 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002030 *outHdrDataSpace = Dataspace::UNKNOWN;
2031
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002032 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002033 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002034 case Dataspace::V0_SCRGB:
2035 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002036 case Dataspace::BT2020:
2037 case Dataspace::BT2020_ITU:
2038 case Dataspace::BT2020_LINEAR:
2039 case Dataspace::DISPLAY_BT2020:
2040 bestDataSpace = Dataspace::DISPLAY_BT2020;
2041 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002042 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002043 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002044 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002045 case Dataspace::BT2020_PQ:
2046 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002047 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002048 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002049 case Dataspace::BT2020_HLG:
2050 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002051 // When there's mixed PQ content and HLG content, we set the HDR
2052 // data space to be BT2020_PQ and convert HLG to PQ.
2053 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2054 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002055 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002056 break;
2057 default:
2058 break;
2059 }
Romain Guy54f154a2017-10-24 21:40:32 +01002060 }
2061
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002062 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002063}
2064
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002065// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002066void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2067 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002068 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2069 *outMode = ColorMode::NATIVE;
2070 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002071 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002072 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002073 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002074
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002075 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002076 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002077
Peiyong Lindfde5112018-06-05 10:58:41 -07002078 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002079 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002080 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002081 if (isHdr) {
2082 bestDataSpace = hdrDataSpace;
2083 }
2084
Chia-I Wu0d711262018-05-21 15:19:35 -07002085 RenderIntent intent;
2086 switch (mDisplayColorSetting) {
2087 case DisplayColorSetting::MANAGED:
2088 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002089 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002090 break;
2091 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002092 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002093 break;
2094 default: // vendor display color setting
2095 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2096 break;
2097 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002098
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002099 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002100}
2101
David Sodmanfa9b2af2017-12-24 13:28:59 -08002102void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002103{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002104 bool dirty = !display->getDirtyRegion(false).isEmpty();
2105 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2106 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002107
David Sodmanfa9b2af2017-12-24 13:28:59 -08002108 // If nothing has changed (!dirty), don't recompose.
2109 // If something changed, but we don't currently have any visible layers,
2110 // and didn't when we last did a composition, then skip it this time.
2111 // The second rule does two things:
2112 // - When all layers are removed from a display, we'll emit one black
2113 // frame, then nothing more until we get new layers.
2114 // - When a display is created with a private layer stack, we won't
2115 // emit any black frames until a layer is added to the layer stack.
2116 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002117
Dominik Laskowski075d3172018-05-24 15:50:06 -07002118 const char flagPrefix[] = {'-', '+'};
2119 static_cast<void>(flagPrefix);
2120 ALOGV_IF(display->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2121 __FUNCTION__, mustRecompose ? "doing" : "skipping", display->getDebugName().c_str(),
2122 flagPrefix[dirty], flagPrefix[empty], flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002123
David Sodmanfa9b2af2017-12-24 13:28:59 -08002124 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002125
David Sodmanfa9b2af2017-12-24 13:28:59 -08002126 if (mustRecompose) {
2127 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002128 }
2129}
2130
David Sodmanfa9b2af2017-12-24 13:28:59 -08002131void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002132{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002133 if (!display->isPoweredOn()) {
2134 return;
David Sodman2b406362017-12-15 13:33:47 -08002135 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002136
Dominik Laskowski05275f12018-11-01 15:03:24 -07002137 status_t result = display->prepareFrame(getHwComposer(),
2138 getBE().mCompositionInfo[display->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002139 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
2140 display->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002141}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002142
David Sodmanfa9b2af2017-12-24 13:28:59 -08002143void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002144 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002145 ALOGV("doComposition");
2146
David Sodmanfa9b2af2017-12-24 13:28:59 -08002147 if (display->isPoweredOn()) {
2148 // transform the dirty region into this screen's coordinate space
2149 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002150
David Sodmanfa9b2af2017-12-24 13:28:59 -08002151 // repaint the framebuffer (if needed)
2152 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002153
David Sodmanfa9b2af2017-12-24 13:28:59 -08002154 display->dirtyRegion.clear();
2155 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002156 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002157 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002158}
2159
David Sodmanfa9b2af2017-12-24 13:28:59 -08002160void SurfaceFlinger::postFrame()
2161{
2162 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002163 const auto display = getDefaultDisplayDeviceLocked();
2164 if (display && getHwComposer().isConnected(*display->getId())) {
2165 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002166 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2167 logFrameStats();
2168 }
2169 }
2170}
2171
2172void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002173{
Mathias Agopian841cde52012-03-01 15:44:37 -08002174 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002175 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002176
David Sodmanfa9b2af2017-12-24 13:28:59 -08002177 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002178
David Sodmanfa9b2af2017-12-24 13:28:59 -08002179 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002180 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002181 if (displayId) {
2182 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002183 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002184 display->onSwapBuffersCompleted();
2185 display->makeCurrent();
David Sodman15094112018-10-11 09:39:37 -07002186 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002187 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002188
Chia-I Wu7b549592017-11-15 09:14:57 -08002189 // The layer buffer from the previous frame (if any) is released
2190 // by HWC only when the release fence from this frame (if any) is
2191 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002192 if (displayId && layer->hasHwcLayer(*displayId)) {
2193 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2194 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002195 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002196
2197 // If the layer was client composited in the previous frame, we
2198 // need to merge with the previous client target acquire fence.
2199 // Since we do not track that, always merge with the current
2200 // client target acquire fence when it is available, even though
2201 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002202 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002203 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002204 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002205 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002206
David Sodman15094112018-10-11 09:39:37 -07002207 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002208 }
Chia-I Wu83806892017-11-16 10:50:20 -08002209
2210 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002211 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002212 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002213 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002214 sp<Fence> presentFence =
2215 displayId ? getBE().mHwc->getPresentFence(*displayId) : Fence::NO_FENCE;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002216 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002217 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002218 }
2219 }
2220
Dominik Laskowski075d3172018-05-24 15:50:06 -07002221 if (displayId) {
2222 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002223 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002224 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002225}
2226
Mathias Agopian87baae12012-07-31 12:38:26 -07002227void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002228{
Mathias Agopian841cde52012-03-01 15:44:37 -08002229 ATRACE_CALL();
2230
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002231 // here we keep a copy of the drawing state (that is the state that's
2232 // going to be overwritten by handleTransactionLocked()) outside of
2233 // mStateLock so that the side-effects of the State assignment
2234 // don't happen with mStateLock held (which can cause deadlocks).
2235 State drawingState(mDrawingState);
2236
Mathias Agopianca4d3602011-05-19 15:38:14 -07002237 Mutex::Autolock _l(mStateLock);
2238 const nsecs_t now = systemTime();
2239 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002240
Mathias Agopianca4d3602011-05-19 15:38:14 -07002241 // Here we're guaranteed that some transaction flags are set
2242 // so we can call handleTransactionLocked() unconditionally.
2243 // We call getTransactionFlags(), which will also clear the flags,
2244 // with mStateLock held to guarantee that mCurrentState won't change
2245 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002246
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002247 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002248 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002249 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002250
Mathias Agopianca4d3602011-05-19 15:38:14 -07002251 mLastTransactionTime = systemTime() - now;
2252 mDebugInTransaction = 0;
2253 invalidateHwcGeometry();
2254 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002255}
2256
Lloyd Piqueba04e622017-12-14 17:11:26 -08002257void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2258 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002259 const std::optional<DisplayIdentificationInfo> info =
2260 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002261
Dominik Laskowski075d3172018-05-24 15:50:06 -07002262 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002263 continue;
2264 }
2265
Lloyd Piqueba04e622017-12-14 17:11:26 -08002266 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002267 if (!mPhysicalDisplayTokens.count(info->id)) {
2268 ALOGV("Creating display %" PRIu64, info->id);
2269 mPhysicalDisplayTokens[info->id] = new BBinder();
2270 DisplayDeviceState state;
2271 state.displayId = info->id;
2272 state.isSecure = true; // All physical displays are currently considered secure.
2273 state.displayName = info->name;
2274 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2275 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002276 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002277 } else {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002278 ALOGV("Removing display %" PRIu64, info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002279
Dominik Laskowski075d3172018-05-24 15:50:06 -07002280 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2281 if (index >= 0) {
2282 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2283 mInterceptor->saveDisplayDeletion(state.sequenceId);
2284 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002285 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002286 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002287 }
2288
2289 processDisplayChangesLocked();
2290 }
2291
2292 mPendingHotplugEvents.clear();
2293}
2294
Lloyd Pique99d3da52018-01-22 17:48:03 -08002295sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002296 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
2297 const DisplayDeviceState& state, const sp<DisplaySurface>& dispSurface,
2298 const sp<IGraphicBufferProducer>& producer) {
2299 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
2300 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002301 creationArgs.isSecure = state.isSecure;
2302 creationArgs.displaySurface = dispSurface;
2303 creationArgs.hasWideColorGamut = false;
2304 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002305
Dominik Laskowski075d3172018-05-24 15:50:06 -07002306 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2307 creationArgs.isPrimary = isInternalDisplay;
2308
2309 if (useColorManagement && displayId) {
2310 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002311 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002312 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002313 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002314 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002315
Dominik Laskowski7e045462018-05-30 13:02:02 -07002316 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002317 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002318 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002319 }
tangrobin6753a022018-08-10 10:58:54 +08002320 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002321
Dominik Laskowski075d3172018-05-24 15:50:06 -07002322 if (displayId) {
2323 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002324 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002325 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002326 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002327
Lloyd Pique90c115d2018-09-18 21:39:42 -07002328 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002329 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002330 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002331
2332 /*
2333 * Create our display's surface
2334 */
Peiyong Lin833074a2018-08-28 11:53:54 -07002335 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002336 renderSurface->setCritical(isInternalDisplay);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002337 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002338 renderSurface->setNativeWindow(nativeWindow.get());
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002339 creationArgs.displayWidth = renderSurface->getWidth();
2340 creationArgs.displayHeight = renderSurface->getHeight();
2341 creationArgs.renderSurface = std::move(renderSurface);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002342
2343 // Make sure that composition can never be stalled by a virtual display
2344 // consumer that isn't processing buffers fast enough. We have to do this
2345 // in two places:
2346 // * Here, in case the display is composed entirely by HWC.
2347 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2348 // window's swap interval in eglMakeCurrent, so they'll override the
2349 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002350 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002351 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2352 }
2353
Dominik Laskowski075d3172018-05-24 15:50:06 -07002354 creationArgs.displayInstallOrientation =
2355 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002356
Lloyd Pique99d3da52018-01-22 17:48:03 -08002357 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002358 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002359
Lloyd Pique90c115d2018-09-18 21:39:42 -07002360 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002361
2362 if (maxFrameBufferAcquiredBuffers >= 3) {
2363 nativeWindowSurface->preallocateBuffers();
2364 }
2365
2366 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002367 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002368 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002369 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002370 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002371 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002372 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002373 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002374 if (!state.isVirtual()) {
2375 LOG_ALWAYS_FATAL_IF(!displayId);
2376 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002377 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002378
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002379 display->setLayerStack(state.layerStack);
2380 display->setProjection(state.orientation, state.viewport, state.frame);
2381 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002382
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002383 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002384}
2385
Lloyd Pique347200f2017-12-14 17:00:15 -08002386void SurfaceFlinger::processDisplayChangesLocked() {
2387 // here we take advantage of Vector's copy-on-write semantics to
2388 // improve performance by skipping the transaction entirely when
2389 // know that the lists are identical
2390 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2391 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2392 if (!curr.isIdenticalTo(draw)) {
2393 mVisibleRegionsDirty = true;
2394 const size_t cc = curr.size();
2395 size_t dc = draw.size();
2396
2397 // find the displays that were removed
2398 // (ie: in drawing state but not in current state)
2399 // also handle displays that changed
2400 // (ie: displays that are in both lists)
2401 for (size_t i = 0; i < dc;) {
2402 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2403 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002404 // Save display IDs before disconnecting.
2405 const auto internalDisplayId = getInternalDisplayId();
2406 const auto externalDisplayId = getExternalDisplayId();
2407
Lloyd Pique347200f2017-12-14 17:00:15 -08002408 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002409 // Call makeCurrent() on the primary display so we can
2410 // be sure that nothing associated with this display
2411 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002412 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2413 defaultDisplay->makeCurrent();
2414 }
2415 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2416 display->disconnect(getHwComposer());
2417 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002418 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002419 if (mUseScheduler) {
2420 mScheduler->hotplugReceived(mAppConnectionHandle,
2421 EventThread::DisplayType::Primary, false);
2422 } else {
2423 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2424 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002425 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002426 if (mUseScheduler) {
2427 mScheduler->hotplugReceived(mAppConnectionHandle,
2428 EventThread::DisplayType::External, false);
2429 } else {
2430 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2431 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002432 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002433 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002434 } else {
2435 // this display is in both lists. see if something changed.
2436 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002437 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002438 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2439 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2440 if (state_binder != draw_binder) {
2441 // changing the surface is like destroying and
2442 // recreating the DisplayDevice, so we just remove it
2443 // from the drawing state, so that it get re-added
2444 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002445 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2446 display->disconnect(getHwComposer());
2447 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002448 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002449 mDrawingState.displays.removeItemsAt(i);
2450 dc--;
2451 // at this point we must loop to the next item
2452 continue;
2453 }
2454
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002455 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002456 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002457 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002458 }
2459 if ((state.orientation != draw[i].orientation) ||
2460 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002461 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002462 }
2463 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002464 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002465 }
2466 }
2467 }
2468 ++i;
2469 }
2470
2471 // find displays that were added
2472 // (ie: in current state but not in drawing state)
2473 for (size_t i = 0; i < cc; i++) {
2474 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2475 const DisplayDeviceState& state(curr[i]);
2476
2477 sp<DisplaySurface> dispSurface;
2478 sp<IGraphicBufferProducer> producer;
2479 sp<IGraphicBufferProducer> bqProducer;
2480 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002481 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002482
Dominik Laskowski075d3172018-05-24 15:50:06 -07002483 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002484 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002485 // Virtual displays without a surface are dormant:
2486 // they have external state (layer stack, projection,
2487 // etc.) but no internal state (i.e. a DisplayDevice).
2488 if (state.surface != nullptr) {
2489 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002490 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002491 int width = 0;
2492 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2493 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2494 int height = 0;
2495 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2496 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2497 int intFormat = 0;
2498 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2499 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002500 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002501
Dominik Laskowski075d3172018-05-24 15:50:06 -07002502 displayId =
2503 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002504 }
2505
2506 // TODO: Plumb requested format back up to consumer
2507
2508 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002509 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002510 bqProducer, bqConsumer,
2511 state.displayName);
2512
2513 dispSurface = vds;
2514 producer = vds;
2515 }
2516 } else {
2517 ALOGE_IF(state.surface != nullptr,
2518 "adding a supported display, but rendering "
2519 "surface is provided (%p), ignoring it",
2520 state.surface.get());
2521
Dominik Laskowski075d3172018-05-24 15:50:06 -07002522 displayId = state.displayId;
2523 LOG_ALWAYS_FATAL_IF(!displayId);
2524 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002525 producer = bqProducer;
2526 }
2527
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002528 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002529 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002530 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002531 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002532 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002533 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002534 LOG_ALWAYS_FATAL_IF(!displayId);
2535
2536 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002537 if (mUseScheduler) {
2538 mScheduler->hotplugReceived(mAppConnectionHandle,
2539 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002540 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002541 } else {
2542 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2543 true);
2544 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002545 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002546 if (mUseScheduler) {
2547 mScheduler->hotplugReceived(mAppConnectionHandle,
2548 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002549 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002550 } else {
2551 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2552 true);
2553 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002554 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002555 }
2556 }
2557 }
2558 }
2559 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002560
2561 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002562}
2563
Mathias Agopian87baae12012-07-31 12:38:26 -07002564void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002565{
Dan Stoza7dde5992015-05-22 09:51:44 -07002566 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002567 mCurrentState.traverseInZOrder([](Layer* layer) {
2568 layer->notifyAvailableFrames();
2569 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002570
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002571 /*
2572 * Traversal of the children
2573 * (perform the transaction for each of them if needed)
2574 */
2575
Mathias Agopian3559b072012-08-15 13:46:03 -07002576 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002577 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002578 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002579 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002580
2581 const uint32_t flags = layer->doTransaction(0);
2582 if (flags & Layer::eVisibleRegion)
2583 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002584 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002585 }
2586
2587 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002588 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002589 */
2590
Mathias Agopiane57f2922012-08-09 16:29:12 -07002591 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002592 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002593 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002594 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002595
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002596 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002597 // The transform hint might have changed for some layers
2598 // (either because a display has changed, or because a layer
2599 // as changed).
2600 //
2601 // Walk through all the layers in currentLayers,
2602 // and update their transform hint.
2603 //
2604 // If a layer is visible only on a single display, then that
2605 // display is used to calculate the hint, otherwise we use the
2606 // default display.
2607 //
2608 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2609 // the hint is set before we acquire a buffer from the surface texture.
2610 //
2611 // NOTE: layer transactions have taken place already, so we use their
2612 // drawing state. However, SurfaceFlinger's own transaction has not
2613 // happened yet, so we must use the current state layer list
2614 // (soon to become the drawing state list).
2615 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002616 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002617 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002618 bool first = true;
2619 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002620 // NOTE: we rely on the fact that layers are sorted by
2621 // layerStack first (so we don't have to traverse the list
2622 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002623 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002624 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002625 currentlayerStack = layerStack;
2626 // figure out if this layerstack is mirrored
2627 // (more than one display) if so, pick the default display,
2628 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002629 hintDisplay = nullptr;
2630 for (const auto& [token, display] : mDisplays) {
2631 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2632 if (hintDisplay) {
2633 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002634 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002635 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002636 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002637 }
2638 }
2639 }
2640 }
Chet Haase91d25932013-04-11 15:24:55 -07002641
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002642 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002643 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2644 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002645
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002646 // could be null when this layer is using a layerStack
2647 // that is not visible on any display. Also can occur at
2648 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002649 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002650 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002651
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002652 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002653 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002654 if (hintDisplay) {
2655 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002656 }
Robert Carr2047fae2016-11-28 14:09:09 -08002657
2658 first = false;
2659 });
Mathias Agopian84300952012-11-21 16:02:13 -08002660 }
2661
2662
Mathias Agopian3559b072012-08-15 13:46:03 -07002663 /*
2664 * Perform our own transaction if needed
2665 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002666
2667 if (mLayersAdded) {
2668 mLayersAdded = false;
2669 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002670 mVisibleRegionsDirty = true;
2671 }
2672
2673 // some layers might have been removed, so
2674 // we need to update the regions they're exposing.
2675 if (mLayersRemoved) {
2676 mLayersRemoved = false;
2677 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002678 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002679 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002680 // this layer is not visible anymore
2681 // TODO: we could traverse the tree from front to back and
2682 // compute the actual visible region
2683 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002684 Region visibleReg;
2685 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002686 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002687 }
Robert Carr2047fae2016-11-28 14:09:09 -08002688 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002689 }
2690
2691 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002692
2693 updateCursorAsync();
2694}
2695
2696void SurfaceFlinger::updateCursorAsync()
2697{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002698 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002699 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002700 continue;
2701 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002702
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002703 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2704 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002705 }
2706 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002707}
2708
2709void SurfaceFlinger::commitTransaction()
2710{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002711 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002712 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002713 for (const auto& l : mLayersPendingRemoval) {
2714 recordBufferingStats(l->getName().string(),
2715 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002716
2717 // We need to release the HWC layers when the Layer is removed
2718 // from the current state otherwise the HWC layer just continues
2719 // showing at its last configured state until we eventually
2720 // abandon the buffer queue.
2721 if (l->isRemovedFromCurrentState()) {
2722 l->destroyAllHwcLayers();
2723 l->releasePendingBuffer(systemTime());
2724 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002725 }
2726 mLayersPendingRemoval.clear();
2727 }
2728
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002729 // If this transaction is part of a window animation then the next frame
2730 // we composite should be considered an animation as well.
2731 mAnimCompositionPending = mAnimTransactionPending;
2732
Mathias Agopian4fec8732012-06-29 14:12:52 -07002733 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002734 // clear the "changed" flags in current state
2735 mCurrentState.colorMatrixChanged = false;
2736
Robert Carr1f0a16a2016-10-24 16:27:39 -07002737 mDrawingState.traverseInZOrder([](Layer* layer) {
2738 layer->commitChildList();
2739 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002740 mTransactionPending = false;
2741 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002742 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002743}
2744
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002745void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2746 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002747 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002748 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002749
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002750 Region aboveOpaqueLayers;
2751 Region aboveCoveredLayers;
2752 Region dirty;
2753
Mathias Agopian87baae12012-07-31 12:38:26 -07002754 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002755
Robert Carr2047fae2016-11-28 14:09:09 -08002756 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002757 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002758 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002759
Jesse Hall01e29052013-02-19 16:13:35 -08002760 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002761 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002762 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002763 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002764
Mathias Agopianab028732010-03-16 16:41:46 -07002765 /*
2766 * opaqueRegion: area of a surface that is fully opaque.
2767 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002768 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002769
2770 /*
2771 * visibleRegion: area of a surface that is visible on screen
2772 * and not fully transparent. This is essentially the layer's
2773 * footprint minus the opaque regions above it.
2774 * Areas covered by a translucent surface are considered visible.
2775 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002776 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002777
2778 /*
2779 * coveredRegion: area of a surface that is covered by all
2780 * visible regions above it (which includes the translucent areas).
2781 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002782 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002783
Jesse Halla8026d22012-09-25 13:25:04 -07002784 /*
2785 * transparentRegion: area of a surface that is hinted to be completely
2786 * transparent. This is only used to tell when the layer has no visible
2787 * non-transparent regions and can be removed from the layer list. It
2788 * does not affect the visibleRegion of this layer or any layers
2789 * beneath it. The hint may not be correct if apps don't respect the
2790 * SurfaceView restrictions (which, sadly, some don't).
2791 */
2792 Region transparentRegion;
2793
Mathias Agopianab028732010-03-16 16:41:46 -07002794
2795 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002796 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002797 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002798 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002799 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002800 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002801 if (!visibleRegion.isEmpty()) {
2802 // Remove the transparent area from the visible region
2803 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002804 if (tr.preserveRects()) {
2805 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002806 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002807 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002808 // transformation too complex, can't do the
2809 // transparent region optimization.
2810 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002811 }
Mathias Agopianab028732010-03-16 16:41:46 -07002812 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002813
Mathias Agopianab028732010-03-16 16:41:46 -07002814 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002815 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002816 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002817 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002818 // the opaque region is the layer's footprint
2819 opaqueRegion = visibleRegion;
2820 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002821 }
2822 }
2823
Robert Carre5f4f692018-01-12 13:12:28 -08002824 if (visibleRegion.isEmpty()) {
2825 layer->clearVisibilityRegions();
2826 return;
2827 }
2828
Mathias Agopianab028732010-03-16 16:41:46 -07002829 // Clip the covered region to the visible region
2830 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2831
2832 // Update aboveCoveredLayers for next (lower) layer
2833 aboveCoveredLayers.orSelf(visibleRegion);
2834
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002835 // subtract the opaque region covered by the layers above us
2836 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002837
2838 // compute this layer's dirty region
2839 if (layer->contentDirty) {
2840 // we need to invalidate the whole region
2841 dirty = visibleRegion;
2842 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002843 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002844 layer->contentDirty = false;
2845 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002846 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002847 * the exposed region consists of two components:
2848 * 1) what's VISIBLE now and was COVERED before
2849 * 2) what's EXPOSED now less what was EXPOSED before
2850 *
2851 * note that (1) is conservative, we start with the whole
2852 * visible region but only keep what used to be covered by
2853 * something -- which mean it may have been exposed.
2854 *
2855 * (2) handles areas that were not covered by anything but got
2856 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002857 */
Mathias Agopianab028732010-03-16 16:41:46 -07002858 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002859 const Region oldVisibleRegion = layer->visibleRegion;
2860 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002861 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2862 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002863 }
2864 dirty.subtractSelf(aboveOpaqueLayers);
2865
2866 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002867 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002868
Mathias Agopianab028732010-03-16 16:41:46 -07002869 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002870 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002871
Jesse Halla8026d22012-09-25 13:25:04 -07002872 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002873 layer->setVisibleRegion(visibleRegion);
2874 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002875 layer->setVisibleNonTransparentRegion(
2876 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002877 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002878
Mathias Agopian87baae12012-07-31 12:38:26 -07002879 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002880}
2881
Chia-I Wuab0c3192017-08-01 11:29:00 -07002882void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002883 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002884 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2885 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002886 }
2887 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002888}
2889
Dan Stoza6b9454d2014-11-07 16:00:59 -08002890bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002891{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002892 ALOGV("handlePageFlip");
2893
Brian Andersond6927fb2016-07-23 23:37:30 -07002894 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002895
Mathias Agopian4fec8732012-06-29 14:12:52 -07002896 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002897 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002898 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002899
2900 // Store the set of layers that need updates. This set must not change as
2901 // buffers are being latched, as this could result in a deadlock.
2902 // Example: Two producers share the same command stream and:
2903 // 1.) Layer 0 is latched
2904 // 2.) Layer 0 gets a new frame
2905 // 2.) Layer 1 gets a new frame
2906 // 3.) Layer 1 is latched.
2907 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2908 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002909 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002910 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002911 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002912 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2913 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002914 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002915 } else {
2916 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002917 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002918 } else {
2919 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002920 }
Robert Carr2047fae2016-11-28 14:09:09 -08002921 });
2922
Dan Stoza9e56aa02015-11-02 13:00:03 -08002923 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri86770e52018-09-24 22:40:58 +00002924 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
Dan Stozaee44edd2015-03-23 15:50:23 -07002925 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002926 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002927 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002928 newDataLatched = true;
2929 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002930 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002931
Alec Mouri86770e52018-09-24 22:40:58 +00002932 // Clear the renderengine fence here...
2933 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
2934 // clear instead of sp::clear.
2935 getBE().flushFence = Fence::NO_FENCE;
2936
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002937 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002938
2939 // If we will need to wake up at some time in the future to deal with a
2940 // queued frame that shouldn't be displayed during this vsync period, wake
2941 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002942 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002943 signalLayerUpdate();
2944 }
2945
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002946 // enter boot animation on first buffer latch
2947 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2948 ALOGI("Enter boot animation");
2949 mBootStage = BootStage::BOOTANIMATION;
2950 }
2951
Dan Stoza6b9454d2014-11-07 16:00:59 -08002952 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002953 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002954}
2955
Mathias Agopianad456f92011-01-13 17:53:01 -08002956void SurfaceFlinger::invalidateHwcGeometry()
2957{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002958 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002959}
2960
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002961void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2962 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002963 // We only need to actually compose the display if:
2964 // 1) It is being handled by hardware composer, which may need this to
2965 // keep its virtual display state machine in sync, or
2966 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002967 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002968 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002969 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002970 return;
2971 }
2972
Dan Stoza9e56aa02015-11-02 13:00:03 -08002973 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002974 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002975
2976 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002977 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002978}
2979
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002980bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002981 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002982
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002983 const Region bounds(display->bounds());
2984 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002985 const auto displayId = display->getId();
2986 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002987 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002988
Peiyong Lind3788632018-09-18 16:01:31 -07002989 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002990 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002991 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002992
Dan Stoza9e56aa02015-11-02 13:00:03 -08002993 if (hasClientComposition) {
2994 ALOGV("hasClientComposition");
2995
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002996 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002997 if (display->hasWideColorGamut()) {
2998 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002999 }
3000 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003001 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003002 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003003
Dominik Laskowski7e045462018-05-30 13:02:02 -07003004 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003005 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3006 HWC2::Capability::SkipClientColorTransform);
3007
Peiyong Lind3788632018-09-18 16:01:31 -07003008 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003009 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3010 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003011 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003012 }
3013
Chia-I Wud49d6692018-06-27 07:17:41 +08003014 // The current enhanced saturation matrix is designed to enhance Display P3,
3015 // thus we only apply this matrix when the render intent is not colorimetric
3016 // and the output color space is Display P3.
3017 needsEnhancedColorMatrix =
3018 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3019 outputDataspace == Dataspace::DISPLAY_P3);
3020 if (needsEnhancedColorMatrix) {
3021 colorMatrix *= mEnhancedSaturationMatrix;
3022 }
3023
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003024 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003025 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003026 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003027 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003028
3029 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003030 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3031 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3032 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003033 }
3034 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003035 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003036
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003037 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003038 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003039 // when using overlays, we assume a fully transparent framebuffer
3040 // NOTE: we could reduce how much we need to clear, for instance
3041 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003042 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003043 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003044 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003045 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003046 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003047 // we're left with the letterbox region
3048 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003049 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003050
3051 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003052 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003053
Mathias Agopianb9494d52012-04-18 02:28:45 -07003054 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003055 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003056 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003057 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003058 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003059 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003060
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003061 const Rect& bounds = display->getBounds();
3062 const Rect& scissor = display->getScissor();
3063 if (scissor != bounds) {
3064 // scissor doesn't match the screen's dimensions, so we
3065 // need to clear everything outside of it and enable
3066 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003067
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003068 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003069 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003070 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003071 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003072
Mathias Agopian85d751c2012-08-29 16:59:24 -07003073 /*
3074 * and then, render the layers targeted at the framebuffer
3075 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003076
Dan Stoza9e56aa02015-11-02 13:00:03 -08003077 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003078 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003079 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003080 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003081 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003082 displayTransform.transform(layer->visibleRegion)));
3083 ALOGV("Layer: %s", layer->getName().string());
3084 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003085 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003086 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003087 case HWC2::Composition::Cursor:
3088 case HWC2::Composition::Device:
3089 case HWC2::Composition::Sideband:
3090 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003091 LOG_ALWAYS_FATAL_IF(!displayId);
David Sodmanc1498e62018-09-12 14:36:26 -07003092 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003093 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
David Sodmanc1498e62018-09-12 14:36:26 -07003094 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3095 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003096 // never clear the very first layer since we're
3097 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003098 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003099 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003100 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003101 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003102 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003103 if (layer->hasColorTransform()) {
3104 mat4 tmpMatrix;
3105 if (applyColorMatrix) {
3106 tmpMatrix = mDrawingState.colorMatrix;
3107 }
3108 tmpMatrix *= layer->getColorTransform();
3109 if (needsEnhancedColorMatrix) {
3110 tmpMatrix *= mEnhancedSaturationMatrix;
3111 }
3112 getRenderEngine().setColorTransform(tmpMatrix);
3113 } else {
3114 getRenderEngine().setColorTransform(colorMatrix);
3115 }
David Sodmanc1498e62018-09-12 14:36:26 -07003116 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003117 break;
3118 }
3119 default:
3120 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003121 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003122 } else {
3123 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003124 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003125 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003126 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003127
Peiyong Lind3788632018-09-18 16:01:31 -07003128 // Clear color transform matrix at the end of the frame.
3129 getRenderEngine().setColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003130
Mathias Agopianf45c5102012-10-24 16:29:17 -07003131 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003132 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003133 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003134}
3135
Chia-I Wu28e3a252018-09-07 12:05:02 -07003136void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003137 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003138 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003139}
3140
Dan Stoza7d89d062015-04-30 13:29:25 -07003141status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003142 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003143 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003144 const sp<Layer>& lbc,
3145 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003146{
Dan Stoza7d89d062015-04-30 13:29:25 -07003147 // add this layer to the current state list
3148 {
3149 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003150 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003151 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3152 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003153 return NO_MEMORY;
3154 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003155 if (parent == nullptr) {
3156 mCurrentState.layersSortedByZ.add(lbc);
3157 } else {
Robert Carr2e102c92018-10-23 12:11:15 -07003158 if (parent->isRemovedFromCurrentState()) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003159 ALOGE("addClientLayer called with a removed parent");
3160 return NAME_NOT_FOUND;
3161 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003162 parent->addChild(lbc);
3163 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003164
Yiwei Zhang243b3782018-05-15 17:40:04 -07003165 if (gbc != nullptr) {
3166 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3167 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3168 mMaxGraphicBufferProducerListSize,
3169 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3170 mGraphicBufferProducerList.size(),
3171 mMaxGraphicBufferProducerListSize, mNumLayers);
3172 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003173 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003174 }
3175
Mathias Agopian96f08192010-06-02 23:28:45 -07003176 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003177 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003178
Dan Stoza7d89d062015-04-30 13:29:25 -07003179 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003180}
3181
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003182status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003183 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003184 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3185}
Robert Carr7f9b8992017-03-10 11:08:39 -08003186
Robert Carr2e102c92018-10-23 12:11:15 -07003187status_t SurfaceFlinger::removeLayerLocked(const Mutex& lock, const sp<Layer>& layer,
chaviwca27f252018-02-06 16:46:39 -08003188 bool topLevelOnly) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003189 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003190 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003191 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003192 if (topLevelOnly) {
3193 return NO_ERROR;
3194 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003195 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003196 } else {
3197 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003198 }
3199
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003200 layer->onRemovedFromCurrentState();
Robert Carr2e102c92018-10-23 12:11:15 -07003201
3202 markLayerPendingRemovalLocked(lock, layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003203 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003204}
3205
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003206uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003207 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003208}
3209
Mathias Agopian3f844832013-08-07 21:24:32 -07003210uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003211 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003212}
3213
Mathias Agopian3f844832013-08-07 21:24:32 -07003214uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003215 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003216}
3217
3218uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003219 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003220 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003221 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003222 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003223 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003224 }
3225 return old;
3226}
3227
chaviwca27f252018-02-06 16:46:39 -08003228bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3229 for (const ComposerState& state : states) {
3230 // Here we need to check that the interface we're given is indeed
3231 // one of our own. A malicious client could give us a nullptr
3232 // IInterface, or one of its own or even one of our own but a
3233 // different type. All these situations would cause us to crash.
3234 if (state.client == nullptr) {
3235 return true;
3236 }
3237
3238 sp<IBinder> binder = IInterface::asBinder(state.client);
3239 if (binder == nullptr) {
3240 return true;
3241 }
3242
3243 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3244 return true;
3245 }
3246 }
3247 return false;
3248}
3249
Mathias Agopian8b33f032012-07-24 20:43:54 -07003250void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003251 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003252 const Vector<DisplayState>& displays,
3253 uint32_t flags)
3254{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003255 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003256 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003257 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003258
chaviwca27f252018-02-06 16:46:39 -08003259 if (containsAnyInvalidClientState(states)) {
3260 return;
3261 }
3262
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003263 if (flags & eAnimation) {
3264 // For window updates that are part of an animation we must wait for
3265 // previous animation "frames" to be handled.
3266 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003267 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003268 if (CC_UNLIKELY(err != NO_ERROR)) {
3269 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003270 // caller after a few seconds.
3271 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3272 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003273 mAnimTransactionPending = false;
3274 break;
3275 }
3276 }
3277 }
3278
chaviwca27f252018-02-06 16:46:39 -08003279 for (const DisplayState& display : displays) {
3280 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003281 }
3282
chaviwca27f252018-02-06 16:46:39 -08003283 for (const ComposerState& state : states) {
3284 transactionFlags |= setClientStateLocked(state);
3285 }
3286
3287 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3288 // as destroyed should only occur after setting all other states. This is to allow for a
3289 // child re-parent to happen before marking its original parent as destroyed (which would
3290 // then mark the child as destroyed).
3291 for (const ComposerState& state : states) {
3292 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003293 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003294
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003295 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3296 // anyway. This can be used as a flush mechanism for previous async transactions.
3297 // Empty animation transaction can be used to simulate back-pressure, so also force a
3298 // transaction for empty animation transactions.
3299 if (transactionFlags == 0 &&
3300 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003301 transactionFlags = eTransactionNeeded;
3302 }
3303
Mathias Agopian386aa982011-11-07 21:58:03 -08003304 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003305 if (mInterceptor->isEnabled()) {
3306 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003307 }
Irvel468051e2016-06-13 16:44:44 -07003308
Mathias Agopian386aa982011-11-07 21:58:03 -08003309 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003310 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3311 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003312 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003313
3314 // if this is a synchronous transaction, wait for it to take effect
3315 // before returning.
3316 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003317 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003318 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003319 if (flags & eAnimation) {
3320 mAnimTransactionPending = true;
3321 }
3322 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003323 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3324 if (CC_UNLIKELY(err != NO_ERROR)) {
3325 // just in case something goes wrong in SF, return to the
3326 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003327 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3328 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003329 break;
3330 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003331 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003332 }
3333}
3334
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003335uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3336 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3337 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003338
Mathias Agopiane57f2922012-08-09 16:29:12 -07003339 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003340 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3341
3342 const uint32_t what = s.what;
3343 if (what & DisplayState::eSurfaceChanged) {
3344 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3345 state.surface = s.surface;
3346 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003347 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003348 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003349 if (what & DisplayState::eLayerStackChanged) {
3350 if (state.layerStack != s.layerStack) {
3351 state.layerStack = s.layerStack;
3352 flags |= eDisplayTransactionNeeded;
3353 }
3354 }
3355 if (what & DisplayState::eDisplayProjectionChanged) {
3356 if (state.orientation != s.orientation) {
3357 state.orientation = s.orientation;
3358 flags |= eDisplayTransactionNeeded;
3359 }
3360 if (state.frame != s.frame) {
3361 state.frame = s.frame;
3362 flags |= eDisplayTransactionNeeded;
3363 }
3364 if (state.viewport != s.viewport) {
3365 state.viewport = s.viewport;
3366 flags |= eDisplayTransactionNeeded;
3367 }
3368 }
3369 if (what & DisplayState::eDisplaySizeChanged) {
3370 if (state.width != s.width) {
3371 state.width = s.width;
3372 flags |= eDisplayTransactionNeeded;
3373 }
3374 if (state.height != s.height) {
3375 state.height = s.height;
3376 flags |= eDisplayTransactionNeeded;
3377 }
3378 }
3379
Mathias Agopiane57f2922012-08-09 16:29:12 -07003380 return flags;
3381}
3382
Robert Carrd4ae7f32018-06-07 16:10:57 -07003383bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3384 IPCThreadState* ipc = IPCThreadState::self();
3385 const int pid = ipc->getCallingPid();
3386 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003387 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003388 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003389 return false;
3390 }
3391 return true;
3392}
3393
chaviwca27f252018-02-06 16:46:39 -08003394uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3395 const layer_state_t& s = composerState.state;
3396 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3397
Mathias Agopian13127d82013-03-05 17:47:11 -08003398 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003399 if (layer == nullptr) {
3400 return 0;
3401 }
3402
chaviw8b3871a2017-11-01 17:41:01 -07003403 uint32_t flags = 0;
3404
3405 const uint32_t what = s.what;
3406 bool geometryAppliesWithResize =
3407 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003408
3409 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3410 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003411 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003412 layer->pushPendingState();
3413 }
3414
chaviw8b3871a2017-11-01 17:41:01 -07003415 if (what & layer_state_t::ePositionChanged) {
3416 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3417 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003418 }
chaviw8b3871a2017-11-01 17:41:01 -07003419 }
3420 if (what & layer_state_t::eLayerChanged) {
3421 // NOTE: index needs to be calculated before we update the state
3422 const auto& p = layer->getParent();
3423 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003424 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003425 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003426 mCurrentState.layersSortedByZ.removeAt(idx);
3427 mCurrentState.layersSortedByZ.add(layer);
3428 // we need traversal (state changed)
3429 // AND transaction (list changed)
3430 flags |= eTransactionNeeded|eTraversalNeeded;
3431 }
chaviw8b3871a2017-11-01 17:41:01 -07003432 } else {
3433 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003434 flags |= eTransactionNeeded|eTraversalNeeded;
3435 }
3436 }
chaviw8b3871a2017-11-01 17:41:01 -07003437 }
3438 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003439 // NOTE: index needs to be calculated before we update the state
3440 const auto& p = layer->getParent();
3441 if (p == nullptr) {
3442 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3443 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3444 mCurrentState.layersSortedByZ.removeAt(idx);
3445 mCurrentState.layersSortedByZ.add(layer);
3446 // we need traversal (state changed)
3447 // AND transaction (list changed)
3448 flags |= eTransactionNeeded|eTraversalNeeded;
3449 }
3450 } else {
3451 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3452 flags |= eTransactionNeeded|eTraversalNeeded;
3453 }
chaviw8b3871a2017-11-01 17:41:01 -07003454 }
3455 }
3456 if (what & layer_state_t::eSizeChanged) {
3457 if (layer->setSize(s.w, s.h)) {
3458 flags |= eTraversalNeeded;
3459 }
3460 }
3461 if (what & layer_state_t::eAlphaChanged) {
3462 if (layer->setAlpha(s.alpha))
3463 flags |= eTraversalNeeded;
3464 }
3465 if (what & layer_state_t::eColorChanged) {
3466 if (layer->setColor(s.color))
3467 flags |= eTraversalNeeded;
3468 }
Peiyong Lind3788632018-09-18 16:01:31 -07003469 if (what & layer_state_t::eColorTransformChanged) {
3470 if (layer->setColorTransform(s.colorTransform)) {
3471 flags |= eTraversalNeeded;
3472 }
3473 }
chaviw8b3871a2017-11-01 17:41:01 -07003474 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003475 // TODO: b/109894387
3476 //
3477 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3478 // rotation. To see the problem observe that if we have a square parent, and a child
3479 // of the same size, then we rotate the child 45 degrees around it's center, the child
3480 // must now be cropped to a non rectangular 8 sided region.
3481 //
3482 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3483 // private API, and the WindowManager only uses rotation in one case, which is on a top
3484 // level layer in which cropping is not an issue.
3485 //
3486 // However given that abuse of rotation matrices could lead to surfaces extending outside
3487 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3488 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3489 // transformations.
3490 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003491 flags |= eTraversalNeeded;
3492 }
3493 if (what & layer_state_t::eTransparentRegionChanged) {
3494 if (layer->setTransparentRegionHint(s.transparentRegion))
3495 flags |= eTraversalNeeded;
3496 }
3497 if (what & layer_state_t::eFlagsChanged) {
3498 if (layer->setFlags(s.flags, s.mask))
3499 flags |= eTraversalNeeded;
3500 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003501 if (what & layer_state_t::eCropChanged_legacy) {
3502 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003503 flags |= eTraversalNeeded;
3504 }
chaviw8b3871a2017-11-01 17:41:01 -07003505 if (what & layer_state_t::eLayerStackChanged) {
3506 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3507 // We only allow setting layer stacks for top level layers,
3508 // everything else inherits layer stack from its parent.
3509 if (layer->hasParent()) {
3510 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3511 layer->getName().string());
3512 } else if (idx < 0) {
3513 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3514 "that also does not appear in the top level layer list. Something"
3515 " has gone wrong.", layer->getName().string());
3516 } else if (layer->setLayerStack(s.layerStack)) {
3517 mCurrentState.layersSortedByZ.removeAt(idx);
3518 mCurrentState.layersSortedByZ.add(layer);
3519 // we need traversal (state changed)
3520 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003521 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003522 }
3523 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003524 if (what & layer_state_t::eDeferTransaction_legacy) {
3525 if (s.barrierHandle_legacy != nullptr) {
3526 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3527 } else if (s.barrierGbp_legacy != nullptr) {
3528 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003529 if (authenticateSurfaceTextureLocked(gbp)) {
3530 const auto& otherLayer =
3531 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003532 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003533 } else {
3534 ALOGE("Attempt to defer transaction to to an"
3535 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003536 }
3537 }
chaviw8b3871a2017-11-01 17:41:01 -07003538 // We don't trigger a traversal here because if no other state is
3539 // changed, we don't want this to cause any more work
3540 }
3541 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003542 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003543 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003544 if (!hadParent) {
3545 mCurrentState.layersSortedByZ.remove(layer);
3546 }
chaviw8b3871a2017-11-01 17:41:01 -07003547 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003548 }
chaviw8b3871a2017-11-01 17:41:01 -07003549 }
3550 if (what & layer_state_t::eReparentChildren) {
3551 if (layer->reparentChildren(s.reparentHandle)) {
3552 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003553 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003554 }
chaviw8b3871a2017-11-01 17:41:01 -07003555 if (what & layer_state_t::eDetachChildren) {
3556 layer->detachChildren();
3557 }
3558 if (what & layer_state_t::eOverrideScalingModeChanged) {
3559 layer->setOverrideScalingMode(s.overrideScalingMode);
3560 // We don't trigger a traversal here because if no other state is
3561 // changed, we don't want this to cause any more work
3562 }
Marissa Wall61c58622018-07-18 10:12:20 -07003563 if (what & layer_state_t::eTransformChanged) {
3564 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3565 }
3566 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3567 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3568 flags |= eTraversalNeeded;
3569 }
3570 if (what & layer_state_t::eCropChanged) {
3571 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3572 }
3573 if (what & layer_state_t::eBufferChanged) {
3574 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3575 }
3576 if (what & layer_state_t::eAcquireFenceChanged) {
3577 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3578 }
3579 if (what & layer_state_t::eDataspaceChanged) {
3580 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3581 }
3582 if (what & layer_state_t::eHdrMetadataChanged) {
3583 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3584 }
3585 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3586 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3587 }
3588 if (what & layer_state_t::eApiChanged) {
3589 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3590 }
3591 if (what & layer_state_t::eSidebandStreamChanged) {
3592 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3593 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003594 return flags;
3595}
3596
chaviwca27f252018-02-06 16:46:39 -08003597void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3598 const layer_state_t& state = composerState.state;
3599 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3600
3601 sp<Layer> layer(client->getLayerUser(state.surface));
3602 if (layer == nullptr) {
3603 return;
3604 }
3605
chaviwca27f252018-02-06 16:46:39 -08003606 if (state.what & layer_state_t::eDestroySurface) {
3607 removeLayerLocked(mStateLock, layer);
3608 }
3609}
3610
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003611status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003612 const String8& name,
3613 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003614 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003615 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003616 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003617{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003618 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003619 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003620 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003621 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003622 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003623
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003624 status_t result = NO_ERROR;
3625
3626 sp<Layer> layer;
3627
Cody Northropbc755282017-03-31 12:00:08 -06003628 String8 uniqueName = getUniqueLayerName(name);
3629
Mathias Agopian3165cc22012-08-08 19:42:09 -07003630 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003631 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003632 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3633 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003634
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003635 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003636 case ISurfaceComposerClient::eFXSurfaceBufferState:
3637 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3638 break;
chaviw13fdc492017-06-27 12:40:18 -07003639 case ISurfaceComposerClient::eFXSurfaceColor:
3640 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003641 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003642 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003643 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003644 case ISurfaceComposerClient::eFXSurfaceContainer:
3645 result = createContainerLayer(client,
3646 uniqueName, w, h, flags,
3647 handle, &layer);
3648 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003649 default:
3650 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003651 break;
3652 }
3653
Dan Stoza7d89d062015-04-30 13:29:25 -07003654 if (result != NO_ERROR) {
3655 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003656 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003657
Chia-I Wuab0c3192017-08-01 11:29:00 -07003658 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3659 // TODO b/64227542
3660 if (windowType == 441731) {
3661 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3662 layer->setPrimaryDisplayOnly();
3663 }
3664
Albert Chaulk479c60c2017-01-27 14:21:34 -05003665 layer->setInfo(windowType, ownerUid);
3666
Robert Carr1f0a16a2016-10-24 16:27:39 -07003667 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003668 if (result != NO_ERROR) {
3669 return result;
3670 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003671 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003672
3673 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003674 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003675}
3676
Cody Northropbc755282017-03-31 12:00:08 -06003677String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3678{
3679 bool matchFound = true;
3680 uint32_t dupeCounter = 0;
3681
3682 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3683 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3684
Dan Stoza436ccf32018-06-21 12:10:12 -07003685 // Grab the state lock since we're accessing mCurrentState
3686 Mutex::Autolock lock(mStateLock);
3687
Cody Northropbc755282017-03-31 12:00:08 -06003688 // Loop over layers until we're sure there is no matching name
3689 while (matchFound) {
3690 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003691 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003692 if (layer->getName() == uniqueName) {
3693 matchFound = true;
3694 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3695 }
3696 });
3697 }
3698
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003699 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3700 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003701
3702 return uniqueName;
3703}
3704
Marissa Wallfd668622018-05-10 10:21:13 -07003705status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3706 uint32_t w, uint32_t h, uint32_t flags,
3707 PixelFormat& format, sp<IBinder>* handle,
3708 sp<IGraphicBufferProducer>* gbp,
3709 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003710 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003711 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003712 case PIXEL_FORMAT_TRANSPARENT:
3713 case PIXEL_FORMAT_TRANSLUCENT:
3714 format = PIXEL_FORMAT_RGBA_8888;
3715 break;
3716 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003717 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003718 break;
3719 }
3720
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003721 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003722 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003723 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003724 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003725 *handle = layer->getHandle();
3726 *gbp = layer->getProducer();
3727 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003728 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003729
Marissa Wallfd668622018-05-10 10:21:13 -07003730 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003731 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003732}
3733
Marissa Wall61c58622018-07-18 10:12:20 -07003734status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3735 uint32_t w, uint32_t h, uint32_t flags,
3736 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003737 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003738 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003739 *handle = layer->getHandle();
3740 *outLayer = layer;
3741
3742 return NO_ERROR;
3743}
3744
chaviw13fdc492017-06-27 12:40:18 -07003745status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003746 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003747 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003748{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003749 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003750 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003751 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003752}
3753
Robert Carr6b3f6c52018-08-13 13:05:17 -07003754status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3755 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3756 sp<IBinder>* handle, sp<Layer>* outLayer)
3757{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003758 *outLayer =
3759 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003760 *handle = (*outLayer)->getHandle();
3761 return NO_ERROR;
3762}
3763
3764
Mathias Agopianac9fa422013-02-11 16:40:36 -08003765status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003766{
Robert Carr9524cb32017-02-13 11:32:32 -08003767 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003768 status_t err = NO_ERROR;
3769 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003770 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003771 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003772 err = removeLayer(l);
3773 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3774 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003775 }
3776 return err;
3777}
3778
Robert Carr2e102c92018-10-23 12:11:15 -07003779void SurfaceFlinger::markLayerPendingRemovalLocked(const Mutex&, const sp<Layer>& layer) {
3780 mLayersPendingRemoval.add(layer);
3781 mLayersRemoved = true;
3782 setTransactionFlags(eTransactionNeeded);
3783}
3784
3785void SurfaceFlinger::onHandleDestroyed(const sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003786{
Robert Carr2e102c92018-10-23 12:11:15 -07003787 Mutex::Autolock lock(mStateLock);
3788 markLayerPendingRemovalLocked(mStateLock, layer);
Rob Carr4bba3702018-10-08 21:53:30 +00003789}
3790
Mathias Agopianb60314a2012-04-10 22:09:54 -07003791// ---------------------------------------------------------------------------
3792
Andy McFadden13a082e2012-08-24 10:16:42 -07003793void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003794 const auto displayToken = getInternalDisplayToken();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003795 if (!displayToken) return;
3796
Jesse Hall01e29052013-02-19 16:13:35 -08003797 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003798 Vector<ComposerState> state;
3799 Vector<DisplayState> displays;
3800 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003801 d.what = DisplayState::eDisplayProjectionChanged |
3802 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003803 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003804 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003805 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003806 d.frame.makeInvalid();
3807 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003808 d.width = 0;
3809 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003810 displays.add(d);
3811 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003812
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003813 const auto display = getDisplayDevice(displayToken);
3814 if (!display) return;
3815
3816 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3817
Dominik Laskowski075d3172018-05-24 15:50:06 -07003818 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003819 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003820 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003821
Brian Andersond0010582017-03-07 13:20:31 -08003822 // Use phase of 0 since phase is not known.
3823 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07003824 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
3825 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003826}
3827
3828void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003829 // Async since we may be called from the main thread.
3830 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003831}
3832
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003833void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3834 bool stateLockHeld) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003835 if (display->isVirtual()) {
3836 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003837 return;
3838 }
3839
Dominik Laskowski075d3172018-05-24 15:50:06 -07003840 const auto displayId = display->getId();
3841 LOG_ALWAYS_FATAL_IF(!displayId);
3842
3843 ALOGD("Setting power mode %d on display %" PRIu64, mode, *displayId);
3844
3845 int currentMode = display->getPowerMode();
3846 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003847 return;
3848 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003849
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003850 display->setPowerMode(mode);
3851
Lloyd Pique4dccc412018-01-22 17:21:36 -08003852 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003853 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003854 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003855 if (idx < 0) {
3856 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3857 return;
3858 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003859 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003860 }
3861
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003862 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003863 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07003864 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003865 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07003866 if (mUseScheduler) {
3867 mScheduler->onScreenAcquired(mAppConnectionHandle);
3868 } else {
3869 mEventThread->onScreenAcquired();
3870 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07003871 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003872 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003873
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003874 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003875 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003876 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003877
3878 struct sched_param param = {0};
3879 param.sched_priority = 1;
3880 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3881 ALOGW("Couldn't set SCHED_FIFO on display on");
3882 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003883 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003884 // Turn off the display
3885 struct sched_param param = {0};
3886 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3887 ALOGW("Couldn't set SCHED_OTHER on display off");
3888 }
3889
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003890 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07003891 if (mUseScheduler) {
3892 mScheduler->disableHardwareVsync(true);
3893 } else {
3894 disableHardwareVsync(true); // also cancels any in-progress resync
3895 }
Ana Krulec98b5b242018-08-10 15:03:23 -07003896 if (mUseScheduler) {
3897 mScheduler->onScreenReleased(mAppConnectionHandle);
3898 } else {
3899 mEventThread->onScreenReleased();
3900 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07003901 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003902
Dominik Laskowski075d3172018-05-24 15:50:06 -07003903 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003904 mVisibleRegionsDirty = true;
3905 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003906 } else if (mode == HWC_POWER_MODE_DOZE ||
3907 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003908 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07003909 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003910 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07003911 if (mUseScheduler) {
3912 mScheduler->onScreenAcquired(mAppConnectionHandle);
3913 } else {
3914 mEventThread->onScreenAcquired();
3915 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003916 resyncToHardwareVsync(true);
3917 }
3918 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3919 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003920 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07003921 if (mUseScheduler) {
3922 mScheduler->disableHardwareVsync(true);
3923 } else {
3924 disableHardwareVsync(true); // also cancels any in-progress resync
3925 }
Ana Krulec98b5b242018-08-10 15:03:23 -07003926 if (mUseScheduler) {
3927 mScheduler->onScreenReleased(mAppConnectionHandle);
3928 } else {
3929 mEventThread->onScreenReleased();
3930 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003931 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07003932 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003933 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003934 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003935 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003936 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003937
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003938 if (display->isPrimary()) {
3939 mTimeStats.setPowerMode(mode);
3940 }
3941
Dominik Laskowski075d3172018-05-24 15:50:06 -07003942 ALOGD("Finished setting power mode %d on display %" PRIu64, mode, *displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003943}
3944
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003945void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003946 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003947 const auto display = getDisplayDevice(displayToken);
3948 if (!display) {
3949 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3950 displayToken.get());
3951 } else if (display->isVirtual()) {
3952 ALOGW("Attempt to set power mode %d for virtual display", mode);
3953 } else {
3954 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003955 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003956 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003957}
3958
3959// ---------------------------------------------------------------------------
3960
Lloyd Pique755e3192018-01-31 16:46:15 -08003961status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3962 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003963 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003964
Mathias Agopianbd115332013-04-18 16:41:04 -07003965 IPCThreadState* ipc = IPCThreadState::self();
3966 const int pid = ipc->getCallingPid();
3967 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003968
Mathias Agopianbd115332013-04-18 16:41:04 -07003969 if ((uid != AID_SHELL) &&
3970 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003971 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003972 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003973 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003974 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003975 // (this would indicate SF is stuck, but we want to be able to
3976 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003977 status_t err = mStateLock.timedLock(s2ns(1));
3978 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003979 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003980 result.appendFormat(
3981 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3982 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003983 }
3984
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003985 bool dumpAll = true;
3986 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003987 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003988
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003989 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003990 if ((index < numArgs) &&
3991 (args[index] == String16("--list"))) {
3992 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003993 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003994 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003995 }
3996
3997 if ((index < numArgs) &&
3998 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003999 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004000 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004001 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004002 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004003
4004 if ((index < numArgs) &&
4005 (args[index] == String16("--latency-clear"))) {
4006 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004007 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004008 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004009 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004010
4011 if ((index < numArgs) &&
4012 (args[index] == String16("--dispsync"))) {
4013 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004014 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004015 dumpAll = false;
4016 }
Dan Stozab90cf072015-03-05 11:05:59 -08004017
4018 if ((index < numArgs) &&
4019 (args[index] == String16("--static-screen"))) {
4020 index++;
4021 dumpStaticScreenStats(result);
4022 dumpAll = false;
4023 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004024
4025 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004026 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004027 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004028 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004029 dumpAll = false;
4030 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004031
4032 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4033 index++;
4034 dumpWideColorInfo(result);
4035 dumpAll = false;
4036 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004037
4038 if ((index < numArgs) &&
4039 (args[index] == String16("--enable-layer-stats"))) {
4040 index++;
4041 mLayerStats.enable();
4042 dumpAll = false;
4043 }
4044
4045 if ((index < numArgs) &&
4046 (args[index] == String16("--disable-layer-stats"))) {
4047 index++;
4048 mLayerStats.disable();
4049 dumpAll = false;
4050 }
4051
4052 if ((index < numArgs) &&
4053 (args[index] == String16("--clear-layer-stats"))) {
4054 index++;
4055 mLayerStats.clear();
4056 dumpAll = false;
4057 }
4058
4059 if ((index < numArgs) &&
4060 (args[index] == String16("--dump-layer-stats"))) {
4061 index++;
4062 mLayerStats.dump(result);
4063 dumpAll = false;
4064 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004065
4066 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004067 (args[index] == String16("--frame-composition"))) {
4068 index++;
4069 dumpFrameCompositionInfo(result);
4070 dumpAll = false;
4071 }
4072
4073 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004074 (args[index] == String16("--display-identification"))) {
4075 index++;
4076 dumpDisplayIdentificationData(result);
4077 dumpAll = false;
4078 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004079
4080 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4081 index++;
4082 mTimeStats.parseArgs(asProto, args, index, result);
4083 dumpAll = false;
4084 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004085 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004086
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004087 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004088 if (asProto) {
4089 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4090 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4091 } else {
4092 dumpAllLocked(args, index, result);
4093 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004094 }
4095
Mathias Agopian9795c422009-08-26 16:36:26 -07004096 if (locked) {
4097 mStateLock.unlock();
4098 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004099 }
4100 write(fd, result.string(), result.size());
4101 return NO_ERROR;
4102}
4103
Dan Stozac7014012014-02-14 15:03:43 -08004104void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4105 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004106{
Robert Carr2047fae2016-11-28 14:09:09 -08004107 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004108 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004109 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004110}
4111
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004112void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004113 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004114{
4115 String8 name;
4116 if (index < args.size()) {
4117 name = String8(args[index]);
4118 index++;
4119 }
4120
Dominik Laskowski075d3172018-05-24 15:50:06 -07004121 if (const auto displayId = getInternalDisplayId();
4122 displayId && getHwComposer().isConnected(*displayId)) {
4123 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004124 const nsecs_t period = activeConfig->getVsyncPeriod();
4125 result.appendFormat("%" PRId64 "\n", period);
4126 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004127
4128 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004129 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004130 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004131 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004132 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004133 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004134 }
Robert Carr2047fae2016-11-28 14:09:09 -08004135 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004136 }
4137}
4138
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004139void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004140 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004141{
4142 String8 name;
4143 if (index < args.size()) {
4144 name = String8(args[index]);
4145 index++;
4146 }
4147
Robert Carr2047fae2016-11-28 14:09:09 -08004148 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004149 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004150 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004151 }
Robert Carr2047fae2016-11-28 14:09:09 -08004152 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004153
Svetoslavd85084b2014-03-20 10:28:31 -07004154 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004155}
4156
Jamie Gennis6547ff42013-07-16 20:12:42 -07004157// This should only be called from the main thread. Otherwise it would need
4158// the lock and should use mCurrentState rather than mDrawingState.
4159void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004160 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004161 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004162 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004163
4164 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4165}
4166
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004167void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004168{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004169 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004170
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004171 if (isLayerTripleBufferingDisabled())
4172 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004173
4174 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004175 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004176 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004177 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004178 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4179 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004180 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004181}
4182
Dan Stozab90cf072015-03-05 11:05:59 -08004183void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4184{
4185 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004186 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4187 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004188 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004189 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004190 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4191 b + 1, bucketTimeSec, percent);
4192 }
David Sodman4a36e932017-11-07 14:29:47 -08004193 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004194 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004195 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004196 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004197 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004198}
4199
Dan Stozae77c7662016-05-13 11:37:28 -07004200void SurfaceFlinger::recordBufferingStats(const char* layerName,
4201 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004202 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4203 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004204 for (const auto& segment : history) {
4205 if (!segment.usedThirdBuffer) {
4206 stats.twoBufferTime += segment.totalTime;
4207 }
4208 if (segment.occupancyAverage < 1.0f) {
4209 stats.doubleBufferedTime += segment.totalTime;
4210 } else if (segment.occupancyAverage < 2.0f) {
4211 stats.tripleBufferedTime += segment.totalTime;
4212 }
4213 ++stats.numSegments;
4214 stats.totalTime += segment.totalTime;
4215 }
4216}
4217
Brian Andersond6927fb2016-07-23 23:37:30 -07004218void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4219 result.appendFormat("Layer frame timestamps:\n");
4220
4221 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4222 const size_t count = currentLayers.size();
4223 for (size_t i=0 ; i<count ; i++) {
4224 currentLayers[i]->dumpFrameEvents(result);
4225 }
4226}
4227
Dan Stozae77c7662016-05-13 11:37:28 -07004228void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4229 result.append("Buffering stats:\n");
4230 result.append(" [Layer name] <Active time> <Two buffer> "
4231 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004232 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004233 typedef std::tuple<std::string, float, float, float> BufferTuple;
4234 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004235 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004236 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004237 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004238 if (stats.numSegments == 0) {
4239 continue;
4240 }
4241 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4242 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4243 stats.totalTime;
4244 float doubleBufferRatio = static_cast<float>(
4245 stats.doubleBufferedTime) / stats.totalTime;
4246 float tripleBufferRatio = static_cast<float>(
4247 stats.tripleBufferedTime) / stats.totalTime;
4248 sorted.insert({activeTime, {name, twoBufferRatio,
4249 doubleBufferRatio, tripleBufferRatio}});
4250 }
4251 for (const auto& sortedPair : sorted) {
4252 float activeTime = sortedPair.first;
4253 const BufferTuple& values = sortedPair.second;
4254 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4255 std::get<0>(values).c_str(), activeTime,
4256 std::get<1>(values), std::get<2>(values),
4257 std::get<3>(values));
4258 }
4259 result.append("\n");
4260}
4261
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004262void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004263 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004264 const auto displayId = display->getId();
4265 if (!displayId) {
4266 continue;
4267 }
4268 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004269 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004270 continue;
4271 }
4272
Dominik Laskowski075d3172018-05-24 15:50:06 -07004273 result.appendFormat("Display %" PRIu64 " (HWC display %" PRIu64 "): ", *displayId,
4274 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004275 uint8_t port;
4276 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004277 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004278 result.append("no identification data\n");
4279 continue;
4280 }
4281
4282 if (!isEdid(data)) {
4283 result.append("unknown identification data: ");
4284 for (uint8_t byte : data) {
4285 result.appendFormat("%x ", byte);
4286 }
4287 result.append("\n");
4288 continue;
4289 }
4290
4291 const auto edid = parseEdid(data);
4292 if (!edid) {
4293 result.append("invalid EDID: ");
4294 for (uint8_t byte : data) {
4295 result.appendFormat("%x ", byte);
4296 }
4297 result.append("\n");
4298 continue;
4299 }
4300
4301 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4302 result.append(edid->displayName.data(), edid->displayName.length());
4303 result.append("\"\n");
4304 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004305}
4306
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004307void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004308 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4309 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004310 result.appendFormat("DisplayColorSetting: %s\n",
4311 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004312
4313 // TODO: print out if wide-color mode is active or not
4314
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004315 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004316 const auto displayId = display->getId();
4317 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004318 continue;
4319 }
4320
Dominik Laskowski075d3172018-05-24 15:50:06 -07004321 result.appendFormat("Display %" PRIu64 " color modes:\n", *displayId);
4322 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004323 for (auto&& mode : modes) {
4324 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4325 }
4326
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004327 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004328 result.appendFormat(" Current color mode: %s (%d)\n",
4329 decodeColorMode(currentMode).c_str(), currentMode);
4330 }
4331 result.append("\n");
4332}
4333
David Sodman7e4ae112018-02-09 15:02:28 -08004334void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4335 std::string stringResult;
4336
4337 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004338 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4339 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004340 continue;
4341 }
4342
Dominik Laskowski05275f12018-11-01 15:03:24 -07004343 const auto& compositionInfoList = it->second;
4344 stringResult += base::StringPrintf("%s\n", display->getDebugName().c_str());
David Sodman7e4ae112018-02-09 15:02:28 -08004345 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4346 for (const auto& compositionInfo : compositionInfoList) {
4347 compositionInfo.dump(stringResult, nullptr);
4348 stringResult += base::StringPrintf("\n");
4349 }
4350 }
4351
4352 result.append(stringResult.c_str());
4353}
4354
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004355LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004356 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004357 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4358 const State& state = useDrawing ? mDrawingState : mCurrentState;
4359 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004360 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004361 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004362 });
4363
4364 return layersProto;
4365}
4366
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004367LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004368 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004369
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004370 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004371 resolution->set_w(display.getWidth());
4372 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004373
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004374 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4375 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4376 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004377
Dominik Laskowski075d3172018-05-24 15:50:06 -07004378 const auto displayId = display.getId();
4379 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004380 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004381 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004382 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004383 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004384 }
4385 });
4386
4387 return layersProto;
4388}
4389
Mathias Agopian74d211a2013-04-22 16:55:35 +02004390void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4391 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004392{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004393 bool colorize = false;
4394 if (index < args.size()
4395 && (args[index] == String16("--color"))) {
4396 colorize = true;
4397 index++;
4398 }
4399
4400 Colorizer colorizer(colorize);
4401
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004402 // figure out if we're stuck somewhere
4403 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004404 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004405 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4406
4407 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004408 * Dump library configuration.
4409 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004410
4411 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004412 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004413 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004414 appendSfConfigString(result);
4415 appendUiConfigString(result);
4416 appendGuiConfigString(result);
4417 result.append("\n");
4418
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004419 result.append("\nDisplay identification data:\n");
4420 dumpDisplayIdentificationData(result);
4421
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004422 result.append("\nWide-Color information:\n");
4423 dumpWideColorInfo(result);
4424
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004425 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004426 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004427 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004428 result.append(SyncFeatures::getInstance().toString());
4429 result.append("\n");
4430
Andy McFadden41d67d72014-04-25 16:58:34 -07004431 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004432 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004433 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004434
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004435 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4436 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004437 if (const auto displayId = getInternalDisplayId();
4438 displayId && getHwComposer().isConnected(*displayId)) {
4439 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
4440 result.appendFormat("Display %" PRIu64 ": app phase %" PRId64 " ns, "
4441 "sf phase %" PRId64 " ns, "
4442 "early app phase %" PRId64 " ns, "
4443 "early sf phase %" PRId64 " ns, "
4444 "early app gl phase %" PRId64 " ns, "
4445 "early sf gl phase %" PRId64 " ns, "
4446 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4447 *displayId, vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, appEarlyOffset,
4448 sfEarlyOffset, appEarlyGlOffset, sfEarlyGlOffset,
4449 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004450 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004451 result.append("\n");
4452
Dan Stozab90cf072015-03-05 11:05:59 -08004453 // Dump static screen stats
4454 result.append("\n");
4455 dumpStaticScreenStats(result);
4456 result.append("\n");
4457
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004458 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4459
Dan Stozae77c7662016-05-13 11:37:28 -07004460 dumpBufferingStats(result);
4461
Andy McFadden4803b742012-09-24 19:07:20 -07004462 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004463 * Dump the visible layer list
4464 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004465 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004466 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004467 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4468 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004469 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004470
Chia-I Wu2f884132018-09-13 15:17:58 -07004471 {
4472 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4473 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4474 result.append(LayerProtoParser::layerTreeToString(layerTree).c_str());
4475 result.append("\n");
4476 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004477
David Sodman7e4ae112018-02-09 15:02:28 -08004478 result.append("\nFrame-Composition information:\n");
4479 dumpFrameCompositionInfo(result);
4480 result.append("\n");
4481
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004482 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004483 * Dump Display state
4484 */
4485
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004486 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004487 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004488 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004489 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004490 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004491 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004492 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004493
4494 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004495 * Dump SurfaceFlinger global state
4496 */
4497
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004498 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004499 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004500 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004501
David Sodmanbc815282017-11-05 18:57:52 -08004502 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004503
Dominik Laskowski075d3172018-05-24 15:50:06 -07004504 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004505 display->undefinedRegion.dump(result, "undefinedRegion");
4506 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4507 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004508 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004509 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004510 " gpu_to_cpu_unsupported : %d\n",
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004511 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004512
Dominik Laskowski075d3172018-05-24 15:50:06 -07004513 if (const auto displayId = getInternalDisplayId();
4514 displayId && getHwComposer().isConnected(*displayId)) {
4515 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004516 result.appendFormat(" refresh-rate : %f fps\n"
4517 " x-dpi : %f\n"
4518 " y-dpi : %f\n",
4519 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4520 activeConfig->getDpiY());
4521 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004522
Mathias Agopian74d211a2013-04-22 16:55:35 +02004523 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004524 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004525
Ana Krulec98b5b242018-08-10 15:03:23 -07004526 result.appendFormat(" use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004527 /*
4528 * VSYNC state
4529 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004530 if (mUseScheduler) {
4531 mScheduler->dump(mAppConnectionHandle, result);
4532 } else {
4533 mEventThread->dump(result);
4534 }
Dan Stozae22aec72016-08-01 13:20:59 -07004535 result.append("\n");
4536
4537 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004538 * Tracing state
4539 */
4540 mTracing.dump(result);
4541 result.append("\n");
4542
4543 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004544 * HWC layer minidump
4545 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004546 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004547 const auto displayId = display->getId();
4548 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004549 continue;
4550 }
4551
Dominik Laskowski075d3172018-05-24 15:50:06 -07004552 result.appendFormat("Display %" PRIu64 " HWC layers:\n", *displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004553 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004554 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004555 result.append("\n");
4556 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004557
4558 /*
4559 * Dump HWComposer state
4560 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004561 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004562 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004563 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004564 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004565 result.appendFormat(" h/w composer %s\n",
4566 hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004567 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004568
4569 /*
4570 * Dump gralloc state
4571 */
4572 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4573 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004574
4575 /*
4576 * Dump VrFlinger state if in use.
4577 */
4578 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4579 result.append("VrFlinger state:\n");
4580 result.append(mVrFlinger->Dump().c_str());
4581 result.append("\n");
4582 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004583}
4584
Dominik Laskowski075d3172018-05-24 15:50:06 -07004585const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004586 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004587 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004588 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004589 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004590 }
4591 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004592
Dominik Laskowski075d3172018-05-24 15:50:06 -07004593 ALOGE("%s: Invalid display %" PRIu64, __FUNCTION__, displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004594 static const Vector<sp<Layer>> empty;
4595 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004596}
4597
Keun young Park63f165f2012-08-31 10:53:36 -07004598bool SurfaceFlinger::startDdmConnection()
4599{
4600 void* libddmconnection_dso =
4601 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4602 if (!libddmconnection_dso) {
4603 return false;
4604 }
4605 void (*DdmConnection_start)(const char* name);
4606 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004607 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004608 if (!DdmConnection_start) {
4609 dlclose(libddmconnection_dso);
4610 return false;
4611 }
4612 (*DdmConnection_start)(getServiceName());
4613 return true;
4614}
4615
Chia-I Wu28f320b2018-05-03 11:02:56 -07004616void SurfaceFlinger::updateColorMatrixLocked() {
4617 mat4 colorMatrix;
4618 if (mGlobalSaturationFactor != 1.0f) {
4619 // Rec.709 luma coefficients
4620 float3 luminance{0.213f, 0.715f, 0.072f};
4621 luminance *= 1.0f - mGlobalSaturationFactor;
4622 mat4 saturationMatrix = mat4(
4623 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4624 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4625 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4626 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4627 );
4628 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4629 } else {
4630 colorMatrix = mClientColorMatrix * mDaltonizer();
4631 }
4632
4633 if (mCurrentState.colorMatrix != colorMatrix) {
4634 mCurrentState.colorMatrix = colorMatrix;
4635 mCurrentState.colorMatrixChanged = true;
4636 setTransactionFlags(eTransactionNeeded);
4637 }
4638}
4639
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004640status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004641#pragma clang diagnostic push
4642#pragma clang diagnostic error "-Wswitch-enum"
4643 switch (static_cast<ISurfaceComposerTag>(code)) {
4644 // These methods should at minimum make sure that the client requested
4645 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004646 case BOOT_FINISHED:
4647 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004648 case CREATE_CONNECTION:
4649 case CREATE_DISPLAY:
4650 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004651 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004652 case GET_ACTIVE_COLOR_MODE:
4653 case GET_ANIMATION_FRAME_STATS:
4654 case GET_HDR_CAPABILITIES:
4655 case SET_ACTIVE_CONFIG:
4656 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004657 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004658 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004659 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4660 IPCThreadState* ipc = IPCThreadState::self();
4661 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4662 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004663 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004664 }
Robert Carr1db73f62016-12-21 12:58:51 -08004665 return OK;
4666 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004667 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004668 IPCThreadState* ipc = IPCThreadState::self();
4669 const int pid = ipc->getCallingPid();
4670 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004671 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4672 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004673 return PERMISSION_DENIED;
4674 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004675 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004676 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004677 // Used by apps to hook Choreographer to SurfaceFlinger.
4678 case CREATE_DISPLAY_EVENT_CONNECTION:
4679 // The following calls are currently used by clients that do not
4680 // request necessary permissions. However, they do not expose any secret
4681 // information, so it is OK to pass them.
4682 case AUTHENTICATE_SURFACE:
4683 case GET_ACTIVE_CONFIG:
4684 case GET_BUILT_IN_DISPLAY:
4685 case GET_DISPLAY_COLOR_MODES:
4686 case GET_DISPLAY_CONFIGS:
4687 case GET_DISPLAY_STATS:
4688 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4689 // Calling setTransactionState is safe, because you need to have been
4690 // granted a reference to Client* and Handle* to do anything with it.
4691 case SET_TRANSACTION_STATE:
4692 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004693 case CREATE_SCOPED_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004694 case GET_COLOR_MANAGEMENT:
Peiyong Lin0256f722018-08-31 15:45:10 -07004695 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004696 return OK;
4697 }
4698 case CAPTURE_LAYERS:
4699 case CAPTURE_SCREEN: {
4700 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004701 IPCThreadState* ipc = IPCThreadState::self();
4702 const int pid = ipc->getCallingPid();
4703 const int uid = ipc->getCallingUid();
4704 if ((uid != AID_GRAPHICS) &&
4705 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4706 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4707 return PERMISSION_DENIED;
4708 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004709 return OK;
4710 }
4711 // The following codes are deprecated and should never be allowed to access SF.
4712 case CONNECT_DISPLAY_UNUSED:
4713 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4714 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4715 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004716 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004717 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004718
4719 // These codes are used for the IBinder protocol to either interrogate the recipient
4720 // side of the transaction for its canonical interface descriptor or to dump its state.
4721 // We let them pass by default.
4722 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4723 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4724 code == IBinder::SYSPROPS_TRANSACTION) {
4725 return OK;
4726 }
Peiyong Lin3b44a032018-10-24 18:18:12 -07004727 // Numbers from 1000 to 1030 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004728 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin3b44a032018-10-24 18:18:12 -07004729 if (code >= 1000 && code <= 1030) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004730 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4731 return OK;
4732 }
4733 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4734 return PERMISSION_DENIED;
4735#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004736}
4737
Ana Krulec13be8ad2018-08-21 02:43:56 +00004738status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4739 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004740 status_t credentialCheck = CheckTransactCodeCredentials(code);
4741 if (credentialCheck != OK) {
4742 return credentialCheck;
4743 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004744
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004745 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4746 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004747 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004748 IPCThreadState* ipc = IPCThreadState::self();
4749 const int uid = ipc->getCallingUid();
4750 if (CC_UNLIKELY(uid != AID_SYSTEM
4751 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004752 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004753 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004754 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004755 return PERMISSION_DENIED;
4756 }
4757 int n;
4758 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004759 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004760 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004761 return NO_ERROR;
4762 case 1002: // SHOW_UPDATES
4763 n = data.readInt32();
4764 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004765 invalidateHwcGeometry();
4766 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004767 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004768 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004769 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004770 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004771 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004772 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004773 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004774 setTransactionFlags(
4775 eTransactionNeeded|
4776 eDisplayTransactionNeeded|
4777 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004778 return NO_ERROR;
4779 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004780 case 1006:{ // send empty update
4781 signalRefresh();
4782 return NO_ERROR;
4783 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004784 case 1008: // toggle use of hw composer
4785 n = data.readInt32();
4786 mDebugDisableHWC = n ? 1 : 0;
4787 invalidateHwcGeometry();
4788 repaintEverything();
4789 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004790 case 1009: // toggle use of transform hint
4791 n = data.readInt32();
4792 mDebugDisableTransformHint = n ? 1 : 0;
4793 invalidateHwcGeometry();
4794 repaintEverything();
4795 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004796 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004797 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004798 reply->writeInt32(0);
4799 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004800 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004801 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004802 return NO_ERROR;
4803 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004804 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004805 if (!display) {
4806 return NAME_NOT_FOUND;
4807 }
4808
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004809 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004810 return NO_ERROR;
4811 }
4812 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004813 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004814 // daltonize
4815 n = data.readInt32();
4816 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004817 case 1:
4818 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4819 break;
4820 case 2:
4821 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4822 break;
4823 case 3:
4824 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4825 break;
4826 default:
4827 mDaltonizer.setType(ColorBlindnessType::None);
4828 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004829 }
4830 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004831 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004832 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004833 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004834 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004835
4836 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004837 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004838 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004839 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004840 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004841 // apply a color matrix
4842 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004843 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004844 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004845 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004846 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004847 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004848 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004849 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004850 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004851 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004852 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004853
4854 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4855 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004856 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004857 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4858 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4859 }
4860
Chia-I Wu28f320b2018-05-03 11:02:56 -07004861 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004862 return NO_ERROR;
4863 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004864 // This is an experimental interface
4865 // Needs to be shifted to proper binder interface when we productize
4866 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004867 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07004868 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07004869 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004870 return NO_ERROR;
4871 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004872 case 1017: {
4873 n = data.readInt32();
4874 mForceFullDamage = static_cast<bool>(n);
4875 return NO_ERROR;
4876 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004877 case 1018: { // Modify Choreographer's phase offset
4878 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004879 if (mUseScheduler) {
4880 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
4881 } else {
4882 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4883 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004884 return NO_ERROR;
4885 }
4886 case 1019: { // Modify SurfaceFlinger's phase offset
4887 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004888 if (mUseScheduler) {
4889 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
4890 } else {
4891 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4892 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004893 return NO_ERROR;
4894 }
Irvel468051e2016-06-13 16:44:44 -07004895 case 1020: { // Layer updates interceptor
4896 n = data.readInt32();
4897 if (n) {
4898 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004899 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004900 }
4901 else{
4902 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004903 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004904 }
4905 return NO_ERROR;
4906 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004907 case 1021: { // Disable HWC virtual displays
4908 n = data.readInt32();
4909 mUseHwcVirtualDisplays = !n;
4910 return NO_ERROR;
4911 }
Romain Guy0147a172017-06-01 13:53:56 -07004912 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004913 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004914 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004915
Chia-I Wu28f320b2018-05-03 11:02:56 -07004916 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004917 return NO_ERROR;
4918 }
Romain Guy54f154a2017-10-24 21:40:32 +01004919 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004920 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004921 invalidateHwcGeometry();
4922 repaintEverything();
4923 return NO_ERROR;
4924 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004925 // Deprecate, use 1030 to check whether the device is color managed.
4926 case 1024: {
4927 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004928 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004929 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004930 n = data.readInt32();
4931 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004932 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004933 mTracing.enable();
4934 doTracing("tracing.enable");
4935 reply->writeInt32(NO_ERROR);
4936 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004937 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004938 status_t err = mTracing.disable();
4939 reply->writeInt32(err);
4940 }
4941 return NO_ERROR;
4942 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004943 case 1026: { // Get layer tracing status
4944 reply->writeBool(mTracing.isEnabled());
4945 return NO_ERROR;
4946 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004947 // Is a DisplayColorSetting supported?
4948 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004949 const auto display = getDefaultDisplayDevice();
4950 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004951 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004952 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004953
4954 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4955 switch (setting) {
4956 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07004957 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004958 break;
4959 case DisplayColorSetting::UNMANAGED:
4960 reply->writeBool(true);
4961 break;
4962 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004963 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004964 break;
4965 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004966 reply->writeBool(
4967 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004968 break;
4969 }
4970 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004971 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004972 // Is VrFlinger active?
4973 case 1028: {
4974 Mutex::Autolock _l(mStateLock);
4975 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4976 return NO_ERROR;
4977 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004978 // Is device color managed?
4979 case 1030: {
4980 reply->writeBool(useColorManagement);
4981 return NO_ERROR;
4982 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004983 }
4984 }
4985 return err;
4986}
4987
Steven Thomas6d8110b2017-08-31 18:24:21 -07004988void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004989 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004990 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004991}
4992
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004993// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4994class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004995public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004996 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4997 ~WindowDisconnector() {
4998 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004999 }
5000
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005001private:
5002 ANativeWindow* mWindow;
5003 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005004};
5005
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005006status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005007 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5008 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005009 uint32_t reqWidth, uint32_t reqHeight,
5010 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005011 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005012 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005013
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005014 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005015
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005016 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5017
Chia-I Wu20261cb2018-08-23 12:55:44 -07005018 sp<DisplayDevice> display;
5019 {
5020 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005021
Chia-I Wu20261cb2018-08-23 12:55:44 -07005022 display = getDisplayDeviceLocked(displayToken);
5023 if (!display) return BAD_VALUE;
5024
Chia-I Wucb023152018-08-28 12:57:23 -07005025 // set the requested width/height to the logical display viewport size
5026 // by default
5027 if (reqWidth == 0 || reqHeight == 0) {
5028 reqWidth = uint32_t(display->getViewport().width());
5029 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005030 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005031 }
5032
Peiyong Lin0e003c92018-09-17 11:09:51 -07005033 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5034 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005035
5036 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005037 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005038 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5039 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005040}
5041
5042status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005043 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5044 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005045 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005046 ATRACE_CALL();
5047
5048 class LayerRenderArea : public RenderArea {
5049 public:
Robert Carr578038f2018-03-09 12:25:24 -08005050 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005051 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5052 bool childrenOnly)
5053 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005054 mLayer(layer),
5055 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005056 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005057 mFlinger(flinger),
5058 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005059 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005060 Rect getBounds() const override {
5061 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005062 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005063 }
Marissa Wall61c58622018-07-18 10:12:20 -07005064 int getHeight() const override {
5065 return mLayer->getActiveHeight(mLayer->getDrawingState());
5066 }
5067 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005068 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005069 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005070 Rect getSourceCrop() const override {
5071 if (mCrop.isEmpty()) {
5072 return getBounds();
5073 } else {
5074 return mCrop;
5075 }
5076 }
Robert Carr578038f2018-03-09 12:25:24 -08005077 class ReparentForDrawing {
5078 public:
5079 const sp<Layer>& oldParent;
5080 const sp<Layer>& newParent;
5081
5082 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5083 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005084 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005085 }
Robert Carr15eae092018-03-23 13:43:53 -07005086 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005087 };
5088
5089 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005090 const Rect sourceCrop = getSourceCrop();
5091 // no need to check rotation because there is none
5092 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5093 sourceCrop.height() != getReqHeight();
5094
Robert Carr578038f2018-03-09 12:25:24 -08005095 if (!mChildrenOnly) {
5096 mTransform = mLayer->getTransform().inverse();
5097 drawLayers();
5098 } else {
5099 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005100 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005101 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5102 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005103
5104 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5105 drawLayers();
5106 }
5107 }
chaviwa76b2712017-09-20 12:02:26 -07005108
chaviwa76b2712017-09-20 12:02:26 -07005109 private:
chaviw7206d492017-11-10 16:16:12 -08005110 const sp<Layer> mLayer;
5111 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005112
5113 // In the "childrenOnly" case we reparent the children to a screenshot
5114 // layer which has no properties set and which does not draw.
5115 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005116 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005117 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005118
5119 SurfaceFlinger* mFlinger;
5120 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005121 };
5122
5123 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5124 auto parent = layerHandle->owner.promote();
5125
Robert Carr2e102c92018-10-23 12:11:15 -07005126 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005127 ALOGE("captureLayers called with a removed parent");
5128 return NAME_NOT_FOUND;
5129 }
5130
Robert Carr578038f2018-03-09 12:25:24 -08005131 const int uid = IPCThreadState::self()->getCallingUid();
5132 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5133 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5134 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5135 return PERMISSION_DENIED;
5136 }
5137
chaviw7206d492017-11-10 16:16:12 -08005138 Rect crop(sourceCrop);
5139 if (sourceCrop.width() <= 0) {
5140 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005141 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005142 }
5143
5144 if (sourceCrop.height() <= 0) {
5145 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005146 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005147 }
5148
5149 int32_t reqWidth = crop.width() * frameScale;
5150 int32_t reqHeight = crop.height() * frameScale;
5151
Chia-I Wu20261cb2018-08-23 12:55:44 -07005152 // really small crop or frameScale
5153 if (reqWidth <= 0) {
5154 reqWidth = 1;
5155 }
5156 if (reqHeight <= 0) {
5157 reqHeight = 1;
5158 }
5159
Peiyong Lin0e003c92018-09-17 11:09:51 -07005160 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005161
Robert Carr578038f2018-03-09 12:25:24 -08005162 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005163 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5164 if (!layer->isVisible()) {
5165 return;
Robert Carr578038f2018-03-09 12:25:24 -08005166 } else if (childrenOnly && layer == parent.get()) {
5167 return;
chaviwa76b2712017-09-20 12:02:26 -07005168 }
5169 visitor(layer);
5170 });
5171 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005172 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005173}
5174
5175status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5176 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005177 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005178 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005179 bool useIdentityTransform) {
5180 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005181
Peiyong Lin0e003c92018-09-17 11:09:51 -07005182 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005183 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5184 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005185 *outBuffer =
5186 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5187 static_cast<android_pixel_format>(reqPixelFormat), 1,
5188 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005189
5190 // This mutex protects syncFd and captureResult for communication of the return values from the
5191 // main thread back to this Binder thread
5192 std::mutex captureMutex;
5193 std::condition_variable captureCondition;
5194 std::unique_lock<std::mutex> captureLock(captureMutex);
5195 int syncFd = -1;
5196 std::optional<status_t> captureResult;
5197
Robert Carr03480e22018-01-04 16:02:06 -08005198 const int uid = IPCThreadState::self()->getCallingUid();
5199 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5200
Dominik Laskowski8c001672018-05-30 16:52:06 -07005201 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005202 // If there is a refresh pending, bug out early and tell the binder thread to try again
5203 // after the refresh.
5204 if (mRefreshPending) {
5205 ATRACE_NAME("Skipping screenshot for now");
5206 std::unique_lock<std::mutex> captureLock(captureMutex);
5207 captureResult = std::make_optional<status_t>(EAGAIN);
5208 captureCondition.notify_one();
5209 return;
5210 }
5211
5212 status_t result = NO_ERROR;
5213 int fd = -1;
5214 {
5215 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005216 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005217 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5218 useIdentityTransform, forSystem, &fd);
5219 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005220 }
5221
5222 {
5223 std::unique_lock<std::mutex> captureLock(captureMutex);
5224 syncFd = fd;
5225 captureResult = std::make_optional<status_t>(result);
5226 captureCondition.notify_one();
5227 }
5228 });
5229
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005230 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005231 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005232 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005233 while (*captureResult == EAGAIN) {
5234 captureResult.reset();
5235 result = postMessageAsync(message);
5236 if (result != NO_ERROR) {
5237 return result;
5238 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005239 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005240 }
5241 result = *captureResult;
5242 }
5243
5244 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005245 sync_wait(syncFd, -1);
5246 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005247 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005248
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005249 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005250}
5251
chaviwa76b2712017-09-20 12:02:26 -07005252void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005253 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005254 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005255 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005256
Lloyd Pique144e1162017-12-20 16:44:52 -08005257 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005258
chaviwa76b2712017-09-20 12:02:26 -07005259 const auto reqWidth = renderArea.getReqWidth();
5260 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005261 const auto sourceCrop = renderArea.getSourceCrop();
5262 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005263
Peiyong Lin0e003c92018-09-17 11:09:51 -07005264 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005265 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005266
Mathias Agopian180f10d2013-04-10 22:55:41 -07005267 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005268 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005269
5270 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005271 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005272 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005273
chaviw50da5042018-04-09 13:49:37 -07005274 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005275 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005276 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005277
chaviwa76b2712017-09-20 12:02:26 -07005278 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005279 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005280 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005281 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005282 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005283}
5284
chaviwa76b2712017-09-20 12:02:26 -07005285status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5286 TraverseLayersFunction traverseLayers,
5287 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005288 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005289 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005290 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005291 ATRACE_CALL();
5292
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005293 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005294
5295 traverseLayers([&](Layer* layer) {
5296 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5297 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005298
Robert Carr03480e22018-01-04 16:02:06 -08005299 // We allow the system server to take screenshots of secure layers for
5300 // use in situations like the Screen-rotation animation and place
5301 // the impetus on WindowManager to not persist them.
5302 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005303 ALOGW("FB is protected: PERMISSION_DENIED");
5304 return PERMISSION_DENIED;
5305 }
5306
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005307 // this binds the given EGLImage as a framebuffer for the
5308 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005309 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005310 if (bufferBond.getStatus() != NO_ERROR) {
5311 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005312 return INVALID_OPERATION;
5313 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005314
Dan Stozaabcda352017-06-01 14:37:39 -07005315 // this will in fact render into our dequeued buffer
5316 // via an FBO, which means we didn't have to create
5317 // an EGLSurface and therefore we're not
5318 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005319 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005320
Alec Mouri492bc572018-09-11 21:40:04 +00005321 base::unique_fd syncFd = getRenderEngine().flush();
5322 if (syncFd < 0) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005323 getRenderEngine().finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005324 }
Alec Mouri492bc572018-09-11 21:40:04 +00005325 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005326
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005327 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005328}
5329
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005330// ---------------------------------------------------------------------------
5331
Dan Stoza412903f2017-04-27 13:42:17 -07005332void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5333 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005334}
5335
Dan Stoza412903f2017-04-27 13:42:17 -07005336void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5337 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005338}
5339
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005340void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005341 const LayerVector::Visitor& visitor) {
5342 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005343 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005344 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005345 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005346 continue;
5347 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005348 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005349 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005350 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005351 return;
5352 }
chaviwa76b2712017-09-20 12:02:26 -07005353 if (!layer->isVisible()) {
5354 return;
5355 }
5356 visitor(layer);
5357 });
5358 }
5359}
5360
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005361}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005362
Lloyd Pique074e8122018-07-26 12:57:23 -07005363
Mathias Agopian3f844832013-08-07 21:24:32 -07005364#if defined(__gl_h_)
5365#error "don't include gl/gl.h in this file"
5366#endif
5367
5368#if defined(__gl2_h_)
5369#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005370#endif