blob: 767c85935038029fee1b71afc4e4d64476c844ae [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"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Steven Thomasb02664d2017-07-26 18:48:28 -070079#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070080#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070085#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070086#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070087#include "Scheduler/EventControlThread.h"
88#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070089#include "Scheduler/InjectVSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070090
Mathias Agopianff2ed702013-09-01 21:36:12 -070091#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070092
David Sodman7e4ae112018-02-09 15:02:28 -080093#include "android-base/stringprintf.h"
94
Jiyong Park4b20c2e2017-01-14 19:45:11 +090095#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080096#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -070097#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080098#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090099#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900100
chaviw1d044282017-09-27 12:19:28 -0700101#include <layerproto/LayerProtoParser.h>
102
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800103#define DISPLAY_COUNT 1
104
Mathias Agopianfee2b462013-07-03 12:34:01 -0700105/*
106 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
107 * black pixels.
108 */
109#define DEBUG_SCREENSHOTS false
110
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800111namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700112
Jaesoo Lee43518572017-01-23 19:03:16 +0900113using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900114using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700115using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700116using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700117using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700118using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900119
Steven Thomasb02664d2017-07-26 18:48:28 -0700120namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700121
122#pragma clang diagnostic push
123#pragma clang diagnostic error "-Wswitch-enum"
124
125bool isWideColorMode(const ColorMode colorMode) {
126 switch (colorMode) {
127 case ColorMode::DISPLAY_P3:
128 case ColorMode::ADOBE_RGB:
129 case ColorMode::DCI_P3:
130 case ColorMode::BT2020:
131 case ColorMode::BT2100_PQ:
132 case ColorMode::BT2100_HLG:
133 return true;
134 case ColorMode::NATIVE:
135 case ColorMode::STANDARD_BT601_625:
136 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
137 case ColorMode::STANDARD_BT601_525:
138 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
139 case ColorMode::STANDARD_BT709:
140 case ColorMode::SRGB:
141 return false;
142 }
143 return false;
144}
145
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700146ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
147 switch (rotation) {
148 case ISurfaceComposer::eRotateNone:
149 return ui::Transform::ROT_0;
150 case ISurfaceComposer::eRotate90:
151 return ui::Transform::ROT_90;
152 case ISurfaceComposer::eRotate180:
153 return ui::Transform::ROT_180;
154 case ISurfaceComposer::eRotate270:
155 return ui::Transform::ROT_270;
156 }
157 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
158 return ui::Transform::ROT_0;
159}
160
Peiyong Linfca547f2018-07-09 13:03:33 -0700161#pragma clang diagnostic pop
162
Steven Thomasb02664d2017-07-26 18:48:28 -0700163class ConditionalLock {
164public:
165 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
166 if (lock) {
167 mMutex.lock();
168 }
169 }
170 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
171private:
172 Mutex& mMutex;
173 bool mLocked;
174};
Peiyong Linfca547f2018-07-09 13:03:33 -0700175
Steven Thomasb02664d2017-07-26 18:48:28 -0700176} // namespace anonymous
177
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800178// ---------------------------------------------------------------------------
179
Mathias Agopian99b49842011-06-27 16:05:52 -0700180const String16 sHardwareTest("android.permission.HARDWARE_TEST");
181const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
182const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
183const String16 sDump("android.permission.DUMP");
184
185// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800186int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
187int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700188int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700189bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800190uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800191bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800192bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800193int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800194// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600195bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700196int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700197bool SurfaceFlinger::useColorManagement;
Mathias Agopian99b49842011-06-27 16:05:52 -0700198
Kalle Raitaa099a242017-01-11 11:17:29 -0800199std::string getHwcServiceName() {
200 char value[PROPERTY_VALUE_MAX] = {};
201 property_get("debug.sf.hwc_service_name", value, "default");
202 ALOGI("Using HWComposer service: '%s'", value);
203 return std::string(value);
204}
205
206bool useTrebleTestingOverride() {
207 char value[PROPERTY_VALUE_MAX] = {};
208 property_get("debug.sf.treble_testing_override", value, "false");
209 ALOGI("Treble testing override: '%s'", value);
210 return std::string(value) == "true";
211}
212
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800213std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
214 switch(displayColorSetting) {
215 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700216 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800217 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700218 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800219 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700220 return std::string("Enhanced");
221 default:
222 return std::string("Unknown ") +
223 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800224 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800225}
226
Lloyd Pique99d3da52018-01-22 17:48:03 -0800227NativeWindowSurface::~NativeWindowSurface() = default;
228
229namespace impl {
230
231class NativeWindowSurface final : public android::NativeWindowSurface {
232public:
233 static std::unique_ptr<android::NativeWindowSurface> create(
234 const sp<IGraphicBufferProducer>& producer) {
235 return std::make_unique<NativeWindowSurface>(producer);
236 }
237
238 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
239 : surface(new Surface(producer, false)) {}
240
241 ~NativeWindowSurface() override = default;
242
243private:
244 sp<ANativeWindow> getNativeWindow() const override { return surface; }
245
246 void preallocateBuffers() override { surface->allocateBuffers(); }
247
248 sp<Surface> surface;
249};
250
251} // namespace impl
252
David Sodmanbc815282017-11-05 18:57:52 -0800253SurfaceFlingerBE::SurfaceFlingerBE()
254 : mHwcServiceName(getHwcServiceName()),
255 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800256 mFrameBuckets(),
257 mTotalTime(0),
258 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800259 mComposerSequenceId(0) {
260}
261
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800262SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800263 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800264 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700265 mTransactionPending(false),
266 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700267 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700268 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700269 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800270 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700271 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800272 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800273 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800274 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800275 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700277 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700278 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700279 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700280 mDebugInTransaction(0),
281 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700282 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700283 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700284 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800285 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800286 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800287 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700288 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800289 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800290 mCreateBufferQueue(&BufferQueue::createBufferQueue),
291 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800292
293SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800294 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800295
296 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
297 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
298
299 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
300 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
301
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800302 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
303 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800304
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700305 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
306 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
307
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700308 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
309 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
310
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800311 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
312 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
313
Steven Thomas050b2c82017-03-06 11:45:16 -0800314 // Vr flinger is only enabled on Daydream ready devices.
315 useVrFlinger = getBool< ISurfaceFlingerConfigs,
316 &ISurfaceFlingerConfigs::useVrFlinger>(false);
317
Fabien Sanglard1971b632017-03-10 14:50:03 -0800318 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
319 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
320
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600321 hasWideColorDisplay =
322 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700323 useColorManagement =
324 getBool<V1_2::ISurfaceFlingerConfigs, &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600325
Iris Chang7501ed62018-04-30 14:45:42 +0800326 V1_1::DisplayOrientation primaryDisplayOrientation =
327 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
328 V1_1::DisplayOrientation::ORIENTATION_0);
329
330 switch (primaryDisplayOrientation) {
331 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700332 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800333 break;
334 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700335 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800336 break;
337 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700338 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800339 break;
340 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700341 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800342 break;
343 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700344 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800345
Lloyd Pique41be5d22018-06-21 13:11:48 -0700346 // Note: We create a local temporary with the real DispSync implementation
347 // type temporarily so we can initialize it with the configured values,
348 // before storing it for more generic use using the interface type.
349 auto primaryDispSync = std::make_unique<impl::DispSync>("PrimaryDispSync");
350 primaryDispSync->init(SurfaceFlinger::hasSyncFramework,
351 SurfaceFlinger::dispSyncPresentTimeOffset);
352 mPrimaryDispSync = std::move(primaryDispSync);
Saurabh Shahf4174532017-07-13 10:45:07 -0700353
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800354 // debugging stuff...
355 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700356
Mathias Agopianb4b17302013-03-20 18:36:41 -0700357 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700358 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700359
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800360 property_get("debug.sf.showupdates", value, "0");
361 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700362
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700363 property_get("debug.sf.ddms", value, "0");
364 mDebugDDMS = atoi(value);
365 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700366 if (!startDdmConnection()) {
367 // start failed, and DDMS debugging not enabled
368 mDebugDDMS = 0;
369 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700370 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700371 ALOGI_IF(mDebugRegion, "showupdates enabled");
372 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700373
374 property_get("debug.sf.disable_backpressure", value, "0");
375 mPropagateBackpressure = !atoi(value);
376 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700377
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800378 property_get("debug.sf.enable_hwc_vds", value, "0");
379 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800380 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800381
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800382 property_get("ro.sf.disable_triple_buffer", value, "1");
383 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800384 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700385
Yiwei Zhang243b3782018-05-15 17:40:04 -0700386 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700387 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
388 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
389
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200390 property_get("debug.sf.early_phase_offset_ns", value, "-1");
391 const int earlySfOffsetNs = atoi(value);
392
393 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
394 const int earlyGlSfOffsetNs = atoi(value);
395
396 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
397 const int earlyAppOffsetNs = atoi(value);
398
399 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
400 const int earlyGlAppOffsetNs = atoi(value);
401
402 const VSyncModulator::Offsets earlyOffsets =
403 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
404 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
405 const VSyncModulator::Offsets earlyGlOffsets =
406 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
407 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
408 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
409 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700410
Romain Guy11d63f42017-07-20 12:47:14 -0700411 // We should be reading 'persist.sys.sf.color_saturation' here
412 // but since /data may be encrypted, we need to wait until after vold
413 // comes online to attempt to read the property. The property is
414 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800415
416 if (useTrebleTestingOverride()) {
417 // Without the override SurfaceFlinger cannot connect to HIDL
418 // services that are not listed in the manifests. Considered
419 // deriving the setting from the set service name, but it
420 // would be brittle if the name that's not 'default' is used
421 // for production purposes later on.
422 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
423 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800424}
425
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800426void SurfaceFlinger::onFirstRef()
427{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800428 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800429}
430
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800431SurfaceFlinger::~SurfaceFlinger()
432{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800433}
434
Dan Stozac7014012014-02-14 15:03:43 -0800435void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800436{
437 // the window manager died on us. prepare its eulogy.
438
Andy McFadden13a082e2012-08-24 10:16:42 -0700439 // restore initial conditions (default device unblank, etc)
440 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800441
442 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700443 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800444}
445
Robert Carr1db73f62016-12-21 12:58:51 -0800446static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700447 status_t err = client->initCheck();
448 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800449 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800450 }
Robert Carr1db73f62016-12-21 12:58:51 -0800451 return nullptr;
452}
453
454sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
455 return initClient(new Client(this));
456}
457
458sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
459 const sp<IGraphicBufferProducer>& gbp) {
460 if (authenticateSurfaceTexture(gbp) == false) {
461 return nullptr;
462 }
463 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
464 if (layer == nullptr) {
465 return nullptr;
466 }
467
468 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800469}
470
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700471sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
472 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700473{
474 class DisplayToken : public BBinder {
475 sp<SurfaceFlinger> flinger;
476 virtual ~DisplayToken() {
477 // no more references, this display must be terminated
478 Mutex::Autolock _l(flinger->mStateLock);
479 flinger->mCurrentState.displays.removeItem(this);
480 flinger->setTransactionFlags(eDisplayTransactionNeeded);
481 }
482 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700483 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700484 : flinger(flinger) {
485 }
486 };
487
488 sp<BBinder> token = new DisplayToken(this);
489
490 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700491 DisplayDeviceState info;
492 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700493 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700494 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700495 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800496 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700497 return token;
498}
499
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700500void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700501 Mutex::Autolock _l(mStateLock);
502
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700503 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700504 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700505 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700506 return;
507 }
508
509 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700510 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700511 ALOGE("destroyDisplay called for non-virtual display");
512 return;
513 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700514 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700515 mCurrentState.displays.removeItemsAt(idx);
516 setTransactionFlags(eDisplayTransactionNeeded);
517}
518
Mathias Agopiane57f2922012-08-09 16:29:12 -0700519sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700520 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700521 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800522 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700523 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700524 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700525}
526
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800527void SurfaceFlinger::bootFinished()
528{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700529 if (mStartPropertySetThread->join() != NO_ERROR) {
530 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800531 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800532 const nsecs_t now = systemTime();
533 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000534 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700535
536 // wait patiently for the window manager death
537 const String16 name("window");
538 sp<IBinder> window(defaultServiceManager()->getService(name));
539 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700540 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700541 }
542
Steven Thomas050b2c82017-03-06 11:45:16 -0800543 if (mVrFlinger) {
544 mVrFlinger->OnBootFinished();
545 }
546
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700547 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700548 // formerly we would just kill the process, but we now ask it to exit so it
549 // can choose where to stop the animation.
550 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700551
552 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
553 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
554 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700555
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800556 postMessageAsync(new LambdaMessage([this] {
557 readPersistentProperties();
558 mBootStage = BootStage::FINISHED;
559 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800560}
561
Dan Stoza436ccf32018-06-21 12:10:12 -0700562uint32_t SurfaceFlinger::getNewTexture() {
563 {
564 std::lock_guard lock(mTexturePoolMutex);
565 if (!mTexturePool.empty()) {
566 uint32_t name = mTexturePool.back();
567 mTexturePool.pop_back();
568 ATRACE_INT("TexturePoolSize", mTexturePool.size());
569 return name;
570 }
571
572 // The pool was too small, so increase it for the future
573 ++mTexturePoolSize;
574 }
575
576 // The pool was empty, so we need to get a new texture name directly using a
577 // blocking call to the main thread
578 uint32_t name = 0;
579 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
580 return name;
581}
582
Mathias Agopian3f844832013-08-07 21:24:32 -0700583void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700584 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700585}
586
Wei Wangf9b05ee2017-07-19 20:59:39 -0700587// Do not call property_set on main thread which will be blocked by init
588// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700589void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700590 ALOGI( "SurfaceFlinger's main thread ready to run. "
591 "Initializing graphics H/W...");
592
Thierry Strudel2924d012017-08-14 15:19:37 -0700593 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900594
Steven Thomasb02664d2017-07-26 18:48:28 -0700595 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800596
Steven Thomasb02664d2017-07-26 18:48:28 -0700597 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800598 mEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700599 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
600 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800601 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700602 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800603 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800604 "appEventThread");
605 mSfEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700606 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800607 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800608
Lloyd Pique24b0a482018-03-09 18:52:26 -0800609 mSFEventThread =
610 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700611 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800612 [this](nsecs_t timestamp) {
613 mInterceptor->saveVSyncEvent(timestamp);
614 },
615 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800616 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200617 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800618
Steven Thomasb02664d2017-07-26 18:48:28 -0700619 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700620 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700621 renderEngineFeature |= (useColorManagement ?
622 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
623 getBE().mRenderEngine = renderengine::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
624 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800625 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700626
627 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
628 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800629 getBE().mHwc.reset(
630 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700631 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800632 // Process any initial hotplug and resulting display changes.
633 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700634 const auto display = getDefaultDisplayDeviceLocked();
635 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
636 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
637 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800638
Lloyd Piquefcd86612017-12-14 17:15:36 -0800639 // make the default display GLContext current so that we can create textures
640 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700641 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800642
Steven Thomas050b2c82017-03-06 11:45:16 -0800643 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700644 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700645 // This callback is called from the vr flinger dispatch thread. We
646 // need to call signalTransaction(), which requires holding
647 // mStateLock when we're not on the main thread. Acquiring
648 // mStateLock from the vr flinger dispatch thread might trigger a
649 // deadlock in surface flinger (see b/66916578), so post a message
650 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700651 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700652 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
653 mVrFlingerRequestsDisplay = requestDisplay;
654 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700655 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800656 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700657 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
658 getHwComposer()
659 .getHwcDisplayId(display->getId())
660 .value_or(0),
661 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800662 if (!mVrFlinger) {
663 ALOGE("Failed to start vrflinger");
664 }
665 }
666
Lloyd Pique379adc12018-01-22 17:31:47 -0800667 mEventControlThread = std::make_unique<impl::EventControlThread>(
668 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700669
Mathias Agopian92a979a2012-08-02 18:32:23 -0700670 // initialize our drawing state
671 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700672
Andy McFadden13a082e2012-08-24 10:16:42 -0700673 // set initial conditions (e.g. unblank default device)
674 initializeDisplays();
675
David Sodmanbc815282017-11-05 18:57:52 -0800676 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700677
Wei Wangf9b05ee2017-07-19 20:59:39 -0700678 // Inform native graphics APIs whether the present timestamp is supported:
679 if (getHwComposer().hasCapability(
680 HWC2::Capability::PresentFenceIsNotReliable)) {
681 mStartPropertySetThread = new StartPropertySetThread(false);
682 } else {
683 mStartPropertySetThread = new StartPropertySetThread(true);
684 }
685
686 if (mStartPropertySetThread->Start() != NO_ERROR) {
687 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800688 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800689
Chia-I Wud49d6692018-06-27 07:17:41 +0800690 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
691 // is used to saturate legacy sRGB content. However, to make sure the same color under
692 // Display P3 will be saturated to the same color, we intentionally break the API spec
693 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
694 // such saturation matrix on Display P3 is understood fully, the API should always return
695 // identify matrix.
696 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
697 Dataspace::SRGB_LINEAR);
698
699 // we will apply this on Display P3.
700 if (mEnhancedSaturationMatrix != mat4()) {
701 ColorSpace srgb(ColorSpace::sRGB());
702 ColorSpace displayP3(ColorSpace::DisplayP3());
703 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
704 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
705 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
706 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800707
Dan Stoza9e56aa02015-11-02 13:00:03 -0800708 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700709}
710
Romain Guy11d63f42017-07-20 12:47:14 -0700711void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700712 Mutex::Autolock _l(mStateLock);
713
Romain Guy11d63f42017-07-20 12:47:14 -0700714 char value[PROPERTY_VALUE_MAX];
715
716 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800717 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700718 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800719 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100720
721 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700722 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700723}
724
Mathias Agopiana67e4182012-06-19 17:26:12 -0700725void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800726 // Start boot animation service by setting a property mailbox
727 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700728 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800729 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700730 if (mStartPropertySetThread->join() != NO_ERROR) {
731 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800732 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700733}
734
Mathias Agopian875d8e12013-06-07 15:35:48 -0700735size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800736 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700737}
738
Mathias Agopian875d8e12013-06-07 15:35:48 -0700739size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800740 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700741}
742
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800743// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800744
Jamie Gennis582270d2011-08-17 18:19:00 -0700745bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800746 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800747 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800748 return authenticateSurfaceTextureLocked(bufferProducer);
749}
750
751bool SurfaceFlinger::authenticateSurfaceTextureLocked(
752 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800753 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800754 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800755}
756
Brian Anderson6b376712017-04-04 10:51:39 -0700757status_t SurfaceFlinger::getSupportedFrameTimestamps(
758 std::vector<FrameEvent>* outSupported) const {
759 *outSupported = {
760 FrameEvent::REQUESTED_PRESENT,
761 FrameEvent::ACQUIRE,
762 FrameEvent::LATCH,
763 FrameEvent::FIRST_REFRESH_START,
764 FrameEvent::LAST_REFRESH_START,
765 FrameEvent::GPU_COMPOSITION_DONE,
766 FrameEvent::DEQUEUE_READY,
767 FrameEvent::RELEASE,
768 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700769 ConditionalLock _l(mStateLock,
770 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700771 if (!getHwComposer().hasCapability(
772 HWC2::Capability::PresentFenceIsNotReliable)) {
773 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
774 }
775 return NO_ERROR;
776}
777
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700778status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
779 Vector<DisplayInfo>* configs) {
780 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700781 return BAD_VALUE;
782 }
783
Jesse Hall692c7232012-11-08 15:41:56 -0800784 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700785 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
786 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700787 type = i;
788 break;
789 }
790 }
791
792 if (type < 0) {
793 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700794 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700795
Mathias Agopian8b736f12012-08-13 17:54:26 -0700796 // TODO: Not sure if display density should handled by SF any longer
797 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700798 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700799 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700800 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800801 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700802 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700803 }
804 return density;
805 }
806 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700807 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700808 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700809 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700810 return getDensityFromProperty("ro.sf.lcd_density"); }
811 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700812
Dan Stoza7f7da322014-05-02 15:26:25 -0700813 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700814
Steven Thomas6d8110b2017-08-31 18:24:21 -0700815 ConditionalLock _l(mStateLock,
816 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800817 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700818 DisplayInfo info = DisplayInfo();
819
Dan Stoza9e56aa02015-11-02 13:00:03 -0800820 float xdpi = hwConfig->getDpiX();
821 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700822
823 if (type == DisplayDevice::DISPLAY_PRIMARY) {
824 // The density of the device is provided by a build property
825 float density = Density::getBuildDensity() / 160.0f;
826 if (density == 0) {
827 // the build doesn't provide a density -- this is wrong!
828 // use xdpi instead
829 ALOGE("ro.sf.lcd_density must be defined as a build property");
830 density = xdpi / 160.0f;
831 }
832 if (Density::getEmuDensity()) {
833 // if "qemu.sf.lcd_density" is specified, it overrides everything
834 xdpi = ydpi = density = Density::getEmuDensity();
835 density /= 160.0f;
836 }
837 info.density = density;
838
839 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700840 const auto display = getDefaultDisplayDeviceLocked();
841 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700842 } else {
843 // TODO: where should this value come from?
844 static const int TV_DENSITY = 213;
845 info.density = TV_DENSITY / 160.0f;
846 info.orientation = 0;
847 }
848
Dan Stoza9e56aa02015-11-02 13:00:03 -0800849 info.w = hwConfig->getWidth();
850 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700851 info.xdpi = xdpi;
852 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800853 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900854 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800855
Andy McFadden91b2ca82014-06-13 14:04:23 -0700856 // This is how far in advance a buffer must be queued for
857 // presentation at a given time. If you want a buffer to appear
858 // on the screen at time N, you must submit the buffer before
859 // (N - presentationDeadline).
860 //
861 // Normally it's one full refresh period (to give SF a chance to
862 // latch the buffer), but this can be reduced by configuring a
863 // DispSync offset. Any additional delays introduced by the hardware
864 // composer or panel must be accounted for here.
865 //
866 // We add an additional 1ms to allow for processing time and
867 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800868 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800869 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700870
871 // All non-virtual displays are currently considered secure.
872 info.secure = true;
873
Iris Chang7501ed62018-04-30 14:45:42 +0800874 if (type == DisplayDevice::DISPLAY_PRIMARY &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700875 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800876 std::swap(info.w, info.h);
877 }
878
Michael Wright28f24d02016-07-12 13:30:53 -0700879 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700880 }
881
Dan Stoza7f7da322014-05-02 15:26:25 -0700882 return NO_ERROR;
883}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700884
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700885status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
886 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700887 return BAD_VALUE;
888 }
889
890 // FIXME for now we always return stats for the primary display
891 memset(stats, 0, sizeof(*stats));
Lloyd Pique41be5d22018-06-21 13:11:48 -0700892 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
893 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700894 return NO_ERROR;
895}
896
Yiwei Zhangcd3f9e92018-08-21 15:15:42 -0700897status_t SurfaceFlinger::getDisplayViewport(const sp<IBinder>& display, Rect* outViewport) {
898 if (outViewport == nullptr || display.get() == nullptr) {
899 return BAD_VALUE;
900 }
901
902 sp<const DisplayDevice> device(getDisplayDevice(display));
903 if (device == nullptr) {
904 return BAD_VALUE;
905 }
906
907 *outViewport = device->getViewport();
908
909 return NO_ERROR;
910}
911
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700912int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
913 const auto display = getDisplayDevice(displayToken);
914 if (!display) {
915 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800916 return BAD_VALUE;
917 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700918
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700919 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700920}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700921
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700922void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
923 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700924 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700925 return;
926 }
927
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700928 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700929 ALOGW("Trying to set config for virtual display");
930 return;
931 }
932
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700933 display->setActiveConfig(mode);
934 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700935}
936
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700937status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700938 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700939 Vector<DisplayInfo> configs;
940 getDisplayConfigs(displayToken, &configs);
941 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
942 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
943 configs.size());
944 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700945 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700946 const auto display = getDisplayDevice(displayToken);
947 if (!display) {
948 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
949 displayToken.get());
950 } else if (display->isVirtual()) {
951 ALOGW("Attempt to set active config %d for virtual display", mode);
952 } else {
953 setActiveConfigInternal(display, mode);
954 }
955 }));
956
Mathias Agopian888c8222012-08-04 21:10:38 -0700957 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700958}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700959status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
960 Vector<ColorMode>* outColorModes) {
961 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700962 return BAD_VALUE;
963 }
964
Michael Wright28f24d02016-07-12 13:30:53 -0700965 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700966 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
967 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700968 type = i;
969 break;
970 }
971 }
972
973 if (type < 0) {
974 return type;
975 }
976
Peiyong Lina52f0292018-03-14 17:26:31 -0700977 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700978 {
979 ConditionalLock _l(mStateLock,
980 std::this_thread::get_id() != mMainThreadId);
981 modes = getHwComposer().getColorModes(type);
982 }
Michael Wright28f24d02016-07-12 13:30:53 -0700983 outColorModes->clear();
984 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
985
986 return NO_ERROR;
987}
988
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700989ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
990 if (const auto display = getDisplayDevice(displayToken)) {
991 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700992 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700993 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700994}
995
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700996void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
997 Dataspace dataSpace, RenderIntent renderIntent) {
998 ColorMode currentMode = display->getActiveColorMode();
999 Dataspace currentDataSpace = display->getCompositionDataSpace();
1000 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001001
Peiyong Lin38e9a562018-04-10 16:24:20 -07001002 if (mode == currentMode && dataSpace == currentDataSpace &&
1003 renderIntent == currentRenderIntent) {
1004 return;
1005 }
1006
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001007 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001008 ALOGW("Trying to set config for virtual display");
1009 return;
1010 }
1011
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001012 display->setActiveColorMode(mode);
1013 display->setCompositionDataSpace(dataSpace);
1014 display->setActiveRenderIntent(renderIntent);
1015 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001016
1017 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001018 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1019 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001020}
1021
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001022status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001023 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001024 Vector<ColorMode> modes;
1025 getDisplayColorModes(displayToken, &modes);
1026 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1027 if (mode < ColorMode::NATIVE || !exists) {
1028 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1029 decodeColorMode(mode).c_str(), mode, displayToken.get());
1030 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001031 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001032 const auto display = getDisplayDevice(displayToken);
1033 if (!display) {
1034 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1035 decodeColorMode(mode).c_str(), mode, displayToken.get());
1036 } else if (display->isVirtual()) {
1037 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1038 decodeColorMode(mode).c_str(), mode);
1039 } else {
1040 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1041 RenderIntent::COLORIMETRIC);
1042 }
1043 }));
1044
Michael Wright28f24d02016-07-12 13:30:53 -07001045 return NO_ERROR;
1046}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001047
Svetoslavd85084b2014-03-20 10:28:31 -07001048status_t SurfaceFlinger::clearAnimationFrameStats() {
1049 Mutex::Autolock _l(mStateLock);
1050 mAnimFrameTracker.clearStats();
1051 return NO_ERROR;
1052}
1053
1054status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1055 Mutex::Autolock _l(mStateLock);
1056 mAnimFrameTracker.getStats(outStats);
1057 return NO_ERROR;
1058}
1059
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001060status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1061 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001062 Mutex::Autolock _l(mStateLock);
1063
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001064 const auto display = getDisplayDeviceLocked(displayToken);
1065 if (!display) {
1066 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001067 return BAD_VALUE;
1068 }
1069
Peiyong Linfb069302018-04-25 14:34:31 -07001070 // At this point the DisplayDeivce should already be set up,
1071 // meaning the luminance information is already queried from
1072 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001073 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001074 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1075 capabilities.getDesiredMaxLuminance(),
1076 capabilities.getDesiredMaxAverageLuminance(),
1077 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001078
1079 return NO_ERROR;
1080}
1081
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001082status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001083 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001084 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001085
Chia-I Wu90f669f2017-10-05 14:24:41 -07001086 if (mInjectVSyncs == enable) {
1087 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001088 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001089
1090 if (enable) {
1091 ALOGV("VSync Injections enabled");
1092 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001093 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001094 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001095 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001096 impl::EventThread::InterceptVSyncsCallback(),
1097 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001098 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001099 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001100 } else {
1101 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001102 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001103 }
1104
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001105 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001106 }));
1107
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001108 return NO_ERROR;
1109}
1110
1111status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001112 Mutex::Autolock _l(mStateLock);
1113
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001114 if (!mInjectVSyncs) {
1115 ALOGE("VSync Injections not enabled");
1116 return BAD_VALUE;
1117 }
1118 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1119 ALOGV("Injecting VSync inside SurfaceFlinger");
1120 mVSyncInjector->onInjectSyncEvent(when);
1121 }
1122 return NO_ERROR;
1123}
1124
Lloyd Pique755e3192018-01-31 16:46:15 -08001125status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1126 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001127 // Try to acquire a lock for 1s, fail gracefully
1128 const status_t err = mStateLock.timedLock(s2ns(1));
1129 const bool locked = (err == NO_ERROR);
1130 if (!locked) {
1131 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1132 return TIMED_OUT;
1133 }
1134
1135 outLayers->clear();
1136 mCurrentState.traverseInZOrder([&](Layer* layer) {
1137 outLayers->push_back(layer->getLayerDebugInfo());
1138 });
1139
1140 mStateLock.unlock();
1141 return NO_ERROR;
1142}
1143
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001144// ----------------------------------------------------------------------------
1145
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001146sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1147 ISurfaceComposer::VsyncSource vsyncSource) {
1148 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1149 return mSFEventThread->createEventConnection();
1150 } else {
1151 return mEventThread->createEventConnection();
1152 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001153}
1154
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001155// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001156
1157void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001158 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001159}
1160
1161void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001162 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001163}
1164
1165void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001166 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001167}
1168
1169void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001170 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001171 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001172}
1173
1174status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001175 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001176 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001177}
1178
1179status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001180 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001181 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001182 if (res == NO_ERROR) {
1183 msg->wait();
1184 }
1185 return res;
1186}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001187
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001188void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001189 do {
1190 waitForEvent();
1191 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001192}
1193
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001194void SurfaceFlinger::enableHardwareVsync() {
1195 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001196 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001197 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001198 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001199 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001200 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001201}
1202
Jesse Hall948fe0c2013-10-14 12:56:09 -07001203void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001204 Mutex::Autolock _l(mHWVsyncLock);
1205
Jesse Hall948fe0c2013-10-14 12:56:09 -07001206 if (makeAvailable) {
1207 mHWVsyncAvailable = true;
1208 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001209 // Hardware vsync is not currently available, so abort the resync
1210 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001211 return;
1212 }
1213
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001214 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1215 if (!getHwComposer().isConnected(displayId)) {
1216 return;
1217 }
1218
1219 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001220 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001221
Lloyd Pique41be5d22018-06-21 13:11:48 -07001222 mPrimaryDispSync->reset();
1223 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001224
1225 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001226 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001227 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001228 mPrimaryHWVsyncEnabled = true;
1229 }
1230}
1231
Jesse Hall948fe0c2013-10-14 12:56:09 -07001232void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001233 Mutex::Autolock _l(mHWVsyncLock);
1234 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001235 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001236 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001237 mPrimaryHWVsyncEnabled = false;
1238 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001239 if (makeUnavailable) {
1240 mHWVsyncAvailable = false;
1241 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001242}
1243
Tim Murray4a4e4a22016-04-19 16:29:23 +00001244void SurfaceFlinger::resyncWithRateLimit() {
1245 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001246
1247 // No explicit locking is needed here since EventThread holds a lock while calling this method
1248 static nsecs_t sLastResyncAttempted = 0;
1249 const nsecs_t now = systemTime();
1250 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001251 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001252 }
Dan Stoza57164302017-05-08 14:03:54 -07001253 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001254}
1255
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001256void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1257 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001258 ATRACE_NAME("SF onVsync");
1259
Steven Thomas3cfac282017-02-06 12:29:30 -08001260 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001261 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001262 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001263 return;
1264 }
1265
1266 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001267 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001268 return;
1269 }
1270
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001271 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1272 // For now, we don't do anything with external display vsyncs.
1273 return;
1274 }
1275
Jamie Gennisd1700752013-10-14 12:22:52 -07001276 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001277
Jamie Gennisd1700752013-10-14 12:22:52 -07001278 { // Scope for the lock
1279 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001280 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001281 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001282 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001283 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001284
1285 if (needsHwVsync) {
1286 enableHardwareVsync();
1287 } else {
1288 disableHardwareVsync(false);
1289 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001290}
1291
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001292void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001293 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1294 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001295}
1296
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001297void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001298 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001299 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001300 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001301
Lloyd Piqueba04e622017-12-14 17:11:26 -08001302 // Ignore events that do not have the right sequenceId.
1303 if (sequenceId != getBE().mComposerSequenceId) {
1304 return;
1305 }
1306
Steven Thomasb02664d2017-07-26 18:48:28 -07001307 // Only lock if we're not on the main thread. This function is normally
1308 // called on a hwbinder thread, but for the primary display it's called on
1309 // the main thread with the state lock already held, so don't attempt to
1310 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001311 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001312
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001313 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001314
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001315 if (std::this_thread::get_id() == mMainThreadId) {
1316 // Process all pending hot plug events immediately if we are on the main thread.
1317 processDisplayHotplugEventsLocked();
1318 }
1319
Lloyd Piqueba04e622017-12-14 17:11:26 -08001320 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001321}
1322
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001323void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001324 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001325 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001326 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001327 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001328 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001329}
1330
Dan Stoza9e56aa02015-11-02 13:00:03 -08001331void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001332 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001333 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001334 getHwComposer().setVsyncEnabled(disp,
1335 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001336}
1337
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001338// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001339void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001340 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001341 // Clear the drawing state so that the logic inside of
1342 // handleTransactionLocked will fire. It will determine the delta between
1343 // mCurrentState and mDrawingState and re-apply all changes when we make the
1344 // transition.
1345 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001346 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001347 mDisplays.clear();
1348}
1349
Steven Thomas050b2c82017-03-06 11:45:16 -08001350void SurfaceFlinger::updateVrFlinger() {
1351 if (!mVrFlinger)
1352 return;
1353 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001354 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001355 return;
1356 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001357
David Sodman105b7dc2017-11-04 20:28:14 -07001358 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001359 ALOGE("Vr flinger is only supported for remote hardware composer"
1360 " service connections. Ignoring request to transition to vr"
1361 " flinger.");
1362 mVrFlingerRequestsDisplay = false;
1363 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001364 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001365
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001366 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001367
Steven Thomas0123ac62018-07-12 11:32:34 -07001368 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001369 LOG_ALWAYS_FATAL_IF(!display);
1370 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001371 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1372 // called below. Clear the reference now so we don't accidentally use it
1373 // later.
1374 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001375
Steven Thomasb02664d2017-07-26 18:48:28 -07001376 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001377 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001378 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001379
Steven Thomasb02664d2017-07-26 18:48:28 -07001380 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001381 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001382 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1383 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001384 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001385
David Sodman105b7dc2017-11-04 20:28:14 -07001386 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1387 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001388
1389 if (vrFlingerRequestsDisplay) {
1390 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001391 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001392
1393 mVisibleRegionsDirty = true;
1394 invalidateHwcGeometry();
1395
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001396 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001397 display = getDefaultDisplayDeviceLocked();
1398 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001399 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001400
Steven Thomasb02664d2017-07-26 18:48:28 -07001401 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001402 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001403 const nsecs_t period = activeConfig->getVsyncPeriod();
1404 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001405
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001406 // The present fences returned from vr_hwc are not an accurate
1407 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001408 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1409 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001410
Steven Thomasb02664d2017-07-26 18:48:28 -07001411 // Use phase of 0 since phase is not known.
1412 // Use latency of 0, which will snap to the ideal latency.
1413 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001414
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001415 resyncToHardwareVsync(false);
1416
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001417 android_atomic_or(1, &mRepaintEverything);
1418 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001419}
1420
Mathias Agopian4fec8732012-06-29 14:12:52 -07001421void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001422 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001423 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001424 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001425 bool frameMissed = !mHadClientComposition &&
1426 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001427 (mPreviousPresentFence->getSignalTime() ==
1428 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001429 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001430 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001431 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001432 mTimeStats.incrementMissedFrames();
1433 if (mPropagateBackpressure) {
1434 signalLayerUpdate();
1435 break;
1436 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001437 }
Dan Stoza50182882016-07-08 12:02:20 -07001438
Steven Thomas050b2c82017-03-06 11:45:16 -08001439 // Now that we're going to make it to the handleMessageTransaction()
1440 // call below it's safe to call updateVrFlinger(), which will
1441 // potentially trigger a display handoff.
1442 updateVrFlinger();
1443
Dan Stoza6b9454d2014-11-07 16:00:59 -08001444 bool refreshNeeded = handleMessageTransaction();
1445 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001446 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001447 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001448 // Signal a refresh if a transaction modified the window state,
1449 // a new buffer was latched, or if HWC has requested a full
1450 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001451 signalRefresh();
1452 }
1453 break;
1454 }
1455 case MessageQueue::REFRESH: {
1456 handleMessageRefresh();
1457 break;
1458 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001459 }
1460}
1461
Dan Stoza6b9454d2014-11-07 16:00:59 -08001462bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001463 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001464 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001465 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001466 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001467 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001468 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001469}
1470
Mathias Agopian4fec8732012-06-29 14:12:52 -07001471void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001472 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001473
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001474 mRefreshPending = false;
1475
David Sodmanfa9b2af2017-12-24 13:28:59 -08001476 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
David Sodman2b406362017-12-15 13:33:47 -08001477 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001478 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001479 calculateWorkingSet();
David Sodman10a41ff2018-08-05 12:14:17 -07001480
David Sodmanfa9b2af2017-12-24 13:28:59 -08001481 for (const auto& [token, display] : mDisplays) {
David Sodman10a41ff2018-08-05 12:14:17 -07001482 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001483 beginFrame(display);
David Sodman10a41ff2018-08-05 12:14:17 -07001484 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
1485 setUpHWComposer(compositionInfo);
1486 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001487 prepareFrame(display);
1488 doDebugFlashRegions(display, repaintEverything);
1489 doComposition(display, repaintEverything);
1490 }
1491
Adrian Roos1e1a1282017-11-01 19:05:31 +01001492 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001493 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001494
1495 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001496 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001497
Dan Stozabfbffeb2016-07-21 14:49:33 -07001498 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001499 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001500 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001501 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001502 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001503
Jorim Jaggi90535212018-05-23 23:44:06 +02001504 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001505
David Sodman7e4ae112018-02-09 15:02:28 -08001506 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001507 for (const auto& [token, display] : mDisplays) {
1508 const auto displayId = display->getId();
David Sodman7e4ae112018-02-09 15:02:28 -08001509 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[displayId]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001510 compositionInfo.hwc.hwcLayer = nullptr;
1511 }
David Sodmanba340492018-08-05 21:51:33 -07001512 }
David Sodman7e4ae112018-02-09 15:02:28 -08001513
1514 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001515}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001516
David Sodmanfa9b2af2017-12-24 13:28:59 -08001517
1518bool SurfaceFlinger::handleMessageInvalidate() {
1519 ATRACE_CALL();
1520 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001521}
1522
David Sodman79bba0e2018-08-05 18:07:49 -07001523void SurfaceFlinger::calculateWorkingSet() {
1524 ATRACE_CALL();
1525 ALOGV(__FUNCTION__);
1526
David Sodman79bba0e2018-08-05 18:07:49 -07001527 // build the h/w work list
1528 if (CC_UNLIKELY(mGeometryInvalid)) {
1529 mGeometryInvalid = false;
1530 for (const auto& [token, display] : mDisplays) {
1531 const auto displayId = display->getId();
1532 if (displayId >= 0) {
1533 const Vector<sp<Layer>>& currentLayers(
1534 display->getVisibleLayersSortedByZ());
1535 for (size_t i = 0; i < currentLayers.size(); i++) {
1536 const auto& layer = currentLayers[i];
1537
1538 if (!layer->hasHwcLayer(displayId)) {
1539 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1540 layer->forceClientComposition(displayId);
1541 continue;
1542 }
1543 }
1544
1545 layer->setGeometry(display, i);
1546 if (mDebugDisableHWC || mDebugRegion) {
1547 layer->forceClientComposition(displayId);
1548 }
1549 }
1550 }
1551 }
1552 }
1553
1554 // Set the per-frame data
1555 for (const auto& [token, display] : mDisplays) {
1556 const auto displayId = display->getId();
1557 if (displayId < 0) {
1558 continue;
1559 }
1560
1561 if (mDrawingState.colorMatrixChanged) {
1562 display->setColorTransform(mDrawingState.colorMatrix);
1563 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1564 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1565 "display %d: %d", displayId, result);
1566 }
1567 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1568 if (layer->isHdrY410()) {
1569 layer->forceClientComposition(displayId);
1570 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1571 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1572 !display->hasHDR10Support()) {
1573 layer->forceClientComposition(displayId);
1574 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1575 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1576 !display->hasHLGSupport()) {
1577 layer->forceClientComposition(displayId);
1578 }
1579
1580 if (layer->getForceClientComposition(displayId)) {
1581 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1582 layer->setCompositionType(displayId, HWC2::Composition::Client);
1583 continue;
1584 }
1585
1586 layer->setPerFrameData(display);
1587 }
1588
Peiyong Lin13effd12018-07-24 17:01:47 -07001589 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001590 ColorMode colorMode;
1591 Dataspace dataSpace;
1592 RenderIntent renderIntent;
1593 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1594 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1595 }
1596 }
1597
1598 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001599
1600 for (const auto& [token, display] : mDisplays) {
David Sodman15fb96e2018-01-07 10:23:24 -08001601 const auto displayId = display->getId();
1602 getBE().mCompositionInfo[displayId].clear();
David Sodmanba340492018-08-05 21:51:33 -07001603 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1604 auto displayId = display->getId();
1605 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1606 if (!layer->setHwcLayer(displayId)) {
1607 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1608 }
David Sodman15fb96e2018-01-07 10:23:24 -08001609 layer->getBE().compositionInfo.hwc.displayId = displayId;
1610 getBE().mCompositionInfo[displayId].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001611 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1612 }
1613 }
David Sodman79bba0e2018-08-05 18:07:49 -07001614}
1615
David Sodmanfa9b2af2017-12-24 13:28:59 -08001616void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001617{
David Sodmanfb95bcc2017-12-22 15:45:30 -08001618 const auto displayId = display->getId();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001619 // is debugging enabled
1620 if (CC_LIKELY(!mDebugRegion))
1621 return;
1622
David Sodmanfa9b2af2017-12-24 13:28:59 -08001623 if (display->isPoweredOn()) {
1624 // transform the dirty region into this screen's coordinate space
1625 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1626 if (!dirtyRegion.isEmpty()) {
1627 // redraw the whole screen
1628 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001629
David Sodmanfa9b2af2017-12-24 13:28:59 -08001630 // and draw the dirty region
1631 const int32_t height = display->getHeight();
1632 auto& engine(getRenderEngine());
1633 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001634
David Sodmanfa9b2af2017-12-24 13:28:59 -08001635 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001636 }
1637 }
1638
David Sodmanfa9b2af2017-12-24 13:28:59 -08001639 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001640
1641 if (mDebugRegion > 1) {
1642 usleep(mDebugRegion * 1000);
1643 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001644
David Sodmanfa9b2af2017-12-24 13:28:59 -08001645 if (display->isPoweredOn()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08001646 status_t result = display->prepareFrame(
1647 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001648 ALOGE_IF(result != NO_ERROR,
1649 "prepareFrame for display %d failed:"
1650 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001651 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001652 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001653}
1654
Adrian Roos1e1a1282017-11-01 19:05:31 +01001655void SurfaceFlinger::doTracing(const char* where) {
1656 ATRACE_CALL();
1657 ATRACE_NAME(where);
1658 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001659 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001660 }
1661}
1662
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001663void SurfaceFlinger::logLayerStats() {
1664 ATRACE_CALL();
1665 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001666 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001667 if (display->isPrimary()) {
1668 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001669 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001670 }
1671 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001672
1673 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001674 }
1675}
1676
David Sodman2b406362017-12-15 13:33:47 -08001677void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001678{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001679 ATRACE_CALL();
1680 ALOGV("preComposition");
1681
David Sodman2b406362017-12-15 13:33:47 -08001682 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1683
Mathias Agopiancd60f992012-08-16 16:28:27 -07001684 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001685 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001686 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001687 needExtraInvalidate = true;
1688 }
Robert Carr2047fae2016-11-28 14:09:09 -08001689 });
1690
Mathias Agopiancd60f992012-08-16 16:28:27 -07001691 if (needExtraInvalidate) {
1692 signalLayerUpdate();
1693 }
1694}
1695
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001696void SurfaceFlinger::updateCompositorTiming(
1697 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1698 std::shared_ptr<FenceTime>& presentFenceTime) {
1699 // Update queue of past composite+present times and determine the
1700 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001701 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001702 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001703 while (!getBE().mCompositePresentTimes.empty()) {
1704 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001705 // Cached values should have been updated before calling this method,
1706 // which helps avoid duplicate syscalls.
1707 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1708 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1709 break;
1710 }
1711 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001712 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001713 }
1714
1715 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001716 while (getBE().mCompositePresentTimes.size() > 16) {
1717 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001718 }
1719
Brian Andersond0010582017-03-07 13:20:31 -08001720 setCompositorTimingSnapped(
1721 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1722}
1723
1724void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1725 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001726 // Integer division and modulo round toward 0 not -inf, so we need to
1727 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001728 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001729 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1730 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1731
Brian Andersond0010582017-03-07 13:20:31 -08001732 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1733 if (idealLatency <= 0) {
1734 idealLatency = vsyncInterval;
1735 }
1736
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001737 // Snap the latency to a value that removes scheduling jitter from the
1738 // composition and present times, which often have >1ms of jitter.
1739 // Reducing jitter is important if an app attempts to extrapolate
1740 // something (such as user input) to an accurate diasplay time.
1741 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1742 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001743 nsecs_t bias = vsyncInterval / 2;
1744 int64_t extraVsyncs =
1745 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1746 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1747 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001748
David Sodman99974d22017-11-28 12:04:33 -08001749 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1750 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1751 getBE().mCompositorTiming.interval = vsyncInterval;
1752 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001753}
1754
David Sodman2b406362017-12-15 13:33:47 -08001755void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001756{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001757 ATRACE_CALL();
1758 ALOGV("postComposition");
1759
Brian Anderson3546a3f2016-07-14 11:51:14 -07001760 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001761 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001762 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001763 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001764 }
1765
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001766 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001767 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001768
David Sodman73beded2017-11-15 11:56:06 -08001769 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001770 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001771 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001772 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001773 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001774 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001775 } else {
1776 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1777 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001778
David Sodman73beded2017-11-15 11:56:06 -08001779 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001780 mPreviousPresentFence =
1781 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1782 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001783 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001784
Lloyd Pique41be5d22018-06-21 13:11:48 -07001785 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1786 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001787
David Sodman2b406362017-12-15 13:33:47 -08001788 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001789 // when we started doing work for this frame, but that should be okay
1790 // since updateCompositorTiming has snapping logic.
1791 updateCompositorTiming(
David Sodman2b406362017-12-15 13:33:47 -08001792 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001793 CompositorTiming compositorTiming;
1794 {
David Sodman99974d22017-11-28 12:04:33 -08001795 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1796 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001797 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001798
Robert Carr2047fae2016-11-28 14:09:09 -08001799 mDrawingState.traverseInZOrder([&](Layer* layer) {
1800 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001801 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001802 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001803 recordBufferingStats(layer->getName().string(),
1804 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001805 }
Robert Carr2047fae2016-11-28 14:09:09 -08001806 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001807
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001808 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001809 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001810 enableHardwareVsync();
1811 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001812 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001813 }
1814 }
1815
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001816 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001817 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001818 enableHardwareVsync();
1819 }
1820 }
1821
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001822 if (mAnimCompositionPending) {
1823 mAnimCompositionPending = false;
1824
Brian Anderson4e606e32017-03-16 15:34:57 -07001825 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001826 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001827 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001828 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001829 // The HWC doesn't support present fences, so use the refresh
1830 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001831 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001832 mAnimFrameTracker.setActualPresentTime(presentTime);
1833 }
1834 mAnimFrameTracker.advanceFrame();
1835 }
Dan Stozab90cf072015-03-05 11:05:59 -08001836
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001837 mTimeStats.incrementTotalFrames();
1838 if (mHadClientComposition) {
1839 mTimeStats.incrementClientCompositionFrames();
1840 }
1841
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001842 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001843 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001844 return;
1845 }
1846
1847 nsecs_t currentTime = systemTime();
1848 if (mHasPoweredOff) {
1849 mHasPoweredOff = false;
1850 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001851 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001852 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001853 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1854 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001855 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001856 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001857 }
David Sodman4a36e932017-11-07 14:29:47 -08001858 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001859 }
David Sodman4a36e932017-11-07 14:29:47 -08001860 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001861
1862 {
1863 std::lock_guard lock(mTexturePoolMutex);
1864 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1865 if (refillCount > 0) {
1866 const size_t offset = mTexturePool.size();
1867 mTexturePool.resize(mTexturePoolSize);
1868 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1869 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1870 }
1871 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001872}
1873
1874void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001875 ATRACE_CALL();
1876 ALOGV("rebuildLayerStacks");
1877
Mathias Agopiancd60f992012-08-16 16:28:27 -07001878 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001879 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001880 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001881 mVisibleRegionsDirty = false;
1882 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001883
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001884 for (const auto& pair : mDisplays) {
1885 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001886 Region opaqueRegion;
1887 Region dirtyRegion;
1888 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001889 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001890 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001891 const Rect bounds = display->getBounds();
1892 if (display->isPoweredOn()) {
1893 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001894
Jeff Sharkey76488112017-02-27 14:15:18 -07001895 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001896 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001897 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001898 Region drawRegion(tr.transform(
1899 layer->visibleNonTransparentRegion));
1900 drawRegion.andSelf(bounds);
1901 if (!drawRegion.isEmpty()) {
1902 layersSortedByZ.add(layer);
1903 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001904 // Clear out the HWC layer if this layer was
1905 // previously visible, but no longer is
1906 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001907 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001908 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001909 // WM changes display->layerStack upon sleep/awake.
1910 // Here we make sure we delete the HWC layers even if
1911 // WM changed their layer stack.
1912 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001913 }
1914
1915 // If a layer is not going to get a release fence because
1916 // it is invisible, but it is also going to release its
1917 // old buffer, add it to the list of layers needing
1918 // fences.
1919 if (hwcLayerDestroyed) {
1920 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1921 mLayersWithQueuedFrames.cend(), layer);
1922 if (found != mLayersWithQueuedFrames.cend()) {
1923 layersNeedingFences.add(layer);
1924 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001925 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001926 });
1927 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001928 display->setVisibleLayersSortedByZ(layersSortedByZ);
1929 display->setLayersNeedingFences(layersNeedingFences);
1930 display->undefinedRegion.set(bounds);
1931 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1932 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001933 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001934 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001935}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001936
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001937// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001938// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001939// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001940// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001941// The returned HDR data space is one of
1942// - Dataspace::UNKNOWN
1943// - Dataspace::BT2020_HLG
1944// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001945Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1946 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001947 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001948 *outHdrDataSpace = Dataspace::UNKNOWN;
1949
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001950 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001951 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001952 case Dataspace::V0_SCRGB:
1953 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001954 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001955 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001956 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001957 case Dataspace::BT2020_PQ:
1958 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001959 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001960 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001961 case Dataspace::BT2020_HLG:
1962 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001963 // When there's mixed PQ content and HLG content, we set the HDR
1964 // data space to be BT2020_PQ and convert HLG to PQ.
1965 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1966 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001967 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001968 break;
1969 default:
1970 break;
1971 }
Romain Guy54f154a2017-10-24 21:40:32 +01001972 }
1973
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001974 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001975}
1976
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001977// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001978void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1979 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001980 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1981 *outMode = ColorMode::NATIVE;
1982 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001983 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001984 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001985 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001986
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001987 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001988 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001989
Peiyong Lindfde5112018-06-05 10:58:41 -07001990 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001991 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001992 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001993 if (isHdr) {
1994 bestDataSpace = hdrDataSpace;
1995 }
1996
Chia-I Wu0d711262018-05-21 15:19:35 -07001997 RenderIntent intent;
1998 switch (mDisplayColorSetting) {
1999 case DisplayColorSetting::MANAGED:
2000 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002001 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002002 break;
2003 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002004 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002005 break;
2006 default: // vendor display color setting
2007 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2008 break;
2009 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002010
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002011 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002012}
2013
David Sodman10a41ff2018-08-05 12:14:17 -07002014void SurfaceFlinger::configureSidebandComposition(const CompositionInfo& compositionInfo) const
2015{
2016 HWC2::Error error;
2017 LOG_ALWAYS_FATAL_IF(compositionInfo.hwc.sidebandStream == nullptr,
2018 "CompositionType is sideband, but sideband stream is nullptr");
2019 error = (compositionInfo.hwc.hwcLayer)
2020 ->setSidebandStream(compositionInfo.hwc.sidebandStream->handle());
2021 if (error != HWC2::Error::None) {
2022 ALOGE("[SF] Failed to set sideband stream %p: %s (%d)",
2023 compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
2024 static_cast<int32_t>(error));
2025 }
2026}
2027
2028void SurfaceFlinger::configureHwcCommonData(const CompositionInfo& compositionInfo) const
2029{
2030 HWC2::Error error;
2031
2032 if (!compositionInfo.hwc.skipGeometry) {
2033 error = (compositionInfo.hwc.hwcLayer)->setBlendMode(compositionInfo.hwc.blendMode);
2034 ALOGE_IF(error != HWC2::Error::None,
2035 "[SF] Failed to set blend mode %s:"
2036 " %s (%d)",
2037 to_string(compositionInfo.hwc.blendMode).c_str(), to_string(error).c_str(),
2038 static_cast<int32_t>(error));
2039
2040 error = (compositionInfo.hwc.hwcLayer)->setDisplayFrame(compositionInfo.hwc.displayFrame);
2041 ALOGE_IF(error != HWC2::Error::None,
2042 "[SF] Failed to set the display frame [%d, %d, %d, %d] %s (%d)",
2043 compositionInfo.hwc.displayFrame.left,
2044 compositionInfo.hwc.displayFrame.right,
2045 compositionInfo.hwc.displayFrame.top,
2046 compositionInfo.hwc.displayFrame.bottom,
2047 to_string(error).c_str(), static_cast<int32_t>(error));
2048
2049 error = (compositionInfo.hwc.hwcLayer)->setSourceCrop(compositionInfo.hwc.sourceCrop);
2050 ALOGE_IF(error != HWC2::Error::None,
2051 "[SF] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: %s (%d)",
2052 compositionInfo.hwc.sourceCrop.left,
2053 compositionInfo.hwc.sourceCrop.right,
2054 compositionInfo.hwc.sourceCrop.top,
2055 compositionInfo.hwc.sourceCrop.bottom,
2056 to_string(error).c_str(), static_cast<int32_t>(error));
2057
2058 error = (compositionInfo.hwc.hwcLayer)->setPlaneAlpha(compositionInfo.hwc.alpha);
2059 ALOGE_IF(error != HWC2::Error::None,
2060 "[SF] Failed to set plane alpha %.3f: "
2061 "%s (%d)",
2062 compositionInfo.hwc.alpha,
2063 to_string(error).c_str(), static_cast<int32_t>(error));
2064
2065
2066 error = (compositionInfo.hwc.hwcLayer)->setZOrder(compositionInfo.hwc.z);
2067 ALOGE_IF(error != HWC2::Error::None,
2068 "[SF] Failed to set Z %u: %s (%d)",
2069 compositionInfo.hwc.z,
2070 to_string(error).c_str(), static_cast<int32_t>(error));
2071
2072 error = (compositionInfo.hwc.hwcLayer)
2073 ->setInfo(compositionInfo.hwc.type, compositionInfo.hwc.appId);
2074 ALOGE_IF(error != HWC2::Error::None,
2075 "[SF] Failed to set info (%d)",
2076 static_cast<int32_t>(error));
2077
2078 error = (compositionInfo.hwc.hwcLayer)->setTransform(compositionInfo.hwc.transform);
2079 ALOGE_IF(error != HWC2::Error::None,
2080 "[SF] Failed to set transform %s: "
2081 "%s (%d)",
2082 to_string(compositionInfo.hwc.transform).c_str(), to_string(error).c_str(),
2083 static_cast<int32_t>(error));
2084 }
2085
2086 error = (compositionInfo.hwc.hwcLayer)->setCompositionType(compositionInfo.compositionType);
2087 ALOGE_IF(error != HWC2::Error::None,
2088 "[SF] Failed to set composition type: %s (%d)",
2089 to_string(error).c_str(), static_cast<int32_t>(error));
2090
2091 error = (compositionInfo.hwc.hwcLayer)->setDataspace(compositionInfo.hwc.dataspace);
2092 ALOGE_IF(error != HWC2::Error::None,
2093 "[SF] Failed to set dataspace: %s (%d)",
2094 to_string(error).c_str(), static_cast<int32_t>(error));
2095
2096 error = (compositionInfo.hwc.hwcLayer)->setPerFrameMetadata(
2097 compositionInfo.hwc.supportedPerFrameMetadata, compositionInfo.hwc.hdrMetadata);
2098 ALOGE_IF(error != HWC2::Error::None && error != HWC2::Error::Unsupported,
2099 "[SF] Failed to set hdrMetadata: %s (%d)",
2100 to_string(error).c_str(), static_cast<int32_t>(error));
2101
2102 if (compositionInfo.compositionType == HWC2::Composition::SolidColor) {
2103 error = (compositionInfo.hwc.hwcLayer)->setColor(compositionInfo.hwc.color);
2104 ALOGE_IF(error != HWC2::Error::None,
2105 "[SF] Failed to set color: %s (%d)",
2106 to_string(error).c_str(), static_cast<int32_t>(error));
2107 }
2108
2109 error = (compositionInfo.hwc.hwcLayer)->setVisibleRegion(compositionInfo.hwc.visibleRegion);
2110 ALOGE_IF(error != HWC2::Error::None,
2111 "[SF] Failed to set visible region: %s (%d)",
2112 to_string(error).c_str(), static_cast<int32_t>(error));
2113
2114 error = (compositionInfo.hwc.hwcLayer)->setSurfaceDamage(compositionInfo.hwc.surfaceDamage);
2115 ALOGE_IF(error != HWC2::Error::None,
2116 "[SF] Failed to set surface damage: %s (%d)",
2117 to_string(error).c_str(), static_cast<int32_t>(error));
2118}
2119
2120void SurfaceFlinger::configureDeviceComposition(const CompositionInfo& compositionInfo) const
2121{
2122 HWC2::Error error;
2123
2124 if (compositionInfo.hwc.fence) {
2125 error = (compositionInfo.hwc.hwcLayer)->setBuffer(compositionInfo.mBufferSlot,
2126 compositionInfo.mBuffer, compositionInfo.hwc.fence);
2127 ALOGE_IF(error != HWC2::Error::None,
2128 "[SF] Failed to set buffer: %s (%d)",
2129 to_string(error).c_str(), static_cast<int32_t>(error));
2130 }
2131}
2132
David Sodmanfa9b2af2017-12-24 13:28:59 -08002133void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002134{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002135 bool dirty = !display->getDirtyRegion(false).isEmpty();
2136 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2137 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002138
David Sodmanfa9b2af2017-12-24 13:28:59 -08002139 // If nothing has changed (!dirty), don't recompose.
2140 // If something changed, but we don't currently have any visible layers,
2141 // and didn't when we last did a composition, then skip it this time.
2142 // The second rule does two things:
2143 // - When all layers are removed from a display, we'll emit one black
2144 // frame, then nothing more until we get new layers.
2145 // - When a display is created with a private layer stack, we won't
2146 // emit any black frames until a layer is added to the layer stack.
2147 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002148
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002149 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2150 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002151 mustRecompose ? "doing" : "skipping",
2152 dirty ? "+" : "-",
2153 empty ? "+" : "-",
2154 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002155
David Sodmanfa9b2af2017-12-24 13:28:59 -08002156 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002157
David Sodmanfa9b2af2017-12-24 13:28:59 -08002158 if (mustRecompose) {
2159 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002160 }
2161}
2162
David Sodmanfa9b2af2017-12-24 13:28:59 -08002163void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002164{
David Sodmanfb95bcc2017-12-22 15:45:30 -08002165 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002166 if (!display->isPoweredOn()) {
2167 return;
David Sodman2b406362017-12-15 13:33:47 -08002168 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002169
David Sodmanfb95bcc2017-12-22 15:45:30 -08002170 status_t result = display->prepareFrame(
2171 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08002172 ALOGE_IF(result != NO_ERROR,
2173 "prepareFrame for display %d failed:"
2174 " %d (%s)",
2175 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002176}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002177
David Sodman10a41ff2018-08-05 12:14:17 -07002178void SurfaceFlinger::setUpHWComposer(const CompositionInfo& compositionInfo) {
2179 ATRACE_CALL();
2180 ALOGV("setUpHWComposer");
2181
2182 switch (compositionInfo.compositionType)
2183 {
2184 case HWC2::Composition::Invalid:
David Sodmana6d42332018-08-29 14:07:04 -07002185 break;
2186
David Sodman10a41ff2018-08-05 12:14:17 -07002187 case HWC2::Composition::Client:
David Sodmana6d42332018-08-29 14:07:04 -07002188 if (compositionInfo.hwc.hwcLayer) {
2189 auto error = (compositionInfo.hwc.hwcLayer)->
2190 setCompositionType(compositionInfo.compositionType);
2191 ALOGE_IF(error != HWC2::Error::None,
2192 "[SF] Failed to set composition type: %s (%d)",
2193 to_string(error).c_str(), static_cast<int32_t>(error));
2194 }
David Sodman10a41ff2018-08-05 12:14:17 -07002195 break;
2196
2197 case HWC2::Composition::Sideband:
2198 configureHwcCommonData(compositionInfo);
2199 configureSidebandComposition(compositionInfo);
2200 break;
2201
2202 case HWC2::Composition::SolidColor:
2203 configureHwcCommonData(compositionInfo);
2204 break;
2205
2206 case HWC2::Composition::Device:
2207 case HWC2::Composition::Cursor:
2208 configureHwcCommonData(compositionInfo);
2209 configureDeviceComposition(compositionInfo);
2210 break;
2211 }
2212}
2213
David Sodmanfa9b2af2017-12-24 13:28:59 -08002214void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002215 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002216 ALOGV("doComposition");
2217
David Sodmanfa9b2af2017-12-24 13:28:59 -08002218 if (display->isPoweredOn()) {
2219 // transform the dirty region into this screen's coordinate space
2220 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002221
David Sodmanfa9b2af2017-12-24 13:28:59 -08002222 // repaint the framebuffer (if needed)
2223 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002224
David Sodmanfa9b2af2017-12-24 13:28:59 -08002225 display->dirtyRegion.clear();
2226 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002227 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002228 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002229}
2230
David Sodmanfa9b2af2017-12-24 13:28:59 -08002231void SurfaceFlinger::postFrame()
2232{
2233 // |mStateLock| not needed as we are on the main thread
2234 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2235 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2236 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2237 logFrameStats();
2238 }
2239 }
2240}
2241
2242void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002243{
Mathias Agopian841cde52012-03-01 15:44:37 -08002244 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002245 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002246
David Sodmanfa9b2af2017-12-24 13:28:59 -08002247 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002248
David Sodmanfa9b2af2017-12-24 13:28:59 -08002249 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002250 const auto displayId = display->getId();
2251 if (displayId >= 0) {
2252 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002253 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002254 display->onSwapBuffersCompleted();
2255 display->makeCurrent();
David Sodman10a41ff2018-08-05 12:14:17 -07002256 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002257 sp<Fence> releaseFence = Fence::NO_FENCE;
Chia-I Wu7b549592017-11-15 09:14:57 -08002258 // The layer buffer from the previous frame (if any) is released
2259 // by HWC only when the release fence from this frame (if any) is
2260 // signaled. Always get the release fence from HWC first.
David Sodman10a41ff2018-08-05 12:14:17 -07002261 auto hwcLayer = compositionInfo.hwc.hwcLayer;
2262 if ((displayId >= 0) && hwcLayer) {
2263 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer.get());
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002264 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002265
2266 // If the layer was client composited in the previous frame, we
2267 // need to merge with the previous client target acquire fence.
2268 // Since we do not track that, always merge with the current
2269 // client target acquire fence when it is available, even though
2270 // this is suboptimal.
David Sodman10a41ff2018-08-05 12:14:17 -07002271 if (compositionInfo.compositionType == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002272 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002273 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002274 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002275
David Sodman10a41ff2018-08-05 12:14:17 -07002276 if (compositionInfo.layer) {
2277 compositionInfo.layer->onLayerDisplayed(releaseFence);
2278 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002279 }
Chia-I Wu83806892017-11-16 10:50:20 -08002280
2281 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002282 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002283 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002284 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002285 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002286 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002287 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002288 }
2289 }
2290
Dominik Laskowski7e045462018-05-30 13:02:02 -07002291 if (displayId >= 0) {
2292 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002293 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002294 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002295}
2296
Mathias Agopian87baae12012-07-31 12:38:26 -07002297void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002298{
Mathias Agopian841cde52012-03-01 15:44:37 -08002299 ATRACE_CALL();
2300
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002301 // here we keep a copy of the drawing state (that is the state that's
2302 // going to be overwritten by handleTransactionLocked()) outside of
2303 // mStateLock so that the side-effects of the State assignment
2304 // don't happen with mStateLock held (which can cause deadlocks).
2305 State drawingState(mDrawingState);
2306
Mathias Agopianca4d3602011-05-19 15:38:14 -07002307 Mutex::Autolock _l(mStateLock);
2308 const nsecs_t now = systemTime();
2309 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002310
Mathias Agopianca4d3602011-05-19 15:38:14 -07002311 // Here we're guaranteed that some transaction flags are set
2312 // so we can call handleTransactionLocked() unconditionally.
2313 // We call getTransactionFlags(), which will also clear the flags,
2314 // with mStateLock held to guarantee that mCurrentState won't change
2315 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002316
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002317 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002318 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002319 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002320
Mathias Agopianca4d3602011-05-19 15:38:14 -07002321 mLastTransactionTime = systemTime() - now;
2322 mDebugInTransaction = 0;
2323 invalidateHwcGeometry();
2324 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002325}
2326
Dominik Laskowski7e045462018-05-30 13:02:02 -07002327DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002328 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002329 // Figure out whether the event is for the primary display or an
2330 // external display by matching the Hwc display id against one for a
2331 // connected display. If we did not find a match, we then check what
2332 // displays are not already connected to determine the type. If we don't
2333 // have a connected primary display, we assume the new display is meant to
2334 // be the primary display, and then if we don't have an external display,
2335 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002336 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2337 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002338 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002339 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002340 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002341 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002342 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002343 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002344 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002345 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002346 return DisplayDevice::DISPLAY_EXTERNAL;
2347 }
2348
2349 return DisplayDevice::DISPLAY_ID_INVALID;
2350}
2351
Lloyd Piqueba04e622017-12-14 17:11:26 -08002352void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2353 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002354 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002355 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002356 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002357 continue;
2358 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002359
2360 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2361 ALOGE("External displays are not supported by the vr hardware composer.");
2362 continue;
2363 }
2364
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002365 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002366 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002367 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002368 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002369 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002370
2371 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002372 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002373 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002374 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002375 DisplayDeviceState info;
2376 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002377 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2378 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002379 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002380 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002381 mInterceptor->saveDisplayCreation(info);
2382 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002383 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002384 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002385
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002386 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002387 if (idx >= 0) {
2388 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002389 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002390 mCurrentState.displays.removeItemsAt(idx);
2391 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002392 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002393 }
2394
2395 processDisplayChangesLocked();
2396 }
2397
2398 mPendingHotplugEvents.clear();
2399}
2400
Lloyd Pique99d3da52018-01-22 17:48:03 -08002401sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002402 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002403 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002404 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002405 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002406 HdrCapabilities hdrCapabilities;
2407 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002408
Peiyong Lin13effd12018-07-24 17:01:47 -07002409 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002410 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002411 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002412 if (isWideColorMode(colorMode)) {
2413 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002414 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002415
Dominik Laskowski7e045462018-05-30 13:02:02 -07002416 std::vector<RenderIntent> renderIntents =
2417 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002418 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002419 }
tangrobin6753a022018-08-10 10:58:54 +08002420 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002421
tangrobin6753a022018-08-10 10:58:54 +08002422 if (displayId >= 0) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002423 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2424 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2425 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002426
2427 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2428 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2429
2430 /*
2431 * Create our display's surface
2432 */
Peiyong Lin833074a2018-08-28 11:53:54 -07002433 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002434 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002435 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002436 renderSurface->setNativeWindow(nativeWindow.get());
2437 const int displayWidth = renderSurface->queryWidth();
2438 const int displayHeight = renderSurface->queryHeight();
2439
2440 // Make sure that composition can never be stalled by a virtual display
2441 // consumer that isn't processing buffers fast enough. We have to do this
2442 // in two places:
2443 // * Here, in case the display is composed entirely by HWC.
2444 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2445 // window's swap interval in eglMakeCurrent, so they'll override the
2446 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002447 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002448 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2449 }
2450
Chia-I Wua02871c2018-08-27 14:38:23 -07002451 const int displayInstallOrientation = state.type == DisplayDevice::DISPLAY_PRIMARY ?
2452 primaryDisplayOrientation : DisplayState::eOrientationDefault;
2453
Lloyd Pique99d3da52018-01-22 17:48:03 -08002454 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002455 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002456
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002457 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002458 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2459 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
Chia-I Wua02871c2018-08-27 14:38:23 -07002460 displayHeight, displayInstallOrientation, hasWideColorGamut,
2461 hdrCapabilities, supportedPerFrameMetadata, hwcColorModes,
2462 initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002463
2464 if (maxFrameBufferAcquiredBuffers >= 3) {
2465 nativeWindowSurface->preallocateBuffers();
2466 }
2467
2468 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002469 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2470 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002471 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002472 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002473 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002474 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002475 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002476 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002477 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002478 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002479 display->setLayerStack(state.layerStack);
2480 display->setProjection(state.orientation, state.viewport, state.frame);
2481 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002482
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002483 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002484}
2485
Lloyd Pique347200f2017-12-14 17:00:15 -08002486void SurfaceFlinger::processDisplayChangesLocked() {
2487 // here we take advantage of Vector's copy-on-write semantics to
2488 // improve performance by skipping the transaction entirely when
2489 // know that the lists are identical
2490 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2491 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2492 if (!curr.isIdenticalTo(draw)) {
2493 mVisibleRegionsDirty = true;
2494 const size_t cc = curr.size();
2495 size_t dc = draw.size();
2496
2497 // find the displays that were removed
2498 // (ie: in drawing state but not in current state)
2499 // also handle displays that changed
2500 // (ie: displays that are in both lists)
2501 for (size_t i = 0; i < dc;) {
2502 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2503 if (j < 0) {
2504 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002505 // Call makeCurrent() on the primary display so we can
2506 // be sure that nothing associated with this display
2507 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002508 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2509 defaultDisplay->makeCurrent();
2510 }
2511 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2512 display->disconnect(getHwComposer());
2513 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002514 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2515 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2516 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2517 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2518 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002519 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002520 } else {
2521 // this display is in both lists. see if something changed.
2522 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002523 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002524 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2525 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2526 if (state_binder != draw_binder) {
2527 // changing the surface is like destroying and
2528 // recreating the DisplayDevice, so we just remove it
2529 // from the drawing state, so that it get re-added
2530 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002531 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2532 display->disconnect(getHwComposer());
2533 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002534 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002535 mDrawingState.displays.removeItemsAt(i);
2536 dc--;
2537 // at this point we must loop to the next item
2538 continue;
2539 }
2540
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002541 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002542 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002543 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002544 }
2545 if ((state.orientation != draw[i].orientation) ||
2546 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002547 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002548 }
2549 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002550 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002551 }
2552 }
2553 }
2554 ++i;
2555 }
2556
2557 // find displays that were added
2558 // (ie: in current state but not in drawing state)
2559 for (size_t i = 0; i < cc; i++) {
2560 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2561 const DisplayDeviceState& state(curr[i]);
2562
2563 sp<DisplaySurface> dispSurface;
2564 sp<IGraphicBufferProducer> producer;
2565 sp<IGraphicBufferProducer> bqProducer;
2566 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002567 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002568
Dominik Laskowski7e045462018-05-30 13:02:02 -07002569 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002570 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002571 // Virtual displays without a surface are dormant:
2572 // they have external state (layer stack, projection,
2573 // etc.) but no internal state (i.e. a DisplayDevice).
2574 if (state.surface != nullptr) {
2575 // Allow VR composer to use virtual displays.
2576 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2577 int width = 0;
2578 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2579 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2580 int height = 0;
2581 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2582 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2583 int intFormat = 0;
2584 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2585 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002586 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002587
Dominik Laskowski7e045462018-05-30 13:02:02 -07002588 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2589 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002590 }
2591
2592 // TODO: Plumb requested format back up to consumer
2593
2594 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002595 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002596 bqProducer, bqConsumer,
2597 state.displayName);
2598
2599 dispSurface = vds;
2600 producer = vds;
2601 }
2602 } else {
2603 ALOGE_IF(state.surface != nullptr,
2604 "adding a supported display, but rendering "
2605 "surface is provided (%p), ignoring it",
2606 state.surface.get());
2607
Dominik Laskowski7e045462018-05-30 13:02:02 -07002608 displayId = state.type;
2609 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002610 producer = bqProducer;
2611 }
2612
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002613 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002614 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002615 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002616 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002617 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002618 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002619 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2620 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2621 true);
2622 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2623 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2624 true);
2625 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002626 }
2627 }
2628 }
2629 }
2630 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002631
2632 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002633}
2634
Mathias Agopian87baae12012-07-31 12:38:26 -07002635void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002636{
Dan Stoza7dde5992015-05-22 09:51:44 -07002637 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002638 mCurrentState.traverseInZOrder([](Layer* layer) {
2639 layer->notifyAvailableFrames();
2640 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002641
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002642 /*
2643 * Traversal of the children
2644 * (perform the transaction for each of them if needed)
2645 */
2646
Mathias Agopian3559b072012-08-15 13:46:03 -07002647 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002648 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002649 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002650 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002651
2652 const uint32_t flags = layer->doTransaction(0);
2653 if (flags & Layer::eVisibleRegion)
2654 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002655 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002656 }
2657
2658 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002659 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002660 */
2661
Mathias Agopiane57f2922012-08-09 16:29:12 -07002662 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002663 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002664 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002665 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002666
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002667 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002668 // The transform hint might have changed for some layers
2669 // (either because a display has changed, or because a layer
2670 // as changed).
2671 //
2672 // Walk through all the layers in currentLayers,
2673 // and update their transform hint.
2674 //
2675 // If a layer is visible only on a single display, then that
2676 // display is used to calculate the hint, otherwise we use the
2677 // default display.
2678 //
2679 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2680 // the hint is set before we acquire a buffer from the surface texture.
2681 //
2682 // NOTE: layer transactions have taken place already, so we use their
2683 // drawing state. However, SurfaceFlinger's own transaction has not
2684 // happened yet, so we must use the current state layer list
2685 // (soon to become the drawing state list).
2686 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002687 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002688 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002689 bool first = true;
2690 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002691 // NOTE: we rely on the fact that layers are sorted by
2692 // layerStack first (so we don't have to traverse the list
2693 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002694 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002695 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002696 currentlayerStack = layerStack;
2697 // figure out if this layerstack is mirrored
2698 // (more than one display) if so, pick the default display,
2699 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002700 hintDisplay = nullptr;
2701 for (const auto& [token, display] : mDisplays) {
2702 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2703 if (hintDisplay) {
2704 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002705 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002706 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002707 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002708 }
2709 }
2710 }
2711 }
Chet Haase91d25932013-04-11 15:24:55 -07002712
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002713 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002714 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2715 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002716
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002717 // could be null when this layer is using a layerStack
2718 // that is not visible on any display. Also can occur at
2719 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002720 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002721 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002722
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002723 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002724 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002725 if (hintDisplay) {
2726 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002727 }
Robert Carr2047fae2016-11-28 14:09:09 -08002728
2729 first = false;
2730 });
Mathias Agopian84300952012-11-21 16:02:13 -08002731 }
2732
2733
Mathias Agopian3559b072012-08-15 13:46:03 -07002734 /*
2735 * Perform our own transaction if needed
2736 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002737
2738 if (mLayersAdded) {
2739 mLayersAdded = false;
2740 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002741 mVisibleRegionsDirty = true;
2742 }
2743
2744 // some layers might have been removed, so
2745 // we need to update the regions they're exposing.
2746 if (mLayersRemoved) {
2747 mLayersRemoved = false;
2748 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002749 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002750 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002751 // this layer is not visible anymore
2752 // TODO: we could traverse the tree from front to back and
2753 // compute the actual visible region
2754 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002755 Region visibleReg;
2756 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002757 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002758 }
Robert Carr2047fae2016-11-28 14:09:09 -08002759 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002760 }
2761
2762 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002763
2764 updateCursorAsync();
2765}
2766
2767void SurfaceFlinger::updateCursorAsync()
2768{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002769 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002770 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002771 continue;
2772 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002773
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002774 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2775 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002776 }
2777 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002778}
2779
2780void SurfaceFlinger::commitTransaction()
2781{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002782 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002783 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002784 for (const auto& l : mLayersPendingRemoval) {
2785 recordBufferingStats(l->getName().string(),
2786 l->getOccupancyHistory(true));
2787 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002788 }
2789 mLayersPendingRemoval.clear();
2790 }
2791
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002792 // If this transaction is part of a window animation then the next frame
2793 // we composite should be considered an animation as well.
2794 mAnimCompositionPending = mAnimTransactionPending;
2795
Mathias Agopian4fec8732012-06-29 14:12:52 -07002796 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002797 // clear the "changed" flags in current state
2798 mCurrentState.colorMatrixChanged = false;
2799
Robert Carr1f0a16a2016-10-24 16:27:39 -07002800 mDrawingState.traverseInZOrder([](Layer* layer) {
2801 layer->commitChildList();
2802 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002803 mTransactionPending = false;
2804 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002805 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002806}
2807
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002808void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2809 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002810 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002811 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002812
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002813 Region aboveOpaqueLayers;
2814 Region aboveCoveredLayers;
2815 Region dirty;
2816
Mathias Agopian87baae12012-07-31 12:38:26 -07002817 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002818
Robert Carr2047fae2016-11-28 14:09:09 -08002819 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002820 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002821 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002822
Jesse Hall01e29052013-02-19 16:13:35 -08002823 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002824 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002825 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002826 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002827
Mathias Agopianab028732010-03-16 16:41:46 -07002828 /*
2829 * opaqueRegion: area of a surface that is fully opaque.
2830 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002831 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002832
2833 /*
2834 * visibleRegion: area of a surface that is visible on screen
2835 * and not fully transparent. This is essentially the layer's
2836 * footprint minus the opaque regions above it.
2837 * Areas covered by a translucent surface are considered visible.
2838 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002839 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002840
2841 /*
2842 * coveredRegion: area of a surface that is covered by all
2843 * visible regions above it (which includes the translucent areas).
2844 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002845 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002846
Jesse Halla8026d22012-09-25 13:25:04 -07002847 /*
2848 * transparentRegion: area of a surface that is hinted to be completely
2849 * transparent. This is only used to tell when the layer has no visible
2850 * non-transparent regions and can be removed from the layer list. It
2851 * does not affect the visibleRegion of this layer or any layers
2852 * beneath it. The hint may not be correct if apps don't respect the
2853 * SurfaceView restrictions (which, sadly, some don't).
2854 */
2855 Region transparentRegion;
2856
Mathias Agopianab028732010-03-16 16:41:46 -07002857
2858 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002859 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002860 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002861 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002862 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002863 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002864 if (!visibleRegion.isEmpty()) {
2865 // Remove the transparent area from the visible region
2866 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002867 if (tr.preserveRects()) {
2868 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002869 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002870 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002871 // transformation too complex, can't do the
2872 // transparent region optimization.
2873 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002874 }
Mathias Agopianab028732010-03-16 16:41:46 -07002875 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002876
Mathias Agopianab028732010-03-16 16:41:46 -07002877 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002878 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002879 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002880 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002881 // the opaque region is the layer's footprint
2882 opaqueRegion = visibleRegion;
2883 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002884 }
2885 }
2886
Robert Carre5f4f692018-01-12 13:12:28 -08002887 if (visibleRegion.isEmpty()) {
2888 layer->clearVisibilityRegions();
2889 return;
2890 }
2891
Mathias Agopianab028732010-03-16 16:41:46 -07002892 // Clip the covered region to the visible region
2893 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2894
2895 // Update aboveCoveredLayers for next (lower) layer
2896 aboveCoveredLayers.orSelf(visibleRegion);
2897
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002898 // subtract the opaque region covered by the layers above us
2899 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002900
2901 // compute this layer's dirty region
2902 if (layer->contentDirty) {
2903 // we need to invalidate the whole region
2904 dirty = visibleRegion;
2905 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002906 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002907 layer->contentDirty = false;
2908 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002909 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002910 * the exposed region consists of two components:
2911 * 1) what's VISIBLE now and was COVERED before
2912 * 2) what's EXPOSED now less what was EXPOSED before
2913 *
2914 * note that (1) is conservative, we start with the whole
2915 * visible region but only keep what used to be covered by
2916 * something -- which mean it may have been exposed.
2917 *
2918 * (2) handles areas that were not covered by anything but got
2919 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002920 */
Mathias Agopianab028732010-03-16 16:41:46 -07002921 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002922 const Region oldVisibleRegion = layer->visibleRegion;
2923 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002924 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2925 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002926 }
2927 dirty.subtractSelf(aboveOpaqueLayers);
2928
2929 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002930 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002931
Mathias Agopianab028732010-03-16 16:41:46 -07002932 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002933 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002934
Jesse Halla8026d22012-09-25 13:25:04 -07002935 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002936 layer->setVisibleRegion(visibleRegion);
2937 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002938 layer->setVisibleNonTransparentRegion(
2939 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002940 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002941
Mathias Agopian87baae12012-07-31 12:38:26 -07002942 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002943}
2944
Chia-I Wuab0c3192017-08-01 11:29:00 -07002945void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002946 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002947 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2948 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002949 }
2950 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002951}
2952
Dan Stoza6b9454d2014-11-07 16:00:59 -08002953bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002954{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002955 ALOGV("handlePageFlip");
2956
Brian Andersond6927fb2016-07-23 23:37:30 -07002957 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002958
Mathias Agopian4fec8732012-06-29 14:12:52 -07002959 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002960 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002961 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002962
2963 // Store the set of layers that need updates. This set must not change as
2964 // buffers are being latched, as this could result in a deadlock.
2965 // Example: Two producers share the same command stream and:
2966 // 1.) Layer 0 is latched
2967 // 2.) Layer 0 gets a new frame
2968 // 2.) Layer 1 gets a new frame
2969 // 3.) Layer 1 is latched.
2970 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2971 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002972 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002973 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002974 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07002975 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002976 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002977 } else {
2978 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002979 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002980 } else {
2981 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002982 }
Robert Carr2047fae2016-11-28 14:09:09 -08002983 });
2984
Dan Stoza9e56aa02015-11-02 13:00:03 -08002985 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002986 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002987 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002988 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002989 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002990 newDataLatched = true;
2991 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002992 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002993
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002994 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002995
2996 // If we will need to wake up at some time in the future to deal with a
2997 // queued frame that shouldn't be displayed during this vsync period, wake
2998 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002999 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003000 signalLayerUpdate();
3001 }
3002
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003003 // enter boot animation on first buffer latch
3004 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3005 ALOGI("Enter boot animation");
3006 mBootStage = BootStage::BOOTANIMATION;
3007 }
3008
Dan Stoza6b9454d2014-11-07 16:00:59 -08003009 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003010 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003011}
3012
Mathias Agopianad456f92011-01-13 17:53:01 -08003013void SurfaceFlinger::invalidateHwcGeometry()
3014{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003015 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003016}
3017
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003018void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
3019 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003020 // We only need to actually compose the display if:
3021 // 1) It is being handled by hardware composer, which may need this to
3022 // keep its virtual display state machine in sync, or
3023 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07003024 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08003025 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003026 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003027 return;
3028 }
3029
Dan Stoza9e56aa02015-11-02 13:00:03 -08003030 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003031 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003032
3033 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003034 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003035}
3036
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003037bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003038 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003039
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003040 const Region bounds(display->bounds());
3041 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003042 const auto displayId = display->getId();
3043 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003044 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003045
Chia-I Wu8e50e692018-05-04 10:12:37 -07003046 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003047 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003048
Dan Stoza9e56aa02015-11-02 13:00:03 -08003049 if (hasClientComposition) {
3050 ALOGV("hasClientComposition");
3051
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003052 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003053 if (display->hasWideColorGamut()) {
3054 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003055 }
3056 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003057 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003058 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003059
Dominik Laskowski7e045462018-05-30 13:02:02 -07003060 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003061 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3062 HWC2::Capability::SkipClientColorTransform);
3063
Chia-I Wud49d6692018-06-27 07:17:41 +08003064 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003065 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3066 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003067 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003068 }
3069
Chia-I Wud49d6692018-06-27 07:17:41 +08003070 // The current enhanced saturation matrix is designed to enhance Display P3,
3071 // thus we only apply this matrix when the render intent is not colorimetric
3072 // and the output color space is Display P3.
3073 needsEnhancedColorMatrix =
3074 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3075 outputDataspace == Dataspace::DISPLAY_P3);
3076 if (needsEnhancedColorMatrix) {
3077 colorMatrix *= mEnhancedSaturationMatrix;
3078 }
3079
3080 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003081
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003082 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003083 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003084 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003085 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003086
3087 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003088 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3089 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3090 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003091 }
3092 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003093 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003094
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003095 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003096 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003097 // when using overlays, we assume a fully transparent framebuffer
3098 // NOTE: we could reduce how much we need to clear, for instance
3099 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003100 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003101 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003102 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003103 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003104 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003105 // we're left with the letterbox region
3106 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003107 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003108
3109 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003110 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003111
Mathias Agopianb9494d52012-04-18 02:28:45 -07003112 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003113 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003114 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003115 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003116 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003117 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003118
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003119 const Rect& bounds = display->getBounds();
3120 const Rect& scissor = display->getScissor();
3121 if (scissor != bounds) {
3122 // scissor doesn't match the screen's dimensions, so we
3123 // need to clear everything outside of it and enable
3124 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003125
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003126 // enable scissor for this frame
3127 const uint32_t height = display->getHeight();
3128 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
3129 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003130 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003131 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003132
Mathias Agopian85d751c2012-08-29 16:59:24 -07003133 /*
3134 * and then, render the layers targeted at the framebuffer
3135 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003136
Dan Stoza9e56aa02015-11-02 13:00:03 -08003137 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003138 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003139 bool firstLayer = true;
David Sodmanfb95bcc2017-12-22 15:45:30 -08003140 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
3141 const Region bounds(display->bounds());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003142 const Region clip(bounds.intersect(
David Sodmanfb95bcc2017-12-22 15:45:30 -08003143 displayTransform.transform(compositionInfo.layer->mLayer->visibleRegion)));
3144 ALOGV("Layer: %s", compositionInfo.layerName.c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003145 if (!clip.isEmpty()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08003146 switch (compositionInfo.compositionType) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003147 case HWC2::Composition::Cursor:
3148 case HWC2::Composition::Device:
3149 case HWC2::Composition::Sideband:
3150 case HWC2::Composition::SolidColor: {
David Sodmanfb95bcc2017-12-22 15:45:30 -08003151 const Layer::State& state(compositionInfo.layer->mLayer->getDrawingState());
3152 const bool opaque = compositionInfo.layer->mLayer->isOpaque(state);
3153 if (compositionInfo.hwc.clearClientTarget && !firstLayer &&
3154 opaque && (state.color.a == 1.0f) && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003155 // never clear the very first layer since we're
3156 // guaranteed the FB is already cleared
David Sodman10a41ff2018-08-05 12:14:17 -07003157 compositionInfo.layer->clear(getRenderEngine());
Mathias Agopiancd60f992012-08-16 16:28:27 -07003158 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003159 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003160 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003161 case HWC2::Composition::Client: {
David Sodmanfb95bcc2017-12-22 15:45:30 -08003162 compositionInfo.layer->mLayer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003163 break;
3164 }
3165 default:
3166 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003167 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003168 } else {
3169 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003170 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003171 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003172 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003173
Chia-I Wud49d6692018-06-27 07:17:41 +08003174 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003175 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003176 }
3177
Mathias Agopianf45c5102012-10-24 16:29:17 -07003178 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003179 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003180 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003181}
3182
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003183void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
3184 const Region& region) const {
3185 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003186 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003187 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003188}
3189
Dan Stoza7d89d062015-04-30 13:29:25 -07003190status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003191 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003192 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003193 const sp<Layer>& lbc,
3194 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003195{
Dan Stoza7d89d062015-04-30 13:29:25 -07003196 // add this layer to the current state list
3197 {
3198 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003199 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003200 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3201 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003202 return NO_MEMORY;
3203 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003204 if (parent == nullptr) {
3205 mCurrentState.layersSortedByZ.add(lbc);
3206 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003207 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003208 ALOGE("addClientLayer called with a removed parent");
3209 return NAME_NOT_FOUND;
3210 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003211 parent->addChild(lbc);
3212 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003213
Yiwei Zhang243b3782018-05-15 17:40:04 -07003214 if (gbc != nullptr) {
3215 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3216 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3217 mMaxGraphicBufferProducerListSize,
3218 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3219 mGraphicBufferProducerList.size(),
3220 mMaxGraphicBufferProducerListSize, mNumLayers);
3221 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003222 mLayersAdded = true;
3223 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003224 }
3225
Mathias Agopian96f08192010-06-02 23:28:45 -07003226 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003227 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003228
Dan Stoza7d89d062015-04-30 13:29:25 -07003229 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003230}
3231
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003232status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003233 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003234 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3235}
Robert Carr7f9b8992017-03-10 11:08:39 -08003236
chaviwca27f252018-02-06 16:46:39 -08003237status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3238 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003239 if (layer->isPendingRemoval()) {
3240 return NO_ERROR;
3241 }
3242
Robert Carr1f0a16a2016-10-24 16:27:39 -07003243 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003244 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003245 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003246 if (topLevelOnly) {
3247 return NO_ERROR;
3248 }
3249
Chia-I Wu98f1c102017-05-30 14:54:08 -07003250 sp<Layer> ancestor = p;
3251 while (ancestor->getParent() != nullptr) {
3252 ancestor = ancestor->getParent();
3253 }
3254 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3255 ALOGE("removeLayer called with a layer whose parent has been removed");
3256 return NAME_NOT_FOUND;
3257 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003258
3259 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003260 } else {
3261 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003262 }
3263
Robert Carr136e2f62017-02-08 17:54:29 -08003264 // As a matter of normal operation, the LayerCleaner will produce a second
3265 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3266 // so we will succeed in promoting it, but it's already been removed
3267 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3268 // otherwise something has gone wrong and we are leaking the layer.
3269 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003270 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3271 layer->getName().string(),
3272 (p != nullptr) ? p->getName().string() : "no-parent");
3273 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003274 } else if (index < 0) {
3275 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003276 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003277
Chia-I Wuc6657022017-08-15 11:18:17 -07003278 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003279 mLayersPendingRemoval.add(layer);
3280 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003281 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003282 setTransactionFlags(eTransactionNeeded);
3283 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003284}
3285
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003286uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003287 return android_atomic_release_load(&mTransactionFlags);
3288}
3289
Mathias Agopian3f844832013-08-07 21:24:32 -07003290uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003291 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3292}
3293
Mathias Agopian3f844832013-08-07 21:24:32 -07003294uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003295 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3296}
3297
3298uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3299 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003300 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003301 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003302 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003303 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003304 }
3305 return old;
3306}
3307
chaviwca27f252018-02-06 16:46:39 -08003308bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3309 for (const ComposerState& state : states) {
3310 // Here we need to check that the interface we're given is indeed
3311 // one of our own. A malicious client could give us a nullptr
3312 // IInterface, or one of its own or even one of our own but a
3313 // different type. All these situations would cause us to crash.
3314 if (state.client == nullptr) {
3315 return true;
3316 }
3317
3318 sp<IBinder> binder = IInterface::asBinder(state.client);
3319 if (binder == nullptr) {
3320 return true;
3321 }
3322
3323 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3324 return true;
3325 }
3326 }
3327 return false;
3328}
3329
Mathias Agopian8b33f032012-07-24 20:43:54 -07003330void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003331 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003332 const Vector<DisplayState>& displays,
3333 uint32_t flags)
3334{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003335 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003336 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003337 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003338
chaviwca27f252018-02-06 16:46:39 -08003339 if (containsAnyInvalidClientState(states)) {
3340 return;
3341 }
3342
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003343 if (flags & eAnimation) {
3344 // For window updates that are part of an animation we must wait for
3345 // previous animation "frames" to be handled.
3346 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003347 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003348 if (CC_UNLIKELY(err != NO_ERROR)) {
3349 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003350 // caller after a few seconds.
3351 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3352 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003353 mAnimTransactionPending = false;
3354 break;
3355 }
3356 }
3357 }
3358
chaviwca27f252018-02-06 16:46:39 -08003359 for (const DisplayState& display : displays) {
3360 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003361 }
3362
chaviwca27f252018-02-06 16:46:39 -08003363 for (const ComposerState& state : states) {
3364 transactionFlags |= setClientStateLocked(state);
3365 }
3366
3367 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3368 // as destroyed should only occur after setting all other states. This is to allow for a
3369 // child re-parent to happen before marking its original parent as destroyed (which would
3370 // then mark the child as destroyed).
3371 for (const ComposerState& state : states) {
3372 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003373 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003374
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003375 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3376 // anyway. This can be used as a flush mechanism for previous async transactions.
3377 // Empty animation transaction can be used to simulate back-pressure, so also force a
3378 // transaction for empty animation transactions.
3379 if (transactionFlags == 0 &&
3380 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003381 transactionFlags = eTransactionNeeded;
3382 }
3383
Mathias Agopian386aa982011-11-07 21:58:03 -08003384 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003385 if (mInterceptor->isEnabled()) {
3386 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003387 }
Irvel468051e2016-06-13 16:44:44 -07003388
Mathias Agopian386aa982011-11-07 21:58:03 -08003389 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003390 const auto start = (flags & eEarlyWakeup)
3391 ? VSyncModulator::TransactionStart::EARLY
3392 : VSyncModulator::TransactionStart::NORMAL;
3393 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003394
3395 // if this is a synchronous transaction, wait for it to take effect
3396 // before returning.
3397 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003398 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003399 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003400 if (flags & eAnimation) {
3401 mAnimTransactionPending = true;
3402 }
3403 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003404 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3405 if (CC_UNLIKELY(err != NO_ERROR)) {
3406 // just in case something goes wrong in SF, return to the
3407 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003408 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3409 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003410 break;
3411 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003412 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003413 }
3414}
3415
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003416uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3417 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3418 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003419
Mathias Agopiane57f2922012-08-09 16:29:12 -07003420 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003421 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3422
3423 const uint32_t what = s.what;
3424 if (what & DisplayState::eSurfaceChanged) {
3425 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3426 state.surface = s.surface;
3427 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003428 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003429 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003430 if (what & DisplayState::eLayerStackChanged) {
3431 if (state.layerStack != s.layerStack) {
3432 state.layerStack = s.layerStack;
3433 flags |= eDisplayTransactionNeeded;
3434 }
3435 }
3436 if (what & DisplayState::eDisplayProjectionChanged) {
3437 if (state.orientation != s.orientation) {
3438 state.orientation = s.orientation;
3439 flags |= eDisplayTransactionNeeded;
3440 }
3441 if (state.frame != s.frame) {
3442 state.frame = s.frame;
3443 flags |= eDisplayTransactionNeeded;
3444 }
3445 if (state.viewport != s.viewport) {
3446 state.viewport = s.viewport;
3447 flags |= eDisplayTransactionNeeded;
3448 }
3449 }
3450 if (what & DisplayState::eDisplaySizeChanged) {
3451 if (state.width != s.width) {
3452 state.width = s.width;
3453 flags |= eDisplayTransactionNeeded;
3454 }
3455 if (state.height != s.height) {
3456 state.height = s.height;
3457 flags |= eDisplayTransactionNeeded;
3458 }
3459 }
3460
Mathias Agopiane57f2922012-08-09 16:29:12 -07003461 return flags;
3462}
3463
Robert Carrd4ae7f32018-06-07 16:10:57 -07003464bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3465 IPCThreadState* ipc = IPCThreadState::self();
3466 const int pid = ipc->getCallingPid();
3467 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003468 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003469 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003470 return false;
3471 }
3472 return true;
3473}
3474
chaviwca27f252018-02-06 16:46:39 -08003475uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3476 const layer_state_t& s = composerState.state;
3477 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3478
Mathias Agopian13127d82013-03-05 17:47:11 -08003479 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003480 if (layer == nullptr) {
3481 return 0;
3482 }
3483
3484 if (layer->isPendingRemoval()) {
3485 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3486 return 0;
3487 }
3488
3489 uint32_t flags = 0;
3490
3491 const uint32_t what = s.what;
3492 bool geometryAppliesWithResize =
3493 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003494
3495 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3496 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003497 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003498 layer->pushPendingState();
3499 }
3500
chaviw8b3871a2017-11-01 17:41:01 -07003501 if (what & layer_state_t::ePositionChanged) {
3502 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3503 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003504 }
chaviw8b3871a2017-11-01 17:41:01 -07003505 }
3506 if (what & layer_state_t::eLayerChanged) {
3507 // NOTE: index needs to be calculated before we update the state
3508 const auto& p = layer->getParent();
3509 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003510 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003511 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003512 mCurrentState.layersSortedByZ.removeAt(idx);
3513 mCurrentState.layersSortedByZ.add(layer);
3514 // we need traversal (state changed)
3515 // AND transaction (list changed)
3516 flags |= eTransactionNeeded|eTraversalNeeded;
3517 }
chaviw8b3871a2017-11-01 17:41:01 -07003518 } else {
3519 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003520 flags |= eTransactionNeeded|eTraversalNeeded;
3521 }
3522 }
chaviw8b3871a2017-11-01 17:41:01 -07003523 }
3524 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003525 // NOTE: index needs to be calculated before we update the state
3526 const auto& p = layer->getParent();
3527 if (p == nullptr) {
3528 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3529 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3530 mCurrentState.layersSortedByZ.removeAt(idx);
3531 mCurrentState.layersSortedByZ.add(layer);
3532 // we need traversal (state changed)
3533 // AND transaction (list changed)
3534 flags |= eTransactionNeeded|eTraversalNeeded;
3535 }
3536 } else {
3537 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3538 flags |= eTransactionNeeded|eTraversalNeeded;
3539 }
chaviw8b3871a2017-11-01 17:41:01 -07003540 }
3541 }
3542 if (what & layer_state_t::eSizeChanged) {
3543 if (layer->setSize(s.w, s.h)) {
3544 flags |= eTraversalNeeded;
3545 }
3546 }
3547 if (what & layer_state_t::eAlphaChanged) {
3548 if (layer->setAlpha(s.alpha))
3549 flags |= eTraversalNeeded;
3550 }
3551 if (what & layer_state_t::eColorChanged) {
3552 if (layer->setColor(s.color))
3553 flags |= eTraversalNeeded;
3554 }
3555 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003556 // TODO: b/109894387
3557 //
3558 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3559 // rotation. To see the problem observe that if we have a square parent, and a child
3560 // of the same size, then we rotate the child 45 degrees around it's center, the child
3561 // must now be cropped to a non rectangular 8 sided region.
3562 //
3563 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3564 // private API, and the WindowManager only uses rotation in one case, which is on a top
3565 // level layer in which cropping is not an issue.
3566 //
3567 // However given that abuse of rotation matrices could lead to surfaces extending outside
3568 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3569 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3570 // transformations.
3571 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003572 flags |= eTraversalNeeded;
3573 }
3574 if (what & layer_state_t::eTransparentRegionChanged) {
3575 if (layer->setTransparentRegionHint(s.transparentRegion))
3576 flags |= eTraversalNeeded;
3577 }
3578 if (what & layer_state_t::eFlagsChanged) {
3579 if (layer->setFlags(s.flags, s.mask))
3580 flags |= eTraversalNeeded;
3581 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003582 if (what & layer_state_t::eCropChanged_legacy) {
3583 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003584 flags |= eTraversalNeeded;
3585 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003586 if (what & layer_state_t::eFinalCropChanged_legacy) {
3587 if (layer->setFinalCrop_legacy(s.finalCrop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003588 flags |= eTraversalNeeded;
3589 }
3590 if (what & layer_state_t::eLayerStackChanged) {
3591 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3592 // We only allow setting layer stacks for top level layers,
3593 // everything else inherits layer stack from its parent.
3594 if (layer->hasParent()) {
3595 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3596 layer->getName().string());
3597 } else if (idx < 0) {
3598 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3599 "that also does not appear in the top level layer list. Something"
3600 " has gone wrong.", layer->getName().string());
3601 } else if (layer->setLayerStack(s.layerStack)) {
3602 mCurrentState.layersSortedByZ.removeAt(idx);
3603 mCurrentState.layersSortedByZ.add(layer);
3604 // we need traversal (state changed)
3605 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003606 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003607 }
3608 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003609 if (what & layer_state_t::eDeferTransaction_legacy) {
3610 if (s.barrierHandle_legacy != nullptr) {
3611 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3612 } else if (s.barrierGbp_legacy != nullptr) {
3613 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003614 if (authenticateSurfaceTextureLocked(gbp)) {
3615 const auto& otherLayer =
3616 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003617 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003618 } else {
3619 ALOGE("Attempt to defer transaction to to an"
3620 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003621 }
3622 }
chaviw8b3871a2017-11-01 17:41:01 -07003623 // We don't trigger a traversal here because if no other state is
3624 // changed, we don't want this to cause any more work
3625 }
3626 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003627 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003628 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003629 if (!hadParent) {
3630 mCurrentState.layersSortedByZ.remove(layer);
3631 }
chaviw8b3871a2017-11-01 17:41:01 -07003632 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003633 }
chaviw8b3871a2017-11-01 17:41:01 -07003634 }
3635 if (what & layer_state_t::eReparentChildren) {
3636 if (layer->reparentChildren(s.reparentHandle)) {
3637 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003638 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003639 }
chaviw8b3871a2017-11-01 17:41:01 -07003640 if (what & layer_state_t::eDetachChildren) {
3641 layer->detachChildren();
3642 }
3643 if (what & layer_state_t::eOverrideScalingModeChanged) {
3644 layer->setOverrideScalingMode(s.overrideScalingMode);
3645 // We don't trigger a traversal here because if no other state is
3646 // changed, we don't want this to cause any more work
3647 }
Marissa Wall61c58622018-07-18 10:12:20 -07003648 if (what & layer_state_t::eTransformChanged) {
3649 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3650 }
3651 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3652 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3653 flags |= eTraversalNeeded;
3654 }
3655 if (what & layer_state_t::eCropChanged) {
3656 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3657 }
3658 if (what & layer_state_t::eBufferChanged) {
3659 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3660 }
3661 if (what & layer_state_t::eAcquireFenceChanged) {
3662 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3663 }
3664 if (what & layer_state_t::eDataspaceChanged) {
3665 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3666 }
3667 if (what & layer_state_t::eHdrMetadataChanged) {
3668 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3669 }
3670 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3671 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3672 }
3673 if (what & layer_state_t::eApiChanged) {
3674 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3675 }
3676 if (what & layer_state_t::eSidebandStreamChanged) {
3677 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3678 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003679 return flags;
3680}
3681
chaviwca27f252018-02-06 16:46:39 -08003682void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3683 const layer_state_t& state = composerState.state;
3684 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3685
3686 sp<Layer> layer(client->getLayerUser(state.surface));
3687 if (layer == nullptr) {
3688 return;
3689 }
3690
3691 if (layer->isPendingRemoval()) {
3692 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3693 return;
3694 }
3695
3696 if (state.what & layer_state_t::eDestroySurface) {
3697 removeLayerLocked(mStateLock, layer);
3698 }
3699}
3700
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003701status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003702 const String8& name,
3703 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003704 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003705 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003706 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003707{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003708 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003709 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003710 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003711 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003712 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003713
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003714 status_t result = NO_ERROR;
3715
3716 sp<Layer> layer;
3717
Cody Northropbc755282017-03-31 12:00:08 -06003718 String8 uniqueName = getUniqueLayerName(name);
3719
Mathias Agopian3165cc22012-08-08 19:42:09 -07003720 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003721 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003722 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3723 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003724
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003725 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003726 case ISurfaceComposerClient::eFXSurfaceBufferState:
3727 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3728 break;
chaviw13fdc492017-06-27 12:40:18 -07003729 case ISurfaceComposerClient::eFXSurfaceColor:
3730 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003731 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003732 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003733 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003734 case ISurfaceComposerClient::eFXSurfaceContainer:
3735 result = createContainerLayer(client,
3736 uniqueName, w, h, flags,
3737 handle, &layer);
3738 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003739 default:
3740 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003741 break;
3742 }
3743
Dan Stoza7d89d062015-04-30 13:29:25 -07003744 if (result != NO_ERROR) {
3745 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003746 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003747
Chia-I Wuab0c3192017-08-01 11:29:00 -07003748 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3749 // TODO b/64227542
3750 if (windowType == 441731) {
3751 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3752 layer->setPrimaryDisplayOnly();
3753 }
3754
Albert Chaulk479c60c2017-01-27 14:21:34 -05003755 layer->setInfo(windowType, ownerUid);
3756
Robert Carr1f0a16a2016-10-24 16:27:39 -07003757 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003758 if (result != NO_ERROR) {
3759 return result;
3760 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003761 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003762
3763 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003764 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003765}
3766
Cody Northropbc755282017-03-31 12:00:08 -06003767String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3768{
3769 bool matchFound = true;
3770 uint32_t dupeCounter = 0;
3771
3772 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3773 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3774
Dan Stoza436ccf32018-06-21 12:10:12 -07003775 // Grab the state lock since we're accessing mCurrentState
3776 Mutex::Autolock lock(mStateLock);
3777
Cody Northropbc755282017-03-31 12:00:08 -06003778 // Loop over layers until we're sure there is no matching name
3779 while (matchFound) {
3780 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003781 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003782 if (layer->getName() == uniqueName) {
3783 matchFound = true;
3784 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3785 }
3786 });
3787 }
3788
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003789 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3790 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003791
3792 return uniqueName;
3793}
3794
Marissa Wallfd668622018-05-10 10:21:13 -07003795status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3796 uint32_t w, uint32_t h, uint32_t flags,
3797 PixelFormat& format, sp<IBinder>* handle,
3798 sp<IGraphicBufferProducer>* gbp,
3799 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003800 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003801 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003802 case PIXEL_FORMAT_TRANSPARENT:
3803 case PIXEL_FORMAT_TRANSLUCENT:
3804 format = PIXEL_FORMAT_RGBA_8888;
3805 break;
3806 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003807 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003808 break;
3809 }
3810
Marissa Wallfd668622018-05-10 10:21:13 -07003811 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3812 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003813 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003814 *handle = layer->getHandle();
3815 *gbp = layer->getProducer();
3816 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003817 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003818
Marissa Wallfd668622018-05-10 10:21:13 -07003819 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003820 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003821}
3822
Marissa Wall61c58622018-07-18 10:12:20 -07003823status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3824 uint32_t w, uint32_t h, uint32_t flags,
3825 sp<IBinder>* handle, sp<Layer>* outLayer) {
3826 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3827 *handle = layer->getHandle();
3828 *outLayer = layer;
3829
3830 return NO_ERROR;
3831}
3832
chaviw13fdc492017-06-27 12:40:18 -07003833status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003834 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003835 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003836{
chaviw13fdc492017-06-27 12:40:18 -07003837 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003838 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003839 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003840}
3841
Robert Carr6b3f6c52018-08-13 13:05:17 -07003842status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3843 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3844 sp<IBinder>* handle, sp<Layer>* outLayer)
3845{
3846 *outLayer = new ContainerLayer(this, client, name, w, h, flags);
3847 *handle = (*outLayer)->getHandle();
3848 return NO_ERROR;
3849}
3850
3851
Mathias Agopianac9fa422013-02-11 16:40:36 -08003852status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003853{
Robert Carr9524cb32017-02-13 11:32:32 -08003854 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003855 status_t err = NO_ERROR;
3856 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003857 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003858 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003859 err = removeLayer(l);
3860 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3861 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003862 }
3863 return err;
3864}
3865
Mathias Agopian13127d82013-03-05 17:47:11 -08003866status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003867{
Mathias Agopian67106042013-03-14 19:18:13 -07003868 // called by ~LayerCleaner() when all references to the IBinder (handle)
3869 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003870 sp<Layer> l = layer.promote();
3871 if (l == nullptr) {
3872 // The layer has already been removed, carry on
3873 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003874 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003875 // If we have a parent, then we can continue to live as long as it does.
3876 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003877}
3878
Mathias Agopianb60314a2012-04-10 22:09:54 -07003879// ---------------------------------------------------------------------------
3880
Andy McFadden13a082e2012-08-24 10:16:42 -07003881void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003882 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3883 if (!displayToken) return;
3884
Jesse Hall01e29052013-02-19 16:13:35 -08003885 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003886 Vector<ComposerState> state;
3887 Vector<DisplayState> displays;
3888 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003889 d.what = DisplayState::eDisplayProjectionChanged |
3890 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003891 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003892 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003893 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003894 d.frame.makeInvalid();
3895 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003896 d.width = 0;
3897 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003898 displays.add(d);
3899 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003900
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003901 const auto display = getDisplayDevice(displayToken);
3902 if (!display) return;
3903
3904 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3905
3906 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003907 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003908 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003909
Brian Andersond0010582017-03-07 13:20:31 -08003910 // Use phase of 0 since phase is not known.
3911 // Use latency of 0, which will snap to the ideal latency.
3912 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003913}
3914
3915void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003916 // Async since we may be called from the main thread.
3917 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003918}
3919
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003920void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3921 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003922 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003923 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003924
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003925 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003926 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003927 return;
3928 }
3929
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003930 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003931 ALOGW("Trying to set power mode for virtual display");
3932 return;
3933 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003934
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003935 display->setPowerMode(mode);
3936
Lloyd Pique4dccc412018-01-22 17:21:36 -08003937 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003938 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003939 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003940 if (idx < 0) {
3941 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3942 return;
3943 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003944 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003945 }
3946
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003947 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003948 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003949 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003950 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003951 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003952 // FIXME: eventthread only knows about the main display right now
3953 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003954 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003955 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003956
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003957 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003958 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003959 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003960
3961 struct sched_param param = {0};
3962 param.sched_priority = 1;
3963 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3964 ALOGW("Couldn't set SCHED_FIFO on display on");
3965 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003966 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003967 // Turn off the display
3968 struct sched_param param = {0};
3969 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3970 ALOGW("Couldn't set SCHED_OTHER on display off");
3971 }
3972
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003973 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003974 disableHardwareVsync(true); // also cancels any in-progress resync
3975
Mathias Agopiancde87a32012-09-13 14:09:01 -07003976 // FIXME: eventthread only knows about the main display right now
3977 mEventThread->onScreenReleased();
3978 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003979
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003980 getHwComposer().setPowerMode(type, mode);
3981 mVisibleRegionsDirty = true;
3982 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003983 } else if (mode == HWC_POWER_MODE_DOZE ||
3984 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003985 // Update display while dozing
3986 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003987 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003988 // FIXME: eventthread only knows about the main display right now
3989 mEventThread->onScreenAcquired();
3990 resyncToHardwareVsync(true);
3991 }
3992 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3993 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003994 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003995 disableHardwareVsync(true); // also cancels any in-progress resync
3996 // FIXME: eventthread only knows about the main display right now
3997 mEventThread->onScreenReleased();
3998 }
3999 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004000 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004001 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004002 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004003 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004004
4005 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004006}
4007
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004008void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004009 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004010 const auto display = getDisplayDevice(displayToken);
4011 if (!display) {
4012 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4013 displayToken.get());
4014 } else if (display->isVirtual()) {
4015 ALOGW("Attempt to set power mode %d for virtual display", mode);
4016 } else {
4017 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004018 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004019 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004020}
4021
4022// ---------------------------------------------------------------------------
4023
Lloyd Pique755e3192018-01-31 16:46:15 -08004024status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4025 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004026 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004027
Mathias Agopianbd115332013-04-18 16:41:04 -07004028 IPCThreadState* ipc = IPCThreadState::self();
4029 const int pid = ipc->getCallingPid();
4030 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004031
Mathias Agopianbd115332013-04-18 16:41:04 -07004032 if ((uid != AID_SHELL) &&
4033 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004034 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07004035 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004036 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004037 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004038 // (this would indicate SF is stuck, but we want to be able to
4039 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004040 status_t err = mStateLock.timedLock(s2ns(1));
4041 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004042 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004043 result.appendFormat(
4044 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4045 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004046 }
4047
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004048 bool dumpAll = true;
4049 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004050 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004051
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004052 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004053 if ((index < numArgs) &&
4054 (args[index] == String16("--list"))) {
4055 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004056 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004057 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004058 }
4059
4060 if ((index < numArgs) &&
4061 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004062 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004063 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004064 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004065 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004066
4067 if ((index < numArgs) &&
4068 (args[index] == String16("--latency-clear"))) {
4069 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004070 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004071 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004072 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004073
4074 if ((index < numArgs) &&
4075 (args[index] == String16("--dispsync"))) {
4076 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004077 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004078 dumpAll = false;
4079 }
Dan Stozab90cf072015-03-05 11:05:59 -08004080
4081 if ((index < numArgs) &&
4082 (args[index] == String16("--static-screen"))) {
4083 index++;
4084 dumpStaticScreenStats(result);
4085 dumpAll = false;
4086 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004087
4088 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004089 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004090 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004091 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004092 dumpAll = false;
4093 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004094
4095 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4096 index++;
4097 dumpWideColorInfo(result);
4098 dumpAll = false;
4099 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004100
4101 if ((index < numArgs) &&
4102 (args[index] == String16("--enable-layer-stats"))) {
4103 index++;
4104 mLayerStats.enable();
4105 dumpAll = false;
4106 }
4107
4108 if ((index < numArgs) &&
4109 (args[index] == String16("--disable-layer-stats"))) {
4110 index++;
4111 mLayerStats.disable();
4112 dumpAll = false;
4113 }
4114
4115 if ((index < numArgs) &&
4116 (args[index] == String16("--clear-layer-stats"))) {
4117 index++;
4118 mLayerStats.clear();
4119 dumpAll = false;
4120 }
4121
4122 if ((index < numArgs) &&
4123 (args[index] == String16("--dump-layer-stats"))) {
4124 index++;
4125 mLayerStats.dump(result);
4126 dumpAll = false;
4127 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004128
4129 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004130 (args[index] == String16("--frame-composition"))) {
4131 index++;
4132 dumpFrameCompositionInfo(result);
4133 dumpAll = false;
4134 }
4135
4136 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004137 (args[index] == String16("--display-identification"))) {
4138 index++;
4139 dumpDisplayIdentificationData(result);
4140 dumpAll = false;
4141 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004142
4143 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4144 index++;
4145 mTimeStats.parseArgs(asProto, args, index, result);
4146 dumpAll = false;
4147 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004148 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004149
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004150 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004151 if (asProto) {
4152 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4153 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4154 } else {
4155 dumpAllLocked(args, index, result);
4156 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004157 }
4158
Mathias Agopian9795c422009-08-26 16:36:26 -07004159 if (locked) {
4160 mStateLock.unlock();
4161 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004162 }
4163 write(fd, result.string(), result.size());
4164 return NO_ERROR;
4165}
4166
Dan Stozac7014012014-02-14 15:03:43 -08004167void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4168 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004169{
Robert Carr2047fae2016-11-28 14:09:09 -08004170 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004171 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004172 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004173}
4174
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004175void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004176 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004177{
4178 String8 name;
4179 if (index < args.size()) {
4180 name = String8(args[index]);
4181 index++;
4182 }
4183
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004184 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4185 getHwComposer().isConnected(displayId)) {
4186 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4187 const nsecs_t period = activeConfig->getVsyncPeriod();
4188 result.appendFormat("%" PRId64 "\n", period);
4189 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004190
4191 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004192 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004193 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004194 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004195 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004196 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004197 }
Robert Carr2047fae2016-11-28 14:09:09 -08004198 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004199 }
4200}
4201
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004202void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004203 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004204{
4205 String8 name;
4206 if (index < args.size()) {
4207 name = String8(args[index]);
4208 index++;
4209 }
4210
Robert Carr2047fae2016-11-28 14:09:09 -08004211 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004212 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004213 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004214 }
Robert Carr2047fae2016-11-28 14:09:09 -08004215 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004216
Svetoslavd85084b2014-03-20 10:28:31 -07004217 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004218}
4219
Jamie Gennis6547ff42013-07-16 20:12:42 -07004220// This should only be called from the main thread. Otherwise it would need
4221// the lock and should use mCurrentState rather than mDrawingState.
4222void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004223 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004224 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004225 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004226
4227 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4228}
4229
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004230void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004231{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004232 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004233
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004234 if (isLayerTripleBufferingDisabled())
4235 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004236
4237 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004238 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004239 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004240 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004241 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4242 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004243 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004244}
4245
Dan Stozab90cf072015-03-05 11:05:59 -08004246void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4247{
4248 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004249 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4250 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004251 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004252 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004253 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4254 b + 1, bucketTimeSec, percent);
4255 }
David Sodman4a36e932017-11-07 14:29:47 -08004256 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004257 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004258 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004259 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004260 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004261}
4262
Dan Stozae77c7662016-05-13 11:37:28 -07004263void SurfaceFlinger::recordBufferingStats(const char* layerName,
4264 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004265 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4266 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004267 for (const auto& segment : history) {
4268 if (!segment.usedThirdBuffer) {
4269 stats.twoBufferTime += segment.totalTime;
4270 }
4271 if (segment.occupancyAverage < 1.0f) {
4272 stats.doubleBufferedTime += segment.totalTime;
4273 } else if (segment.occupancyAverage < 2.0f) {
4274 stats.tripleBufferedTime += segment.totalTime;
4275 }
4276 ++stats.numSegments;
4277 stats.totalTime += segment.totalTime;
4278 }
4279}
4280
Brian Andersond6927fb2016-07-23 23:37:30 -07004281void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4282 result.appendFormat("Layer frame timestamps:\n");
4283
4284 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4285 const size_t count = currentLayers.size();
4286 for (size_t i=0 ; i<count ; i++) {
4287 currentLayers[i]->dumpFrameEvents(result);
4288 }
4289}
4290
Dan Stozae77c7662016-05-13 11:37:28 -07004291void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4292 result.append("Buffering stats:\n");
4293 result.append(" [Layer name] <Active time> <Two buffer> "
4294 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004295 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004296 typedef std::tuple<std::string, float, float, float> BufferTuple;
4297 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004298 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004299 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004300 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004301 if (stats.numSegments == 0) {
4302 continue;
4303 }
4304 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4305 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4306 stats.totalTime;
4307 float doubleBufferRatio = static_cast<float>(
4308 stats.doubleBufferedTime) / stats.totalTime;
4309 float tripleBufferRatio = static_cast<float>(
4310 stats.tripleBufferedTime) / stats.totalTime;
4311 sorted.insert({activeTime, {name, twoBufferRatio,
4312 doubleBufferRatio, tripleBufferRatio}});
4313 }
4314 for (const auto& sortedPair : sorted) {
4315 float activeTime = sortedPair.first;
4316 const BufferTuple& values = sortedPair.second;
4317 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4318 std::get<0>(values).c_str(), activeTime,
4319 std::get<1>(values), std::get<2>(values),
4320 std::get<3>(values));
4321 }
4322 result.append("\n");
4323}
4324
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004325void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004326 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004327 const int32_t displayId = display->getId();
4328 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4329 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004330 continue;
4331 }
4332
Dominik Laskowski7e045462018-05-30 13:02:02 -07004333 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004334 uint8_t port;
4335 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004336 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004337 result.append("no identification data\n");
4338 continue;
4339 }
4340
4341 if (!isEdid(data)) {
4342 result.append("unknown identification data: ");
4343 for (uint8_t byte : data) {
4344 result.appendFormat("%x ", byte);
4345 }
4346 result.append("\n");
4347 continue;
4348 }
4349
4350 const auto edid = parseEdid(data);
4351 if (!edid) {
4352 result.append("invalid EDID: ");
4353 for (uint8_t byte : data) {
4354 result.appendFormat("%x ", byte);
4355 }
4356 result.append("\n");
4357 continue;
4358 }
4359
4360 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4361 result.append(edid->displayName.data(), edid->displayName.length());
4362 result.append("\"\n");
4363 }
4364 result.append("\n");
4365}
4366
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004367void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004368 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4369 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004370 result.appendFormat("DisplayColorSetting: %s\n",
4371 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004372
4373 // TODO: print out if wide-color mode is active or not
4374
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004375 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004376 const int32_t displayId = display->getId();
4377 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004378 continue;
4379 }
4380
Dominik Laskowski7e045462018-05-30 13:02:02 -07004381 result.appendFormat("Display %d color modes:\n", displayId);
4382 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004383 for (auto&& mode : modes) {
4384 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4385 }
4386
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004387 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004388 result.appendFormat(" Current color mode: %s (%d)\n",
4389 decodeColorMode(currentMode).c_str(), currentMode);
4390 }
4391 result.append("\n");
4392}
4393
David Sodman7e4ae112018-02-09 15:02:28 -08004394void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4395 std::string stringResult;
4396
4397 for (const auto& [token, display] : mDisplays) {
4398 const auto displayId = display->getId();
4399 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
4400 continue;
4401 }
4402
4403 const auto& compositionInfoIt = getBE().mEndOfFrameCompositionInfo.find(displayId);
4404 if (compositionInfoIt == getBE().mEndOfFrameCompositionInfo.end()) {
4405 break;
4406 }
4407 const auto& compositionInfoList = compositionInfoIt->second;
4408 stringResult += base::StringPrintf("Display: %d\n", displayId);
4409 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4410 for (const auto& compositionInfo : compositionInfoList) {
4411 compositionInfo.dump(stringResult, nullptr);
4412 stringResult += base::StringPrintf("\n");
4413 }
4414 }
4415
4416 result.append(stringResult.c_str());
4417}
4418
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004419LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004420 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004421 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4422 const State& state = useDrawing ? mDrawingState : mCurrentState;
4423 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004424 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004425 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004426 });
4427
4428 return layersProto;
4429}
4430
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004431LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004432 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004433
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004434 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004435 resolution->set_w(display.getWidth());
4436 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004437
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004438 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4439 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4440 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004441
Dominik Laskowski7e045462018-05-30 13:02:02 -07004442 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004443 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004444 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004445 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004446 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004447 }
4448 });
4449
4450 return layersProto;
4451}
4452
Mathias Agopian74d211a2013-04-22 16:55:35 +02004453void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4454 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004455{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004456 bool colorize = false;
4457 if (index < args.size()
4458 && (args[index] == String16("--color"))) {
4459 colorize = true;
4460 index++;
4461 }
4462
4463 Colorizer colorizer(colorize);
4464
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004465 // figure out if we're stuck somewhere
4466 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004467 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004468 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4469
4470 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004471 * Dump library configuration.
4472 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004473
4474 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004475 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004476 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004477 appendSfConfigString(result);
4478 appendUiConfigString(result);
4479 appendGuiConfigString(result);
4480 result.append("\n");
4481
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004482 result.append("\nDisplay identification data:\n");
4483 dumpDisplayIdentificationData(result);
4484
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004485 result.append("\nWide-Color information:\n");
4486 dumpWideColorInfo(result);
4487
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004488 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004489 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004490 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004491 result.append(SyncFeatures::getInstance().toString());
4492 result.append("\n");
4493
Andy McFadden41d67d72014-04-25 16:58:34 -07004494 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004495 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004496 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004497
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004498 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4499 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004500 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4501 getHwComposer().isConnected(displayId)) {
4502 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004503 result.appendFormat("Display %d: "
4504 "app phase %" PRId64 " ns, "
4505 "sf phase %" PRId64 " ns, "
4506 "early app phase %" PRId64 " ns, "
4507 "early sf phase %" PRId64 " ns, "
4508 "early app gl phase %" PRId64 " ns, "
4509 "early sf gl phase %" PRId64 " ns, "
4510 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4511 displayId,
4512 vsyncPhaseOffsetNs,
4513 sfVsyncPhaseOffsetNs,
4514 appEarlyOffset,
4515 sfEarlyOffset,
4516 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004517 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004518 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004519 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004520 result.append("\n");
4521
Dan Stozab90cf072015-03-05 11:05:59 -08004522 // Dump static screen stats
4523 result.append("\n");
4524 dumpStaticScreenStats(result);
4525 result.append("\n");
4526
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004527 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4528
Dan Stozae77c7662016-05-13 11:37:28 -07004529 dumpBufferingStats(result);
4530
Andy McFadden4803b742012-09-24 19:07:20 -07004531 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004532 * Dump the visible layer list
4533 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004534 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004535 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004536 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4537 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004538 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004539
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004540 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004541 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004542 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004543 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004544
David Sodman7e4ae112018-02-09 15:02:28 -08004545 result.append("\nFrame-Composition information:\n");
4546 dumpFrameCompositionInfo(result);
4547 result.append("\n");
4548
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004549 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004550 * Dump Display state
4551 */
4552
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004553 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004554 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004555 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004556 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004557 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004558 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004559 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004560
4561 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004562 * Dump SurfaceFlinger global state
4563 */
4564
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004565 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004566 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004567 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004568
Mathias Agopian888c8222012-08-04 21:10:38 -07004569 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004570 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004571
David Sodmanbc815282017-11-05 18:57:52 -08004572 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004573
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004574 if (display) {
4575 display->undefinedRegion.dump(result, "undefinedRegion");
4576 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4577 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004578 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004579 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004580 " gpu_to_cpu_unsupported : %d\n",
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004581 mTransactionFlags, !mGpuToCpuSupported);
4582
4583 if (display) {
4584 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4585 result.appendFormat(" refresh-rate : %f fps\n"
4586 " x-dpi : %f\n"
4587 " y-dpi : %f\n",
4588 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4589 activeConfig->getDpiY());
4590 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004591
Mathias Agopian74d211a2013-04-22 16:55:35 +02004592 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004593 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004594
4595 /*
4596 * VSYNC state
4597 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004598 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004599 result.append("\n");
4600
4601 /*
4602 * HWC layer minidump
4603 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004604 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004605 const int32_t displayId = display->getId();
4606 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004607 continue;
4608 }
4609
Dominik Laskowski7e045462018-05-30 13:02:02 -07004610 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004611 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004612 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004613 result.append("\n");
4614 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004615
4616 /*
4617 * Dump HWComposer state
4618 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004619 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004620 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004621 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004622 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004623 result.appendFormat(" h/w composer %s\n",
4624 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004625 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004626
4627 /*
4628 * Dump gralloc state
4629 */
4630 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4631 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004632
4633 /*
4634 * Dump VrFlinger state if in use.
4635 */
4636 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4637 result.append("VrFlinger state:\n");
4638 result.append(mVrFlinger->Dump().c_str());
4639 result.append("\n");
4640 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004641}
4642
Dominik Laskowski7e045462018-05-30 13:02:02 -07004643const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004644 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004645 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004646 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004647 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004648 }
4649 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004650
4651 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4652 static const Vector<sp<Layer>> empty;
4653 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004654}
4655
Keun young Park63f165f2012-08-31 10:53:36 -07004656bool SurfaceFlinger::startDdmConnection()
4657{
4658 void* libddmconnection_dso =
4659 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4660 if (!libddmconnection_dso) {
4661 return false;
4662 }
4663 void (*DdmConnection_start)(const char* name);
4664 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004665 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004666 if (!DdmConnection_start) {
4667 dlclose(libddmconnection_dso);
4668 return false;
4669 }
4670 (*DdmConnection_start)(getServiceName());
4671 return true;
4672}
4673
Chia-I Wu28f320b2018-05-03 11:02:56 -07004674void SurfaceFlinger::updateColorMatrixLocked() {
4675 mat4 colorMatrix;
4676 if (mGlobalSaturationFactor != 1.0f) {
4677 // Rec.709 luma coefficients
4678 float3 luminance{0.213f, 0.715f, 0.072f};
4679 luminance *= 1.0f - mGlobalSaturationFactor;
4680 mat4 saturationMatrix = mat4(
4681 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4682 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4683 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4684 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4685 );
4686 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4687 } else {
4688 colorMatrix = mClientColorMatrix * mDaltonizer();
4689 }
4690
4691 if (mCurrentState.colorMatrix != colorMatrix) {
4692 mCurrentState.colorMatrix = colorMatrix;
4693 mCurrentState.colorMatrixChanged = true;
4694 setTransactionFlags(eTransactionNeeded);
4695 }
4696}
4697
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004698status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004699#pragma clang diagnostic push
4700#pragma clang diagnostic error "-Wswitch-enum"
4701 switch (static_cast<ISurfaceComposerTag>(code)) {
4702 // These methods should at minimum make sure that the client requested
4703 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004704 case BOOT_FINISHED:
4705 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004706 case CREATE_CONNECTION:
4707 case CREATE_DISPLAY:
4708 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004709 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004710 case GET_ACTIVE_COLOR_MODE:
4711 case GET_ANIMATION_FRAME_STATS:
4712 case GET_HDR_CAPABILITIES:
4713 case SET_ACTIVE_CONFIG:
4714 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004715 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004716 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004717 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4718 IPCThreadState* ipc = IPCThreadState::self();
4719 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4720 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004721 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004722 }
Robert Carr1db73f62016-12-21 12:58:51 -08004723 return OK;
4724 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004725 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004726 IPCThreadState* ipc = IPCThreadState::self();
4727 const int pid = ipc->getCallingPid();
4728 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004729 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4730 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004731 return PERMISSION_DENIED;
4732 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004733 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004734 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004735 // Used by apps to hook Choreographer to SurfaceFlinger.
4736 case CREATE_DISPLAY_EVENT_CONNECTION:
4737 // The following calls are currently used by clients that do not
4738 // request necessary permissions. However, they do not expose any secret
4739 // information, so it is OK to pass them.
4740 case AUTHENTICATE_SURFACE:
4741 case GET_ACTIVE_CONFIG:
4742 case GET_BUILT_IN_DISPLAY:
4743 case GET_DISPLAY_COLOR_MODES:
4744 case GET_DISPLAY_CONFIGS:
4745 case GET_DISPLAY_STATS:
Yiwei Zhangcd3f9e92018-08-21 15:15:42 -07004746 case GET_DISPLAY_VIEWPORT:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004747 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4748 // Calling setTransactionState is safe, because you need to have been
4749 // granted a reference to Client* and Handle* to do anything with it.
4750 case SET_TRANSACTION_STATE:
4751 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4752 case CREATE_SCOPED_CONNECTION: {
4753 return OK;
4754 }
4755 case CAPTURE_LAYERS:
4756 case CAPTURE_SCREEN: {
4757 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004758 IPCThreadState* ipc = IPCThreadState::self();
4759 const int pid = ipc->getCallingPid();
4760 const int uid = ipc->getCallingUid();
4761 if ((uid != AID_GRAPHICS) &&
4762 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4763 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4764 return PERMISSION_DENIED;
4765 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004766 return OK;
4767 }
4768 // The following codes are deprecated and should never be allowed to access SF.
4769 case CONNECT_DISPLAY_UNUSED:
4770 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4771 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4772 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004773 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004774 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004775
4776 // These codes are used for the IBinder protocol to either interrogate the recipient
4777 // side of the transaction for its canonical interface descriptor or to dump its state.
4778 // We let them pass by default.
4779 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4780 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4781 code == IBinder::SYSPROPS_TRANSACTION) {
4782 return OK;
4783 }
4784 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4785 // in onTransact verifies that the user is root, and has access to use SF.
4786 if (code >= 1000 && code <= 1029) {
4787 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4788 return OK;
4789 }
4790 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4791 return PERMISSION_DENIED;
4792#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004793}
4794
Ana Krulec13be8ad2018-08-21 02:43:56 +00004795status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4796 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004797 status_t credentialCheck = CheckTransactCodeCredentials(code);
4798 if (credentialCheck != OK) {
4799 return credentialCheck;
4800 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004801
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004802 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4803 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004804 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004805 IPCThreadState* ipc = IPCThreadState::self();
4806 const int uid = ipc->getCallingUid();
4807 if (CC_UNLIKELY(uid != AID_SYSTEM
4808 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004809 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004810 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004811 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004812 return PERMISSION_DENIED;
4813 }
4814 int n;
4815 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004816 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004817 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004818 return NO_ERROR;
4819 case 1002: // SHOW_UPDATES
4820 n = data.readInt32();
4821 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004822 invalidateHwcGeometry();
4823 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004824 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004825 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004826 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004827 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004828 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004829 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004830 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004831 setTransactionFlags(
4832 eTransactionNeeded|
4833 eDisplayTransactionNeeded|
4834 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004835 return NO_ERROR;
4836 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004837 case 1006:{ // send empty update
4838 signalRefresh();
4839 return NO_ERROR;
4840 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004841 case 1008: // toggle use of hw composer
4842 n = data.readInt32();
4843 mDebugDisableHWC = n ? 1 : 0;
4844 invalidateHwcGeometry();
4845 repaintEverything();
4846 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004847 case 1009: // toggle use of transform hint
4848 n = data.readInt32();
4849 mDebugDisableTransformHint = n ? 1 : 0;
4850 invalidateHwcGeometry();
4851 repaintEverything();
4852 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004853 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004854 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004855 reply->writeInt32(0);
4856 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004857 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004858 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004859 return NO_ERROR;
4860 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004861 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004862 if (!display) {
4863 return NAME_NOT_FOUND;
4864 }
4865
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004866 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004867 return NO_ERROR;
4868 }
4869 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004870 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004871 // daltonize
4872 n = data.readInt32();
4873 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004874 case 1:
4875 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4876 break;
4877 case 2:
4878 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4879 break;
4880 case 3:
4881 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4882 break;
4883 default:
4884 mDaltonizer.setType(ColorBlindnessType::None);
4885 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004886 }
4887 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004888 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004889 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004890 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004891 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004892
4893 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004894 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004895 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004896 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004897 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004898 // apply a color matrix
4899 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004900 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004901 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004902 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004903 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004904 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004905 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004906 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004907 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004908 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004909 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004910
4911 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4912 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004913 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004914 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4915 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4916 }
4917
Chia-I Wu28f320b2018-05-03 11:02:56 -07004918 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004919 return NO_ERROR;
4920 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004921 // This is an experimental interface
4922 // Needs to be shifted to proper binder interface when we productize
4923 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004924 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07004925 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004926 return NO_ERROR;
4927 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004928 case 1017: {
4929 n = data.readInt32();
4930 mForceFullDamage = static_cast<bool>(n);
4931 return NO_ERROR;
4932 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004933 case 1018: { // Modify Choreographer's phase offset
4934 n = data.readInt32();
4935 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4936 return NO_ERROR;
4937 }
4938 case 1019: { // Modify SurfaceFlinger's phase offset
4939 n = data.readInt32();
4940 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4941 return NO_ERROR;
4942 }
Irvel468051e2016-06-13 16:44:44 -07004943 case 1020: { // Layer updates interceptor
4944 n = data.readInt32();
4945 if (n) {
4946 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004947 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004948 }
4949 else{
4950 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004951 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004952 }
4953 return NO_ERROR;
4954 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004955 case 1021: { // Disable HWC virtual displays
4956 n = data.readInt32();
4957 mUseHwcVirtualDisplays = !n;
4958 return NO_ERROR;
4959 }
Romain Guy0147a172017-06-01 13:53:56 -07004960 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004961 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004962 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004963
Chia-I Wu28f320b2018-05-03 11:02:56 -07004964 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004965 return NO_ERROR;
4966 }
Romain Guy54f154a2017-10-24 21:40:32 +01004967 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004968 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004969 invalidateHwcGeometry();
4970 repaintEverything();
4971 return NO_ERROR;
4972 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004973 // TODO(b/111505327): Find out whether the usage of 1024 can switch to 1030,
4974 // deprecate 1024 if they can.
4975 case 1024: { // Does device have wide color gamut display?
Romain Guy54f154a2017-10-24 21:40:32 +01004976 reply->writeBool(hasWideColorDisplay);
4977 return NO_ERROR;
4978 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004979 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004980 n = data.readInt32();
4981 if (n) {
4982 ALOGV("LayerTracing enabled");
4983 mTracing.enable();
4984 doTracing("tracing.enable");
4985 reply->writeInt32(NO_ERROR);
4986 } else {
4987 ALOGV("LayerTracing disabled");
4988 status_t err = mTracing.disable();
4989 reply->writeInt32(err);
4990 }
4991 return NO_ERROR;
4992 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004993 case 1026: { // Get layer tracing status
4994 reply->writeBool(mTracing.isEnabled());
4995 return NO_ERROR;
4996 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004997 // Is a DisplayColorSetting supported?
4998 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004999 const auto display = getDefaultDisplayDevice();
5000 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005001 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005002 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005003
5004 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5005 switch (setting) {
5006 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005007 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005008 break;
5009 case DisplayColorSetting::UNMANAGED:
5010 reply->writeBool(true);
5011 break;
5012 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005013 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005014 break;
5015 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005016 reply->writeBool(
5017 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005018 break;
5019 }
5020 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005021 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005022 // Is VrFlinger active?
5023 case 1028: {
5024 Mutex::Autolock _l(mStateLock);
5025 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5026 return NO_ERROR;
5027 }
David Sodman6d46c1e2018-07-13 12:59:48 -07005028 case 1029: {
5029 // Code 1029 is an experimental feature that allows applications to
5030 // simulate a high frequency panel by setting a multiplier and divisor
5031 // on the VSYNC-sf clock. If either the multiplier or divisor are
David Sodman44b5de02018-08-21 16:28:53 -07005032 // 0, then the code simply return the current multiplier and divisor.
5033 HWC2::Device::FrequencyScaler frequencyScaler;
5034 frequencyScaler.multiplier = data.readInt32();
5035 frequencyScaler.divisor = data.readInt32();
David Sodman6d46c1e2018-07-13 12:59:48 -07005036
David Sodman44b5de02018-08-21 16:28:53 -07005037 if ((frequencyScaler.multiplier == 0) || (frequencyScaler.divisor == 0)) {
5038 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5039 reply->writeInt32(frequencyScaler.multiplier);
5040 reply->writeInt32(frequencyScaler.divisor);
5041 return NO_ERROR;
David Sodman6d46c1e2018-07-13 12:59:48 -07005042 }
5043
David Sodman44b5de02018-08-21 16:28:53 -07005044 if ((frequencyScaler.multiplier == 1) && (frequencyScaler.divisor == 1)) {
David Sodman6d46c1e2018-07-13 12:59:48 -07005045 enableHardwareVsync();
5046 } else {
5047 disableHardwareVsync(true);
5048 }
David Sodman44b5de02018-08-21 16:28:53 -07005049 mPrimaryDispSync->scalePeriod(frequencyScaler);
5050 getBE().mHwc->setDisplayFrequencyScaleParameters(frequencyScaler);
David Sodman6d46c1e2018-07-13 12:59:48 -07005051
David Sodman44b5de02018-08-21 16:28:53 -07005052 ATRACE_INT("PeriodMultiplier", frequencyScaler.multiplier);
5053 ATRACE_INT("PeriodDivisor", frequencyScaler.divisor);
5054
5055 const hwc2_display_t hwcDisplayId = getBE().mHwc->getActiveConfig(
5056 DisplayDevice::DISPLAY_PRIMARY)->getDisplayId();
5057
5058 onHotplugReceived(getBE().mComposerSequenceId,
5059 hwcDisplayId, HWC2::Connection::Disconnected);
5060 onHotplugReceived(getBE().mComposerSequenceId,
5061 hwcDisplayId, HWC2::Connection::Connected);
5062 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5063 reply->writeInt32(frequencyScaler.multiplier);
5064 reply->writeInt32(frequencyScaler.divisor);
5065
David Sodman6d46c1e2018-07-13 12:59:48 -07005066 return NO_ERROR;
5067 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005068 // Is device color managed?
5069 case 1030: {
5070 reply->writeBool(useColorManagement);
5071 return NO_ERROR;
5072 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005073 }
5074 }
5075 return err;
5076}
5077
Steven Thomas6d8110b2017-08-31 18:24:21 -07005078void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07005079 android_atomic_or(1, &mRepaintEverything);
5080 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005081}
5082
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005083// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5084class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005085public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005086 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5087 ~WindowDisconnector() {
5088 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005089 }
5090
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005091private:
5092 ANativeWindow* mWindow;
5093 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005094};
5095
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005096status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
5097 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
5098 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
5099 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005100 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005101 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005102
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005103 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005104
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005105 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5106
Chia-I Wu20261cb2018-08-23 12:55:44 -07005107 sp<DisplayDevice> display;
5108 {
5109 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005110
Chia-I Wu20261cb2018-08-23 12:55:44 -07005111 display = getDisplayDeviceLocked(displayToken);
5112 if (!display) return BAD_VALUE;
5113
Chia-I Wucb023152018-08-28 12:57:23 -07005114 // set the source crop to the (projected) logical display viewport
5115 // unconditionally until the framework is fixed
5116 sourceCrop.set(display->getScissor());
5117
5118 // set the requested width/height to the logical display viewport size
5119 // by default
5120 if (reqWidth == 0 || reqHeight == 0) {
5121 reqWidth = uint32_t(display->getViewport().width());
5122 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005123 }
5124
Chia-I Wua02871c2018-08-27 14:38:23 -07005125 // XXX display->getInstallOrientation() is ignored
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005126 }
5127
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005128 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005129
5130 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005131 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005132 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005133}
5134
5135status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08005136 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005137 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005138 ATRACE_CALL();
5139
5140 class LayerRenderArea : public RenderArea {
5141 public:
Robert Carr578038f2018-03-09 12:25:24 -08005142 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
5143 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
Chia-I Wu9d1abea2018-08-23 13:44:43 -07005144 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08005145 mLayer(layer),
5146 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005147 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005148 mFlinger(flinger),
5149 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005150 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005151 Rect getBounds() const override {
5152 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005153 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005154 }
Marissa Wall61c58622018-07-18 10:12:20 -07005155 int getHeight() const override {
5156 return mLayer->getActiveHeight(mLayer->getDrawingState());
5157 }
5158 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005159 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005160 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005161 Rect getSourceCrop() const override {
5162 if (mCrop.isEmpty()) {
5163 return getBounds();
5164 } else {
5165 return mCrop;
5166 }
5167 }
Robert Carr578038f2018-03-09 12:25:24 -08005168 class ReparentForDrawing {
5169 public:
5170 const sp<Layer>& oldParent;
5171 const sp<Layer>& newParent;
5172
5173 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5174 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005175 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005176 }
Robert Carr15eae092018-03-23 13:43:53 -07005177 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005178 };
5179
5180 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005181 const Rect sourceCrop = getSourceCrop();
5182 // no need to check rotation because there is none
5183 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5184 sourceCrop.height() != getReqHeight();
5185
Robert Carr578038f2018-03-09 12:25:24 -08005186 if (!mChildrenOnly) {
5187 mTransform = mLayer->getTransform().inverse();
5188 drawLayers();
5189 } else {
5190 Rect bounds = getBounds();
5191 screenshotParentLayer =
5192 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
5193 bounds.getWidth(), bounds.getHeight(), 0);
5194
5195 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5196 drawLayers();
5197 }
5198 }
chaviwa76b2712017-09-20 12:02:26 -07005199
chaviwa76b2712017-09-20 12:02:26 -07005200 private:
chaviw7206d492017-11-10 16:16:12 -08005201 const sp<Layer> mLayer;
5202 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005203
5204 // In the "childrenOnly" case we reparent the children to a screenshot
5205 // layer which has no properties set and which does not draw.
5206 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005207 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005208 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005209
5210 SurfaceFlinger* mFlinger;
5211 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005212 };
5213
5214 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5215 auto parent = layerHandle->owner.promote();
5216
chaviw7206d492017-11-10 16:16:12 -08005217 if (parent == nullptr || parent->isPendingRemoval()) {
5218 ALOGE("captureLayers called with a removed parent");
5219 return NAME_NOT_FOUND;
5220 }
5221
Robert Carr578038f2018-03-09 12:25:24 -08005222 const int uid = IPCThreadState::self()->getCallingUid();
5223 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5224 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5225 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5226 return PERMISSION_DENIED;
5227 }
5228
chaviw7206d492017-11-10 16:16:12 -08005229 Rect crop(sourceCrop);
5230 if (sourceCrop.width() <= 0) {
5231 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005232 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005233 }
5234
5235 if (sourceCrop.height() <= 0) {
5236 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005237 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005238 }
5239
5240 int32_t reqWidth = crop.width() * frameScale;
5241 int32_t reqHeight = crop.height() * frameScale;
5242
Chia-I Wu20261cb2018-08-23 12:55:44 -07005243 // really small crop or frameScale
5244 if (reqWidth <= 0) {
5245 reqWidth = 1;
5246 }
5247 if (reqHeight <= 0) {
5248 reqHeight = 1;
5249 }
5250
Robert Carr578038f2018-03-09 12:25:24 -08005251 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005252
Robert Carr578038f2018-03-09 12:25:24 -08005253 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005254 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5255 if (!layer->isVisible()) {
5256 return;
Robert Carr578038f2018-03-09 12:25:24 -08005257 } else if (childrenOnly && layer == parent.get()) {
5258 return;
chaviwa76b2712017-09-20 12:02:26 -07005259 }
5260 visitor(layer);
5261 });
5262 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005263 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005264}
5265
5266status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5267 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005268 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005269 bool useIdentityTransform) {
5270 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005271
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005272 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5273 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5274 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5275 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005276
5277 // This mutex protects syncFd and captureResult for communication of the return values from the
5278 // main thread back to this Binder thread
5279 std::mutex captureMutex;
5280 std::condition_variable captureCondition;
5281 std::unique_lock<std::mutex> captureLock(captureMutex);
5282 int syncFd = -1;
5283 std::optional<status_t> captureResult;
5284
Robert Carr03480e22018-01-04 16:02:06 -08005285 const int uid = IPCThreadState::self()->getCallingUid();
5286 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5287
Dominik Laskowski8c001672018-05-30 16:52:06 -07005288 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005289 // If there is a refresh pending, bug out early and tell the binder thread to try again
5290 // after the refresh.
5291 if (mRefreshPending) {
5292 ATRACE_NAME("Skipping screenshot for now");
5293 std::unique_lock<std::mutex> captureLock(captureMutex);
5294 captureResult = std::make_optional<status_t>(EAGAIN);
5295 captureCondition.notify_one();
5296 return;
5297 }
5298
5299 status_t result = NO_ERROR;
5300 int fd = -1;
5301 {
5302 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005303 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005304 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5305 useIdentityTransform, forSystem, &fd);
5306 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005307 }
5308
5309 {
5310 std::unique_lock<std::mutex> captureLock(captureMutex);
5311 syncFd = fd;
5312 captureResult = std::make_optional<status_t>(result);
5313 captureCondition.notify_one();
5314 }
5315 });
5316
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005317 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005318 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005319 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005320 while (*captureResult == EAGAIN) {
5321 captureResult.reset();
5322 result = postMessageAsync(message);
5323 if (result != NO_ERROR) {
5324 return result;
5325 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005326 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005327 }
5328 result = *captureResult;
5329 }
5330
5331 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005332 sync_wait(syncFd, -1);
5333 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005334 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005335
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005336 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005337}
5338
chaviwa76b2712017-09-20 12:02:26 -07005339void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5340 TraverseLayersFunction traverseLayers, bool yswap,
5341 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005342 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005343
Lloyd Pique144e1162017-12-20 16:44:52 -08005344 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005345
5346 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005347 const auto raHeight = renderArea.getHeight();
5348
5349 const auto reqWidth = renderArea.getReqWidth();
5350 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005351 const auto sourceCrop = renderArea.getSourceCrop();
5352 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005353
Chia-I Wu36574d92018-05-16 10:54:36 -07005354 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5355 engine.setOutputDataSpace(Dataspace::SRGB);
5356 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005357
Mathias Agopian180f10d2013-04-10 22:55:41 -07005358 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005359 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005360
5361 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005362 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005363 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005364 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005365
chaviw50da5042018-04-09 13:49:37 -07005366 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005367 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005368 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005369
chaviwa76b2712017-09-20 12:02:26 -07005370 traverseLayers([&](Layer* layer) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08005371 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005372 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005373}
5374
chaviwa76b2712017-09-20 12:02:26 -07005375status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5376 TraverseLayersFunction traverseLayers,
5377 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005378 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005379 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005380 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005381 ATRACE_CALL();
5382
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005383 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005384
5385 traverseLayers([&](Layer* layer) {
5386 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5387 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005388
Robert Carr03480e22018-01-04 16:02:06 -08005389 // We allow the system server to take screenshots of secure layers for
5390 // use in situations like the Screen-rotation animation and place
5391 // the impetus on WindowManager to not persist them.
5392 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005393 ALOGW("FB is protected: PERMISSION_DENIED");
5394 return PERMISSION_DENIED;
5395 }
5396
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005397 // this binds the given EGLImage as a framebuffer for the
5398 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005399 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005400 if (bufferBond.getStatus() != NO_ERROR) {
5401 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005402 return INVALID_OPERATION;
5403 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005404
Dan Stozaabcda352017-06-01 14:37:39 -07005405 // this will in fact render into our dequeued buffer
5406 // via an FBO, which means we didn't have to create
5407 // an EGLSurface and therefore we're not
5408 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005409 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005410
Dan Stozaabcda352017-06-01 14:37:39 -07005411 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005412 getRenderEngine().finish();
5413 *outSyncFd = -1;
5414
chaviwa76b2712017-09-20 12:02:26 -07005415 const auto reqWidth = renderArea.getReqWidth();
5416 const auto reqHeight = renderArea.getReqHeight();
5417
Dan Stozaabcda352017-06-01 14:37:39 -07005418 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5419 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005420 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005421 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005422 } else {
5423 base::unique_fd syncFd = getRenderEngine().flush();
5424 if (syncFd < 0) {
5425 getRenderEngine().finish();
5426 }
5427 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005428 }
5429
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005430 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005431}
5432
Mathias Agopiand5556842013-09-19 17:08:37 -07005433void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005434 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005435 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005436 for (size_t y = 0; y < h; y++) {
5437 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5438 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005439 if (p[x] != 0xFF000000) return;
5440 }
5441 }
chaviwa76b2712017-09-20 12:02:26 -07005442 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005443
Robert Carr2047fae2016-11-28 14:09:09 -08005444 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005445 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005446 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005447 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5448 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5449 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5450 static_cast<float>(state.color.a));
5451 i++;
5452 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005453 }
5454}
5455
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005456// ---------------------------------------------------------------------------
5457
Dan Stoza412903f2017-04-27 13:42:17 -07005458void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5459 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005460}
5461
Dan Stoza412903f2017-04-27 13:42:17 -07005462void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5463 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005464}
5465
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005466void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5467 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005468 const LayerVector::Visitor& visitor) {
5469 // We loop through the first level of layers without traversing,
5470 // as we need to interpret min/max layer Z in the top level Z space.
5471 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005472 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005473 continue;
5474 }
5475 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005476 // relative layers are traversed in Layer::traverseInZOrder
5477 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005478 continue;
5479 }
5480 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005481 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005482 return;
5483 }
chaviwa76b2712017-09-20 12:02:26 -07005484 if (!layer->isVisible()) {
5485 return;
5486 }
5487 visitor(layer);
5488 });
5489 }
5490}
5491
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005492}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005493
Lloyd Pique074e8122018-07-26 12:57:23 -07005494
Mathias Agopian3f844832013-08-07 21:24:32 -07005495#if defined(__gl_h_)
5496#error "don't include gl/gl.h in this file"
5497#endif
5498
5499#if defined(__gl2_h_)
5500#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005501#endif