blob: 124b773ac9857fae2cb309e13b897bf868324342 [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
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700823 info.w = hwConfig->getWidth();
824 info.h = hwConfig->getHeight();
825 // Default display viewport to display width and height
826 info.viewportW = info.w;
827 info.viewportH = info.h;
828
Dan Stoza7f7da322014-05-02 15:26:25 -0700829 if (type == DisplayDevice::DISPLAY_PRIMARY) {
830 // The density of the device is provided by a build property
831 float density = Density::getBuildDensity() / 160.0f;
832 if (density == 0) {
833 // the build doesn't provide a density -- this is wrong!
834 // use xdpi instead
835 ALOGE("ro.sf.lcd_density must be defined as a build property");
836 density = xdpi / 160.0f;
837 }
838 if (Density::getEmuDensity()) {
839 // if "qemu.sf.lcd_density" is specified, it overrides everything
840 xdpi = ydpi = density = Density::getEmuDensity();
841 density /= 160.0f;
842 }
843 info.density = density;
844
845 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700846 const auto display = getDefaultDisplayDeviceLocked();
847 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700848
849 // This is for screenrecord
850 const Rect viewport = display->getViewport();
851 if (viewport.isValid()) {
852 info.viewportW = uint32_t(viewport.getWidth());
853 info.viewportH = uint32_t(viewport.getHeight());
854 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700855 } else {
856 // TODO: where should this value come from?
857 static const int TV_DENSITY = 213;
858 info.density = TV_DENSITY / 160.0f;
859 info.orientation = 0;
860 }
861
Dan Stoza7f7da322014-05-02 15:26:25 -0700862 info.xdpi = xdpi;
863 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800864 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900865 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800866
Andy McFadden91b2ca82014-06-13 14:04:23 -0700867 // This is how far in advance a buffer must be queued for
868 // presentation at a given time. If you want a buffer to appear
869 // on the screen at time N, you must submit the buffer before
870 // (N - presentationDeadline).
871 //
872 // Normally it's one full refresh period (to give SF a chance to
873 // latch the buffer), but this can be reduced by configuring a
874 // DispSync offset. Any additional delays introduced by the hardware
875 // composer or panel must be accounted for here.
876 //
877 // We add an additional 1ms to allow for processing time and
878 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800879 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800880 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700881
882 // All non-virtual displays are currently considered secure.
883 info.secure = true;
884
Iris Chang7501ed62018-04-30 14:45:42 +0800885 if (type == DisplayDevice::DISPLAY_PRIMARY &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700886 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800887 std::swap(info.w, info.h);
888 }
889
Michael Wright28f24d02016-07-12 13:30:53 -0700890 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700891 }
892
Dan Stoza7f7da322014-05-02 15:26:25 -0700893 return NO_ERROR;
894}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700895
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700896status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
897 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700898 return BAD_VALUE;
899 }
900
901 // FIXME for now we always return stats for the primary display
902 memset(stats, 0, sizeof(*stats));
Lloyd Pique41be5d22018-06-21 13:11:48 -0700903 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
904 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700905 return NO_ERROR;
906}
907
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700908int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
909 const auto display = getDisplayDevice(displayToken);
910 if (!display) {
911 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800912 return BAD_VALUE;
913 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700914
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700915 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700916}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700917
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700918void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
919 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700920 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700921 return;
922 }
923
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700924 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700925 ALOGW("Trying to set config for virtual display");
926 return;
927 }
928
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700929 display->setActiveConfig(mode);
930 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700931}
932
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700933status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700934 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700935 Vector<DisplayInfo> configs;
936 getDisplayConfigs(displayToken, &configs);
937 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
938 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
939 configs.size());
940 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700941 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700942 const auto display = getDisplayDevice(displayToken);
943 if (!display) {
944 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
945 displayToken.get());
946 } else if (display->isVirtual()) {
947 ALOGW("Attempt to set active config %d for virtual display", mode);
948 } else {
949 setActiveConfigInternal(display, mode);
950 }
951 }));
952
Mathias Agopian888c8222012-08-04 21:10:38 -0700953 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700954}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700955status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
956 Vector<ColorMode>* outColorModes) {
957 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700958 return BAD_VALUE;
959 }
960
Michael Wright28f24d02016-07-12 13:30:53 -0700961 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700962 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
963 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700964 type = i;
965 break;
966 }
967 }
968
969 if (type < 0) {
970 return type;
971 }
972
Peiyong Lina52f0292018-03-14 17:26:31 -0700973 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700974 {
975 ConditionalLock _l(mStateLock,
976 std::this_thread::get_id() != mMainThreadId);
977 modes = getHwComposer().getColorModes(type);
978 }
Michael Wright28f24d02016-07-12 13:30:53 -0700979 outColorModes->clear();
980 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
981
982 return NO_ERROR;
983}
984
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700985ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
986 if (const auto display = getDisplayDevice(displayToken)) {
987 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700988 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700989 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700990}
991
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700992void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
993 Dataspace dataSpace, RenderIntent renderIntent) {
994 ColorMode currentMode = display->getActiveColorMode();
995 Dataspace currentDataSpace = display->getCompositionDataSpace();
996 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -0700997
Peiyong Lin38e9a562018-04-10 16:24:20 -0700998 if (mode == currentMode && dataSpace == currentDataSpace &&
999 renderIntent == currentRenderIntent) {
1000 return;
1001 }
1002
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001003 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001004 ALOGW("Trying to set config for virtual display");
1005 return;
1006 }
1007
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001008 display->setActiveColorMode(mode);
1009 display->setCompositionDataSpace(dataSpace);
1010 display->setActiveRenderIntent(renderIntent);
1011 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001012
1013 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001014 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1015 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001016}
1017
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001018status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001019 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001020 Vector<ColorMode> modes;
1021 getDisplayColorModes(displayToken, &modes);
1022 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1023 if (mode < ColorMode::NATIVE || !exists) {
1024 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1025 decodeColorMode(mode).c_str(), mode, displayToken.get());
1026 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001027 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001028 const auto display = getDisplayDevice(displayToken);
1029 if (!display) {
1030 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1031 decodeColorMode(mode).c_str(), mode, displayToken.get());
1032 } else if (display->isVirtual()) {
1033 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1034 decodeColorMode(mode).c_str(), mode);
1035 } else {
1036 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1037 RenderIntent::COLORIMETRIC);
1038 }
1039 }));
1040
Michael Wright28f24d02016-07-12 13:30:53 -07001041 return NO_ERROR;
1042}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001043
Svetoslavd85084b2014-03-20 10:28:31 -07001044status_t SurfaceFlinger::clearAnimationFrameStats() {
1045 Mutex::Autolock _l(mStateLock);
1046 mAnimFrameTracker.clearStats();
1047 return NO_ERROR;
1048}
1049
1050status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1051 Mutex::Autolock _l(mStateLock);
1052 mAnimFrameTracker.getStats(outStats);
1053 return NO_ERROR;
1054}
1055
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001056status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1057 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001058 Mutex::Autolock _l(mStateLock);
1059
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001060 const auto display = getDisplayDeviceLocked(displayToken);
1061 if (!display) {
1062 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001063 return BAD_VALUE;
1064 }
1065
Peiyong Linfb069302018-04-25 14:34:31 -07001066 // At this point the DisplayDeivce should already be set up,
1067 // meaning the luminance information is already queried from
1068 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001069 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001070 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1071 capabilities.getDesiredMaxLuminance(),
1072 capabilities.getDesiredMaxAverageLuminance(),
1073 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001074
1075 return NO_ERROR;
1076}
1077
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001078status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001079 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001080 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001081
Chia-I Wu90f669f2017-10-05 14:24:41 -07001082 if (mInjectVSyncs == enable) {
1083 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001084 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001085
1086 if (enable) {
1087 ALOGV("VSync Injections enabled");
1088 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001089 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001090 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001091 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001092 impl::EventThread::InterceptVSyncsCallback(),
1093 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001094 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001095 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001096 } else {
1097 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001098 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001099 }
1100
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001101 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001102 }));
1103
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001104 return NO_ERROR;
1105}
1106
1107status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001108 Mutex::Autolock _l(mStateLock);
1109
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001110 if (!mInjectVSyncs) {
1111 ALOGE("VSync Injections not enabled");
1112 return BAD_VALUE;
1113 }
1114 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1115 ALOGV("Injecting VSync inside SurfaceFlinger");
1116 mVSyncInjector->onInjectSyncEvent(when);
1117 }
1118 return NO_ERROR;
1119}
1120
Lloyd Pique755e3192018-01-31 16:46:15 -08001121status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1122 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001123 // Try to acquire a lock for 1s, fail gracefully
1124 const status_t err = mStateLock.timedLock(s2ns(1));
1125 const bool locked = (err == NO_ERROR);
1126 if (!locked) {
1127 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1128 return TIMED_OUT;
1129 }
1130
1131 outLayers->clear();
1132 mCurrentState.traverseInZOrder([&](Layer* layer) {
1133 outLayers->push_back(layer->getLayerDebugInfo());
1134 });
1135
1136 mStateLock.unlock();
1137 return NO_ERROR;
1138}
1139
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001140// ----------------------------------------------------------------------------
1141
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001142sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1143 ISurfaceComposer::VsyncSource vsyncSource) {
1144 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1145 return mSFEventThread->createEventConnection();
1146 } else {
1147 return mEventThread->createEventConnection();
1148 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001149}
1150
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001151// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001152
1153void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001154 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001155}
1156
1157void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001158 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001159}
1160
1161void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001162 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001163}
1164
1165void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001166 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001167 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001168}
1169
1170status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001171 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001172 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001173}
1174
1175status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001176 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001177 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001178 if (res == NO_ERROR) {
1179 msg->wait();
1180 }
1181 return res;
1182}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001183
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001184void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001185 do {
1186 waitForEvent();
1187 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001188}
1189
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001190void SurfaceFlinger::enableHardwareVsync() {
1191 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001192 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001193 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001194 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001195 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001196 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001197}
1198
Jesse Hall948fe0c2013-10-14 12:56:09 -07001199void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001200 Mutex::Autolock _l(mHWVsyncLock);
1201
Jesse Hall948fe0c2013-10-14 12:56:09 -07001202 if (makeAvailable) {
1203 mHWVsyncAvailable = true;
1204 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001205 // Hardware vsync is not currently available, so abort the resync
1206 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001207 return;
1208 }
1209
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001210 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1211 if (!getHwComposer().isConnected(displayId)) {
1212 return;
1213 }
1214
1215 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001216 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001217
Lloyd Pique41be5d22018-06-21 13:11:48 -07001218 mPrimaryDispSync->reset();
1219 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001220
1221 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001222 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001223 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001224 mPrimaryHWVsyncEnabled = true;
1225 }
1226}
1227
Jesse Hall948fe0c2013-10-14 12:56:09 -07001228void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001229 Mutex::Autolock _l(mHWVsyncLock);
1230 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001231 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001232 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001233 mPrimaryHWVsyncEnabled = false;
1234 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001235 if (makeUnavailable) {
1236 mHWVsyncAvailable = false;
1237 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001238}
1239
Tim Murray4a4e4a22016-04-19 16:29:23 +00001240void SurfaceFlinger::resyncWithRateLimit() {
1241 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001242
1243 // No explicit locking is needed here since EventThread holds a lock while calling this method
1244 static nsecs_t sLastResyncAttempted = 0;
1245 const nsecs_t now = systemTime();
1246 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001247 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001248 }
Dan Stoza57164302017-05-08 14:03:54 -07001249 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001250}
1251
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001252void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1253 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001254 ATRACE_NAME("SF onVsync");
1255
Steven Thomas3cfac282017-02-06 12:29:30 -08001256 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001257 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001258 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001259 return;
1260 }
1261
1262 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001263 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001264 return;
1265 }
1266
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001267 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1268 // For now, we don't do anything with external display vsyncs.
1269 return;
1270 }
1271
Jamie Gennisd1700752013-10-14 12:22:52 -07001272 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001273
Jamie Gennisd1700752013-10-14 12:22:52 -07001274 { // Scope for the lock
1275 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001276 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001277 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001278 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001279 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001280
1281 if (needsHwVsync) {
1282 enableHardwareVsync();
1283 } else {
1284 disableHardwareVsync(false);
1285 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001286}
1287
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001288void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001289 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1290 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001291}
1292
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001293void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001294 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001295 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001296 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001297
Lloyd Piqueba04e622017-12-14 17:11:26 -08001298 // Ignore events that do not have the right sequenceId.
1299 if (sequenceId != getBE().mComposerSequenceId) {
1300 return;
1301 }
1302
Steven Thomasb02664d2017-07-26 18:48:28 -07001303 // Only lock if we're not on the main thread. This function is normally
1304 // called on a hwbinder thread, but for the primary display it's called on
1305 // the main thread with the state lock already held, so don't attempt to
1306 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001307 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001308
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001309 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001310
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001311 if (std::this_thread::get_id() == mMainThreadId) {
1312 // Process all pending hot plug events immediately if we are on the main thread.
1313 processDisplayHotplugEventsLocked();
1314 }
1315
Lloyd Piqueba04e622017-12-14 17:11:26 -08001316 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001317}
1318
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001319void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001320 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001321 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001322 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001323 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001324 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001325}
1326
Dan Stoza9e56aa02015-11-02 13:00:03 -08001327void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001328 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001329 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001330 getHwComposer().setVsyncEnabled(disp,
1331 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001332}
1333
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001334// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001335void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001336 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001337 // Clear the drawing state so that the logic inside of
1338 // handleTransactionLocked will fire. It will determine the delta between
1339 // mCurrentState and mDrawingState and re-apply all changes when we make the
1340 // transition.
1341 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001342 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001343 mDisplays.clear();
1344}
1345
Steven Thomas050b2c82017-03-06 11:45:16 -08001346void SurfaceFlinger::updateVrFlinger() {
1347 if (!mVrFlinger)
1348 return;
1349 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001350 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001351 return;
1352 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001353
David Sodman105b7dc2017-11-04 20:28:14 -07001354 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001355 ALOGE("Vr flinger is only supported for remote hardware composer"
1356 " service connections. Ignoring request to transition to vr"
1357 " flinger.");
1358 mVrFlingerRequestsDisplay = false;
1359 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001360 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001361
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001362 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001363
Steven Thomas0123ac62018-07-12 11:32:34 -07001364 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001365 LOG_ALWAYS_FATAL_IF(!display);
1366 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001367 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1368 // called below. Clear the reference now so we don't accidentally use it
1369 // later.
1370 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001371
Steven Thomasb02664d2017-07-26 18:48:28 -07001372 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001373 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001374 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001375
Steven Thomasb02664d2017-07-26 18:48:28 -07001376 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001377 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001378 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1379 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001380 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001381
David Sodman105b7dc2017-11-04 20:28:14 -07001382 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1383 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001384
1385 if (vrFlingerRequestsDisplay) {
1386 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001387 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001388
1389 mVisibleRegionsDirty = true;
1390 invalidateHwcGeometry();
1391
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001392 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001393 display = getDefaultDisplayDeviceLocked();
1394 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001395 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001396
Steven Thomasb02664d2017-07-26 18:48:28 -07001397 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001398 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001399 const nsecs_t period = activeConfig->getVsyncPeriod();
1400 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001401
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001402 // The present fences returned from vr_hwc are not an accurate
1403 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001404 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1405 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001406
Steven Thomasb02664d2017-07-26 18:48:28 -07001407 // Use phase of 0 since phase is not known.
1408 // Use latency of 0, which will snap to the ideal latency.
1409 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001410
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001411 resyncToHardwareVsync(false);
1412
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001413 android_atomic_or(1, &mRepaintEverything);
1414 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001415}
1416
Mathias Agopian4fec8732012-06-29 14:12:52 -07001417void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001418 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001419 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001420 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001421 bool frameMissed = !mHadClientComposition &&
1422 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001423 (mPreviousPresentFence->getSignalTime() ==
1424 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001425 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001426 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001427 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001428 mTimeStats.incrementMissedFrames();
1429 if (mPropagateBackpressure) {
1430 signalLayerUpdate();
1431 break;
1432 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001433 }
Dan Stoza50182882016-07-08 12:02:20 -07001434
Steven Thomas050b2c82017-03-06 11:45:16 -08001435 // Now that we're going to make it to the handleMessageTransaction()
1436 // call below it's safe to call updateVrFlinger(), which will
1437 // potentially trigger a display handoff.
1438 updateVrFlinger();
1439
Dan Stoza6b9454d2014-11-07 16:00:59 -08001440 bool refreshNeeded = handleMessageTransaction();
1441 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001442 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001443 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001444 // Signal a refresh if a transaction modified the window state,
1445 // a new buffer was latched, or if HWC has requested a full
1446 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001447 signalRefresh();
1448 }
1449 break;
1450 }
1451 case MessageQueue::REFRESH: {
1452 handleMessageRefresh();
1453 break;
1454 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001455 }
1456}
1457
Dan Stoza6b9454d2014-11-07 16:00:59 -08001458bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001459 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001460 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001461 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001462 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001463 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001464 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001465}
1466
Mathias Agopian4fec8732012-06-29 14:12:52 -07001467void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001468 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001469
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001470 mRefreshPending = false;
1471
David Sodmanfa9b2af2017-12-24 13:28:59 -08001472 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
David Sodman2b406362017-12-15 13:33:47 -08001473 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001474 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001475 calculateWorkingSet();
David Sodman10a41ff2018-08-05 12:14:17 -07001476
David Sodmanfa9b2af2017-12-24 13:28:59 -08001477 for (const auto& [token, display] : mDisplays) {
David Sodman10a41ff2018-08-05 12:14:17 -07001478 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001479 beginFrame(display);
David Sodman10a41ff2018-08-05 12:14:17 -07001480 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
1481 setUpHWComposer(compositionInfo);
1482 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001483 prepareFrame(display);
1484 doDebugFlashRegions(display, repaintEverything);
1485 doComposition(display, repaintEverything);
1486 }
1487
Adrian Roos1e1a1282017-11-01 19:05:31 +01001488 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001489 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001490
1491 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001492 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001493
Dan Stozabfbffeb2016-07-21 14:49:33 -07001494 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001495 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001496 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001497 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001498 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001499
Jorim Jaggi90535212018-05-23 23:44:06 +02001500 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001501
David Sodman7e4ae112018-02-09 15:02:28 -08001502 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001503 for (const auto& [token, display] : mDisplays) {
1504 const auto displayId = display->getId();
David Sodman7e4ae112018-02-09 15:02:28 -08001505 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[displayId]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001506 compositionInfo.hwc.hwcLayer = nullptr;
1507 }
David Sodmanba340492018-08-05 21:51:33 -07001508 }
David Sodman7e4ae112018-02-09 15:02:28 -08001509
1510 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001511}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001512
David Sodmanfa9b2af2017-12-24 13:28:59 -08001513
1514bool SurfaceFlinger::handleMessageInvalidate() {
1515 ATRACE_CALL();
1516 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001517}
1518
David Sodman79bba0e2018-08-05 18:07:49 -07001519void SurfaceFlinger::calculateWorkingSet() {
1520 ATRACE_CALL();
1521 ALOGV(__FUNCTION__);
1522
David Sodman79bba0e2018-08-05 18:07:49 -07001523 // build the h/w work list
1524 if (CC_UNLIKELY(mGeometryInvalid)) {
1525 mGeometryInvalid = false;
1526 for (const auto& [token, display] : mDisplays) {
1527 const auto displayId = display->getId();
1528 if (displayId >= 0) {
1529 const Vector<sp<Layer>>& currentLayers(
1530 display->getVisibleLayersSortedByZ());
1531 for (size_t i = 0; i < currentLayers.size(); i++) {
1532 const auto& layer = currentLayers[i];
1533
1534 if (!layer->hasHwcLayer(displayId)) {
1535 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1536 layer->forceClientComposition(displayId);
1537 continue;
1538 }
1539 }
1540
1541 layer->setGeometry(display, i);
1542 if (mDebugDisableHWC || mDebugRegion) {
1543 layer->forceClientComposition(displayId);
1544 }
1545 }
1546 }
1547 }
1548 }
1549
1550 // Set the per-frame data
1551 for (const auto& [token, display] : mDisplays) {
1552 const auto displayId = display->getId();
1553 if (displayId < 0) {
1554 continue;
1555 }
1556
1557 if (mDrawingState.colorMatrixChanged) {
1558 display->setColorTransform(mDrawingState.colorMatrix);
1559 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1560 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1561 "display %d: %d", displayId, result);
1562 }
1563 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1564 if (layer->isHdrY410()) {
1565 layer->forceClientComposition(displayId);
1566 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1567 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1568 !display->hasHDR10Support()) {
1569 layer->forceClientComposition(displayId);
1570 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1571 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1572 !display->hasHLGSupport()) {
1573 layer->forceClientComposition(displayId);
1574 }
1575
1576 if (layer->getForceClientComposition(displayId)) {
1577 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1578 layer->setCompositionType(displayId, HWC2::Composition::Client);
1579 continue;
1580 }
1581
1582 layer->setPerFrameData(display);
1583 }
1584
Peiyong Lin13effd12018-07-24 17:01:47 -07001585 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001586 ColorMode colorMode;
1587 Dataspace dataSpace;
1588 RenderIntent renderIntent;
1589 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1590 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1591 }
1592 }
1593
1594 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001595
1596 for (const auto& [token, display] : mDisplays) {
David Sodman15fb96e2018-01-07 10:23:24 -08001597 const auto displayId = display->getId();
1598 getBE().mCompositionInfo[displayId].clear();
David Sodmanba340492018-08-05 21:51:33 -07001599 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1600 auto displayId = display->getId();
1601 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1602 if (!layer->setHwcLayer(displayId)) {
1603 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1604 }
David Sodman15fb96e2018-01-07 10:23:24 -08001605 layer->getBE().compositionInfo.hwc.displayId = displayId;
1606 getBE().mCompositionInfo[displayId].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001607 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1608 }
1609 }
David Sodman79bba0e2018-08-05 18:07:49 -07001610}
1611
David Sodmanfa9b2af2017-12-24 13:28:59 -08001612void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001613{
David Sodmanfb95bcc2017-12-22 15:45:30 -08001614 const auto displayId = display->getId();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001615 // is debugging enabled
1616 if (CC_LIKELY(!mDebugRegion))
1617 return;
1618
David Sodmanfa9b2af2017-12-24 13:28:59 -08001619 if (display->isPoweredOn()) {
1620 // transform the dirty region into this screen's coordinate space
1621 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1622 if (!dirtyRegion.isEmpty()) {
1623 // redraw the whole screen
1624 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001625
David Sodmanfa9b2af2017-12-24 13:28:59 -08001626 // and draw the dirty region
1627 const int32_t height = display->getHeight();
1628 auto& engine(getRenderEngine());
1629 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001630
David Sodmanfa9b2af2017-12-24 13:28:59 -08001631 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001632 }
1633 }
1634
David Sodmanfa9b2af2017-12-24 13:28:59 -08001635 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001636
1637 if (mDebugRegion > 1) {
1638 usleep(mDebugRegion * 1000);
1639 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001640
David Sodmanfa9b2af2017-12-24 13:28:59 -08001641 if (display->isPoweredOn()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08001642 status_t result = display->prepareFrame(
1643 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001644 ALOGE_IF(result != NO_ERROR,
1645 "prepareFrame for display %d failed:"
1646 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001647 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001648 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001649}
1650
Adrian Roos1e1a1282017-11-01 19:05:31 +01001651void SurfaceFlinger::doTracing(const char* where) {
1652 ATRACE_CALL();
1653 ATRACE_NAME(where);
1654 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001655 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001656 }
1657}
1658
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001659void SurfaceFlinger::logLayerStats() {
1660 ATRACE_CALL();
1661 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001662 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001663 if (display->isPrimary()) {
1664 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001665 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001666 }
1667 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001668
1669 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001670 }
1671}
1672
David Sodman2b406362017-12-15 13:33:47 -08001673void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001674{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001675 ATRACE_CALL();
1676 ALOGV("preComposition");
1677
David Sodman2b406362017-12-15 13:33:47 -08001678 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1679
Mathias Agopiancd60f992012-08-16 16:28:27 -07001680 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001681 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001682 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001683 needExtraInvalidate = true;
1684 }
Robert Carr2047fae2016-11-28 14:09:09 -08001685 });
1686
Mathias Agopiancd60f992012-08-16 16:28:27 -07001687 if (needExtraInvalidate) {
1688 signalLayerUpdate();
1689 }
1690}
1691
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001692void SurfaceFlinger::updateCompositorTiming(
1693 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1694 std::shared_ptr<FenceTime>& presentFenceTime) {
1695 // Update queue of past composite+present times and determine the
1696 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001697 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001698 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001699 while (!getBE().mCompositePresentTimes.empty()) {
1700 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001701 // Cached values should have been updated before calling this method,
1702 // which helps avoid duplicate syscalls.
1703 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1704 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1705 break;
1706 }
1707 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001708 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001709 }
1710
1711 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001712 while (getBE().mCompositePresentTimes.size() > 16) {
1713 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001714 }
1715
Brian Andersond0010582017-03-07 13:20:31 -08001716 setCompositorTimingSnapped(
1717 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1718}
1719
1720void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1721 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001722 // Integer division and modulo round toward 0 not -inf, so we need to
1723 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001724 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001725 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1726 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1727
Brian Andersond0010582017-03-07 13:20:31 -08001728 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1729 if (idealLatency <= 0) {
1730 idealLatency = vsyncInterval;
1731 }
1732
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001733 // Snap the latency to a value that removes scheduling jitter from the
1734 // composition and present times, which often have >1ms of jitter.
1735 // Reducing jitter is important if an app attempts to extrapolate
1736 // something (such as user input) to an accurate diasplay time.
1737 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1738 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001739 nsecs_t bias = vsyncInterval / 2;
1740 int64_t extraVsyncs =
1741 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1742 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1743 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001744
David Sodman99974d22017-11-28 12:04:33 -08001745 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1746 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1747 getBE().mCompositorTiming.interval = vsyncInterval;
1748 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001749}
1750
David Sodman2b406362017-12-15 13:33:47 -08001751void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001752{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001753 ATRACE_CALL();
1754 ALOGV("postComposition");
1755
Brian Anderson3546a3f2016-07-14 11:51:14 -07001756 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001757 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001758 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001759 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001760 }
1761
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001762 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001763 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001764
David Sodman73beded2017-11-15 11:56:06 -08001765 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001766 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001767 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001768 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001769 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001770 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001771 } else {
1772 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1773 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001774
David Sodman73beded2017-11-15 11:56:06 -08001775 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001776 mPreviousPresentFence =
1777 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1778 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001779 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001780
Lloyd Pique41be5d22018-06-21 13:11:48 -07001781 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1782 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001783
David Sodman2b406362017-12-15 13:33:47 -08001784 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001785 // when we started doing work for this frame, but that should be okay
1786 // since updateCompositorTiming has snapping logic.
1787 updateCompositorTiming(
David Sodman2b406362017-12-15 13:33:47 -08001788 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001789 CompositorTiming compositorTiming;
1790 {
David Sodman99974d22017-11-28 12:04:33 -08001791 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1792 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001793 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001794
Robert Carr2047fae2016-11-28 14:09:09 -08001795 mDrawingState.traverseInZOrder([&](Layer* layer) {
1796 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001797 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001798 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001799 recordBufferingStats(layer->getName().string(),
1800 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001801 }
Robert Carr2047fae2016-11-28 14:09:09 -08001802 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001803
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001804 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001805 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001806 enableHardwareVsync();
1807 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001808 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001809 }
1810 }
1811
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001812 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001813 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001814 enableHardwareVsync();
1815 }
1816 }
1817
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001818 if (mAnimCompositionPending) {
1819 mAnimCompositionPending = false;
1820
Brian Anderson4e606e32017-03-16 15:34:57 -07001821 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001822 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001823 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001824 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001825 // The HWC doesn't support present fences, so use the refresh
1826 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001827 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001828 mAnimFrameTracker.setActualPresentTime(presentTime);
1829 }
1830 mAnimFrameTracker.advanceFrame();
1831 }
Dan Stozab90cf072015-03-05 11:05:59 -08001832
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001833 mTimeStats.incrementTotalFrames();
1834 if (mHadClientComposition) {
1835 mTimeStats.incrementClientCompositionFrames();
1836 }
1837
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001838 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001839 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001840 return;
1841 }
1842
1843 nsecs_t currentTime = systemTime();
1844 if (mHasPoweredOff) {
1845 mHasPoweredOff = false;
1846 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001847 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001848 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001849 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1850 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001851 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001852 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001853 }
David Sodman4a36e932017-11-07 14:29:47 -08001854 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001855 }
David Sodman4a36e932017-11-07 14:29:47 -08001856 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001857
1858 {
1859 std::lock_guard lock(mTexturePoolMutex);
1860 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1861 if (refillCount > 0) {
1862 const size_t offset = mTexturePool.size();
1863 mTexturePool.resize(mTexturePoolSize);
1864 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1865 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1866 }
1867 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001868}
1869
1870void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001871 ATRACE_CALL();
1872 ALOGV("rebuildLayerStacks");
1873
Mathias Agopiancd60f992012-08-16 16:28:27 -07001874 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001875 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001876 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001877 mVisibleRegionsDirty = false;
1878 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001879
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001880 for (const auto& pair : mDisplays) {
1881 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001882 Region opaqueRegion;
1883 Region dirtyRegion;
1884 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001885 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001886 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001887 const Rect bounds = display->getBounds();
1888 if (display->isPoweredOn()) {
1889 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001890
Jeff Sharkey76488112017-02-27 14:15:18 -07001891 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001892 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001893 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001894 Region drawRegion(tr.transform(
1895 layer->visibleNonTransparentRegion));
1896 drawRegion.andSelf(bounds);
1897 if (!drawRegion.isEmpty()) {
1898 layersSortedByZ.add(layer);
1899 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001900 // Clear out the HWC layer if this layer was
1901 // previously visible, but no longer is
1902 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001903 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001904 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001905 // WM changes display->layerStack upon sleep/awake.
1906 // Here we make sure we delete the HWC layers even if
1907 // WM changed their layer stack.
1908 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001909 }
1910
1911 // If a layer is not going to get a release fence because
1912 // it is invisible, but it is also going to release its
1913 // old buffer, add it to the list of layers needing
1914 // fences.
1915 if (hwcLayerDestroyed) {
1916 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1917 mLayersWithQueuedFrames.cend(), layer);
1918 if (found != mLayersWithQueuedFrames.cend()) {
1919 layersNeedingFences.add(layer);
1920 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001921 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001922 });
1923 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001924 display->setVisibleLayersSortedByZ(layersSortedByZ);
1925 display->setLayersNeedingFences(layersNeedingFences);
1926 display->undefinedRegion.set(bounds);
1927 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1928 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001929 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001930 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001931}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001932
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001933// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001934// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001935// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001936// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001937// The returned HDR data space is one of
1938// - Dataspace::UNKNOWN
1939// - Dataspace::BT2020_HLG
1940// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001941Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1942 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001943 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001944 *outHdrDataSpace = Dataspace::UNKNOWN;
1945
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001946 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001947 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001948 case Dataspace::V0_SCRGB:
1949 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001950 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001951 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001952 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001953 case Dataspace::BT2020_PQ:
1954 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001955 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001956 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001957 case Dataspace::BT2020_HLG:
1958 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001959 // When there's mixed PQ content and HLG content, we set the HDR
1960 // data space to be BT2020_PQ and convert HLG to PQ.
1961 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1962 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001963 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001964 break;
1965 default:
1966 break;
1967 }
Romain Guy54f154a2017-10-24 21:40:32 +01001968 }
1969
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001970 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001971}
1972
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001973// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001974void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1975 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001976 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1977 *outMode = ColorMode::NATIVE;
1978 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001979 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001980 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001981 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001982
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001983 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001984 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001985
Peiyong Lindfde5112018-06-05 10:58:41 -07001986 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001987 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001988 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001989 if (isHdr) {
1990 bestDataSpace = hdrDataSpace;
1991 }
1992
Chia-I Wu0d711262018-05-21 15:19:35 -07001993 RenderIntent intent;
1994 switch (mDisplayColorSetting) {
1995 case DisplayColorSetting::MANAGED:
1996 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001997 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001998 break;
1999 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002000 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002001 break;
2002 default: // vendor display color setting
2003 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2004 break;
2005 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002006
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002007 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002008}
2009
David Sodman10a41ff2018-08-05 12:14:17 -07002010void SurfaceFlinger::configureSidebandComposition(const CompositionInfo& compositionInfo) const
2011{
2012 HWC2::Error error;
2013 LOG_ALWAYS_FATAL_IF(compositionInfo.hwc.sidebandStream == nullptr,
2014 "CompositionType is sideband, but sideband stream is nullptr");
2015 error = (compositionInfo.hwc.hwcLayer)
2016 ->setSidebandStream(compositionInfo.hwc.sidebandStream->handle());
2017 if (error != HWC2::Error::None) {
2018 ALOGE("[SF] Failed to set sideband stream %p: %s (%d)",
2019 compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
2020 static_cast<int32_t>(error));
2021 }
2022}
2023
2024void SurfaceFlinger::configureHwcCommonData(const CompositionInfo& compositionInfo) const
2025{
2026 HWC2::Error error;
2027
2028 if (!compositionInfo.hwc.skipGeometry) {
2029 error = (compositionInfo.hwc.hwcLayer)->setBlendMode(compositionInfo.hwc.blendMode);
2030 ALOGE_IF(error != HWC2::Error::None,
2031 "[SF] Failed to set blend mode %s:"
2032 " %s (%d)",
2033 to_string(compositionInfo.hwc.blendMode).c_str(), to_string(error).c_str(),
2034 static_cast<int32_t>(error));
2035
2036 error = (compositionInfo.hwc.hwcLayer)->setDisplayFrame(compositionInfo.hwc.displayFrame);
2037 ALOGE_IF(error != HWC2::Error::None,
2038 "[SF] Failed to set the display frame [%d, %d, %d, %d] %s (%d)",
2039 compositionInfo.hwc.displayFrame.left,
2040 compositionInfo.hwc.displayFrame.right,
2041 compositionInfo.hwc.displayFrame.top,
2042 compositionInfo.hwc.displayFrame.bottom,
2043 to_string(error).c_str(), static_cast<int32_t>(error));
2044
2045 error = (compositionInfo.hwc.hwcLayer)->setSourceCrop(compositionInfo.hwc.sourceCrop);
2046 ALOGE_IF(error != HWC2::Error::None,
2047 "[SF] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: %s (%d)",
2048 compositionInfo.hwc.sourceCrop.left,
2049 compositionInfo.hwc.sourceCrop.right,
2050 compositionInfo.hwc.sourceCrop.top,
2051 compositionInfo.hwc.sourceCrop.bottom,
2052 to_string(error).c_str(), static_cast<int32_t>(error));
2053
2054 error = (compositionInfo.hwc.hwcLayer)->setPlaneAlpha(compositionInfo.hwc.alpha);
2055 ALOGE_IF(error != HWC2::Error::None,
2056 "[SF] Failed to set plane alpha %.3f: "
2057 "%s (%d)",
2058 compositionInfo.hwc.alpha,
2059 to_string(error).c_str(), static_cast<int32_t>(error));
2060
2061
2062 error = (compositionInfo.hwc.hwcLayer)->setZOrder(compositionInfo.hwc.z);
2063 ALOGE_IF(error != HWC2::Error::None,
2064 "[SF] Failed to set Z %u: %s (%d)",
2065 compositionInfo.hwc.z,
2066 to_string(error).c_str(), static_cast<int32_t>(error));
2067
2068 error = (compositionInfo.hwc.hwcLayer)
2069 ->setInfo(compositionInfo.hwc.type, compositionInfo.hwc.appId);
2070 ALOGE_IF(error != HWC2::Error::None,
2071 "[SF] Failed to set info (%d)",
2072 static_cast<int32_t>(error));
2073
2074 error = (compositionInfo.hwc.hwcLayer)->setTransform(compositionInfo.hwc.transform);
2075 ALOGE_IF(error != HWC2::Error::None,
2076 "[SF] Failed to set transform %s: "
2077 "%s (%d)",
2078 to_string(compositionInfo.hwc.transform).c_str(), to_string(error).c_str(),
2079 static_cast<int32_t>(error));
2080 }
2081
2082 error = (compositionInfo.hwc.hwcLayer)->setCompositionType(compositionInfo.compositionType);
2083 ALOGE_IF(error != HWC2::Error::None,
2084 "[SF] Failed to set composition type: %s (%d)",
2085 to_string(error).c_str(), static_cast<int32_t>(error));
2086
2087 error = (compositionInfo.hwc.hwcLayer)->setDataspace(compositionInfo.hwc.dataspace);
2088 ALOGE_IF(error != HWC2::Error::None,
2089 "[SF] Failed to set dataspace: %s (%d)",
2090 to_string(error).c_str(), static_cast<int32_t>(error));
2091
2092 error = (compositionInfo.hwc.hwcLayer)->setPerFrameMetadata(
2093 compositionInfo.hwc.supportedPerFrameMetadata, compositionInfo.hwc.hdrMetadata);
2094 ALOGE_IF(error != HWC2::Error::None && error != HWC2::Error::Unsupported,
2095 "[SF] Failed to set hdrMetadata: %s (%d)",
2096 to_string(error).c_str(), static_cast<int32_t>(error));
2097
2098 if (compositionInfo.compositionType == HWC2::Composition::SolidColor) {
2099 error = (compositionInfo.hwc.hwcLayer)->setColor(compositionInfo.hwc.color);
2100 ALOGE_IF(error != HWC2::Error::None,
2101 "[SF] Failed to set color: %s (%d)",
2102 to_string(error).c_str(), static_cast<int32_t>(error));
2103 }
2104
2105 error = (compositionInfo.hwc.hwcLayer)->setVisibleRegion(compositionInfo.hwc.visibleRegion);
2106 ALOGE_IF(error != HWC2::Error::None,
2107 "[SF] Failed to set visible region: %s (%d)",
2108 to_string(error).c_str(), static_cast<int32_t>(error));
2109
2110 error = (compositionInfo.hwc.hwcLayer)->setSurfaceDamage(compositionInfo.hwc.surfaceDamage);
2111 ALOGE_IF(error != HWC2::Error::None,
2112 "[SF] Failed to set surface damage: %s (%d)",
2113 to_string(error).c_str(), static_cast<int32_t>(error));
2114}
2115
2116void SurfaceFlinger::configureDeviceComposition(const CompositionInfo& compositionInfo) const
2117{
2118 HWC2::Error error;
2119
2120 if (compositionInfo.hwc.fence) {
2121 error = (compositionInfo.hwc.hwcLayer)->setBuffer(compositionInfo.mBufferSlot,
2122 compositionInfo.mBuffer, compositionInfo.hwc.fence);
2123 ALOGE_IF(error != HWC2::Error::None,
2124 "[SF] Failed to set buffer: %s (%d)",
2125 to_string(error).c_str(), static_cast<int32_t>(error));
2126 }
2127}
2128
David Sodmanfa9b2af2017-12-24 13:28:59 -08002129void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002130{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002131 bool dirty = !display->getDirtyRegion(false).isEmpty();
2132 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2133 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002134
David Sodmanfa9b2af2017-12-24 13:28:59 -08002135 // If nothing has changed (!dirty), don't recompose.
2136 // If something changed, but we don't currently have any visible layers,
2137 // and didn't when we last did a composition, then skip it this time.
2138 // The second rule does two things:
2139 // - When all layers are removed from a display, we'll emit one black
2140 // frame, then nothing more until we get new layers.
2141 // - When a display is created with a private layer stack, we won't
2142 // emit any black frames until a layer is added to the layer stack.
2143 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002144
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002145 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2146 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002147 mustRecompose ? "doing" : "skipping",
2148 dirty ? "+" : "-",
2149 empty ? "+" : "-",
2150 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002151
David Sodmanfa9b2af2017-12-24 13:28:59 -08002152 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002153
David Sodmanfa9b2af2017-12-24 13:28:59 -08002154 if (mustRecompose) {
2155 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002156 }
2157}
2158
David Sodmanfa9b2af2017-12-24 13:28:59 -08002159void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002160{
David Sodmanfb95bcc2017-12-22 15:45:30 -08002161 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002162 if (!display->isPoweredOn()) {
2163 return;
David Sodman2b406362017-12-15 13:33:47 -08002164 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002165
David Sodmanfb95bcc2017-12-22 15:45:30 -08002166 status_t result = display->prepareFrame(
2167 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08002168 ALOGE_IF(result != NO_ERROR,
2169 "prepareFrame for display %d failed:"
2170 " %d (%s)",
2171 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002172}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002173
David Sodman10a41ff2018-08-05 12:14:17 -07002174void SurfaceFlinger::setUpHWComposer(const CompositionInfo& compositionInfo) {
2175 ATRACE_CALL();
2176 ALOGV("setUpHWComposer");
2177
2178 switch (compositionInfo.compositionType)
2179 {
2180 case HWC2::Composition::Invalid:
David Sodmana6d42332018-08-29 14:07:04 -07002181 break;
2182
David Sodman10a41ff2018-08-05 12:14:17 -07002183 case HWC2::Composition::Client:
David Sodmana6d42332018-08-29 14:07:04 -07002184 if (compositionInfo.hwc.hwcLayer) {
2185 auto error = (compositionInfo.hwc.hwcLayer)->
2186 setCompositionType(compositionInfo.compositionType);
2187 ALOGE_IF(error != HWC2::Error::None,
2188 "[SF] Failed to set composition type: %s (%d)",
2189 to_string(error).c_str(), static_cast<int32_t>(error));
2190 }
David Sodman10a41ff2018-08-05 12:14:17 -07002191 break;
2192
2193 case HWC2::Composition::Sideband:
2194 configureHwcCommonData(compositionInfo);
2195 configureSidebandComposition(compositionInfo);
2196 break;
2197
2198 case HWC2::Composition::SolidColor:
2199 configureHwcCommonData(compositionInfo);
2200 break;
2201
2202 case HWC2::Composition::Device:
2203 case HWC2::Composition::Cursor:
2204 configureHwcCommonData(compositionInfo);
2205 configureDeviceComposition(compositionInfo);
2206 break;
2207 }
2208}
2209
David Sodmanfa9b2af2017-12-24 13:28:59 -08002210void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002211 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002212 ALOGV("doComposition");
2213
David Sodmanfa9b2af2017-12-24 13:28:59 -08002214 if (display->isPoweredOn()) {
2215 // transform the dirty region into this screen's coordinate space
2216 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002217
David Sodmanfa9b2af2017-12-24 13:28:59 -08002218 // repaint the framebuffer (if needed)
2219 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002220
David Sodmanfa9b2af2017-12-24 13:28:59 -08002221 display->dirtyRegion.clear();
2222 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002223 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002224 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002225}
2226
David Sodmanfa9b2af2017-12-24 13:28:59 -08002227void SurfaceFlinger::postFrame()
2228{
2229 // |mStateLock| not needed as we are on the main thread
2230 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2231 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2232 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2233 logFrameStats();
2234 }
2235 }
2236}
2237
2238void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002239{
Mathias Agopian841cde52012-03-01 15:44:37 -08002240 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002241 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002242
David Sodmanfa9b2af2017-12-24 13:28:59 -08002243 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002244
David Sodmanfa9b2af2017-12-24 13:28:59 -08002245 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002246 const auto displayId = display->getId();
2247 if (displayId >= 0) {
2248 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002249 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002250 display->onSwapBuffersCompleted();
2251 display->makeCurrent();
David Sodman10a41ff2018-08-05 12:14:17 -07002252 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002253 sp<Fence> releaseFence = Fence::NO_FENCE;
Chia-I Wu7b549592017-11-15 09:14:57 -08002254 // The layer buffer from the previous frame (if any) is released
2255 // by HWC only when the release fence from this frame (if any) is
2256 // signaled. Always get the release fence from HWC first.
David Sodman10a41ff2018-08-05 12:14:17 -07002257 auto hwcLayer = compositionInfo.hwc.hwcLayer;
2258 if ((displayId >= 0) && hwcLayer) {
2259 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer.get());
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002260 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002261
2262 // If the layer was client composited in the previous frame, we
2263 // need to merge with the previous client target acquire fence.
2264 // Since we do not track that, always merge with the current
2265 // client target acquire fence when it is available, even though
2266 // this is suboptimal.
David Sodman10a41ff2018-08-05 12:14:17 -07002267 if (compositionInfo.compositionType == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002268 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002269 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002270 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002271
David Sodman10a41ff2018-08-05 12:14:17 -07002272 if (compositionInfo.layer) {
2273 compositionInfo.layer->onLayerDisplayed(releaseFence);
2274 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002275 }
Chia-I Wu83806892017-11-16 10:50:20 -08002276
2277 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002278 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002279 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002280 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002281 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002282 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002283 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002284 }
2285 }
2286
Dominik Laskowski7e045462018-05-30 13:02:02 -07002287 if (displayId >= 0) {
2288 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002289 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002290 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002291}
2292
Mathias Agopian87baae12012-07-31 12:38:26 -07002293void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002294{
Mathias Agopian841cde52012-03-01 15:44:37 -08002295 ATRACE_CALL();
2296
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002297 // here we keep a copy of the drawing state (that is the state that's
2298 // going to be overwritten by handleTransactionLocked()) outside of
2299 // mStateLock so that the side-effects of the State assignment
2300 // don't happen with mStateLock held (which can cause deadlocks).
2301 State drawingState(mDrawingState);
2302
Mathias Agopianca4d3602011-05-19 15:38:14 -07002303 Mutex::Autolock _l(mStateLock);
2304 const nsecs_t now = systemTime();
2305 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002306
Mathias Agopianca4d3602011-05-19 15:38:14 -07002307 // Here we're guaranteed that some transaction flags are set
2308 // so we can call handleTransactionLocked() unconditionally.
2309 // We call getTransactionFlags(), which will also clear the flags,
2310 // with mStateLock held to guarantee that mCurrentState won't change
2311 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002312
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002313 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002314 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002315 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002316
Mathias Agopianca4d3602011-05-19 15:38:14 -07002317 mLastTransactionTime = systemTime() - now;
2318 mDebugInTransaction = 0;
2319 invalidateHwcGeometry();
2320 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002321}
2322
Dominik Laskowski7e045462018-05-30 13:02:02 -07002323DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002324 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002325 // Figure out whether the event is for the primary display or an
2326 // external display by matching the Hwc display id against one for a
2327 // connected display. If we did not find a match, we then check what
2328 // displays are not already connected to determine the type. If we don't
2329 // have a connected primary display, we assume the new display is meant to
2330 // be the primary display, and then if we don't have an external display,
2331 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002332 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2333 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002334 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002335 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002336 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002337 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002338 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002339 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002340 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002341 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002342 return DisplayDevice::DISPLAY_EXTERNAL;
2343 }
2344
2345 return DisplayDevice::DISPLAY_ID_INVALID;
2346}
2347
Lloyd Piqueba04e622017-12-14 17:11:26 -08002348void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2349 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002350 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002351 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002352 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002353 continue;
2354 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002355
2356 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2357 ALOGE("External displays are not supported by the vr hardware composer.");
2358 continue;
2359 }
2360
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002361 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002362 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002363 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002364 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002365 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002366
2367 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002368 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002369 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002370 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002371 DisplayDeviceState info;
2372 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002373 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2374 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002375 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002376 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002377 mInterceptor->saveDisplayCreation(info);
2378 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002379 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002380 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002381
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002382 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002383 if (idx >= 0) {
2384 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002385 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002386 mCurrentState.displays.removeItemsAt(idx);
2387 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002388 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002389 }
2390
2391 processDisplayChangesLocked();
2392 }
2393
2394 mPendingHotplugEvents.clear();
2395}
2396
Lloyd Pique99d3da52018-01-22 17:48:03 -08002397sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002398 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002399 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002400 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002401 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002402 HdrCapabilities hdrCapabilities;
2403 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002404
Peiyong Lin13effd12018-07-24 17:01:47 -07002405 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002406 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002407 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002408 if (isWideColorMode(colorMode)) {
2409 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002410 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002411
Dominik Laskowski7e045462018-05-30 13:02:02 -07002412 std::vector<RenderIntent> renderIntents =
2413 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002414 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002415 }
tangrobin6753a022018-08-10 10:58:54 +08002416 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002417
tangrobin6753a022018-08-10 10:58:54 +08002418 if (displayId >= 0) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002419 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2420 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2421 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002422
2423 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2424 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2425
2426 /*
2427 * Create our display's surface
2428 */
Peiyong Lin833074a2018-08-28 11:53:54 -07002429 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002430 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002431 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002432 renderSurface->setNativeWindow(nativeWindow.get());
2433 const int displayWidth = renderSurface->queryWidth();
2434 const int displayHeight = renderSurface->queryHeight();
2435
2436 // Make sure that composition can never be stalled by a virtual display
2437 // consumer that isn't processing buffers fast enough. We have to do this
2438 // in two places:
2439 // * Here, in case the display is composed entirely by HWC.
2440 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2441 // window's swap interval in eglMakeCurrent, so they'll override the
2442 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002443 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002444 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2445 }
2446
Chia-I Wua02871c2018-08-27 14:38:23 -07002447 const int displayInstallOrientation = state.type == DisplayDevice::DISPLAY_PRIMARY ?
2448 primaryDisplayOrientation : DisplayState::eOrientationDefault;
2449
Lloyd Pique99d3da52018-01-22 17:48:03 -08002450 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002451 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002452
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002453 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002454 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2455 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
Chia-I Wua02871c2018-08-27 14:38:23 -07002456 displayHeight, displayInstallOrientation, hasWideColorGamut,
2457 hdrCapabilities, supportedPerFrameMetadata, hwcColorModes,
2458 initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002459
2460 if (maxFrameBufferAcquiredBuffers >= 3) {
2461 nativeWindowSurface->preallocateBuffers();
2462 }
2463
2464 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002465 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2466 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002467 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002468 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002469 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002470 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002471 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002472 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002473 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002474 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002475 display->setLayerStack(state.layerStack);
2476 display->setProjection(state.orientation, state.viewport, state.frame);
2477 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002478
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002479 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002480}
2481
Lloyd Pique347200f2017-12-14 17:00:15 -08002482void SurfaceFlinger::processDisplayChangesLocked() {
2483 // here we take advantage of Vector's copy-on-write semantics to
2484 // improve performance by skipping the transaction entirely when
2485 // know that the lists are identical
2486 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2487 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2488 if (!curr.isIdenticalTo(draw)) {
2489 mVisibleRegionsDirty = true;
2490 const size_t cc = curr.size();
2491 size_t dc = draw.size();
2492
2493 // find the displays that were removed
2494 // (ie: in drawing state but not in current state)
2495 // also handle displays that changed
2496 // (ie: displays that are in both lists)
2497 for (size_t i = 0; i < dc;) {
2498 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2499 if (j < 0) {
2500 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002501 // Call makeCurrent() on the primary display so we can
2502 // be sure that nothing associated with this display
2503 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002504 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2505 defaultDisplay->makeCurrent();
2506 }
2507 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2508 display->disconnect(getHwComposer());
2509 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002510 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2511 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2512 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2513 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2514 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002515 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002516 } else {
2517 // this display is in both lists. see if something changed.
2518 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002519 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002520 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2521 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2522 if (state_binder != draw_binder) {
2523 // changing the surface is like destroying and
2524 // recreating the DisplayDevice, so we just remove it
2525 // from the drawing state, so that it get re-added
2526 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002527 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2528 display->disconnect(getHwComposer());
2529 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002530 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002531 mDrawingState.displays.removeItemsAt(i);
2532 dc--;
2533 // at this point we must loop to the next item
2534 continue;
2535 }
2536
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002537 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002538 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002539 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002540 }
2541 if ((state.orientation != draw[i].orientation) ||
2542 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002543 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002544 }
2545 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002546 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002547 }
2548 }
2549 }
2550 ++i;
2551 }
2552
2553 // find displays that were added
2554 // (ie: in current state but not in drawing state)
2555 for (size_t i = 0; i < cc; i++) {
2556 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2557 const DisplayDeviceState& state(curr[i]);
2558
2559 sp<DisplaySurface> dispSurface;
2560 sp<IGraphicBufferProducer> producer;
2561 sp<IGraphicBufferProducer> bqProducer;
2562 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002563 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002564
Dominik Laskowski7e045462018-05-30 13:02:02 -07002565 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002566 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002567 // Virtual displays without a surface are dormant:
2568 // they have external state (layer stack, projection,
2569 // etc.) but no internal state (i.e. a DisplayDevice).
2570 if (state.surface != nullptr) {
2571 // Allow VR composer to use virtual displays.
2572 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2573 int width = 0;
2574 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2575 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2576 int height = 0;
2577 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2578 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2579 int intFormat = 0;
2580 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2581 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002582 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002583
Dominik Laskowski7e045462018-05-30 13:02:02 -07002584 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2585 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002586 }
2587
2588 // TODO: Plumb requested format back up to consumer
2589
2590 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002591 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002592 bqProducer, bqConsumer,
2593 state.displayName);
2594
2595 dispSurface = vds;
2596 producer = vds;
2597 }
2598 } else {
2599 ALOGE_IF(state.surface != nullptr,
2600 "adding a supported display, but rendering "
2601 "surface is provided (%p), ignoring it",
2602 state.surface.get());
2603
Dominik Laskowski7e045462018-05-30 13:02:02 -07002604 displayId = state.type;
2605 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002606 producer = bqProducer;
2607 }
2608
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002609 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002610 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002611 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002612 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002613 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002614 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002615 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2616 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2617 true);
2618 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2619 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2620 true);
2621 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002622 }
2623 }
2624 }
2625 }
2626 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002627
2628 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002629}
2630
Mathias Agopian87baae12012-07-31 12:38:26 -07002631void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002632{
Dan Stoza7dde5992015-05-22 09:51:44 -07002633 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002634 mCurrentState.traverseInZOrder([](Layer* layer) {
2635 layer->notifyAvailableFrames();
2636 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002637
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002638 /*
2639 * Traversal of the children
2640 * (perform the transaction for each of them if needed)
2641 */
2642
Mathias Agopian3559b072012-08-15 13:46:03 -07002643 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002644 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002645 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002646 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002647
2648 const uint32_t flags = layer->doTransaction(0);
2649 if (flags & Layer::eVisibleRegion)
2650 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002651 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002652 }
2653
2654 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002655 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002656 */
2657
Mathias Agopiane57f2922012-08-09 16:29:12 -07002658 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002659 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002660 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002661 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002662
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002663 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002664 // The transform hint might have changed for some layers
2665 // (either because a display has changed, or because a layer
2666 // as changed).
2667 //
2668 // Walk through all the layers in currentLayers,
2669 // and update their transform hint.
2670 //
2671 // If a layer is visible only on a single display, then that
2672 // display is used to calculate the hint, otherwise we use the
2673 // default display.
2674 //
2675 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2676 // the hint is set before we acquire a buffer from the surface texture.
2677 //
2678 // NOTE: layer transactions have taken place already, so we use their
2679 // drawing state. However, SurfaceFlinger's own transaction has not
2680 // happened yet, so we must use the current state layer list
2681 // (soon to become the drawing state list).
2682 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002683 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002684 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002685 bool first = true;
2686 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002687 // NOTE: we rely on the fact that layers are sorted by
2688 // layerStack first (so we don't have to traverse the list
2689 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002690 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002691 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002692 currentlayerStack = layerStack;
2693 // figure out if this layerstack is mirrored
2694 // (more than one display) if so, pick the default display,
2695 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002696 hintDisplay = nullptr;
2697 for (const auto& [token, display] : mDisplays) {
2698 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2699 if (hintDisplay) {
2700 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002701 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002702 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002703 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002704 }
2705 }
2706 }
2707 }
Chet Haase91d25932013-04-11 15:24:55 -07002708
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002709 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002710 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2711 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002712
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002713 // could be null when this layer is using a layerStack
2714 // that is not visible on any display. Also can occur at
2715 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002716 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002717 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002718
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002719 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002720 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002721 if (hintDisplay) {
2722 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002723 }
Robert Carr2047fae2016-11-28 14:09:09 -08002724
2725 first = false;
2726 });
Mathias Agopian84300952012-11-21 16:02:13 -08002727 }
2728
2729
Mathias Agopian3559b072012-08-15 13:46:03 -07002730 /*
2731 * Perform our own transaction if needed
2732 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002733
2734 if (mLayersAdded) {
2735 mLayersAdded = false;
2736 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002737 mVisibleRegionsDirty = true;
2738 }
2739
2740 // some layers might have been removed, so
2741 // we need to update the regions they're exposing.
2742 if (mLayersRemoved) {
2743 mLayersRemoved = false;
2744 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002745 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002746 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002747 // this layer is not visible anymore
2748 // TODO: we could traverse the tree from front to back and
2749 // compute the actual visible region
2750 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002751 Region visibleReg;
2752 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002753 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002754 }
Robert Carr2047fae2016-11-28 14:09:09 -08002755 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002756 }
2757
2758 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002759
2760 updateCursorAsync();
2761}
2762
2763void SurfaceFlinger::updateCursorAsync()
2764{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002765 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002766 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002767 continue;
2768 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002769
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002770 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2771 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002772 }
2773 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002774}
2775
2776void SurfaceFlinger::commitTransaction()
2777{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002778 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002779 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002780 for (const auto& l : mLayersPendingRemoval) {
2781 recordBufferingStats(l->getName().string(),
2782 l->getOccupancyHistory(true));
2783 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002784 }
2785 mLayersPendingRemoval.clear();
2786 }
2787
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002788 // If this transaction is part of a window animation then the next frame
2789 // we composite should be considered an animation as well.
2790 mAnimCompositionPending = mAnimTransactionPending;
2791
Mathias Agopian4fec8732012-06-29 14:12:52 -07002792 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002793 // clear the "changed" flags in current state
2794 mCurrentState.colorMatrixChanged = false;
2795
Robert Carr1f0a16a2016-10-24 16:27:39 -07002796 mDrawingState.traverseInZOrder([](Layer* layer) {
2797 layer->commitChildList();
2798 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002799 mTransactionPending = false;
2800 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002801 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002802}
2803
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002804void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2805 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002806 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002807 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002808
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002809 Region aboveOpaqueLayers;
2810 Region aboveCoveredLayers;
2811 Region dirty;
2812
Mathias Agopian87baae12012-07-31 12:38:26 -07002813 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002814
Robert Carr2047fae2016-11-28 14:09:09 -08002815 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002816 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002817 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002818
Jesse Hall01e29052013-02-19 16:13:35 -08002819 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002820 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002821 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002822 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002823
Mathias Agopianab028732010-03-16 16:41:46 -07002824 /*
2825 * opaqueRegion: area of a surface that is fully opaque.
2826 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002827 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002828
2829 /*
2830 * visibleRegion: area of a surface that is visible on screen
2831 * and not fully transparent. This is essentially the layer's
2832 * footprint minus the opaque regions above it.
2833 * Areas covered by a translucent surface are considered visible.
2834 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002835 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002836
2837 /*
2838 * coveredRegion: area of a surface that is covered by all
2839 * visible regions above it (which includes the translucent areas).
2840 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002841 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002842
Jesse Halla8026d22012-09-25 13:25:04 -07002843 /*
2844 * transparentRegion: area of a surface that is hinted to be completely
2845 * transparent. This is only used to tell when the layer has no visible
2846 * non-transparent regions and can be removed from the layer list. It
2847 * does not affect the visibleRegion of this layer or any layers
2848 * beneath it. The hint may not be correct if apps don't respect the
2849 * SurfaceView restrictions (which, sadly, some don't).
2850 */
2851 Region transparentRegion;
2852
Mathias Agopianab028732010-03-16 16:41:46 -07002853
2854 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002855 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002856 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002857 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002858 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002859 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002860 if (!visibleRegion.isEmpty()) {
2861 // Remove the transparent area from the visible region
2862 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002863 if (tr.preserveRects()) {
2864 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002865 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002866 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002867 // transformation too complex, can't do the
2868 // transparent region optimization.
2869 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002870 }
Mathias Agopianab028732010-03-16 16:41:46 -07002871 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002872
Mathias Agopianab028732010-03-16 16:41:46 -07002873 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002874 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002875 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002876 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002877 // the opaque region is the layer's footprint
2878 opaqueRegion = visibleRegion;
2879 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002880 }
2881 }
2882
Robert Carre5f4f692018-01-12 13:12:28 -08002883 if (visibleRegion.isEmpty()) {
2884 layer->clearVisibilityRegions();
2885 return;
2886 }
2887
Mathias Agopianab028732010-03-16 16:41:46 -07002888 // Clip the covered region to the visible region
2889 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2890
2891 // Update aboveCoveredLayers for next (lower) layer
2892 aboveCoveredLayers.orSelf(visibleRegion);
2893
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002894 // subtract the opaque region covered by the layers above us
2895 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002896
2897 // compute this layer's dirty region
2898 if (layer->contentDirty) {
2899 // we need to invalidate the whole region
2900 dirty = visibleRegion;
2901 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002902 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002903 layer->contentDirty = false;
2904 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002905 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002906 * the exposed region consists of two components:
2907 * 1) what's VISIBLE now and was COVERED before
2908 * 2) what's EXPOSED now less what was EXPOSED before
2909 *
2910 * note that (1) is conservative, we start with the whole
2911 * visible region but only keep what used to be covered by
2912 * something -- which mean it may have been exposed.
2913 *
2914 * (2) handles areas that were not covered by anything but got
2915 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002916 */
Mathias Agopianab028732010-03-16 16:41:46 -07002917 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002918 const Region oldVisibleRegion = layer->visibleRegion;
2919 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002920 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2921 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002922 }
2923 dirty.subtractSelf(aboveOpaqueLayers);
2924
2925 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002926 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002927
Mathias Agopianab028732010-03-16 16:41:46 -07002928 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002929 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002930
Jesse Halla8026d22012-09-25 13:25:04 -07002931 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002932 layer->setVisibleRegion(visibleRegion);
2933 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002934 layer->setVisibleNonTransparentRegion(
2935 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002936 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002937
Mathias Agopian87baae12012-07-31 12:38:26 -07002938 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002939}
2940
Chia-I Wuab0c3192017-08-01 11:29:00 -07002941void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002942 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002943 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2944 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002945 }
2946 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002947}
2948
Dan Stoza6b9454d2014-11-07 16:00:59 -08002949bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002950{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002951 ALOGV("handlePageFlip");
2952
Brian Andersond6927fb2016-07-23 23:37:30 -07002953 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002954
Mathias Agopian4fec8732012-06-29 14:12:52 -07002955 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002956 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002957 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002958
2959 // Store the set of layers that need updates. This set must not change as
2960 // buffers are being latched, as this could result in a deadlock.
2961 // Example: Two producers share the same command stream and:
2962 // 1.) Layer 0 is latched
2963 // 2.) Layer 0 gets a new frame
2964 // 2.) Layer 1 gets a new frame
2965 // 3.) Layer 1 is latched.
2966 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2967 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002968 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002969 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002970 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07002971 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002972 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002973 } else {
2974 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002975 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002976 } else {
2977 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002978 }
Robert Carr2047fae2016-11-28 14:09:09 -08002979 });
2980
Dan Stoza9e56aa02015-11-02 13:00:03 -08002981 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002982 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002983 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002984 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002985 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002986 newDataLatched = true;
2987 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002988 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002989
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002990 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002991
2992 // If we will need to wake up at some time in the future to deal with a
2993 // queued frame that shouldn't be displayed during this vsync period, wake
2994 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002995 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002996 signalLayerUpdate();
2997 }
2998
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002999 // enter boot animation on first buffer latch
3000 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3001 ALOGI("Enter boot animation");
3002 mBootStage = BootStage::BOOTANIMATION;
3003 }
3004
Dan Stoza6b9454d2014-11-07 16:00:59 -08003005 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003006 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003007}
3008
Mathias Agopianad456f92011-01-13 17:53:01 -08003009void SurfaceFlinger::invalidateHwcGeometry()
3010{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003011 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003012}
3013
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003014void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
3015 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003016 // We only need to actually compose the display if:
3017 // 1) It is being handled by hardware composer, which may need this to
3018 // keep its virtual display state machine in sync, or
3019 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07003020 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08003021 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003022 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003023 return;
3024 }
3025
Dan Stoza9e56aa02015-11-02 13:00:03 -08003026 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003027 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003028
3029 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003030 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003031}
3032
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003033bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003034 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003035
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003036 const Region bounds(display->bounds());
3037 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003038 const auto displayId = display->getId();
3039 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003040 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003041
Chia-I Wu8e50e692018-05-04 10:12:37 -07003042 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003043 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003044
Dan Stoza9e56aa02015-11-02 13:00:03 -08003045 if (hasClientComposition) {
3046 ALOGV("hasClientComposition");
3047
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003048 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003049 if (display->hasWideColorGamut()) {
3050 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003051 }
3052 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003053 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003054 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003055
Dominik Laskowski7e045462018-05-30 13:02:02 -07003056 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003057 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3058 HWC2::Capability::SkipClientColorTransform);
3059
Chia-I Wud49d6692018-06-27 07:17:41 +08003060 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003061 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3062 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003063 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003064 }
3065
Chia-I Wud49d6692018-06-27 07:17:41 +08003066 // The current enhanced saturation matrix is designed to enhance Display P3,
3067 // thus we only apply this matrix when the render intent is not colorimetric
3068 // and the output color space is Display P3.
3069 needsEnhancedColorMatrix =
3070 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3071 outputDataspace == Dataspace::DISPLAY_P3);
3072 if (needsEnhancedColorMatrix) {
3073 colorMatrix *= mEnhancedSaturationMatrix;
3074 }
3075
3076 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003077
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003078 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003079 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003080 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003081 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003082
3083 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003084 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3085 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3086 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003087 }
3088 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003089 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003090
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003091 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003092 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003093 // when using overlays, we assume a fully transparent framebuffer
3094 // NOTE: we could reduce how much we need to clear, for instance
3095 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003096 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003097 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003098 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003099 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003100 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003101 // we're left with the letterbox region
3102 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003103 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003104
3105 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003106 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003107
Mathias Agopianb9494d52012-04-18 02:28:45 -07003108 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003109 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003110 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003111 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003112 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003113 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003114
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003115 const Rect& bounds = display->getBounds();
3116 const Rect& scissor = display->getScissor();
3117 if (scissor != bounds) {
3118 // scissor doesn't match the screen's dimensions, so we
3119 // need to clear everything outside of it and enable
3120 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003121
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003122 // enable scissor for this frame
3123 const uint32_t height = display->getHeight();
3124 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
3125 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003126 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003127 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003128
Mathias Agopian85d751c2012-08-29 16:59:24 -07003129 /*
3130 * and then, render the layers targeted at the framebuffer
3131 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003132
Dan Stoza9e56aa02015-11-02 13:00:03 -08003133 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003134 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003135 bool firstLayer = true;
David Sodmanfb95bcc2017-12-22 15:45:30 -08003136 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
3137 const Region bounds(display->bounds());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003138 const Region clip(bounds.intersect(
David Sodmanfb95bcc2017-12-22 15:45:30 -08003139 displayTransform.transform(compositionInfo.layer->mLayer->visibleRegion)));
3140 ALOGV("Layer: %s", compositionInfo.layerName.c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003141 if (!clip.isEmpty()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08003142 switch (compositionInfo.compositionType) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003143 case HWC2::Composition::Cursor:
3144 case HWC2::Composition::Device:
3145 case HWC2::Composition::Sideband:
3146 case HWC2::Composition::SolidColor: {
David Sodmanfb95bcc2017-12-22 15:45:30 -08003147 const Layer::State& state(compositionInfo.layer->mLayer->getDrawingState());
3148 const bool opaque = compositionInfo.layer->mLayer->isOpaque(state);
3149 if (compositionInfo.hwc.clearClientTarget && !firstLayer &&
3150 opaque && (state.color.a == 1.0f) && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003151 // never clear the very first layer since we're
3152 // guaranteed the FB is already cleared
David Sodman10a41ff2018-08-05 12:14:17 -07003153 compositionInfo.layer->clear(getRenderEngine());
Mathias Agopiancd60f992012-08-16 16:28:27 -07003154 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003155 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003156 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003157 case HWC2::Composition::Client: {
David Sodmanfb95bcc2017-12-22 15:45:30 -08003158 compositionInfo.layer->mLayer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003159 break;
3160 }
3161 default:
3162 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003163 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003164 } else {
3165 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003166 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003167 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003168 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003169
Chia-I Wud49d6692018-06-27 07:17:41 +08003170 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003171 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003172 }
3173
Mathias Agopianf45c5102012-10-24 16:29:17 -07003174 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003175 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003176 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003177}
3178
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003179void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
3180 const Region& region) const {
3181 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003182 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003183 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003184}
3185
Dan Stoza7d89d062015-04-30 13:29:25 -07003186status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003187 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003188 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003189 const sp<Layer>& lbc,
3190 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003191{
Dan Stoza7d89d062015-04-30 13:29:25 -07003192 // add this layer to the current state list
3193 {
3194 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003195 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003196 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3197 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003198 return NO_MEMORY;
3199 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003200 if (parent == nullptr) {
3201 mCurrentState.layersSortedByZ.add(lbc);
3202 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003203 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003204 ALOGE("addClientLayer called with a removed parent");
3205 return NAME_NOT_FOUND;
3206 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003207 parent->addChild(lbc);
3208 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003209
Yiwei Zhang243b3782018-05-15 17:40:04 -07003210 if (gbc != nullptr) {
3211 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3212 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3213 mMaxGraphicBufferProducerListSize,
3214 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3215 mGraphicBufferProducerList.size(),
3216 mMaxGraphicBufferProducerListSize, mNumLayers);
3217 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003218 mLayersAdded = true;
3219 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003220 }
3221
Mathias Agopian96f08192010-06-02 23:28:45 -07003222 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003223 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003224
Dan Stoza7d89d062015-04-30 13:29:25 -07003225 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003226}
3227
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003228status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003229 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003230 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3231}
Robert Carr7f9b8992017-03-10 11:08:39 -08003232
chaviwca27f252018-02-06 16:46:39 -08003233status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3234 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003235 if (layer->isPendingRemoval()) {
3236 return NO_ERROR;
3237 }
3238
Robert Carr1f0a16a2016-10-24 16:27:39 -07003239 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003240 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003241 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003242 if (topLevelOnly) {
3243 return NO_ERROR;
3244 }
3245
Chia-I Wu98f1c102017-05-30 14:54:08 -07003246 sp<Layer> ancestor = p;
3247 while (ancestor->getParent() != nullptr) {
3248 ancestor = ancestor->getParent();
3249 }
3250 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3251 ALOGE("removeLayer called with a layer whose parent has been removed");
3252 return NAME_NOT_FOUND;
3253 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003254
3255 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003256 } else {
3257 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003258 }
3259
Robert Carr136e2f62017-02-08 17:54:29 -08003260 // As a matter of normal operation, the LayerCleaner will produce a second
3261 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3262 // so we will succeed in promoting it, but it's already been removed
3263 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3264 // otherwise something has gone wrong and we are leaking the layer.
3265 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003266 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3267 layer->getName().string(),
3268 (p != nullptr) ? p->getName().string() : "no-parent");
3269 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003270 } else if (index < 0) {
3271 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003272 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003273
Chia-I Wuc6657022017-08-15 11:18:17 -07003274 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003275 mLayersPendingRemoval.add(layer);
3276 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003277 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003278 setTransactionFlags(eTransactionNeeded);
3279 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003280}
3281
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003282uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003283 return android_atomic_release_load(&mTransactionFlags);
3284}
3285
Mathias Agopian3f844832013-08-07 21:24:32 -07003286uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003287 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3288}
3289
Mathias Agopian3f844832013-08-07 21:24:32 -07003290uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003291 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3292}
3293
3294uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3295 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003296 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003297 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003298 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003299 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003300 }
3301 return old;
3302}
3303
chaviwca27f252018-02-06 16:46:39 -08003304bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3305 for (const ComposerState& state : states) {
3306 // Here we need to check that the interface we're given is indeed
3307 // one of our own. A malicious client could give us a nullptr
3308 // IInterface, or one of its own or even one of our own but a
3309 // different type. All these situations would cause us to crash.
3310 if (state.client == nullptr) {
3311 return true;
3312 }
3313
3314 sp<IBinder> binder = IInterface::asBinder(state.client);
3315 if (binder == nullptr) {
3316 return true;
3317 }
3318
3319 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3320 return true;
3321 }
3322 }
3323 return false;
3324}
3325
Mathias Agopian8b33f032012-07-24 20:43:54 -07003326void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003327 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003328 const Vector<DisplayState>& displays,
3329 uint32_t flags)
3330{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003331 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003332 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003333 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003334
chaviwca27f252018-02-06 16:46:39 -08003335 if (containsAnyInvalidClientState(states)) {
3336 return;
3337 }
3338
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003339 if (flags & eAnimation) {
3340 // For window updates that are part of an animation we must wait for
3341 // previous animation "frames" to be handled.
3342 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003343 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003344 if (CC_UNLIKELY(err != NO_ERROR)) {
3345 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003346 // caller after a few seconds.
3347 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3348 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003349 mAnimTransactionPending = false;
3350 break;
3351 }
3352 }
3353 }
3354
chaviwca27f252018-02-06 16:46:39 -08003355 for (const DisplayState& display : displays) {
3356 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003357 }
3358
chaviwca27f252018-02-06 16:46:39 -08003359 for (const ComposerState& state : states) {
3360 transactionFlags |= setClientStateLocked(state);
3361 }
3362
3363 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3364 // as destroyed should only occur after setting all other states. This is to allow for a
3365 // child re-parent to happen before marking its original parent as destroyed (which would
3366 // then mark the child as destroyed).
3367 for (const ComposerState& state : states) {
3368 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003369 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003370
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003371 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3372 // anyway. This can be used as a flush mechanism for previous async transactions.
3373 // Empty animation transaction can be used to simulate back-pressure, so also force a
3374 // transaction for empty animation transactions.
3375 if (transactionFlags == 0 &&
3376 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003377 transactionFlags = eTransactionNeeded;
3378 }
3379
Mathias Agopian386aa982011-11-07 21:58:03 -08003380 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003381 if (mInterceptor->isEnabled()) {
3382 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003383 }
Irvel468051e2016-06-13 16:44:44 -07003384
Mathias Agopian386aa982011-11-07 21:58:03 -08003385 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003386 const auto start = (flags & eEarlyWakeup)
3387 ? VSyncModulator::TransactionStart::EARLY
3388 : VSyncModulator::TransactionStart::NORMAL;
3389 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003390
3391 // if this is a synchronous transaction, wait for it to take effect
3392 // before returning.
3393 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003394 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003395 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003396 if (flags & eAnimation) {
3397 mAnimTransactionPending = true;
3398 }
3399 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003400 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3401 if (CC_UNLIKELY(err != NO_ERROR)) {
3402 // just in case something goes wrong in SF, return to the
3403 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003404 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3405 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003406 break;
3407 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003408 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003409 }
3410}
3411
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003412uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3413 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3414 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003415
Mathias Agopiane57f2922012-08-09 16:29:12 -07003416 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003417 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3418
3419 const uint32_t what = s.what;
3420 if (what & DisplayState::eSurfaceChanged) {
3421 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3422 state.surface = s.surface;
3423 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003424 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003425 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003426 if (what & DisplayState::eLayerStackChanged) {
3427 if (state.layerStack != s.layerStack) {
3428 state.layerStack = s.layerStack;
3429 flags |= eDisplayTransactionNeeded;
3430 }
3431 }
3432 if (what & DisplayState::eDisplayProjectionChanged) {
3433 if (state.orientation != s.orientation) {
3434 state.orientation = s.orientation;
3435 flags |= eDisplayTransactionNeeded;
3436 }
3437 if (state.frame != s.frame) {
3438 state.frame = s.frame;
3439 flags |= eDisplayTransactionNeeded;
3440 }
3441 if (state.viewport != s.viewport) {
3442 state.viewport = s.viewport;
3443 flags |= eDisplayTransactionNeeded;
3444 }
3445 }
3446 if (what & DisplayState::eDisplaySizeChanged) {
3447 if (state.width != s.width) {
3448 state.width = s.width;
3449 flags |= eDisplayTransactionNeeded;
3450 }
3451 if (state.height != s.height) {
3452 state.height = s.height;
3453 flags |= eDisplayTransactionNeeded;
3454 }
3455 }
3456
Mathias Agopiane57f2922012-08-09 16:29:12 -07003457 return flags;
3458}
3459
Robert Carrd4ae7f32018-06-07 16:10:57 -07003460bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3461 IPCThreadState* ipc = IPCThreadState::self();
3462 const int pid = ipc->getCallingPid();
3463 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003464 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003465 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003466 return false;
3467 }
3468 return true;
3469}
3470
chaviwca27f252018-02-06 16:46:39 -08003471uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3472 const layer_state_t& s = composerState.state;
3473 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3474
Mathias Agopian13127d82013-03-05 17:47:11 -08003475 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003476 if (layer == nullptr) {
3477 return 0;
3478 }
3479
3480 if (layer->isPendingRemoval()) {
3481 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3482 return 0;
3483 }
3484
3485 uint32_t flags = 0;
3486
3487 const uint32_t what = s.what;
3488 bool geometryAppliesWithResize =
3489 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003490
3491 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3492 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003493 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003494 layer->pushPendingState();
3495 }
3496
chaviw8b3871a2017-11-01 17:41:01 -07003497 if (what & layer_state_t::ePositionChanged) {
3498 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3499 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003500 }
chaviw8b3871a2017-11-01 17:41:01 -07003501 }
3502 if (what & layer_state_t::eLayerChanged) {
3503 // NOTE: index needs to be calculated before we update the state
3504 const auto& p = layer->getParent();
3505 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003506 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003507 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003508 mCurrentState.layersSortedByZ.removeAt(idx);
3509 mCurrentState.layersSortedByZ.add(layer);
3510 // we need traversal (state changed)
3511 // AND transaction (list changed)
3512 flags |= eTransactionNeeded|eTraversalNeeded;
3513 }
chaviw8b3871a2017-11-01 17:41:01 -07003514 } else {
3515 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003516 flags |= eTransactionNeeded|eTraversalNeeded;
3517 }
3518 }
chaviw8b3871a2017-11-01 17:41:01 -07003519 }
3520 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003521 // NOTE: index needs to be calculated before we update the state
3522 const auto& p = layer->getParent();
3523 if (p == nullptr) {
3524 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3525 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3526 mCurrentState.layersSortedByZ.removeAt(idx);
3527 mCurrentState.layersSortedByZ.add(layer);
3528 // we need traversal (state changed)
3529 // AND transaction (list changed)
3530 flags |= eTransactionNeeded|eTraversalNeeded;
3531 }
3532 } else {
3533 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3534 flags |= eTransactionNeeded|eTraversalNeeded;
3535 }
chaviw8b3871a2017-11-01 17:41:01 -07003536 }
3537 }
3538 if (what & layer_state_t::eSizeChanged) {
3539 if (layer->setSize(s.w, s.h)) {
3540 flags |= eTraversalNeeded;
3541 }
3542 }
3543 if (what & layer_state_t::eAlphaChanged) {
3544 if (layer->setAlpha(s.alpha))
3545 flags |= eTraversalNeeded;
3546 }
3547 if (what & layer_state_t::eColorChanged) {
3548 if (layer->setColor(s.color))
3549 flags |= eTraversalNeeded;
3550 }
3551 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003552 // TODO: b/109894387
3553 //
3554 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3555 // rotation. To see the problem observe that if we have a square parent, and a child
3556 // of the same size, then we rotate the child 45 degrees around it's center, the child
3557 // must now be cropped to a non rectangular 8 sided region.
3558 //
3559 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3560 // private API, and the WindowManager only uses rotation in one case, which is on a top
3561 // level layer in which cropping is not an issue.
3562 //
3563 // However given that abuse of rotation matrices could lead to surfaces extending outside
3564 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3565 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3566 // transformations.
3567 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003568 flags |= eTraversalNeeded;
3569 }
3570 if (what & layer_state_t::eTransparentRegionChanged) {
3571 if (layer->setTransparentRegionHint(s.transparentRegion))
3572 flags |= eTraversalNeeded;
3573 }
3574 if (what & layer_state_t::eFlagsChanged) {
3575 if (layer->setFlags(s.flags, s.mask))
3576 flags |= eTraversalNeeded;
3577 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003578 if (what & layer_state_t::eCropChanged_legacy) {
3579 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003580 flags |= eTraversalNeeded;
3581 }
chaviw8b3871a2017-11-01 17:41:01 -07003582 if (what & layer_state_t::eLayerStackChanged) {
3583 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3584 // We only allow setting layer stacks for top level layers,
3585 // everything else inherits layer stack from its parent.
3586 if (layer->hasParent()) {
3587 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3588 layer->getName().string());
3589 } else if (idx < 0) {
3590 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3591 "that also does not appear in the top level layer list. Something"
3592 " has gone wrong.", layer->getName().string());
3593 } else if (layer->setLayerStack(s.layerStack)) {
3594 mCurrentState.layersSortedByZ.removeAt(idx);
3595 mCurrentState.layersSortedByZ.add(layer);
3596 // we need traversal (state changed)
3597 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003598 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003599 }
3600 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003601 if (what & layer_state_t::eDeferTransaction_legacy) {
3602 if (s.barrierHandle_legacy != nullptr) {
3603 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3604 } else if (s.barrierGbp_legacy != nullptr) {
3605 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003606 if (authenticateSurfaceTextureLocked(gbp)) {
3607 const auto& otherLayer =
3608 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003609 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003610 } else {
3611 ALOGE("Attempt to defer transaction to to an"
3612 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003613 }
3614 }
chaviw8b3871a2017-11-01 17:41:01 -07003615 // We don't trigger a traversal here because if no other state is
3616 // changed, we don't want this to cause any more work
3617 }
3618 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003619 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003620 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003621 if (!hadParent) {
3622 mCurrentState.layersSortedByZ.remove(layer);
3623 }
chaviw8b3871a2017-11-01 17:41:01 -07003624 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003625 }
chaviw8b3871a2017-11-01 17:41:01 -07003626 }
3627 if (what & layer_state_t::eReparentChildren) {
3628 if (layer->reparentChildren(s.reparentHandle)) {
3629 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003630 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003631 }
chaviw8b3871a2017-11-01 17:41:01 -07003632 if (what & layer_state_t::eDetachChildren) {
3633 layer->detachChildren();
3634 }
3635 if (what & layer_state_t::eOverrideScalingModeChanged) {
3636 layer->setOverrideScalingMode(s.overrideScalingMode);
3637 // We don't trigger a traversal here because if no other state is
3638 // changed, we don't want this to cause any more work
3639 }
Marissa Wall61c58622018-07-18 10:12:20 -07003640 if (what & layer_state_t::eTransformChanged) {
3641 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3642 }
3643 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3644 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3645 flags |= eTraversalNeeded;
3646 }
3647 if (what & layer_state_t::eCropChanged) {
3648 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3649 }
3650 if (what & layer_state_t::eBufferChanged) {
3651 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3652 }
3653 if (what & layer_state_t::eAcquireFenceChanged) {
3654 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3655 }
3656 if (what & layer_state_t::eDataspaceChanged) {
3657 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3658 }
3659 if (what & layer_state_t::eHdrMetadataChanged) {
3660 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3661 }
3662 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3663 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3664 }
3665 if (what & layer_state_t::eApiChanged) {
3666 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3667 }
3668 if (what & layer_state_t::eSidebandStreamChanged) {
3669 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3670 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003671 return flags;
3672}
3673
chaviwca27f252018-02-06 16:46:39 -08003674void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3675 const layer_state_t& state = composerState.state;
3676 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3677
3678 sp<Layer> layer(client->getLayerUser(state.surface));
3679 if (layer == nullptr) {
3680 return;
3681 }
3682
3683 if (layer->isPendingRemoval()) {
3684 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3685 return;
3686 }
3687
3688 if (state.what & layer_state_t::eDestroySurface) {
3689 removeLayerLocked(mStateLock, layer);
3690 }
3691}
3692
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003693status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003694 const String8& name,
3695 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003696 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003697 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003698 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003699{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003700 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003701 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003702 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003703 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003704 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003705
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003706 status_t result = NO_ERROR;
3707
3708 sp<Layer> layer;
3709
Cody Northropbc755282017-03-31 12:00:08 -06003710 String8 uniqueName = getUniqueLayerName(name);
3711
Mathias Agopian3165cc22012-08-08 19:42:09 -07003712 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003713 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003714 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3715 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003716
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003717 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003718 case ISurfaceComposerClient::eFXSurfaceBufferState:
3719 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3720 break;
chaviw13fdc492017-06-27 12:40:18 -07003721 case ISurfaceComposerClient::eFXSurfaceColor:
3722 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003723 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003724 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003725 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003726 case ISurfaceComposerClient::eFXSurfaceContainer:
3727 result = createContainerLayer(client,
3728 uniqueName, w, h, flags,
3729 handle, &layer);
3730 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003731 default:
3732 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003733 break;
3734 }
3735
Dan Stoza7d89d062015-04-30 13:29:25 -07003736 if (result != NO_ERROR) {
3737 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003738 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003739
Chia-I Wuab0c3192017-08-01 11:29:00 -07003740 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3741 // TODO b/64227542
3742 if (windowType == 441731) {
3743 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3744 layer->setPrimaryDisplayOnly();
3745 }
3746
Albert Chaulk479c60c2017-01-27 14:21:34 -05003747 layer->setInfo(windowType, ownerUid);
3748
Robert Carr1f0a16a2016-10-24 16:27:39 -07003749 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003750 if (result != NO_ERROR) {
3751 return result;
3752 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003753 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003754
3755 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003756 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003757}
3758
Cody Northropbc755282017-03-31 12:00:08 -06003759String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3760{
3761 bool matchFound = true;
3762 uint32_t dupeCounter = 0;
3763
3764 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3765 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3766
Dan Stoza436ccf32018-06-21 12:10:12 -07003767 // Grab the state lock since we're accessing mCurrentState
3768 Mutex::Autolock lock(mStateLock);
3769
Cody Northropbc755282017-03-31 12:00:08 -06003770 // Loop over layers until we're sure there is no matching name
3771 while (matchFound) {
3772 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003773 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003774 if (layer->getName() == uniqueName) {
3775 matchFound = true;
3776 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3777 }
3778 });
3779 }
3780
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003781 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3782 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003783
3784 return uniqueName;
3785}
3786
Marissa Wallfd668622018-05-10 10:21:13 -07003787status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3788 uint32_t w, uint32_t h, uint32_t flags,
3789 PixelFormat& format, sp<IBinder>* handle,
3790 sp<IGraphicBufferProducer>* gbp,
3791 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003792 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003793 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003794 case PIXEL_FORMAT_TRANSPARENT:
3795 case PIXEL_FORMAT_TRANSLUCENT:
3796 format = PIXEL_FORMAT_RGBA_8888;
3797 break;
3798 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003799 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003800 break;
3801 }
3802
Marissa Wallfd668622018-05-10 10:21:13 -07003803 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3804 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003805 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003806 *handle = layer->getHandle();
3807 *gbp = layer->getProducer();
3808 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003809 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003810
Marissa Wallfd668622018-05-10 10:21:13 -07003811 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003812 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003813}
3814
Marissa Wall61c58622018-07-18 10:12:20 -07003815status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3816 uint32_t w, uint32_t h, uint32_t flags,
3817 sp<IBinder>* handle, sp<Layer>* outLayer) {
3818 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3819 *handle = layer->getHandle();
3820 *outLayer = layer;
3821
3822 return NO_ERROR;
3823}
3824
chaviw13fdc492017-06-27 12:40:18 -07003825status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003826 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003827 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003828{
chaviw13fdc492017-06-27 12:40:18 -07003829 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003830 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003831 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003832}
3833
Robert Carr6b3f6c52018-08-13 13:05:17 -07003834status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3835 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3836 sp<IBinder>* handle, sp<Layer>* outLayer)
3837{
3838 *outLayer = new ContainerLayer(this, client, name, w, h, flags);
3839 *handle = (*outLayer)->getHandle();
3840 return NO_ERROR;
3841}
3842
3843
Mathias Agopianac9fa422013-02-11 16:40:36 -08003844status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003845{
Robert Carr9524cb32017-02-13 11:32:32 -08003846 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003847 status_t err = NO_ERROR;
3848 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003849 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003850 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003851 err = removeLayer(l);
3852 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3853 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003854 }
3855 return err;
3856}
3857
Mathias Agopian13127d82013-03-05 17:47:11 -08003858status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003859{
Mathias Agopian67106042013-03-14 19:18:13 -07003860 // called by ~LayerCleaner() when all references to the IBinder (handle)
3861 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003862 sp<Layer> l = layer.promote();
3863 if (l == nullptr) {
3864 // The layer has already been removed, carry on
3865 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003866 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003867 // If we have a parent, then we can continue to live as long as it does.
3868 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003869}
3870
Mathias Agopianb60314a2012-04-10 22:09:54 -07003871// ---------------------------------------------------------------------------
3872
Andy McFadden13a082e2012-08-24 10:16:42 -07003873void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003874 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3875 if (!displayToken) return;
3876
Jesse Hall01e29052013-02-19 16:13:35 -08003877 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003878 Vector<ComposerState> state;
3879 Vector<DisplayState> displays;
3880 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003881 d.what = DisplayState::eDisplayProjectionChanged |
3882 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003883 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003884 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003885 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003886 d.frame.makeInvalid();
3887 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003888 d.width = 0;
3889 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003890 displays.add(d);
3891 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003892
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003893 const auto display = getDisplayDevice(displayToken);
3894 if (!display) return;
3895
3896 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3897
3898 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003899 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003900 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003901
Brian Andersond0010582017-03-07 13:20:31 -08003902 // Use phase of 0 since phase is not known.
3903 // Use latency of 0, which will snap to the ideal latency.
3904 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003905}
3906
3907void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003908 // Async since we may be called from the main thread.
3909 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003910}
3911
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003912void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3913 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003914 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003915 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003916
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003917 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003918 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003919 return;
3920 }
3921
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003922 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003923 ALOGW("Trying to set power mode for virtual display");
3924 return;
3925 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003926
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003927 display->setPowerMode(mode);
3928
Lloyd Pique4dccc412018-01-22 17:21:36 -08003929 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003930 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003931 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003932 if (idx < 0) {
3933 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3934 return;
3935 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003936 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003937 }
3938
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003939 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003940 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003941 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003942 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003943 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003944 // FIXME: eventthread only knows about the main display right now
3945 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003946 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003947 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003948
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003949 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003950 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003951 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003952
3953 struct sched_param param = {0};
3954 param.sched_priority = 1;
3955 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3956 ALOGW("Couldn't set SCHED_FIFO on display on");
3957 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003958 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003959 // Turn off the display
3960 struct sched_param param = {0};
3961 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3962 ALOGW("Couldn't set SCHED_OTHER on display off");
3963 }
3964
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003965 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003966 disableHardwareVsync(true); // also cancels any in-progress resync
3967
Mathias Agopiancde87a32012-09-13 14:09:01 -07003968 // FIXME: eventthread only knows about the main display right now
3969 mEventThread->onScreenReleased();
3970 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003971
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003972 getHwComposer().setPowerMode(type, mode);
3973 mVisibleRegionsDirty = true;
3974 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003975 } else if (mode == HWC_POWER_MODE_DOZE ||
3976 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003977 // Update display while dozing
3978 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003979 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003980 // FIXME: eventthread only knows about the main display right now
3981 mEventThread->onScreenAcquired();
3982 resyncToHardwareVsync(true);
3983 }
3984 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3985 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003986 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003987 disableHardwareVsync(true); // also cancels any in-progress resync
3988 // FIXME: eventthread only knows about the main display right now
3989 mEventThread->onScreenReleased();
3990 }
3991 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003992 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003993 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003994 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003995 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003996
3997 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003998}
3999
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004000void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004001 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004002 const auto display = getDisplayDevice(displayToken);
4003 if (!display) {
4004 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4005 displayToken.get());
4006 } else if (display->isVirtual()) {
4007 ALOGW("Attempt to set power mode %d for virtual display", mode);
4008 } else {
4009 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004010 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004011 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004012}
4013
4014// ---------------------------------------------------------------------------
4015
Lloyd Pique755e3192018-01-31 16:46:15 -08004016status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4017 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004018 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004019
Mathias Agopianbd115332013-04-18 16:41:04 -07004020 IPCThreadState* ipc = IPCThreadState::self();
4021 const int pid = ipc->getCallingPid();
4022 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004023
Mathias Agopianbd115332013-04-18 16:41:04 -07004024 if ((uid != AID_SHELL) &&
4025 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004026 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07004027 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004028 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004029 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004030 // (this would indicate SF is stuck, but we want to be able to
4031 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004032 status_t err = mStateLock.timedLock(s2ns(1));
4033 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004034 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004035 result.appendFormat(
4036 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4037 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004038 }
4039
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004040 bool dumpAll = true;
4041 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004042 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004043
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004044 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004045 if ((index < numArgs) &&
4046 (args[index] == String16("--list"))) {
4047 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004048 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004049 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004050 }
4051
4052 if ((index < numArgs) &&
4053 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004054 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004055 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004056 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004057 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004058
4059 if ((index < numArgs) &&
4060 (args[index] == String16("--latency-clear"))) {
4061 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004062 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004063 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004064 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004065
4066 if ((index < numArgs) &&
4067 (args[index] == String16("--dispsync"))) {
4068 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004069 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004070 dumpAll = false;
4071 }
Dan Stozab90cf072015-03-05 11:05:59 -08004072
4073 if ((index < numArgs) &&
4074 (args[index] == String16("--static-screen"))) {
4075 index++;
4076 dumpStaticScreenStats(result);
4077 dumpAll = false;
4078 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004079
4080 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004081 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004082 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004083 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004084 dumpAll = false;
4085 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004086
4087 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4088 index++;
4089 dumpWideColorInfo(result);
4090 dumpAll = false;
4091 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004092
4093 if ((index < numArgs) &&
4094 (args[index] == String16("--enable-layer-stats"))) {
4095 index++;
4096 mLayerStats.enable();
4097 dumpAll = false;
4098 }
4099
4100 if ((index < numArgs) &&
4101 (args[index] == String16("--disable-layer-stats"))) {
4102 index++;
4103 mLayerStats.disable();
4104 dumpAll = false;
4105 }
4106
4107 if ((index < numArgs) &&
4108 (args[index] == String16("--clear-layer-stats"))) {
4109 index++;
4110 mLayerStats.clear();
4111 dumpAll = false;
4112 }
4113
4114 if ((index < numArgs) &&
4115 (args[index] == String16("--dump-layer-stats"))) {
4116 index++;
4117 mLayerStats.dump(result);
4118 dumpAll = false;
4119 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004120
4121 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004122 (args[index] == String16("--frame-composition"))) {
4123 index++;
4124 dumpFrameCompositionInfo(result);
4125 dumpAll = false;
4126 }
4127
4128 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004129 (args[index] == String16("--display-identification"))) {
4130 index++;
4131 dumpDisplayIdentificationData(result);
4132 dumpAll = false;
4133 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004134
4135 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4136 index++;
4137 mTimeStats.parseArgs(asProto, args, index, result);
4138 dumpAll = false;
4139 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004140 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004141
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004142 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004143 if (asProto) {
4144 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4145 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4146 } else {
4147 dumpAllLocked(args, index, result);
4148 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004149 }
4150
Mathias Agopian9795c422009-08-26 16:36:26 -07004151 if (locked) {
4152 mStateLock.unlock();
4153 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004154 }
4155 write(fd, result.string(), result.size());
4156 return NO_ERROR;
4157}
4158
Dan Stozac7014012014-02-14 15:03:43 -08004159void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4160 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004161{
Robert Carr2047fae2016-11-28 14:09:09 -08004162 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004163 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004164 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004165}
4166
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004167void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004168 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004169{
4170 String8 name;
4171 if (index < args.size()) {
4172 name = String8(args[index]);
4173 index++;
4174 }
4175
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004176 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4177 getHwComposer().isConnected(displayId)) {
4178 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4179 const nsecs_t period = activeConfig->getVsyncPeriod();
4180 result.appendFormat("%" PRId64 "\n", period);
4181 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004182
4183 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004184 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004185 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004186 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004187 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004188 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004189 }
Robert Carr2047fae2016-11-28 14:09:09 -08004190 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004191 }
4192}
4193
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004194void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004195 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004196{
4197 String8 name;
4198 if (index < args.size()) {
4199 name = String8(args[index]);
4200 index++;
4201 }
4202
Robert Carr2047fae2016-11-28 14:09:09 -08004203 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004204 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004205 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004206 }
Robert Carr2047fae2016-11-28 14:09:09 -08004207 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004208
Svetoslavd85084b2014-03-20 10:28:31 -07004209 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004210}
4211
Jamie Gennis6547ff42013-07-16 20:12:42 -07004212// This should only be called from the main thread. Otherwise it would need
4213// the lock and should use mCurrentState rather than mDrawingState.
4214void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004215 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004216 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004217 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004218
4219 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4220}
4221
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004222void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004223{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004224 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004225
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004226 if (isLayerTripleBufferingDisabled())
4227 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004228
4229 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004230 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004231 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004232 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004233 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4234 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004235 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004236}
4237
Dan Stozab90cf072015-03-05 11:05:59 -08004238void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4239{
4240 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004241 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4242 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004243 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004244 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004245 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4246 b + 1, bucketTimeSec, percent);
4247 }
David Sodman4a36e932017-11-07 14:29:47 -08004248 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004249 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004250 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004251 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004252 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004253}
4254
Dan Stozae77c7662016-05-13 11:37:28 -07004255void SurfaceFlinger::recordBufferingStats(const char* layerName,
4256 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004257 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4258 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004259 for (const auto& segment : history) {
4260 if (!segment.usedThirdBuffer) {
4261 stats.twoBufferTime += segment.totalTime;
4262 }
4263 if (segment.occupancyAverage < 1.0f) {
4264 stats.doubleBufferedTime += segment.totalTime;
4265 } else if (segment.occupancyAverage < 2.0f) {
4266 stats.tripleBufferedTime += segment.totalTime;
4267 }
4268 ++stats.numSegments;
4269 stats.totalTime += segment.totalTime;
4270 }
4271}
4272
Brian Andersond6927fb2016-07-23 23:37:30 -07004273void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4274 result.appendFormat("Layer frame timestamps:\n");
4275
4276 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4277 const size_t count = currentLayers.size();
4278 for (size_t i=0 ; i<count ; i++) {
4279 currentLayers[i]->dumpFrameEvents(result);
4280 }
4281}
4282
Dan Stozae77c7662016-05-13 11:37:28 -07004283void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4284 result.append("Buffering stats:\n");
4285 result.append(" [Layer name] <Active time> <Two buffer> "
4286 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004287 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004288 typedef std::tuple<std::string, float, float, float> BufferTuple;
4289 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004290 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004291 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004292 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004293 if (stats.numSegments == 0) {
4294 continue;
4295 }
4296 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4297 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4298 stats.totalTime;
4299 float doubleBufferRatio = static_cast<float>(
4300 stats.doubleBufferedTime) / stats.totalTime;
4301 float tripleBufferRatio = static_cast<float>(
4302 stats.tripleBufferedTime) / stats.totalTime;
4303 sorted.insert({activeTime, {name, twoBufferRatio,
4304 doubleBufferRatio, tripleBufferRatio}});
4305 }
4306 for (const auto& sortedPair : sorted) {
4307 float activeTime = sortedPair.first;
4308 const BufferTuple& values = sortedPair.second;
4309 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4310 std::get<0>(values).c_str(), activeTime,
4311 std::get<1>(values), std::get<2>(values),
4312 std::get<3>(values));
4313 }
4314 result.append("\n");
4315}
4316
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004317void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004318 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004319 const int32_t displayId = display->getId();
4320 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4321 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004322 continue;
4323 }
4324
Dominik Laskowski7e045462018-05-30 13:02:02 -07004325 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004326 uint8_t port;
4327 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004328 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004329 result.append("no identification data\n");
4330 continue;
4331 }
4332
4333 if (!isEdid(data)) {
4334 result.append("unknown identification data: ");
4335 for (uint8_t byte : data) {
4336 result.appendFormat("%x ", byte);
4337 }
4338 result.append("\n");
4339 continue;
4340 }
4341
4342 const auto edid = parseEdid(data);
4343 if (!edid) {
4344 result.append("invalid EDID: ");
4345 for (uint8_t byte : data) {
4346 result.appendFormat("%x ", byte);
4347 }
4348 result.append("\n");
4349 continue;
4350 }
4351
4352 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4353 result.append(edid->displayName.data(), edid->displayName.length());
4354 result.append("\"\n");
4355 }
4356 result.append("\n");
4357}
4358
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004359void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004360 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4361 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004362 result.appendFormat("DisplayColorSetting: %s\n",
4363 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004364
4365 // TODO: print out if wide-color mode is active or not
4366
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004367 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004368 const int32_t displayId = display->getId();
4369 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004370 continue;
4371 }
4372
Dominik Laskowski7e045462018-05-30 13:02:02 -07004373 result.appendFormat("Display %d color modes:\n", displayId);
4374 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004375 for (auto&& mode : modes) {
4376 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4377 }
4378
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004379 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004380 result.appendFormat(" Current color mode: %s (%d)\n",
4381 decodeColorMode(currentMode).c_str(), currentMode);
4382 }
4383 result.append("\n");
4384}
4385
David Sodman7e4ae112018-02-09 15:02:28 -08004386void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4387 std::string stringResult;
4388
4389 for (const auto& [token, display] : mDisplays) {
4390 const auto displayId = display->getId();
4391 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
4392 continue;
4393 }
4394
4395 const auto& compositionInfoIt = getBE().mEndOfFrameCompositionInfo.find(displayId);
4396 if (compositionInfoIt == getBE().mEndOfFrameCompositionInfo.end()) {
4397 break;
4398 }
4399 const auto& compositionInfoList = compositionInfoIt->second;
4400 stringResult += base::StringPrintf("Display: %d\n", displayId);
4401 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4402 for (const auto& compositionInfo : compositionInfoList) {
4403 compositionInfo.dump(stringResult, nullptr);
4404 stringResult += base::StringPrintf("\n");
4405 }
4406 }
4407
4408 result.append(stringResult.c_str());
4409}
4410
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004411LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004412 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004413 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4414 const State& state = useDrawing ? mDrawingState : mCurrentState;
4415 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004416 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004417 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004418 });
4419
4420 return layersProto;
4421}
4422
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004423LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004424 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004425
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004426 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004427 resolution->set_w(display.getWidth());
4428 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004429
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004430 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4431 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4432 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004433
Dominik Laskowski7e045462018-05-30 13:02:02 -07004434 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004435 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004436 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004437 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004438 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004439 }
4440 });
4441
4442 return layersProto;
4443}
4444
Mathias Agopian74d211a2013-04-22 16:55:35 +02004445void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4446 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004447{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004448 bool colorize = false;
4449 if (index < args.size()
4450 && (args[index] == String16("--color"))) {
4451 colorize = true;
4452 index++;
4453 }
4454
4455 Colorizer colorizer(colorize);
4456
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004457 // figure out if we're stuck somewhere
4458 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004459 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004460 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4461
4462 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004463 * Dump library configuration.
4464 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004465
4466 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004467 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004468 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004469 appendSfConfigString(result);
4470 appendUiConfigString(result);
4471 appendGuiConfigString(result);
4472 result.append("\n");
4473
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004474 result.append("\nDisplay identification data:\n");
4475 dumpDisplayIdentificationData(result);
4476
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004477 result.append("\nWide-Color information:\n");
4478 dumpWideColorInfo(result);
4479
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004480 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004481 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004482 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004483 result.append(SyncFeatures::getInstance().toString());
4484 result.append("\n");
4485
Andy McFadden41d67d72014-04-25 16:58:34 -07004486 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004487 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004488 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004489
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004490 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4491 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004492 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4493 getHwComposer().isConnected(displayId)) {
4494 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004495 result.appendFormat("Display %d: "
4496 "app phase %" PRId64 " ns, "
4497 "sf phase %" PRId64 " ns, "
4498 "early app phase %" PRId64 " ns, "
4499 "early sf phase %" PRId64 " ns, "
4500 "early app gl phase %" PRId64 " ns, "
4501 "early sf gl phase %" PRId64 " ns, "
4502 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4503 displayId,
4504 vsyncPhaseOffsetNs,
4505 sfVsyncPhaseOffsetNs,
4506 appEarlyOffset,
4507 sfEarlyOffset,
4508 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004509 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004510 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004511 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004512 result.append("\n");
4513
Dan Stozab90cf072015-03-05 11:05:59 -08004514 // Dump static screen stats
4515 result.append("\n");
4516 dumpStaticScreenStats(result);
4517 result.append("\n");
4518
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004519 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4520
Dan Stozae77c7662016-05-13 11:37:28 -07004521 dumpBufferingStats(result);
4522
Andy McFadden4803b742012-09-24 19:07:20 -07004523 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004524 * Dump the visible layer list
4525 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004526 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004527 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004528 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4529 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004530 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004531
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004532 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004533 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004534 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004535 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004536
David Sodman7e4ae112018-02-09 15:02:28 -08004537 result.append("\nFrame-Composition information:\n");
4538 dumpFrameCompositionInfo(result);
4539 result.append("\n");
4540
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004541 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004542 * Dump Display state
4543 */
4544
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004545 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004546 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004547 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004548 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004549 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004550 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004551 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004552
4553 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004554 * Dump SurfaceFlinger global state
4555 */
4556
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004557 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004558 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004559 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004560
Mathias Agopian888c8222012-08-04 21:10:38 -07004561 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004562 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004563
David Sodmanbc815282017-11-05 18:57:52 -08004564 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004565
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004566 if (display) {
4567 display->undefinedRegion.dump(result, "undefinedRegion");
4568 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4569 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004570 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004571 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004572 " gpu_to_cpu_unsupported : %d\n",
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004573 mTransactionFlags, !mGpuToCpuSupported);
4574
4575 if (display) {
4576 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4577 result.appendFormat(" refresh-rate : %f fps\n"
4578 " x-dpi : %f\n"
4579 " y-dpi : %f\n",
4580 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4581 activeConfig->getDpiY());
4582 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004583
Mathias Agopian74d211a2013-04-22 16:55:35 +02004584 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004585 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004586
4587 /*
4588 * VSYNC state
4589 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004590 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004591 result.append("\n");
4592
4593 /*
4594 * HWC layer minidump
4595 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004596 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004597 const int32_t displayId = display->getId();
4598 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004599 continue;
4600 }
4601
Dominik Laskowski7e045462018-05-30 13:02:02 -07004602 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004603 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004604 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004605 result.append("\n");
4606 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004607
4608 /*
4609 * Dump HWComposer state
4610 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004611 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004612 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004613 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004614 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004615 result.appendFormat(" h/w composer %s\n",
4616 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004617 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004618
4619 /*
4620 * Dump gralloc state
4621 */
4622 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4623 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004624
4625 /*
4626 * Dump VrFlinger state if in use.
4627 */
4628 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4629 result.append("VrFlinger state:\n");
4630 result.append(mVrFlinger->Dump().c_str());
4631 result.append("\n");
4632 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004633}
4634
Dominik Laskowski7e045462018-05-30 13:02:02 -07004635const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004636 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004637 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004638 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004639 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004640 }
4641 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004642
4643 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4644 static const Vector<sp<Layer>> empty;
4645 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004646}
4647
Keun young Park63f165f2012-08-31 10:53:36 -07004648bool SurfaceFlinger::startDdmConnection()
4649{
4650 void* libddmconnection_dso =
4651 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4652 if (!libddmconnection_dso) {
4653 return false;
4654 }
4655 void (*DdmConnection_start)(const char* name);
4656 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004657 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004658 if (!DdmConnection_start) {
4659 dlclose(libddmconnection_dso);
4660 return false;
4661 }
4662 (*DdmConnection_start)(getServiceName());
4663 return true;
4664}
4665
Chia-I Wu28f320b2018-05-03 11:02:56 -07004666void SurfaceFlinger::updateColorMatrixLocked() {
4667 mat4 colorMatrix;
4668 if (mGlobalSaturationFactor != 1.0f) {
4669 // Rec.709 luma coefficients
4670 float3 luminance{0.213f, 0.715f, 0.072f};
4671 luminance *= 1.0f - mGlobalSaturationFactor;
4672 mat4 saturationMatrix = mat4(
4673 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4674 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4675 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4676 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4677 );
4678 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4679 } else {
4680 colorMatrix = mClientColorMatrix * mDaltonizer();
4681 }
4682
4683 if (mCurrentState.colorMatrix != colorMatrix) {
4684 mCurrentState.colorMatrix = colorMatrix;
4685 mCurrentState.colorMatrixChanged = true;
4686 setTransactionFlags(eTransactionNeeded);
4687 }
4688}
4689
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004690status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004691#pragma clang diagnostic push
4692#pragma clang diagnostic error "-Wswitch-enum"
4693 switch (static_cast<ISurfaceComposerTag>(code)) {
4694 // These methods should at minimum make sure that the client requested
4695 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004696 case BOOT_FINISHED:
4697 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004698 case CREATE_CONNECTION:
4699 case CREATE_DISPLAY:
4700 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004701 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004702 case GET_ACTIVE_COLOR_MODE:
4703 case GET_ANIMATION_FRAME_STATS:
4704 case GET_HDR_CAPABILITIES:
4705 case SET_ACTIVE_CONFIG:
4706 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004707 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004708 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004709 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4710 IPCThreadState* ipc = IPCThreadState::self();
4711 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4712 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004713 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004714 }
Robert Carr1db73f62016-12-21 12:58:51 -08004715 return OK;
4716 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004717 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004718 IPCThreadState* ipc = IPCThreadState::self();
4719 const int pid = ipc->getCallingPid();
4720 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004721 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4722 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004723 return PERMISSION_DENIED;
4724 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004725 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004726 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004727 // Used by apps to hook Choreographer to SurfaceFlinger.
4728 case CREATE_DISPLAY_EVENT_CONNECTION:
4729 // The following calls are currently used by clients that do not
4730 // request necessary permissions. However, they do not expose any secret
4731 // information, so it is OK to pass them.
4732 case AUTHENTICATE_SURFACE:
4733 case GET_ACTIVE_CONFIG:
4734 case GET_BUILT_IN_DISPLAY:
4735 case GET_DISPLAY_COLOR_MODES:
4736 case GET_DISPLAY_CONFIGS:
4737 case GET_DISPLAY_STATS:
4738 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4739 // Calling setTransactionState is safe, because you need to have been
4740 // granted a reference to Client* and Handle* to do anything with it.
4741 case SET_TRANSACTION_STATE:
4742 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4743 case CREATE_SCOPED_CONNECTION: {
4744 return OK;
4745 }
4746 case CAPTURE_LAYERS:
4747 case CAPTURE_SCREEN: {
4748 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004749 IPCThreadState* ipc = IPCThreadState::self();
4750 const int pid = ipc->getCallingPid();
4751 const int uid = ipc->getCallingUid();
4752 if ((uid != AID_GRAPHICS) &&
4753 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4754 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4755 return PERMISSION_DENIED;
4756 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004757 return OK;
4758 }
4759 // The following codes are deprecated and should never be allowed to access SF.
4760 case CONNECT_DISPLAY_UNUSED:
4761 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4762 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4763 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004764 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004765 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004766
4767 // These codes are used for the IBinder protocol to either interrogate the recipient
4768 // side of the transaction for its canonical interface descriptor or to dump its state.
4769 // We let them pass by default.
4770 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4771 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4772 code == IBinder::SYSPROPS_TRANSACTION) {
4773 return OK;
4774 }
4775 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4776 // in onTransact verifies that the user is root, and has access to use SF.
4777 if (code >= 1000 && code <= 1029) {
4778 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4779 return OK;
4780 }
4781 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4782 return PERMISSION_DENIED;
4783#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004784}
4785
Ana Krulec13be8ad2018-08-21 02:43:56 +00004786status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4787 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004788 status_t credentialCheck = CheckTransactCodeCredentials(code);
4789 if (credentialCheck != OK) {
4790 return credentialCheck;
4791 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004792
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004793 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4794 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004795 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004796 IPCThreadState* ipc = IPCThreadState::self();
4797 const int uid = ipc->getCallingUid();
4798 if (CC_UNLIKELY(uid != AID_SYSTEM
4799 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004800 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004801 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004802 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004803 return PERMISSION_DENIED;
4804 }
4805 int n;
4806 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004807 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004808 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004809 return NO_ERROR;
4810 case 1002: // SHOW_UPDATES
4811 n = data.readInt32();
4812 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004813 invalidateHwcGeometry();
4814 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004815 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004816 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004817 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004818 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004819 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004820 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004821 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004822 setTransactionFlags(
4823 eTransactionNeeded|
4824 eDisplayTransactionNeeded|
4825 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004826 return NO_ERROR;
4827 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004828 case 1006:{ // send empty update
4829 signalRefresh();
4830 return NO_ERROR;
4831 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004832 case 1008: // toggle use of hw composer
4833 n = data.readInt32();
4834 mDebugDisableHWC = n ? 1 : 0;
4835 invalidateHwcGeometry();
4836 repaintEverything();
4837 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004838 case 1009: // toggle use of transform hint
4839 n = data.readInt32();
4840 mDebugDisableTransformHint = n ? 1 : 0;
4841 invalidateHwcGeometry();
4842 repaintEverything();
4843 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004844 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004845 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004846 reply->writeInt32(0);
4847 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004848 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004849 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004850 return NO_ERROR;
4851 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004852 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004853 if (!display) {
4854 return NAME_NOT_FOUND;
4855 }
4856
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004857 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004858 return NO_ERROR;
4859 }
4860 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004861 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004862 // daltonize
4863 n = data.readInt32();
4864 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004865 case 1:
4866 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4867 break;
4868 case 2:
4869 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4870 break;
4871 case 3:
4872 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4873 break;
4874 default:
4875 mDaltonizer.setType(ColorBlindnessType::None);
4876 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004877 }
4878 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004879 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004880 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004881 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004882 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004883
4884 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004885 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004886 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004887 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004888 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004889 // apply a color matrix
4890 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004891 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004892 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004893 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004894 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004895 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004896 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004897 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004898 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004899 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004900 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004901
4902 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4903 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004904 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004905 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4906 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4907 }
4908
Chia-I Wu28f320b2018-05-03 11:02:56 -07004909 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004910 return NO_ERROR;
4911 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004912 // This is an experimental interface
4913 // Needs to be shifted to proper binder interface when we productize
4914 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004915 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07004916 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004917 return NO_ERROR;
4918 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004919 case 1017: {
4920 n = data.readInt32();
4921 mForceFullDamage = static_cast<bool>(n);
4922 return NO_ERROR;
4923 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004924 case 1018: { // Modify Choreographer's phase offset
4925 n = data.readInt32();
4926 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4927 return NO_ERROR;
4928 }
4929 case 1019: { // Modify SurfaceFlinger's phase offset
4930 n = data.readInt32();
4931 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4932 return NO_ERROR;
4933 }
Irvel468051e2016-06-13 16:44:44 -07004934 case 1020: { // Layer updates interceptor
4935 n = data.readInt32();
4936 if (n) {
4937 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004938 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004939 }
4940 else{
4941 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004942 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004943 }
4944 return NO_ERROR;
4945 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004946 case 1021: { // Disable HWC virtual displays
4947 n = data.readInt32();
4948 mUseHwcVirtualDisplays = !n;
4949 return NO_ERROR;
4950 }
Romain Guy0147a172017-06-01 13:53:56 -07004951 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004952 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004953 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004954
Chia-I Wu28f320b2018-05-03 11:02:56 -07004955 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004956 return NO_ERROR;
4957 }
Romain Guy54f154a2017-10-24 21:40:32 +01004958 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004959 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004960 invalidateHwcGeometry();
4961 repaintEverything();
4962 return NO_ERROR;
4963 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004964 // TODO(b/111505327): Find out whether the usage of 1024 can switch to 1030,
4965 // deprecate 1024 if they can.
4966 case 1024: { // Does device have wide color gamut display?
Romain Guy54f154a2017-10-24 21:40:32 +01004967 reply->writeBool(hasWideColorDisplay);
4968 return NO_ERROR;
4969 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004970 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004971 n = data.readInt32();
4972 if (n) {
4973 ALOGV("LayerTracing enabled");
4974 mTracing.enable();
4975 doTracing("tracing.enable");
4976 reply->writeInt32(NO_ERROR);
4977 } else {
4978 ALOGV("LayerTracing disabled");
4979 status_t err = mTracing.disable();
4980 reply->writeInt32(err);
4981 }
4982 return NO_ERROR;
4983 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004984 case 1026: { // Get layer tracing status
4985 reply->writeBool(mTracing.isEnabled());
4986 return NO_ERROR;
4987 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004988 // Is a DisplayColorSetting supported?
4989 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004990 const auto display = getDefaultDisplayDevice();
4991 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004992 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004993 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004994
4995 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4996 switch (setting) {
4997 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07004998 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004999 break;
5000 case DisplayColorSetting::UNMANAGED:
5001 reply->writeBool(true);
5002 break;
5003 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005004 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005005 break;
5006 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005007 reply->writeBool(
5008 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005009 break;
5010 }
5011 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005012 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005013 // Is VrFlinger active?
5014 case 1028: {
5015 Mutex::Autolock _l(mStateLock);
5016 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5017 return NO_ERROR;
5018 }
David Sodman6d46c1e2018-07-13 12:59:48 -07005019 case 1029: {
5020 // Code 1029 is an experimental feature that allows applications to
5021 // simulate a high frequency panel by setting a multiplier and divisor
5022 // on the VSYNC-sf clock. If either the multiplier or divisor are
David Sodman44b5de02018-08-21 16:28:53 -07005023 // 0, then the code simply return the current multiplier and divisor.
5024 HWC2::Device::FrequencyScaler frequencyScaler;
5025 frequencyScaler.multiplier = data.readInt32();
5026 frequencyScaler.divisor = data.readInt32();
David Sodman6d46c1e2018-07-13 12:59:48 -07005027
David Sodman44b5de02018-08-21 16:28:53 -07005028 if ((frequencyScaler.multiplier == 0) || (frequencyScaler.divisor == 0)) {
5029 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5030 reply->writeInt32(frequencyScaler.multiplier);
5031 reply->writeInt32(frequencyScaler.divisor);
5032 return NO_ERROR;
David Sodman6d46c1e2018-07-13 12:59:48 -07005033 }
5034
David Sodman44b5de02018-08-21 16:28:53 -07005035 if ((frequencyScaler.multiplier == 1) && (frequencyScaler.divisor == 1)) {
David Sodman6d46c1e2018-07-13 12:59:48 -07005036 enableHardwareVsync();
5037 } else {
5038 disableHardwareVsync(true);
5039 }
David Sodman44b5de02018-08-21 16:28:53 -07005040 mPrimaryDispSync->scalePeriod(frequencyScaler);
5041 getBE().mHwc->setDisplayFrequencyScaleParameters(frequencyScaler);
David Sodman6d46c1e2018-07-13 12:59:48 -07005042
David Sodman44b5de02018-08-21 16:28:53 -07005043 ATRACE_INT("PeriodMultiplier", frequencyScaler.multiplier);
5044 ATRACE_INT("PeriodDivisor", frequencyScaler.divisor);
5045
5046 const hwc2_display_t hwcDisplayId = getBE().mHwc->getActiveConfig(
5047 DisplayDevice::DISPLAY_PRIMARY)->getDisplayId();
5048
5049 onHotplugReceived(getBE().mComposerSequenceId,
5050 hwcDisplayId, HWC2::Connection::Disconnected);
5051 onHotplugReceived(getBE().mComposerSequenceId,
5052 hwcDisplayId, HWC2::Connection::Connected);
5053 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5054 reply->writeInt32(frequencyScaler.multiplier);
5055 reply->writeInt32(frequencyScaler.divisor);
5056
David Sodman6d46c1e2018-07-13 12:59:48 -07005057 return NO_ERROR;
5058 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005059 // Is device color managed?
5060 case 1030: {
5061 reply->writeBool(useColorManagement);
5062 return NO_ERROR;
5063 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005064 }
5065 }
5066 return err;
5067}
5068
Steven Thomas6d8110b2017-08-31 18:24:21 -07005069void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07005070 android_atomic_or(1, &mRepaintEverything);
5071 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005072}
5073
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005074// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5075class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005076public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005077 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5078 ~WindowDisconnector() {
5079 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005080 }
5081
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005082private:
5083 ANativeWindow* mWindow;
5084 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005085};
5086
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005087status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
5088 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
5089 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
5090 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005091 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005092 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005093
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005094 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005095
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005096 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5097
Chia-I Wu20261cb2018-08-23 12:55:44 -07005098 sp<DisplayDevice> display;
5099 {
5100 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005101
Chia-I Wu20261cb2018-08-23 12:55:44 -07005102 display = getDisplayDeviceLocked(displayToken);
5103 if (!display) return BAD_VALUE;
5104
Chia-I Wu8730ba82018-08-29 09:25:59 -07005105 // ignore sourceCrop (i.e., use the projected logical display
5106 // viewport) until the framework is fixed
5107 sourceCrop.clear();
Chia-I Wucb023152018-08-28 12:57:23 -07005108
5109 // set the requested width/height to the logical display viewport size
5110 // by default
5111 if (reqWidth == 0 || reqHeight == 0) {
5112 reqWidth = uint32_t(display->getViewport().width());
5113 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005114 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005115 }
5116
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005117 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005118
5119 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005120 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005121 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005122}
5123
5124status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08005125 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005126 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005127 ATRACE_CALL();
5128
5129 class LayerRenderArea : public RenderArea {
5130 public:
Robert Carr578038f2018-03-09 12:25:24 -08005131 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
5132 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
Chia-I Wu9d1abea2018-08-23 13:44:43 -07005133 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08005134 mLayer(layer),
5135 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005136 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005137 mFlinger(flinger),
5138 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005139 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005140 Rect getBounds() const override {
5141 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005142 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005143 }
Marissa Wall61c58622018-07-18 10:12:20 -07005144 int getHeight() const override {
5145 return mLayer->getActiveHeight(mLayer->getDrawingState());
5146 }
5147 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005148 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005149 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005150 Rect getSourceCrop() const override {
5151 if (mCrop.isEmpty()) {
5152 return getBounds();
5153 } else {
5154 return mCrop;
5155 }
5156 }
Robert Carr578038f2018-03-09 12:25:24 -08005157 class ReparentForDrawing {
5158 public:
5159 const sp<Layer>& oldParent;
5160 const sp<Layer>& newParent;
5161
5162 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5163 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005164 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005165 }
Robert Carr15eae092018-03-23 13:43:53 -07005166 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005167 };
5168
5169 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005170 const Rect sourceCrop = getSourceCrop();
5171 // no need to check rotation because there is none
5172 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5173 sourceCrop.height() != getReqHeight();
5174
Robert Carr578038f2018-03-09 12:25:24 -08005175 if (!mChildrenOnly) {
5176 mTransform = mLayer->getTransform().inverse();
5177 drawLayers();
5178 } else {
5179 Rect bounds = getBounds();
5180 screenshotParentLayer =
5181 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
5182 bounds.getWidth(), bounds.getHeight(), 0);
5183
5184 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5185 drawLayers();
5186 }
5187 }
chaviwa76b2712017-09-20 12:02:26 -07005188
chaviwa76b2712017-09-20 12:02:26 -07005189 private:
chaviw7206d492017-11-10 16:16:12 -08005190 const sp<Layer> mLayer;
5191 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005192
5193 // In the "childrenOnly" case we reparent the children to a screenshot
5194 // layer which has no properties set and which does not draw.
5195 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005196 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005197 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005198
5199 SurfaceFlinger* mFlinger;
5200 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005201 };
5202
5203 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5204 auto parent = layerHandle->owner.promote();
5205
chaviw7206d492017-11-10 16:16:12 -08005206 if (parent == nullptr || parent->isPendingRemoval()) {
5207 ALOGE("captureLayers called with a removed parent");
5208 return NAME_NOT_FOUND;
5209 }
5210
Robert Carr578038f2018-03-09 12:25:24 -08005211 const int uid = IPCThreadState::self()->getCallingUid();
5212 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5213 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5214 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5215 return PERMISSION_DENIED;
5216 }
5217
chaviw7206d492017-11-10 16:16:12 -08005218 Rect crop(sourceCrop);
5219 if (sourceCrop.width() <= 0) {
5220 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005221 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005222 }
5223
5224 if (sourceCrop.height() <= 0) {
5225 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005226 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005227 }
5228
5229 int32_t reqWidth = crop.width() * frameScale;
5230 int32_t reqHeight = crop.height() * frameScale;
5231
Chia-I Wu20261cb2018-08-23 12:55:44 -07005232 // really small crop or frameScale
5233 if (reqWidth <= 0) {
5234 reqWidth = 1;
5235 }
5236 if (reqHeight <= 0) {
5237 reqHeight = 1;
5238 }
5239
Robert Carr578038f2018-03-09 12:25:24 -08005240 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005241
Robert Carr578038f2018-03-09 12:25:24 -08005242 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005243 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5244 if (!layer->isVisible()) {
5245 return;
Robert Carr578038f2018-03-09 12:25:24 -08005246 } else if (childrenOnly && layer == parent.get()) {
5247 return;
chaviwa76b2712017-09-20 12:02:26 -07005248 }
5249 visitor(layer);
5250 });
5251 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005252 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005253}
5254
5255status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5256 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005257 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005258 bool useIdentityTransform) {
5259 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005260
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005261 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5262 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5263 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5264 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005265
5266 // This mutex protects syncFd and captureResult for communication of the return values from the
5267 // main thread back to this Binder thread
5268 std::mutex captureMutex;
5269 std::condition_variable captureCondition;
5270 std::unique_lock<std::mutex> captureLock(captureMutex);
5271 int syncFd = -1;
5272 std::optional<status_t> captureResult;
5273
Robert Carr03480e22018-01-04 16:02:06 -08005274 const int uid = IPCThreadState::self()->getCallingUid();
5275 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5276
Dominik Laskowski8c001672018-05-30 16:52:06 -07005277 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005278 // If there is a refresh pending, bug out early and tell the binder thread to try again
5279 // after the refresh.
5280 if (mRefreshPending) {
5281 ATRACE_NAME("Skipping screenshot for now");
5282 std::unique_lock<std::mutex> captureLock(captureMutex);
5283 captureResult = std::make_optional<status_t>(EAGAIN);
5284 captureCondition.notify_one();
5285 return;
5286 }
5287
5288 status_t result = NO_ERROR;
5289 int fd = -1;
5290 {
5291 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005292 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005293 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5294 useIdentityTransform, forSystem, &fd);
5295 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005296 }
5297
5298 {
5299 std::unique_lock<std::mutex> captureLock(captureMutex);
5300 syncFd = fd;
5301 captureResult = std::make_optional<status_t>(result);
5302 captureCondition.notify_one();
5303 }
5304 });
5305
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005306 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005307 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005308 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005309 while (*captureResult == EAGAIN) {
5310 captureResult.reset();
5311 result = postMessageAsync(message);
5312 if (result != NO_ERROR) {
5313 return result;
5314 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005315 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005316 }
5317 result = *captureResult;
5318 }
5319
5320 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005321 sync_wait(syncFd, -1);
5322 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005323 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005324
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005325 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005326}
5327
chaviwa76b2712017-09-20 12:02:26 -07005328void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005329 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005330 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005331 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005332
Lloyd Pique144e1162017-12-20 16:44:52 -08005333 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005334
chaviwa76b2712017-09-20 12:02:26 -07005335 const auto reqWidth = renderArea.getReqWidth();
5336 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005337 const auto sourceCrop = renderArea.getSourceCrop();
5338 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005339
Chia-I Wu36574d92018-05-16 10:54:36 -07005340 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5341 engine.setOutputDataSpace(Dataspace::SRGB);
5342 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005343
Mathias Agopian180f10d2013-04-10 22:55:41 -07005344 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005345 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005346
5347 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005348 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005349 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005350
chaviw50da5042018-04-09 13:49:37 -07005351 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005352 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005353 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005354
chaviwa76b2712017-09-20 12:02:26 -07005355 traverseLayers([&](Layer* layer) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08005356 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005357 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005358}
5359
chaviwa76b2712017-09-20 12:02:26 -07005360status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5361 TraverseLayersFunction traverseLayers,
5362 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005363 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005364 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005365 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005366 ATRACE_CALL();
5367
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005368 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005369
5370 traverseLayers([&](Layer* layer) {
5371 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5372 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005373
Robert Carr03480e22018-01-04 16:02:06 -08005374 // We allow the system server to take screenshots of secure layers for
5375 // use in situations like the Screen-rotation animation and place
5376 // the impetus on WindowManager to not persist them.
5377 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005378 ALOGW("FB is protected: PERMISSION_DENIED");
5379 return PERMISSION_DENIED;
5380 }
5381
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005382 // this binds the given EGLImage as a framebuffer for the
5383 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005384 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005385 if (bufferBond.getStatus() != NO_ERROR) {
5386 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005387 return INVALID_OPERATION;
5388 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005389
Dan Stozaabcda352017-06-01 14:37:39 -07005390 // this will in fact render into our dequeued buffer
5391 // via an FBO, which means we didn't have to create
5392 // an EGLSurface and therefore we're not
5393 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005394 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005395
Dan Stozaabcda352017-06-01 14:37:39 -07005396 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005397 getRenderEngine().finish();
5398 *outSyncFd = -1;
5399
chaviwa76b2712017-09-20 12:02:26 -07005400 const auto reqWidth = renderArea.getReqWidth();
5401 const auto reqHeight = renderArea.getReqHeight();
5402
Dan Stozaabcda352017-06-01 14:37:39 -07005403 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5404 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005405 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005406 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005407 } else {
5408 base::unique_fd syncFd = getRenderEngine().flush();
5409 if (syncFd < 0) {
5410 getRenderEngine().finish();
5411 }
5412 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005413 }
5414
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005415 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005416}
5417
Mathias Agopiand5556842013-09-19 17:08:37 -07005418void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005419 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005420 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005421 for (size_t y = 0; y < h; y++) {
5422 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5423 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005424 if (p[x] != 0xFF000000) return;
5425 }
5426 }
chaviwa76b2712017-09-20 12:02:26 -07005427 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005428
Robert Carr2047fae2016-11-28 14:09:09 -08005429 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005430 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005431 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005432 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5433 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5434 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5435 static_cast<float>(state.color.a));
5436 i++;
5437 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005438 }
5439}
5440
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005441// ---------------------------------------------------------------------------
5442
Dan Stoza412903f2017-04-27 13:42:17 -07005443void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5444 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005445}
5446
Dan Stoza412903f2017-04-27 13:42:17 -07005447void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5448 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005449}
5450
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005451void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5452 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005453 const LayerVector::Visitor& visitor) {
5454 // We loop through the first level of layers without traversing,
5455 // as we need to interpret min/max layer Z in the top level Z space.
5456 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005457 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005458 continue;
5459 }
5460 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005461 // relative layers are traversed in Layer::traverseInZOrder
5462 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005463 continue;
5464 }
5465 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005466 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005467 return;
5468 }
chaviwa76b2712017-09-20 12:02:26 -07005469 if (!layer->isVisible()) {
5470 return;
5471 }
5472 visitor(layer);
5473 });
5474 }
5475}
5476
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005477}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005478
Lloyd Pique074e8122018-07-26 12:57:23 -07005479
Mathias Agopian3f844832013-08-07 21:24:32 -07005480#if defined(__gl_h_)
5481#error "don't include gl/gl.h in this file"
5482#endif
5483
5484#if defined(__gl2_h_)
5485#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005486#endif