blob: 278713272f838c6d543aea3b74b9d2d1f7558945 [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;
Peiyong Lin13effd12018-07-24 17:01:47 -0700196bool SurfaceFlinger::useColorManagement;
Mathias Agopian99b49842011-06-27 16:05:52 -0700197
Kalle Raitaa099a242017-01-11 11:17:29 -0800198
199std::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:
332 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
333 break;
334 case V1_1::DisplayOrientation::ORIENTATION_180:
335 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
336 break;
337 case V1_1::DisplayOrientation::ORIENTATION_270:
338 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
339 break;
340 default:
341 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
342 break;
343 }
344 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
345
Lloyd Pique41be5d22018-06-21 13:11:48 -0700346 // Note: We create a local temporary with the real DispSync implementation
347 // type temporarily so we can initialize it with the configured values,
348 // before storing it for more generic use using the interface type.
349 auto primaryDispSync = std::make_unique<impl::DispSync>("PrimaryDispSync");
350 primaryDispSync->init(SurfaceFlinger::hasSyncFramework,
351 SurfaceFlinger::dispSyncPresentTimeOffset);
352 mPrimaryDispSync = std::move(primaryDispSync);
Saurabh Shahf4174532017-07-13 10:45:07 -0700353
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800354 // debugging stuff...
355 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700356
Mathias Agopianb4b17302013-03-20 18:36:41 -0700357 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700358 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700359
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800360 property_get("debug.sf.showupdates", value, "0");
361 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700362
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700363 property_get("debug.sf.ddms", value, "0");
364 mDebugDDMS = atoi(value);
365 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700366 if (!startDdmConnection()) {
367 // start failed, and DDMS debugging not enabled
368 mDebugDDMS = 0;
369 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700370 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700371 ALOGI_IF(mDebugRegion, "showupdates enabled");
372 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700373
374 property_get("debug.sf.disable_backpressure", value, "0");
375 mPropagateBackpressure = !atoi(value);
376 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700377
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800378 property_get("debug.sf.enable_hwc_vds", value, "0");
379 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800380 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800381
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800382 property_get("ro.sf.disable_triple_buffer", value, "1");
383 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800384 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700385
Yiwei Zhang243b3782018-05-15 17:40:04 -0700386 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700387 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
388 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
389
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200390 property_get("debug.sf.early_phase_offset_ns", value, "-1");
391 const int earlySfOffsetNs = atoi(value);
392
393 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
394 const int earlyGlSfOffsetNs = atoi(value);
395
396 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
397 const int earlyAppOffsetNs = atoi(value);
398
399 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
400 const int earlyGlAppOffsetNs = atoi(value);
401
402 const VSyncModulator::Offsets earlyOffsets =
403 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
404 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
405 const VSyncModulator::Offsets earlyGlOffsets =
406 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
407 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
408 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
409 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700410
Romain Guy11d63f42017-07-20 12:47:14 -0700411 // We should be reading 'persist.sys.sf.color_saturation' here
412 // but since /data may be encrypted, we need to wait until after vold
413 // comes online to attempt to read the property. The property is
414 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800415
416 if (useTrebleTestingOverride()) {
417 // Without the override SurfaceFlinger cannot connect to HIDL
418 // services that are not listed in the manifests. Considered
419 // deriving the setting from the set service name, but it
420 // would be brittle if the name that's not 'default' is used
421 // for production purposes later on.
422 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
423 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800424}
425
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800426void SurfaceFlinger::onFirstRef()
427{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800428 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800429}
430
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800431SurfaceFlinger::~SurfaceFlinger()
432{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800433}
434
Dan Stozac7014012014-02-14 15:03:43 -0800435void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800436{
437 // the window manager died on us. prepare its eulogy.
438
Andy McFadden13a082e2012-08-24 10:16:42 -0700439 // restore initial conditions (default device unblank, etc)
440 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800441
442 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700443 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800444}
445
Robert Carr1db73f62016-12-21 12:58:51 -0800446static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700447 status_t err = client->initCheck();
448 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800449 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800450 }
Robert Carr1db73f62016-12-21 12:58:51 -0800451 return nullptr;
452}
453
454sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
455 return initClient(new Client(this));
456}
457
458sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
459 const sp<IGraphicBufferProducer>& gbp) {
460 if (authenticateSurfaceTexture(gbp) == false) {
461 return nullptr;
462 }
463 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
464 if (layer == nullptr) {
465 return nullptr;
466 }
467
468 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800469}
470
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700471sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
472 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700473{
474 class DisplayToken : public BBinder {
475 sp<SurfaceFlinger> flinger;
476 virtual ~DisplayToken() {
477 // no more references, this display must be terminated
478 Mutex::Autolock _l(flinger->mStateLock);
479 flinger->mCurrentState.displays.removeItem(this);
480 flinger->setTransactionFlags(eDisplayTransactionNeeded);
481 }
482 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700483 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700484 : flinger(flinger) {
485 }
486 };
487
488 sp<BBinder> token = new DisplayToken(this);
489
490 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700491 DisplayDeviceState info;
492 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700493 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700494 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700495 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800496 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700497 return token;
498}
499
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700500void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700501 Mutex::Autolock _l(mStateLock);
502
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700503 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700504 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700505 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700506 return;
507 }
508
509 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700510 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700511 ALOGE("destroyDisplay called for non-virtual display");
512 return;
513 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700514 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700515 mCurrentState.displays.removeItemsAt(idx);
516 setTransactionFlags(eDisplayTransactionNeeded);
517}
518
Mathias Agopiane57f2922012-08-09 16:29:12 -0700519sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700520 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700521 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800522 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700523 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700524 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700525}
526
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800527void SurfaceFlinger::bootFinished()
528{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700529 if (mStartPropertySetThread->join() != NO_ERROR) {
530 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800531 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800532 const nsecs_t now = systemTime();
533 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000534 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700535
536 // wait patiently for the window manager death
537 const String16 name("window");
538 sp<IBinder> window(defaultServiceManager()->getService(name));
539 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700540 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700541 }
542
Steven Thomas050b2c82017-03-06 11:45:16 -0800543 if (mVrFlinger) {
544 mVrFlinger->OnBootFinished();
545 }
546
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700547 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700548 // formerly we would just kill the process, but we now ask it to exit so it
549 // can choose where to stop the animation.
550 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700551
552 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
553 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
554 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700555
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800556 postMessageAsync(new LambdaMessage([this] {
557 readPersistentProperties();
558 mBootStage = BootStage::FINISHED;
559 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800560}
561
Dan Stoza436ccf32018-06-21 12:10:12 -0700562uint32_t SurfaceFlinger::getNewTexture() {
563 {
564 std::lock_guard lock(mTexturePoolMutex);
565 if (!mTexturePool.empty()) {
566 uint32_t name = mTexturePool.back();
567 mTexturePool.pop_back();
568 ATRACE_INT("TexturePoolSize", mTexturePool.size());
569 return name;
570 }
571
572 // The pool was too small, so increase it for the future
573 ++mTexturePoolSize;
574 }
575
576 // The pool was empty, so we need to get a new texture name directly using a
577 // blocking call to the main thread
578 uint32_t name = 0;
579 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
580 return name;
581}
582
Mathias Agopian3f844832013-08-07 21:24:32 -0700583void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700584 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700585}
586
Wei Wangf9b05ee2017-07-19 20:59:39 -0700587// Do not call property_set on main thread which will be blocked by init
588// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700589void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700590 ALOGI( "SurfaceFlinger's main thread ready to run. "
591 "Initializing graphics H/W...");
592
Thierry Strudel2924d012017-08-14 15:19:37 -0700593 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900594
Steven Thomasb02664d2017-07-26 18:48:28 -0700595 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800596
Steven Thomasb02664d2017-07-26 18:48:28 -0700597 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800598 mEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700599 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
600 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800601 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700602 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800603 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800604 "appEventThread");
605 mSfEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700606 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800607 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800608
Lloyd Pique24b0a482018-03-09 18:52:26 -0800609 mSFEventThread =
610 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700611 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800612 [this](nsecs_t timestamp) {
613 mInterceptor->saveVSyncEvent(timestamp);
614 },
615 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800616 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200617 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800618
Steven Thomasb02664d2017-07-26 18:48:28 -0700619 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700620 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700621 renderEngineFeature |= (useColorManagement ?
622 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
623 getBE().mRenderEngine = renderengine::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
624 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800625 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700626
627 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
628 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800629 getBE().mHwc.reset(
630 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700631 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800632 // Process any initial hotplug and resulting display changes.
633 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700634 const auto display = getDefaultDisplayDeviceLocked();
635 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
636 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
637 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800638
Lloyd Piquefcd86612017-12-14 17:15:36 -0800639 // make the default display GLContext current so that we can create textures
640 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700641 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800642
Steven Thomas050b2c82017-03-06 11:45:16 -0800643 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700644 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700645 // This callback is called from the vr flinger dispatch thread. We
646 // need to call signalTransaction(), which requires holding
647 // mStateLock when we're not on the main thread. Acquiring
648 // mStateLock from the vr flinger dispatch thread might trigger a
649 // deadlock in surface flinger (see b/66916578), so post a message
650 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700651 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700652 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
653 mVrFlingerRequestsDisplay = requestDisplay;
654 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700655 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800656 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700657 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
658 getHwComposer()
659 .getHwcDisplayId(display->getId())
660 .value_or(0),
661 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800662 if (!mVrFlinger) {
663 ALOGE("Failed to start vrflinger");
664 }
665 }
666
Lloyd Pique379adc12018-01-22 17:31:47 -0800667 mEventControlThread = std::make_unique<impl::EventControlThread>(
668 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700669
Mathias Agopian92a979a2012-08-02 18:32:23 -0700670 // initialize our drawing state
671 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700672
Andy McFadden13a082e2012-08-24 10:16:42 -0700673 // set initial conditions (e.g. unblank default device)
674 initializeDisplays();
675
David Sodmanbc815282017-11-05 18:57:52 -0800676 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700677
Wei Wangf9b05ee2017-07-19 20:59:39 -0700678 // Inform native graphics APIs whether the present timestamp is supported:
679 if (getHwComposer().hasCapability(
680 HWC2::Capability::PresentFenceIsNotReliable)) {
681 mStartPropertySetThread = new StartPropertySetThread(false);
682 } else {
683 mStartPropertySetThread = new StartPropertySetThread(true);
684 }
685
686 if (mStartPropertySetThread->Start() != NO_ERROR) {
687 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800688 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800689
Chia-I Wud49d6692018-06-27 07:17:41 +0800690 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
691 // is used to saturate legacy sRGB content. However, to make sure the same color under
692 // Display P3 will be saturated to the same color, we intentionally break the API spec
693 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
694 // such saturation matrix on Display P3 is understood fully, the API should always return
695 // identify matrix.
696 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
697 Dataspace::SRGB_LINEAR);
698
699 // we will apply this on Display P3.
700 if (mEnhancedSaturationMatrix != mat4()) {
701 ColorSpace srgb(ColorSpace::sRGB());
702 ColorSpace displayP3(ColorSpace::DisplayP3());
703 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
704 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
705 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
706 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800707
Dan Stoza9e56aa02015-11-02 13:00:03 -0800708 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700709}
710
Romain Guy11d63f42017-07-20 12:47:14 -0700711void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700712 Mutex::Autolock _l(mStateLock);
713
Romain Guy11d63f42017-07-20 12:47:14 -0700714 char value[PROPERTY_VALUE_MAX];
715
716 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800717 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700718 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800719 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100720
721 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700722 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700723}
724
Mathias Agopiana67e4182012-06-19 17:26:12 -0700725void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800726 // Start boot animation service by setting a property mailbox
727 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700728 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800729 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700730 if (mStartPropertySetThread->join() != NO_ERROR) {
731 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800732 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700733}
734
Mathias Agopian875d8e12013-06-07 15:35:48 -0700735size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800736 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700737}
738
Mathias Agopian875d8e12013-06-07 15:35:48 -0700739size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800740 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700741}
742
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800743// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800744
Jamie Gennis582270d2011-08-17 18:19:00 -0700745bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800746 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800747 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800748 return authenticateSurfaceTextureLocked(bufferProducer);
749}
750
751bool SurfaceFlinger::authenticateSurfaceTextureLocked(
752 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800753 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800754 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800755}
756
Brian Anderson6b376712017-04-04 10:51:39 -0700757status_t SurfaceFlinger::getSupportedFrameTimestamps(
758 std::vector<FrameEvent>* outSupported) const {
759 *outSupported = {
760 FrameEvent::REQUESTED_PRESENT,
761 FrameEvent::ACQUIRE,
762 FrameEvent::LATCH,
763 FrameEvent::FIRST_REFRESH_START,
764 FrameEvent::LAST_REFRESH_START,
765 FrameEvent::GPU_COMPOSITION_DONE,
766 FrameEvent::DEQUEUE_READY,
767 FrameEvent::RELEASE,
768 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700769 ConditionalLock _l(mStateLock,
770 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700771 if (!getHwComposer().hasCapability(
772 HWC2::Capability::PresentFenceIsNotReliable)) {
773 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
774 }
775 return NO_ERROR;
776}
777
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700778status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
779 Vector<DisplayInfo>* configs) {
780 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700781 return BAD_VALUE;
782 }
783
Jesse Hall692c7232012-11-08 15:41:56 -0800784 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700785 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
786 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700787 type = i;
788 break;
789 }
790 }
791
792 if (type < 0) {
793 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700794 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700795
Mathias Agopian8b736f12012-08-13 17:54:26 -0700796 // TODO: Not sure if display density should handled by SF any longer
797 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700798 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700799 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700800 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800801 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700802 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700803 }
804 return density;
805 }
806 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700807 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700808 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700809 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700810 return getDensityFromProperty("ro.sf.lcd_density"); }
811 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700812
Dan Stoza7f7da322014-05-02 15:26:25 -0700813 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700814
Steven Thomas6d8110b2017-08-31 18:24:21 -0700815 ConditionalLock _l(mStateLock,
816 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800817 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700818 DisplayInfo info = DisplayInfo();
819
Dan Stoza9e56aa02015-11-02 13:00:03 -0800820 float xdpi = hwConfig->getDpiX();
821 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700822
823 if (type == DisplayDevice::DISPLAY_PRIMARY) {
824 // The density of the device is provided by a build property
825 float density = Density::getBuildDensity() / 160.0f;
826 if (density == 0) {
827 // the build doesn't provide a density -- this is wrong!
828 // use xdpi instead
829 ALOGE("ro.sf.lcd_density must be defined as a build property");
830 density = xdpi / 160.0f;
831 }
832 if (Density::getEmuDensity()) {
833 // if "qemu.sf.lcd_density" is specified, it overrides everything
834 xdpi = ydpi = density = Density::getEmuDensity();
835 density /= 160.0f;
836 }
837 info.density = density;
838
839 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700840 const auto display = getDefaultDisplayDeviceLocked();
841 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700842 } else {
843 // TODO: where should this value come from?
844 static const int TV_DENSITY = 213;
845 info.density = TV_DENSITY / 160.0f;
846 info.orientation = 0;
847 }
848
Dan Stoza9e56aa02015-11-02 13:00:03 -0800849 info.w = hwConfig->getWidth();
850 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700851 info.xdpi = xdpi;
852 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800853 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900854 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800855
Andy McFadden91b2ca82014-06-13 14:04:23 -0700856 // This is how far in advance a buffer must be queued for
857 // presentation at a given time. If you want a buffer to appear
858 // on the screen at time N, you must submit the buffer before
859 // (N - presentationDeadline).
860 //
861 // Normally it's one full refresh period (to give SF a chance to
862 // latch the buffer), but this can be reduced by configuring a
863 // DispSync offset. Any additional delays introduced by the hardware
864 // composer or panel must be accounted for here.
865 //
866 // We add an additional 1ms to allow for processing time and
867 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800868 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800869 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700870
871 // All non-virtual displays are currently considered secure.
872 info.secure = true;
873
Iris Chang7501ed62018-04-30 14:45:42 +0800874 if (type == DisplayDevice::DISPLAY_PRIMARY &&
875 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
876 std::swap(info.w, info.h);
877 }
878
Michael Wright28f24d02016-07-12 13:30:53 -0700879 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700880 }
881
Dan Stoza7f7da322014-05-02 15:26:25 -0700882 return NO_ERROR;
883}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700884
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700885status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
886 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700887 return BAD_VALUE;
888 }
889
890 // FIXME for now we always return stats for the primary display
891 memset(stats, 0, sizeof(*stats));
Lloyd Pique41be5d22018-06-21 13:11:48 -0700892 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
893 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700894 return NO_ERROR;
895}
896
Yiwei Zhangcd3f9e92018-08-21 15:15:42 -0700897status_t SurfaceFlinger::getDisplayViewport(const sp<IBinder>& display, Rect* outViewport) {
898 if (outViewport == nullptr || display.get() == nullptr) {
899 return BAD_VALUE;
900 }
901
902 sp<const DisplayDevice> device(getDisplayDevice(display));
903 if (device == nullptr) {
904 return BAD_VALUE;
905 }
906
907 *outViewport = device->getViewport();
908
909 return NO_ERROR;
910}
911
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700912int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
913 const auto display = getDisplayDevice(displayToken);
914 if (!display) {
915 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800916 return BAD_VALUE;
917 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700918
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700919 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700920}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700921
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700922void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
923 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700924 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700925 return;
926 }
927
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700928 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700929 ALOGW("Trying to set config for virtual display");
930 return;
931 }
932
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700933 display->setActiveConfig(mode);
934 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700935}
936
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700937status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700938 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700939 Vector<DisplayInfo> configs;
940 getDisplayConfigs(displayToken, &configs);
941 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
942 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
943 configs.size());
944 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700945 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700946 const auto display = getDisplayDevice(displayToken);
947 if (!display) {
948 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
949 displayToken.get());
950 } else if (display->isVirtual()) {
951 ALOGW("Attempt to set active config %d for virtual display", mode);
952 } else {
953 setActiveConfigInternal(display, mode);
954 }
955 }));
956
Mathias Agopian888c8222012-08-04 21:10:38 -0700957 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700958}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700959status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
960 Vector<ColorMode>* outColorModes) {
961 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700962 return BAD_VALUE;
963 }
964
Michael Wright28f24d02016-07-12 13:30:53 -0700965 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700966 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
967 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700968 type = i;
969 break;
970 }
971 }
972
973 if (type < 0) {
974 return type;
975 }
976
Peiyong Lina52f0292018-03-14 17:26:31 -0700977 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700978 {
979 ConditionalLock _l(mStateLock,
980 std::this_thread::get_id() != mMainThreadId);
981 modes = getHwComposer().getColorModes(type);
982 }
Michael Wright28f24d02016-07-12 13:30:53 -0700983 outColorModes->clear();
984 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
985
986 return NO_ERROR;
987}
988
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700989ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
990 if (const auto display = getDisplayDevice(displayToken)) {
991 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700992 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700993 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700994}
995
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700996void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
997 Dataspace dataSpace, RenderIntent renderIntent) {
998 ColorMode currentMode = display->getActiveColorMode();
999 Dataspace currentDataSpace = display->getCompositionDataSpace();
1000 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001001
Peiyong Lin38e9a562018-04-10 16:24:20 -07001002 if (mode == currentMode && dataSpace == currentDataSpace &&
1003 renderIntent == currentRenderIntent) {
1004 return;
1005 }
1006
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001007 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001008 ALOGW("Trying to set config for virtual display");
1009 return;
1010 }
1011
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001012 display->setActiveColorMode(mode);
1013 display->setCompositionDataSpace(dataSpace);
1014 display->setActiveRenderIntent(renderIntent);
1015 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001016
1017 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001018 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1019 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001020}
1021
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001022status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001023 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001024 Vector<ColorMode> modes;
1025 getDisplayColorModes(displayToken, &modes);
1026 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1027 if (mode < ColorMode::NATIVE || !exists) {
1028 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1029 decodeColorMode(mode).c_str(), mode, displayToken.get());
1030 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001031 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001032 const auto display = getDisplayDevice(displayToken);
1033 if (!display) {
1034 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1035 decodeColorMode(mode).c_str(), mode, displayToken.get());
1036 } else if (display->isVirtual()) {
1037 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1038 decodeColorMode(mode).c_str(), mode);
1039 } else {
1040 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1041 RenderIntent::COLORIMETRIC);
1042 }
1043 }));
1044
Michael Wright28f24d02016-07-12 13:30:53 -07001045 return NO_ERROR;
1046}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001047
Svetoslavd85084b2014-03-20 10:28:31 -07001048status_t SurfaceFlinger::clearAnimationFrameStats() {
1049 Mutex::Autolock _l(mStateLock);
1050 mAnimFrameTracker.clearStats();
1051 return NO_ERROR;
1052}
1053
1054status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1055 Mutex::Autolock _l(mStateLock);
1056 mAnimFrameTracker.getStats(outStats);
1057 return NO_ERROR;
1058}
1059
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001060status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1061 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001062 Mutex::Autolock _l(mStateLock);
1063
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001064 const auto display = getDisplayDeviceLocked(displayToken);
1065 if (!display) {
1066 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001067 return BAD_VALUE;
1068 }
1069
Peiyong Linfb069302018-04-25 14:34:31 -07001070 // At this point the DisplayDeivce should already be set up,
1071 // meaning the luminance information is already queried from
1072 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001073 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001074 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1075 capabilities.getDesiredMaxLuminance(),
1076 capabilities.getDesiredMaxAverageLuminance(),
1077 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001078
1079 return NO_ERROR;
1080}
1081
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001082status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001083 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001084 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001085
Chia-I Wu90f669f2017-10-05 14:24:41 -07001086 if (mInjectVSyncs == enable) {
1087 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001088 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001089
1090 if (enable) {
1091 ALOGV("VSync Injections enabled");
1092 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001093 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001094 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001095 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001096 impl::EventThread::InterceptVSyncsCallback(),
1097 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001098 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001099 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001100 } else {
1101 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001102 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001103 }
1104
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001105 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001106 }));
1107
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001108 return NO_ERROR;
1109}
1110
1111status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001112 Mutex::Autolock _l(mStateLock);
1113
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001114 if (!mInjectVSyncs) {
1115 ALOGE("VSync Injections not enabled");
1116 return BAD_VALUE;
1117 }
1118 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1119 ALOGV("Injecting VSync inside SurfaceFlinger");
1120 mVSyncInjector->onInjectSyncEvent(when);
1121 }
1122 return NO_ERROR;
1123}
1124
Lloyd Pique755e3192018-01-31 16:46:15 -08001125status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1126 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001127 // Try to acquire a lock for 1s, fail gracefully
1128 const status_t err = mStateLock.timedLock(s2ns(1));
1129 const bool locked = (err == NO_ERROR);
1130 if (!locked) {
1131 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1132 return TIMED_OUT;
1133 }
1134
1135 outLayers->clear();
1136 mCurrentState.traverseInZOrder([&](Layer* layer) {
1137 outLayers->push_back(layer->getLayerDebugInfo());
1138 });
1139
1140 mStateLock.unlock();
1141 return NO_ERROR;
1142}
1143
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001144// ----------------------------------------------------------------------------
1145
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001146sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1147 ISurfaceComposer::VsyncSource vsyncSource) {
1148 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1149 return mSFEventThread->createEventConnection();
1150 } else {
1151 return mEventThread->createEventConnection();
1152 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001153}
1154
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001155// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001156
1157void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001158 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001159}
1160
1161void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001162 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001163}
1164
1165void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001166 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001167}
1168
1169void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001170 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001171 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001172}
1173
1174status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001175 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001176 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001177}
1178
1179status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001180 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001181 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001182 if (res == NO_ERROR) {
1183 msg->wait();
1184 }
1185 return res;
1186}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001187
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001188void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001189 do {
1190 waitForEvent();
1191 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001192}
1193
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001194void SurfaceFlinger::enableHardwareVsync() {
1195 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001196 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001197 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001198 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001199 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001200 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001201}
1202
Jesse Hall948fe0c2013-10-14 12:56:09 -07001203void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001204 Mutex::Autolock _l(mHWVsyncLock);
1205
Jesse Hall948fe0c2013-10-14 12:56:09 -07001206 if (makeAvailable) {
1207 mHWVsyncAvailable = true;
1208 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001209 // Hardware vsync is not currently available, so abort the resync
1210 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001211 return;
1212 }
1213
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001214 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1215 if (!getHwComposer().isConnected(displayId)) {
1216 return;
1217 }
1218
1219 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001220 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001221
Lloyd Pique41be5d22018-06-21 13:11:48 -07001222 mPrimaryDispSync->reset();
1223 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001224
1225 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001226 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001227 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001228 mPrimaryHWVsyncEnabled = true;
1229 }
1230}
1231
Jesse Hall948fe0c2013-10-14 12:56:09 -07001232void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001233 Mutex::Autolock _l(mHWVsyncLock);
1234 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001235 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001236 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001237 mPrimaryHWVsyncEnabled = false;
1238 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001239 if (makeUnavailable) {
1240 mHWVsyncAvailable = false;
1241 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001242}
1243
Tim Murray4a4e4a22016-04-19 16:29:23 +00001244void SurfaceFlinger::resyncWithRateLimit() {
1245 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001246
1247 // No explicit locking is needed here since EventThread holds a lock while calling this method
1248 static nsecs_t sLastResyncAttempted = 0;
1249 const nsecs_t now = systemTime();
1250 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001251 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001252 }
Dan Stoza57164302017-05-08 14:03:54 -07001253 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001254}
1255
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001256void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1257 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001258 ATRACE_NAME("SF onVsync");
1259
Steven Thomas3cfac282017-02-06 12:29:30 -08001260 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001261 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001262 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001263 return;
1264 }
1265
1266 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001267 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001268 return;
1269 }
1270
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001271 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1272 // For now, we don't do anything with external display vsyncs.
1273 return;
1274 }
1275
Jamie Gennisd1700752013-10-14 12:22:52 -07001276 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001277
Jamie Gennisd1700752013-10-14 12:22:52 -07001278 { // Scope for the lock
1279 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001280 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001281 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001282 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001283 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001284
1285 if (needsHwVsync) {
1286 enableHardwareVsync();
1287 } else {
1288 disableHardwareVsync(false);
1289 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001290}
1291
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001292void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001293 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1294 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001295}
1296
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001297void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001298 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001299 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001300 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001301
Lloyd Piqueba04e622017-12-14 17:11:26 -08001302 // Ignore events that do not have the right sequenceId.
1303 if (sequenceId != getBE().mComposerSequenceId) {
1304 return;
1305 }
1306
Steven Thomasb02664d2017-07-26 18:48:28 -07001307 // Only lock if we're not on the main thread. This function is normally
1308 // called on a hwbinder thread, but for the primary display it's called on
1309 // the main thread with the state lock already held, so don't attempt to
1310 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001311 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001312
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001313 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001314
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001315 if (std::this_thread::get_id() == mMainThreadId) {
1316 // Process all pending hot plug events immediately if we are on the main thread.
1317 processDisplayHotplugEventsLocked();
1318 }
1319
Lloyd Piqueba04e622017-12-14 17:11:26 -08001320 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001321}
1322
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001323void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001324 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001325 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001326 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001327 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001328 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001329}
1330
Dan Stoza9e56aa02015-11-02 13:00:03 -08001331void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001332 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001333 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001334 getHwComposer().setVsyncEnabled(disp,
1335 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001336}
1337
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001338// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001339void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001340 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001341 // Clear the drawing state so that the logic inside of
1342 // handleTransactionLocked will fire. It will determine the delta between
1343 // mCurrentState and mDrawingState and re-apply all changes when we make the
1344 // transition.
1345 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001346 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001347 mDisplays.clear();
1348}
1349
Steven Thomas050b2c82017-03-06 11:45:16 -08001350void SurfaceFlinger::updateVrFlinger() {
1351 if (!mVrFlinger)
1352 return;
1353 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001354 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001355 return;
1356 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001357
David Sodman105b7dc2017-11-04 20:28:14 -07001358 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001359 ALOGE("Vr flinger is only supported for remote hardware composer"
1360 " service connections. Ignoring request to transition to vr"
1361 " flinger.");
1362 mVrFlingerRequestsDisplay = false;
1363 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001364 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001365
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001366 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001367
Steven Thomas0123ac62018-07-12 11:32:34 -07001368 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001369 LOG_ALWAYS_FATAL_IF(!display);
1370 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001371 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1372 // called below. Clear the reference now so we don't accidentally use it
1373 // later.
1374 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001375
Steven Thomasb02664d2017-07-26 18:48:28 -07001376 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001377 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001378 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001379
Steven Thomasb02664d2017-07-26 18:48:28 -07001380 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001381 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001382 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1383 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001384 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001385
David Sodman105b7dc2017-11-04 20:28:14 -07001386 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1387 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001388
1389 if (vrFlingerRequestsDisplay) {
1390 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001391 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001392
1393 mVisibleRegionsDirty = true;
1394 invalidateHwcGeometry();
1395
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001396 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001397 display = getDefaultDisplayDeviceLocked();
1398 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001399 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001400
Steven Thomasb02664d2017-07-26 18:48:28 -07001401 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001402 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001403 const nsecs_t period = activeConfig->getVsyncPeriod();
1404 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001405
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001406 // The present fences returned from vr_hwc are not an accurate
1407 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001408 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1409 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001410
Steven Thomasb02664d2017-07-26 18:48:28 -07001411 // Use phase of 0 since phase is not known.
1412 // Use latency of 0, which will snap to the ideal latency.
1413 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001414
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001415 resyncToHardwareVsync(false);
1416
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001417 android_atomic_or(1, &mRepaintEverything);
1418 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001419}
1420
Mathias Agopian4fec8732012-06-29 14:12:52 -07001421void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001422 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001423 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001424 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001425 bool frameMissed = !mHadClientComposition &&
1426 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001427 (mPreviousPresentFence->getSignalTime() ==
1428 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001429 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001430 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001431 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001432 mTimeStats.incrementMissedFrames();
1433 if (mPropagateBackpressure) {
1434 signalLayerUpdate();
1435 break;
1436 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001437 }
Dan Stoza50182882016-07-08 12:02:20 -07001438
Steven Thomas050b2c82017-03-06 11:45:16 -08001439 // Now that we're going to make it to the handleMessageTransaction()
1440 // call below it's safe to call updateVrFlinger(), which will
1441 // potentially trigger a display handoff.
1442 updateVrFlinger();
1443
Dan Stoza6b9454d2014-11-07 16:00:59 -08001444 bool refreshNeeded = handleMessageTransaction();
1445 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001446 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001447 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001448 // Signal a refresh if a transaction modified the window state,
1449 // a new buffer was latched, or if HWC has requested a full
1450 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001451 signalRefresh();
1452 }
1453 break;
1454 }
1455 case MessageQueue::REFRESH: {
1456 handleMessageRefresh();
1457 break;
1458 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001459 }
1460}
1461
Dan Stoza6b9454d2014-11-07 16:00:59 -08001462bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001463 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001464 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001465 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001466 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001467 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001468 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001469}
1470
Mathias Agopian4fec8732012-06-29 14:12:52 -07001471void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001472 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001473
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001474 mRefreshPending = false;
1475
David Sodmanfa9b2af2017-12-24 13:28:59 -08001476 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
David Sodman2b406362017-12-15 13:33:47 -08001477 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001478 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001479 calculateWorkingSet();
David Sodman10a41ff2018-08-05 12:14:17 -07001480
David Sodmanfa9b2af2017-12-24 13:28:59 -08001481 for (const auto& [token, display] : mDisplays) {
David Sodman10a41ff2018-08-05 12:14:17 -07001482 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001483 beginFrame(display);
David Sodman10a41ff2018-08-05 12:14:17 -07001484 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
1485 setUpHWComposer(compositionInfo);
1486 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001487 prepareFrame(display);
1488 doDebugFlashRegions(display, repaintEverything);
1489 doComposition(display, repaintEverything);
1490 }
1491
Adrian Roos1e1a1282017-11-01 19:05:31 +01001492 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001493 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001494
1495 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001496 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001497
Dan Stozabfbffeb2016-07-21 14:49:33 -07001498 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001499 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001500 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001501 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001502 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001503
Jorim Jaggi90535212018-05-23 23:44:06 +02001504 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001505
David Sodman7e4ae112018-02-09 15:02:28 -08001506 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001507 for (const auto& [token, display] : mDisplays) {
1508 const auto displayId = display->getId();
David Sodman7e4ae112018-02-09 15:02:28 -08001509 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[displayId]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001510 compositionInfo.hwc.hwcLayer = nullptr;
1511 }
David Sodmanba340492018-08-05 21:51:33 -07001512 }
David Sodman7e4ae112018-02-09 15:02:28 -08001513
1514 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001515}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001516
David Sodmanfa9b2af2017-12-24 13:28:59 -08001517
1518bool SurfaceFlinger::handleMessageInvalidate() {
1519 ATRACE_CALL();
1520 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001521}
1522
David Sodman79bba0e2018-08-05 18:07:49 -07001523void SurfaceFlinger::calculateWorkingSet() {
1524 ATRACE_CALL();
1525 ALOGV(__FUNCTION__);
1526
David Sodman79bba0e2018-08-05 18:07:49 -07001527 // build the h/w work list
1528 if (CC_UNLIKELY(mGeometryInvalid)) {
1529 mGeometryInvalid = false;
1530 for (const auto& [token, display] : mDisplays) {
1531 const auto displayId = display->getId();
1532 if (displayId >= 0) {
1533 const Vector<sp<Layer>>& currentLayers(
1534 display->getVisibleLayersSortedByZ());
1535 for (size_t i = 0; i < currentLayers.size(); i++) {
1536 const auto& layer = currentLayers[i];
1537
1538 if (!layer->hasHwcLayer(displayId)) {
1539 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1540 layer->forceClientComposition(displayId);
1541 continue;
1542 }
1543 }
1544
1545 layer->setGeometry(display, i);
1546 if (mDebugDisableHWC || mDebugRegion) {
1547 layer->forceClientComposition(displayId);
1548 }
1549 }
1550 }
1551 }
1552 }
1553
1554 // Set the per-frame data
1555 for (const auto& [token, display] : mDisplays) {
1556 const auto displayId = display->getId();
1557 if (displayId < 0) {
1558 continue;
1559 }
1560
1561 if (mDrawingState.colorMatrixChanged) {
1562 display->setColorTransform(mDrawingState.colorMatrix);
1563 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1564 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1565 "display %d: %d", displayId, result);
1566 }
1567 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1568 if (layer->isHdrY410()) {
1569 layer->forceClientComposition(displayId);
1570 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1571 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1572 !display->hasHDR10Support()) {
1573 layer->forceClientComposition(displayId);
1574 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1575 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1576 !display->hasHLGSupport()) {
1577 layer->forceClientComposition(displayId);
1578 }
1579
1580 if (layer->getForceClientComposition(displayId)) {
1581 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1582 layer->setCompositionType(displayId, HWC2::Composition::Client);
1583 continue;
1584 }
1585
1586 layer->setPerFrameData(display);
1587 }
1588
Peiyong Lin13effd12018-07-24 17:01:47 -07001589 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001590 ColorMode colorMode;
1591 Dataspace dataSpace;
1592 RenderIntent renderIntent;
1593 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1594 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1595 }
1596 }
1597
1598 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001599
1600 for (const auto& [token, display] : mDisplays) {
David Sodman15fb96e2018-01-07 10:23:24 -08001601 const auto displayId = display->getId();
1602 getBE().mCompositionInfo[displayId].clear();
David Sodmanba340492018-08-05 21:51:33 -07001603 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1604 auto displayId = display->getId();
1605 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1606 if (!layer->setHwcLayer(displayId)) {
1607 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1608 }
David Sodman15fb96e2018-01-07 10:23:24 -08001609 layer->getBE().compositionInfo.hwc.displayId = displayId;
1610 getBE().mCompositionInfo[displayId].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001611 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1612 }
1613 }
David Sodman79bba0e2018-08-05 18:07:49 -07001614}
1615
David Sodmanfa9b2af2017-12-24 13:28:59 -08001616void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001617{
David Sodmanfb95bcc2017-12-22 15:45:30 -08001618 const auto displayId = display->getId();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001619 // is debugging enabled
1620 if (CC_LIKELY(!mDebugRegion))
1621 return;
1622
David Sodmanfa9b2af2017-12-24 13:28:59 -08001623 if (display->isPoweredOn()) {
1624 // transform the dirty region into this screen's coordinate space
1625 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1626 if (!dirtyRegion.isEmpty()) {
1627 // redraw the whole screen
1628 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001629
David Sodmanfa9b2af2017-12-24 13:28:59 -08001630 // and draw the dirty region
1631 const int32_t height = display->getHeight();
1632 auto& engine(getRenderEngine());
1633 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001634
David Sodmanfa9b2af2017-12-24 13:28:59 -08001635 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001636 }
1637 }
1638
David Sodmanfa9b2af2017-12-24 13:28:59 -08001639 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001640
1641 if (mDebugRegion > 1) {
1642 usleep(mDebugRegion * 1000);
1643 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001644
David Sodmanfa9b2af2017-12-24 13:28:59 -08001645 if (display->isPoweredOn()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08001646 status_t result = display->prepareFrame(
1647 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001648 ALOGE_IF(result != NO_ERROR,
1649 "prepareFrame for display %d failed:"
1650 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001651 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001652 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001653}
1654
Adrian Roos1e1a1282017-11-01 19:05:31 +01001655void SurfaceFlinger::doTracing(const char* where) {
1656 ATRACE_CALL();
1657 ATRACE_NAME(where);
1658 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001659 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001660 }
1661}
1662
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001663void SurfaceFlinger::logLayerStats() {
1664 ATRACE_CALL();
1665 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001666 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001667 if (display->isPrimary()) {
1668 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001669 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001670 }
1671 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001672
1673 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001674 }
1675}
1676
David Sodman2b406362017-12-15 13:33:47 -08001677void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001678{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001679 ATRACE_CALL();
1680 ALOGV("preComposition");
1681
David Sodman2b406362017-12-15 13:33:47 -08001682 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1683
Mathias Agopiancd60f992012-08-16 16:28:27 -07001684 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001685 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001686 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001687 needExtraInvalidate = true;
1688 }
Robert Carr2047fae2016-11-28 14:09:09 -08001689 });
1690
Mathias Agopiancd60f992012-08-16 16:28:27 -07001691 if (needExtraInvalidate) {
1692 signalLayerUpdate();
1693 }
1694}
1695
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001696void SurfaceFlinger::updateCompositorTiming(
1697 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1698 std::shared_ptr<FenceTime>& presentFenceTime) {
1699 // Update queue of past composite+present times and determine the
1700 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001701 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001702 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001703 while (!getBE().mCompositePresentTimes.empty()) {
1704 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001705 // Cached values should have been updated before calling this method,
1706 // which helps avoid duplicate syscalls.
1707 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1708 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1709 break;
1710 }
1711 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001712 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001713 }
1714
1715 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001716 while (getBE().mCompositePresentTimes.size() > 16) {
1717 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001718 }
1719
Brian Andersond0010582017-03-07 13:20:31 -08001720 setCompositorTimingSnapped(
1721 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1722}
1723
1724void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1725 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001726 // Integer division and modulo round toward 0 not -inf, so we need to
1727 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001728 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001729 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1730 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1731
Brian Andersond0010582017-03-07 13:20:31 -08001732 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1733 if (idealLatency <= 0) {
1734 idealLatency = vsyncInterval;
1735 }
1736
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001737 // Snap the latency to a value that removes scheduling jitter from the
1738 // composition and present times, which often have >1ms of jitter.
1739 // Reducing jitter is important if an app attempts to extrapolate
1740 // something (such as user input) to an accurate diasplay time.
1741 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1742 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001743 nsecs_t bias = vsyncInterval / 2;
1744 int64_t extraVsyncs =
1745 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1746 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1747 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001748
David Sodman99974d22017-11-28 12:04:33 -08001749 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1750 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1751 getBE().mCompositorTiming.interval = vsyncInterval;
1752 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001753}
1754
David Sodman2b406362017-12-15 13:33:47 -08001755void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001756{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001757 ATRACE_CALL();
1758 ALOGV("postComposition");
1759
Brian Anderson3546a3f2016-07-14 11:51:14 -07001760 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001761 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001762 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001763 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001764 }
1765
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001766 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001767 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001768
David Sodman73beded2017-11-15 11:56:06 -08001769 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001770 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001771 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001772 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001773 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001774 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001775 } else {
1776 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1777 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001778
David Sodman73beded2017-11-15 11:56:06 -08001779 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001780 mPreviousPresentFence =
1781 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1782 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001783 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001784
Lloyd Pique41be5d22018-06-21 13:11:48 -07001785 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1786 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001787
David Sodman2b406362017-12-15 13:33:47 -08001788 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001789 // when we started doing work for this frame, but that should be okay
1790 // since updateCompositorTiming has snapping logic.
1791 updateCompositorTiming(
David Sodman2b406362017-12-15 13:33:47 -08001792 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001793 CompositorTiming compositorTiming;
1794 {
David Sodman99974d22017-11-28 12:04:33 -08001795 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1796 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001797 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001798
Robert Carr2047fae2016-11-28 14:09:09 -08001799 mDrawingState.traverseInZOrder([&](Layer* layer) {
1800 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001801 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001802 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001803 recordBufferingStats(layer->getName().string(),
1804 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001805 }
Robert Carr2047fae2016-11-28 14:09:09 -08001806 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001807
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001808 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001809 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001810 enableHardwareVsync();
1811 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001812 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001813 }
1814 }
1815
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001816 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001817 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001818 enableHardwareVsync();
1819 }
1820 }
1821
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001822 if (mAnimCompositionPending) {
1823 mAnimCompositionPending = false;
1824
Brian Anderson4e606e32017-03-16 15:34:57 -07001825 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001826 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001827 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001828 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001829 // The HWC doesn't support present fences, so use the refresh
1830 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001831 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001832 mAnimFrameTracker.setActualPresentTime(presentTime);
1833 }
1834 mAnimFrameTracker.advanceFrame();
1835 }
Dan Stozab90cf072015-03-05 11:05:59 -08001836
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001837 mTimeStats.incrementTotalFrames();
1838 if (mHadClientComposition) {
1839 mTimeStats.incrementClientCompositionFrames();
1840 }
1841
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001842 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001843 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001844 return;
1845 }
1846
1847 nsecs_t currentTime = systemTime();
1848 if (mHasPoweredOff) {
1849 mHasPoweredOff = false;
1850 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001851 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001852 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001853 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1854 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001855 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001856 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001857 }
David Sodman4a36e932017-11-07 14:29:47 -08001858 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001859 }
David Sodman4a36e932017-11-07 14:29:47 -08001860 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001861
1862 {
1863 std::lock_guard lock(mTexturePoolMutex);
1864 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1865 if (refillCount > 0) {
1866 const size_t offset = mTexturePool.size();
1867 mTexturePool.resize(mTexturePoolSize);
1868 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1869 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1870 }
1871 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001872}
1873
1874void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001875 ATRACE_CALL();
1876 ALOGV("rebuildLayerStacks");
1877
Mathias Agopiancd60f992012-08-16 16:28:27 -07001878 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001879 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001880 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001881 mVisibleRegionsDirty = false;
1882 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001883
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001884 for (const auto& pair : mDisplays) {
1885 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001886 Region opaqueRegion;
1887 Region dirtyRegion;
1888 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001889 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001890 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001891 const Rect bounds = display->getBounds();
1892 if (display->isPoweredOn()) {
1893 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001894
Jeff Sharkey76488112017-02-27 14:15:18 -07001895 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001896 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001897 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001898 Region drawRegion(tr.transform(
1899 layer->visibleNonTransparentRegion));
1900 drawRegion.andSelf(bounds);
1901 if (!drawRegion.isEmpty()) {
1902 layersSortedByZ.add(layer);
1903 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001904 // Clear out the HWC layer if this layer was
1905 // previously visible, but no longer is
1906 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001907 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001908 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001909 // WM changes display->layerStack upon sleep/awake.
1910 // Here we make sure we delete the HWC layers even if
1911 // WM changed their layer stack.
1912 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001913 }
1914
1915 // If a layer is not going to get a release fence because
1916 // it is invisible, but it is also going to release its
1917 // old buffer, add it to the list of layers needing
1918 // fences.
1919 if (hwcLayerDestroyed) {
1920 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1921 mLayersWithQueuedFrames.cend(), layer);
1922 if (found != mLayersWithQueuedFrames.cend()) {
1923 layersNeedingFences.add(layer);
1924 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001925 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001926 });
1927 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001928 display->setVisibleLayersSortedByZ(layersSortedByZ);
1929 display->setLayersNeedingFences(layersNeedingFences);
1930 display->undefinedRegion.set(bounds);
1931 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1932 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001933 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001934 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001935}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001936
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001937// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001938// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001939// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001940// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001941// The returned HDR data space is one of
1942// - Dataspace::UNKNOWN
1943// - Dataspace::BT2020_HLG
1944// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001945Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1946 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001947 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001948 *outHdrDataSpace = Dataspace::UNKNOWN;
1949
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001950 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001951 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001952 case Dataspace::V0_SCRGB:
1953 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001954 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001955 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001956 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001957 case Dataspace::BT2020_PQ:
1958 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001959 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001960 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001961 case Dataspace::BT2020_HLG:
1962 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001963 // When there's mixed PQ content and HLG content, we set the HDR
1964 // data space to be BT2020_PQ and convert HLG to PQ.
1965 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1966 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001967 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001968 break;
1969 default:
1970 break;
1971 }
Romain Guy54f154a2017-10-24 21:40:32 +01001972 }
1973
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001974 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001975}
1976
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001977// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001978void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1979 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001980 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1981 *outMode = ColorMode::NATIVE;
1982 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001983 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001984 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001985 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001986
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001987 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001988 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001989
Peiyong Lindfde5112018-06-05 10:58:41 -07001990 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001991 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001992 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001993 if (isHdr) {
1994 bestDataSpace = hdrDataSpace;
1995 }
1996
Chia-I Wu0d711262018-05-21 15:19:35 -07001997 RenderIntent intent;
1998 switch (mDisplayColorSetting) {
1999 case DisplayColorSetting::MANAGED:
2000 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002001 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002002 break;
2003 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002004 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002005 break;
2006 default: // vendor display color setting
2007 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2008 break;
2009 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002010
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002011 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002012}
2013
David Sodman10a41ff2018-08-05 12:14:17 -07002014void SurfaceFlinger::configureSidebandComposition(const CompositionInfo& compositionInfo) const
2015{
2016 HWC2::Error error;
2017 LOG_ALWAYS_FATAL_IF(compositionInfo.hwc.sidebandStream == nullptr,
2018 "CompositionType is sideband, but sideband stream is nullptr");
2019 error = (compositionInfo.hwc.hwcLayer)
2020 ->setSidebandStream(compositionInfo.hwc.sidebandStream->handle());
2021 if (error != HWC2::Error::None) {
2022 ALOGE("[SF] Failed to set sideband stream %p: %s (%d)",
2023 compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
2024 static_cast<int32_t>(error));
2025 }
2026}
2027
2028void SurfaceFlinger::configureHwcCommonData(const CompositionInfo& compositionInfo) const
2029{
2030 HWC2::Error error;
2031
2032 if (!compositionInfo.hwc.skipGeometry) {
2033 error = (compositionInfo.hwc.hwcLayer)->setBlendMode(compositionInfo.hwc.blendMode);
2034 ALOGE_IF(error != HWC2::Error::None,
2035 "[SF] Failed to set blend mode %s:"
2036 " %s (%d)",
2037 to_string(compositionInfo.hwc.blendMode).c_str(), to_string(error).c_str(),
2038 static_cast<int32_t>(error));
2039
2040 error = (compositionInfo.hwc.hwcLayer)->setDisplayFrame(compositionInfo.hwc.displayFrame);
2041 ALOGE_IF(error != HWC2::Error::None,
2042 "[SF] Failed to set the display frame [%d, %d, %d, %d] %s (%d)",
2043 compositionInfo.hwc.displayFrame.left,
2044 compositionInfo.hwc.displayFrame.right,
2045 compositionInfo.hwc.displayFrame.top,
2046 compositionInfo.hwc.displayFrame.bottom,
2047 to_string(error).c_str(), static_cast<int32_t>(error));
2048
2049 error = (compositionInfo.hwc.hwcLayer)->setSourceCrop(compositionInfo.hwc.sourceCrop);
2050 ALOGE_IF(error != HWC2::Error::None,
2051 "[SF] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: %s (%d)",
2052 compositionInfo.hwc.sourceCrop.left,
2053 compositionInfo.hwc.sourceCrop.right,
2054 compositionInfo.hwc.sourceCrop.top,
2055 compositionInfo.hwc.sourceCrop.bottom,
2056 to_string(error).c_str(), static_cast<int32_t>(error));
2057
2058 error = (compositionInfo.hwc.hwcLayer)->setPlaneAlpha(compositionInfo.hwc.alpha);
2059 ALOGE_IF(error != HWC2::Error::None,
2060 "[SF] Failed to set plane alpha %.3f: "
2061 "%s (%d)",
2062 compositionInfo.hwc.alpha,
2063 to_string(error).c_str(), static_cast<int32_t>(error));
2064
2065
2066 error = (compositionInfo.hwc.hwcLayer)->setZOrder(compositionInfo.hwc.z);
2067 ALOGE_IF(error != HWC2::Error::None,
2068 "[SF] Failed to set Z %u: %s (%d)",
2069 compositionInfo.hwc.z,
2070 to_string(error).c_str(), static_cast<int32_t>(error));
2071
2072 error = (compositionInfo.hwc.hwcLayer)
2073 ->setInfo(compositionInfo.hwc.type, compositionInfo.hwc.appId);
2074 ALOGE_IF(error != HWC2::Error::None,
2075 "[SF] Failed to set info (%d)",
2076 static_cast<int32_t>(error));
2077
2078 error = (compositionInfo.hwc.hwcLayer)->setTransform(compositionInfo.hwc.transform);
2079 ALOGE_IF(error != HWC2::Error::None,
2080 "[SF] Failed to set transform %s: "
2081 "%s (%d)",
2082 to_string(compositionInfo.hwc.transform).c_str(), to_string(error).c_str(),
2083 static_cast<int32_t>(error));
2084 }
2085
2086 error = (compositionInfo.hwc.hwcLayer)->setCompositionType(compositionInfo.compositionType);
2087 ALOGE_IF(error != HWC2::Error::None,
2088 "[SF] Failed to set composition type: %s (%d)",
2089 to_string(error).c_str(), static_cast<int32_t>(error));
2090
2091 error = (compositionInfo.hwc.hwcLayer)->setDataspace(compositionInfo.hwc.dataspace);
2092 ALOGE_IF(error != HWC2::Error::None,
2093 "[SF] Failed to set dataspace: %s (%d)",
2094 to_string(error).c_str(), static_cast<int32_t>(error));
2095
2096 error = (compositionInfo.hwc.hwcLayer)->setPerFrameMetadata(
2097 compositionInfo.hwc.supportedPerFrameMetadata, compositionInfo.hwc.hdrMetadata);
2098 ALOGE_IF(error != HWC2::Error::None && error != HWC2::Error::Unsupported,
2099 "[SF] Failed to set hdrMetadata: %s (%d)",
2100 to_string(error).c_str(), static_cast<int32_t>(error));
2101
2102 if (compositionInfo.compositionType == HWC2::Composition::SolidColor) {
2103 error = (compositionInfo.hwc.hwcLayer)->setColor(compositionInfo.hwc.color);
2104 ALOGE_IF(error != HWC2::Error::None,
2105 "[SF] Failed to set color: %s (%d)",
2106 to_string(error).c_str(), static_cast<int32_t>(error));
2107 }
2108
2109 error = (compositionInfo.hwc.hwcLayer)->setVisibleRegion(compositionInfo.hwc.visibleRegion);
2110 ALOGE_IF(error != HWC2::Error::None,
2111 "[SF] Failed to set visible region: %s (%d)",
2112 to_string(error).c_str(), static_cast<int32_t>(error));
2113
2114 error = (compositionInfo.hwc.hwcLayer)->setSurfaceDamage(compositionInfo.hwc.surfaceDamage);
2115 ALOGE_IF(error != HWC2::Error::None,
2116 "[SF] Failed to set surface damage: %s (%d)",
2117 to_string(error).c_str(), static_cast<int32_t>(error));
2118}
2119
2120void SurfaceFlinger::configureDeviceComposition(const CompositionInfo& compositionInfo) const
2121{
2122 HWC2::Error error;
2123
2124 if (compositionInfo.hwc.fence) {
2125 error = (compositionInfo.hwc.hwcLayer)->setBuffer(compositionInfo.mBufferSlot,
2126 compositionInfo.mBuffer, compositionInfo.hwc.fence);
2127 ALOGE_IF(error != HWC2::Error::None,
2128 "[SF] Failed to set buffer: %s (%d)",
2129 to_string(error).c_str(), static_cast<int32_t>(error));
2130 }
2131}
2132
David Sodmanfa9b2af2017-12-24 13:28:59 -08002133void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002134{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002135 bool dirty = !display->getDirtyRegion(false).isEmpty();
2136 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2137 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002138
David Sodmanfa9b2af2017-12-24 13:28:59 -08002139 // If nothing has changed (!dirty), don't recompose.
2140 // If something changed, but we don't currently have any visible layers,
2141 // and didn't when we last did a composition, then skip it this time.
2142 // The second rule does two things:
2143 // - When all layers are removed from a display, we'll emit one black
2144 // frame, then nothing more until we get new layers.
2145 // - When a display is created with a private layer stack, we won't
2146 // emit any black frames until a layer is added to the layer stack.
2147 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002148
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002149 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2150 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002151 mustRecompose ? "doing" : "skipping",
2152 dirty ? "+" : "-",
2153 empty ? "+" : "-",
2154 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002155
David Sodmanfa9b2af2017-12-24 13:28:59 -08002156 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002157
David Sodmanfa9b2af2017-12-24 13:28:59 -08002158 if (mustRecompose) {
2159 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002160 }
2161}
2162
David Sodmanfa9b2af2017-12-24 13:28:59 -08002163void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002164{
David Sodmanfb95bcc2017-12-22 15:45:30 -08002165 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002166 if (!display->isPoweredOn()) {
2167 return;
David Sodman2b406362017-12-15 13:33:47 -08002168 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002169
David Sodmanfb95bcc2017-12-22 15:45:30 -08002170 status_t result = display->prepareFrame(
2171 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08002172 ALOGE_IF(result != NO_ERROR,
2173 "prepareFrame for display %d failed:"
2174 " %d (%s)",
2175 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002176}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002177
David Sodman10a41ff2018-08-05 12:14:17 -07002178void SurfaceFlinger::setUpHWComposer(const CompositionInfo& compositionInfo) {
2179 ATRACE_CALL();
2180 ALOGV("setUpHWComposer");
2181
2182 switch (compositionInfo.compositionType)
2183 {
2184 case HWC2::Composition::Invalid:
2185 case HWC2::Composition::Client:
2186 break;
2187
2188 case HWC2::Composition::Sideband:
2189 configureHwcCommonData(compositionInfo);
2190 configureSidebandComposition(compositionInfo);
2191 break;
2192
2193 case HWC2::Composition::SolidColor:
2194 configureHwcCommonData(compositionInfo);
2195 break;
2196
2197 case HWC2::Composition::Device:
2198 case HWC2::Composition::Cursor:
2199 configureHwcCommonData(compositionInfo);
2200 configureDeviceComposition(compositionInfo);
2201 break;
2202 }
2203}
2204
David Sodmanfa9b2af2017-12-24 13:28:59 -08002205void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002206 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002207 ALOGV("doComposition");
2208
David Sodmanfa9b2af2017-12-24 13:28:59 -08002209 if (display->isPoweredOn()) {
2210 // transform the dirty region into this screen's coordinate space
2211 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002212
David Sodmanfa9b2af2017-12-24 13:28:59 -08002213 // repaint the framebuffer (if needed)
2214 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002215
David Sodmanfa9b2af2017-12-24 13:28:59 -08002216 display->dirtyRegion.clear();
2217 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002218 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002219 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002220}
2221
David Sodmanfa9b2af2017-12-24 13:28:59 -08002222void SurfaceFlinger::postFrame()
2223{
2224 // |mStateLock| not needed as we are on the main thread
2225 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2226 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2227 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2228 logFrameStats();
2229 }
2230 }
2231}
2232
2233void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002234{
Mathias Agopian841cde52012-03-01 15:44:37 -08002235 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002236 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002237
David Sodmanfa9b2af2017-12-24 13:28:59 -08002238 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002239
David Sodmanfa9b2af2017-12-24 13:28:59 -08002240 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002241 const auto displayId = display->getId();
2242 if (displayId >= 0) {
2243 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002244 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002245 display->onSwapBuffersCompleted();
2246 display->makeCurrent();
David Sodman10a41ff2018-08-05 12:14:17 -07002247 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002248 sp<Fence> releaseFence = Fence::NO_FENCE;
Chia-I Wu7b549592017-11-15 09:14:57 -08002249 // The layer buffer from the previous frame (if any) is released
2250 // by HWC only when the release fence from this frame (if any) is
2251 // signaled. Always get the release fence from HWC first.
David Sodman10a41ff2018-08-05 12:14:17 -07002252 auto hwcLayer = compositionInfo.hwc.hwcLayer;
2253 if ((displayId >= 0) && hwcLayer) {
2254 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer.get());
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002255 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002256
2257 // If the layer was client composited in the previous frame, we
2258 // need to merge with the previous client target acquire fence.
2259 // Since we do not track that, always merge with the current
2260 // client target acquire fence when it is available, even though
2261 // this is suboptimal.
David Sodman10a41ff2018-08-05 12:14:17 -07002262 if (compositionInfo.compositionType == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002263 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002264 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002265 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002266
David Sodman10a41ff2018-08-05 12:14:17 -07002267 if (compositionInfo.layer) {
2268 compositionInfo.layer->onLayerDisplayed(releaseFence);
2269 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002270 }
Chia-I Wu83806892017-11-16 10:50:20 -08002271
2272 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002273 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002274 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002275 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002276 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002277 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002278 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002279 }
2280 }
2281
Dominik Laskowski7e045462018-05-30 13:02:02 -07002282 if (displayId >= 0) {
2283 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002284 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002285 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002286}
2287
Mathias Agopian87baae12012-07-31 12:38:26 -07002288void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002289{
Mathias Agopian841cde52012-03-01 15:44:37 -08002290 ATRACE_CALL();
2291
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002292 // here we keep a copy of the drawing state (that is the state that's
2293 // going to be overwritten by handleTransactionLocked()) outside of
2294 // mStateLock so that the side-effects of the State assignment
2295 // don't happen with mStateLock held (which can cause deadlocks).
2296 State drawingState(mDrawingState);
2297
Mathias Agopianca4d3602011-05-19 15:38:14 -07002298 Mutex::Autolock _l(mStateLock);
2299 const nsecs_t now = systemTime();
2300 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002301
Mathias Agopianca4d3602011-05-19 15:38:14 -07002302 // Here we're guaranteed that some transaction flags are set
2303 // so we can call handleTransactionLocked() unconditionally.
2304 // We call getTransactionFlags(), which will also clear the flags,
2305 // with mStateLock held to guarantee that mCurrentState won't change
2306 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002307
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002308 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002309 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002310 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002311
Mathias Agopianca4d3602011-05-19 15:38:14 -07002312 mLastTransactionTime = systemTime() - now;
2313 mDebugInTransaction = 0;
2314 invalidateHwcGeometry();
2315 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002316}
2317
Dominik Laskowski7e045462018-05-30 13:02:02 -07002318DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002319 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002320 // Figure out whether the event is for the primary display or an
2321 // external display by matching the Hwc display id against one for a
2322 // connected display. If we did not find a match, we then check what
2323 // displays are not already connected to determine the type. If we don't
2324 // have a connected primary display, we assume the new display is meant to
2325 // be the primary display, and then if we don't have an external display,
2326 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002327 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2328 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002329 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002330 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002331 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002332 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002333 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002334 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002335 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002336 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002337 return DisplayDevice::DISPLAY_EXTERNAL;
2338 }
2339
2340 return DisplayDevice::DISPLAY_ID_INVALID;
2341}
2342
Lloyd Piqueba04e622017-12-14 17:11:26 -08002343void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2344 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002345 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002346 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002347 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002348 continue;
2349 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002350
2351 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2352 ALOGE("External displays are not supported by the vr hardware composer.");
2353 continue;
2354 }
2355
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002356 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002357 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002358 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002359 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002360 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002361
2362 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002363 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002364 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002365 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002366 DisplayDeviceState info;
2367 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002368 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2369 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002370 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002371 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002372 mInterceptor->saveDisplayCreation(info);
2373 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002374 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002375 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002376
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002377 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002378 if (idx >= 0) {
2379 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002380 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002381 mCurrentState.displays.removeItemsAt(idx);
2382 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002383 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002384 }
2385
2386 processDisplayChangesLocked();
2387 }
2388
2389 mPendingHotplugEvents.clear();
2390}
2391
Lloyd Pique99d3da52018-01-22 17:48:03 -08002392sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002393 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002394 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002395 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002396 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002397 HdrCapabilities hdrCapabilities;
2398 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002399
Peiyong Lin13effd12018-07-24 17:01:47 -07002400 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002401 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002402 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002403 if (isWideColorMode(colorMode)) {
2404 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002405 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002406
Dominik Laskowski7e045462018-05-30 13:02:02 -07002407 std::vector<RenderIntent> renderIntents =
2408 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002409 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002410 }
tangrobin6753a022018-08-10 10:58:54 +08002411 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002412
tangrobin6753a022018-08-10 10:58:54 +08002413 if (displayId >= 0) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002414 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2415 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2416 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002417
2418 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2419 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2420
2421 /*
2422 * Create our display's surface
2423 */
Peiyong Lin833074a2018-08-28 11:53:54 -07002424 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002425 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002426 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002427 renderSurface->setNativeWindow(nativeWindow.get());
2428 const int displayWidth = renderSurface->queryWidth();
2429 const int displayHeight = renderSurface->queryHeight();
2430
2431 // Make sure that composition can never be stalled by a virtual display
2432 // consumer that isn't processing buffers fast enough. We have to do this
2433 // in two places:
2434 // * Here, in case the display is composed entirely by HWC.
2435 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2436 // window's swap interval in eglMakeCurrent, so they'll override the
2437 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002438 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002439 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2440 }
2441
2442 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002443 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002444
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002445 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002446 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2447 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2448 displayHeight, hasWideColorGamut, hdrCapabilities,
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002449 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002450
2451 if (maxFrameBufferAcquiredBuffers >= 3) {
2452 nativeWindowSurface->preallocateBuffers();
2453 }
2454
2455 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002456 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2457 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002458 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002459 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002460 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002461 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002462 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002463 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002464 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002465 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002466 display->setLayerStack(state.layerStack);
2467 display->setProjection(state.orientation, state.viewport, state.frame);
2468 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002469
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002470 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002471}
2472
Lloyd Pique347200f2017-12-14 17:00:15 -08002473void SurfaceFlinger::processDisplayChangesLocked() {
2474 // here we take advantage of Vector's copy-on-write semantics to
2475 // improve performance by skipping the transaction entirely when
2476 // know that the lists are identical
2477 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2478 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2479 if (!curr.isIdenticalTo(draw)) {
2480 mVisibleRegionsDirty = true;
2481 const size_t cc = curr.size();
2482 size_t dc = draw.size();
2483
2484 // find the displays that were removed
2485 // (ie: in drawing state but not in current state)
2486 // also handle displays that changed
2487 // (ie: displays that are in both lists)
2488 for (size_t i = 0; i < dc;) {
2489 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2490 if (j < 0) {
2491 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002492 // Call makeCurrent() on the primary display so we can
2493 // be sure that nothing associated with this display
2494 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002495 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2496 defaultDisplay->makeCurrent();
2497 }
2498 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2499 display->disconnect(getHwComposer());
2500 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002501 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2502 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2503 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2504 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2505 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002506 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002507 } else {
2508 // this display is in both lists. see if something changed.
2509 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002510 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002511 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2512 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2513 if (state_binder != draw_binder) {
2514 // changing the surface is like destroying and
2515 // recreating the DisplayDevice, so we just remove it
2516 // from the drawing state, so that it get re-added
2517 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002518 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2519 display->disconnect(getHwComposer());
2520 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002521 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002522 mDrawingState.displays.removeItemsAt(i);
2523 dc--;
2524 // at this point we must loop to the next item
2525 continue;
2526 }
2527
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002528 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002529 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002530 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002531 }
2532 if ((state.orientation != draw[i].orientation) ||
2533 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002534 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002535 }
2536 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002537 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002538 }
2539 }
2540 }
2541 ++i;
2542 }
2543
2544 // find displays that were added
2545 // (ie: in current state but not in drawing state)
2546 for (size_t i = 0; i < cc; i++) {
2547 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2548 const DisplayDeviceState& state(curr[i]);
2549
2550 sp<DisplaySurface> dispSurface;
2551 sp<IGraphicBufferProducer> producer;
2552 sp<IGraphicBufferProducer> bqProducer;
2553 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002554 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002555
Dominik Laskowski7e045462018-05-30 13:02:02 -07002556 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002557 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002558 // Virtual displays without a surface are dormant:
2559 // they have external state (layer stack, projection,
2560 // etc.) but no internal state (i.e. a DisplayDevice).
2561 if (state.surface != nullptr) {
2562 // Allow VR composer to use virtual displays.
2563 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2564 int width = 0;
2565 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2566 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2567 int height = 0;
2568 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2569 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2570 int intFormat = 0;
2571 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2572 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002573 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002574
Dominik Laskowski7e045462018-05-30 13:02:02 -07002575 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2576 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002577 }
2578
2579 // TODO: Plumb requested format back up to consumer
2580
2581 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002582 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002583 bqProducer, bqConsumer,
2584 state.displayName);
2585
2586 dispSurface = vds;
2587 producer = vds;
2588 }
2589 } else {
2590 ALOGE_IF(state.surface != nullptr,
2591 "adding a supported display, but rendering "
2592 "surface is provided (%p), ignoring it",
2593 state.surface.get());
2594
Dominik Laskowski7e045462018-05-30 13:02:02 -07002595 displayId = state.type;
2596 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002597 producer = bqProducer;
2598 }
2599
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002600 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002601 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002602 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002603 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002604 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002605 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002606 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2607 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2608 true);
2609 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2610 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2611 true);
2612 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002613 }
2614 }
2615 }
2616 }
2617 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002618
2619 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002620}
2621
Mathias Agopian87baae12012-07-31 12:38:26 -07002622void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002623{
Dan Stoza7dde5992015-05-22 09:51:44 -07002624 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002625 mCurrentState.traverseInZOrder([](Layer* layer) {
2626 layer->notifyAvailableFrames();
2627 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002628
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002629 /*
2630 * Traversal of the children
2631 * (perform the transaction for each of them if needed)
2632 */
2633
Mathias Agopian3559b072012-08-15 13:46:03 -07002634 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002635 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002636 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002637 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002638
2639 const uint32_t flags = layer->doTransaction(0);
2640 if (flags & Layer::eVisibleRegion)
2641 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002642 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002643 }
2644
2645 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002646 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002647 */
2648
Mathias Agopiane57f2922012-08-09 16:29:12 -07002649 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002650 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002651 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002652 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002653
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002654 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002655 // The transform hint might have changed for some layers
2656 // (either because a display has changed, or because a layer
2657 // as changed).
2658 //
2659 // Walk through all the layers in currentLayers,
2660 // and update their transform hint.
2661 //
2662 // If a layer is visible only on a single display, then that
2663 // display is used to calculate the hint, otherwise we use the
2664 // default display.
2665 //
2666 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2667 // the hint is set before we acquire a buffer from the surface texture.
2668 //
2669 // NOTE: layer transactions have taken place already, so we use their
2670 // drawing state. However, SurfaceFlinger's own transaction has not
2671 // happened yet, so we must use the current state layer list
2672 // (soon to become the drawing state list).
2673 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002674 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002675 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002676 bool first = true;
2677 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002678 // NOTE: we rely on the fact that layers are sorted by
2679 // layerStack first (so we don't have to traverse the list
2680 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002681 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002682 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002683 currentlayerStack = layerStack;
2684 // figure out if this layerstack is mirrored
2685 // (more than one display) if so, pick the default display,
2686 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002687 hintDisplay = nullptr;
2688 for (const auto& [token, display] : mDisplays) {
2689 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2690 if (hintDisplay) {
2691 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002692 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002693 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002694 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002695 }
2696 }
2697 }
2698 }
Chet Haase91d25932013-04-11 15:24:55 -07002699
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002700 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002701 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2702 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002703
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002704 // could be null when this layer is using a layerStack
2705 // that is not visible on any display. Also can occur at
2706 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002707 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002708 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002709
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002710 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002711 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002712 if (hintDisplay) {
2713 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002714 }
Robert Carr2047fae2016-11-28 14:09:09 -08002715
2716 first = false;
2717 });
Mathias Agopian84300952012-11-21 16:02:13 -08002718 }
2719
2720
Mathias Agopian3559b072012-08-15 13:46:03 -07002721 /*
2722 * Perform our own transaction if needed
2723 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002724
2725 if (mLayersAdded) {
2726 mLayersAdded = false;
2727 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002728 mVisibleRegionsDirty = true;
2729 }
2730
2731 // some layers might have been removed, so
2732 // we need to update the regions they're exposing.
2733 if (mLayersRemoved) {
2734 mLayersRemoved = false;
2735 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002736 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002737 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002738 // this layer is not visible anymore
2739 // TODO: we could traverse the tree from front to back and
2740 // compute the actual visible region
2741 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002742 Region visibleReg;
2743 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002744 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002745 }
Robert Carr2047fae2016-11-28 14:09:09 -08002746 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002747 }
2748
2749 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002750
2751 updateCursorAsync();
2752}
2753
2754void SurfaceFlinger::updateCursorAsync()
2755{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002756 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002757 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002758 continue;
2759 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002760
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002761 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2762 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002763 }
2764 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002765}
2766
2767void SurfaceFlinger::commitTransaction()
2768{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002769 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002770 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002771 for (const auto& l : mLayersPendingRemoval) {
2772 recordBufferingStats(l->getName().string(),
2773 l->getOccupancyHistory(true));
2774 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002775 }
2776 mLayersPendingRemoval.clear();
2777 }
2778
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002779 // If this transaction is part of a window animation then the next frame
2780 // we composite should be considered an animation as well.
2781 mAnimCompositionPending = mAnimTransactionPending;
2782
Mathias Agopian4fec8732012-06-29 14:12:52 -07002783 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002784 // clear the "changed" flags in current state
2785 mCurrentState.colorMatrixChanged = false;
2786
Robert Carr1f0a16a2016-10-24 16:27:39 -07002787 mDrawingState.traverseInZOrder([](Layer* layer) {
2788 layer->commitChildList();
2789 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002790 mTransactionPending = false;
2791 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002792 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002793}
2794
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002795void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2796 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002797 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002798 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002799
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002800 Region aboveOpaqueLayers;
2801 Region aboveCoveredLayers;
2802 Region dirty;
2803
Mathias Agopian87baae12012-07-31 12:38:26 -07002804 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002805
Robert Carr2047fae2016-11-28 14:09:09 -08002806 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002807 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002808 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002809
Jesse Hall01e29052013-02-19 16:13:35 -08002810 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002811 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002812 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002813 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002814
Mathias Agopianab028732010-03-16 16:41:46 -07002815 /*
2816 * opaqueRegion: area of a surface that is fully opaque.
2817 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002818 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002819
2820 /*
2821 * visibleRegion: area of a surface that is visible on screen
2822 * and not fully transparent. This is essentially the layer's
2823 * footprint minus the opaque regions above it.
2824 * Areas covered by a translucent surface are considered visible.
2825 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002826 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002827
2828 /*
2829 * coveredRegion: area of a surface that is covered by all
2830 * visible regions above it (which includes the translucent areas).
2831 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002832 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002833
Jesse Halla8026d22012-09-25 13:25:04 -07002834 /*
2835 * transparentRegion: area of a surface that is hinted to be completely
2836 * transparent. This is only used to tell when the layer has no visible
2837 * non-transparent regions and can be removed from the layer list. It
2838 * does not affect the visibleRegion of this layer or any layers
2839 * beneath it. The hint may not be correct if apps don't respect the
2840 * SurfaceView restrictions (which, sadly, some don't).
2841 */
2842 Region transparentRegion;
2843
Mathias Agopianab028732010-03-16 16:41:46 -07002844
2845 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002846 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002847 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002848 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002849 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002850 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002851 if (!visibleRegion.isEmpty()) {
2852 // Remove the transparent area from the visible region
2853 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002854 if (tr.preserveRects()) {
2855 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002856 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002857 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002858 // transformation too complex, can't do the
2859 // transparent region optimization.
2860 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002861 }
Mathias Agopianab028732010-03-16 16:41:46 -07002862 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002863
Mathias Agopianab028732010-03-16 16:41:46 -07002864 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002865 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002866 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002867 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002868 // the opaque region is the layer's footprint
2869 opaqueRegion = visibleRegion;
2870 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002871 }
2872 }
2873
Robert Carre5f4f692018-01-12 13:12:28 -08002874 if (visibleRegion.isEmpty()) {
2875 layer->clearVisibilityRegions();
2876 return;
2877 }
2878
Mathias Agopianab028732010-03-16 16:41:46 -07002879 // Clip the covered region to the visible region
2880 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2881
2882 // Update aboveCoveredLayers for next (lower) layer
2883 aboveCoveredLayers.orSelf(visibleRegion);
2884
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002885 // subtract the opaque region covered by the layers above us
2886 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002887
2888 // compute this layer's dirty region
2889 if (layer->contentDirty) {
2890 // we need to invalidate the whole region
2891 dirty = visibleRegion;
2892 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002893 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002894 layer->contentDirty = false;
2895 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002896 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002897 * the exposed region consists of two components:
2898 * 1) what's VISIBLE now and was COVERED before
2899 * 2) what's EXPOSED now less what was EXPOSED before
2900 *
2901 * note that (1) is conservative, we start with the whole
2902 * visible region but only keep what used to be covered by
2903 * something -- which mean it may have been exposed.
2904 *
2905 * (2) handles areas that were not covered by anything but got
2906 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002907 */
Mathias Agopianab028732010-03-16 16:41:46 -07002908 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002909 const Region oldVisibleRegion = layer->visibleRegion;
2910 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002911 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2912 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002913 }
2914 dirty.subtractSelf(aboveOpaqueLayers);
2915
2916 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002917 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002918
Mathias Agopianab028732010-03-16 16:41:46 -07002919 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002920 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002921
Jesse Halla8026d22012-09-25 13:25:04 -07002922 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002923 layer->setVisibleRegion(visibleRegion);
2924 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002925 layer->setVisibleNonTransparentRegion(
2926 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002927 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002928
Mathias Agopian87baae12012-07-31 12:38:26 -07002929 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002930}
2931
Chia-I Wuab0c3192017-08-01 11:29:00 -07002932void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002933 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002934 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2935 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002936 }
2937 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002938}
2939
Dan Stoza6b9454d2014-11-07 16:00:59 -08002940bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002941{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002942 ALOGV("handlePageFlip");
2943
Brian Andersond6927fb2016-07-23 23:37:30 -07002944 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002945
Mathias Agopian4fec8732012-06-29 14:12:52 -07002946 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002947 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002948 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002949
2950 // Store the set of layers that need updates. This set must not change as
2951 // buffers are being latched, as this could result in a deadlock.
2952 // Example: Two producers share the same command stream and:
2953 // 1.) Layer 0 is latched
2954 // 2.) Layer 0 gets a new frame
2955 // 2.) Layer 1 gets a new frame
2956 // 3.) Layer 1 is latched.
2957 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2958 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002959 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002960 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002961 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07002962 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002963 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002964 } else {
2965 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002966 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002967 } else {
2968 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002969 }
Robert Carr2047fae2016-11-28 14:09:09 -08002970 });
2971
Dan Stoza9e56aa02015-11-02 13:00:03 -08002972 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002973 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002974 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002975 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002976 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002977 newDataLatched = true;
2978 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002979 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002980
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002981 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002982
2983 // If we will need to wake up at some time in the future to deal with a
2984 // queued frame that shouldn't be displayed during this vsync period, wake
2985 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002986 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002987 signalLayerUpdate();
2988 }
2989
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002990 // enter boot animation on first buffer latch
2991 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2992 ALOGI("Enter boot animation");
2993 mBootStage = BootStage::BOOTANIMATION;
2994 }
2995
Dan Stoza6b9454d2014-11-07 16:00:59 -08002996 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002997 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002998}
2999
Mathias Agopianad456f92011-01-13 17:53:01 -08003000void SurfaceFlinger::invalidateHwcGeometry()
3001{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003002 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003003}
3004
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003005void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
3006 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003007 // We only need to actually compose the display if:
3008 // 1) It is being handled by hardware composer, which may need this to
3009 // keep its virtual display state machine in sync, or
3010 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07003011 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08003012 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003013 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003014 return;
3015 }
3016
Dan Stoza9e56aa02015-11-02 13:00:03 -08003017 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003018 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003019
3020 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003021 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003022}
3023
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003024bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003025 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003026
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003027 const Region bounds(display->bounds());
3028 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003029 const auto displayId = display->getId();
3030 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003031 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003032
Chia-I Wu8e50e692018-05-04 10:12:37 -07003033 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003034 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003035
Dan Stoza9e56aa02015-11-02 13:00:03 -08003036 if (hasClientComposition) {
3037 ALOGV("hasClientComposition");
3038
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003039 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003040 if (display->hasWideColorGamut()) {
3041 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003042 }
3043 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003044 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003045 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003046
Dominik Laskowski7e045462018-05-30 13:02:02 -07003047 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003048 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3049 HWC2::Capability::SkipClientColorTransform);
3050
Chia-I Wud49d6692018-06-27 07:17:41 +08003051 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003052 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3053 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003054 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003055 }
3056
Chia-I Wud49d6692018-06-27 07:17:41 +08003057 // The current enhanced saturation matrix is designed to enhance Display P3,
3058 // thus we only apply this matrix when the render intent is not colorimetric
3059 // and the output color space is Display P3.
3060 needsEnhancedColorMatrix =
3061 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3062 outputDataspace == Dataspace::DISPLAY_P3);
3063 if (needsEnhancedColorMatrix) {
3064 colorMatrix *= mEnhancedSaturationMatrix;
3065 }
3066
3067 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003068
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003069 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003070 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003071 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003072 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003073
3074 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003075 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3076 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3077 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003078 }
3079 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003080 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003081
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003082 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003083 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003084 // when using overlays, we assume a fully transparent framebuffer
3085 // NOTE: we could reduce how much we need to clear, for instance
3086 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003087 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003088 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003089 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003090 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003091 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003092 // we're left with the letterbox region
3093 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003094 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003095
3096 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003097 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003098
Mathias Agopianb9494d52012-04-18 02:28:45 -07003099 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003100 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003101 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003102 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003103 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003104 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003105
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003106 const Rect& bounds = display->getBounds();
3107 const Rect& scissor = display->getScissor();
3108 if (scissor != bounds) {
3109 // scissor doesn't match the screen's dimensions, so we
3110 // need to clear everything outside of it and enable
3111 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003112
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003113 // enable scissor for this frame
3114 const uint32_t height = display->getHeight();
3115 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
3116 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003117 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003118 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003119
Mathias Agopian85d751c2012-08-29 16:59:24 -07003120 /*
3121 * and then, render the layers targeted at the framebuffer
3122 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003123
Dan Stoza9e56aa02015-11-02 13:00:03 -08003124 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003125 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003126 bool firstLayer = true;
David Sodmanfb95bcc2017-12-22 15:45:30 -08003127 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
3128 const Region bounds(display->bounds());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003129 const Region clip(bounds.intersect(
David Sodmanfb95bcc2017-12-22 15:45:30 -08003130 displayTransform.transform(compositionInfo.layer->mLayer->visibleRegion)));
3131 ALOGV("Layer: %s", compositionInfo.layerName.c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003132 if (!clip.isEmpty()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08003133 switch (compositionInfo.compositionType) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003134 case HWC2::Composition::Cursor:
3135 case HWC2::Composition::Device:
3136 case HWC2::Composition::Sideband:
3137 case HWC2::Composition::SolidColor: {
David Sodmanfb95bcc2017-12-22 15:45:30 -08003138 const Layer::State& state(compositionInfo.layer->mLayer->getDrawingState());
3139 const bool opaque = compositionInfo.layer->mLayer->isOpaque(state);
3140 if (compositionInfo.hwc.clearClientTarget && !firstLayer &&
3141 opaque && (state.color.a == 1.0f) && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003142 // never clear the very first layer since we're
3143 // guaranteed the FB is already cleared
David Sodman10a41ff2018-08-05 12:14:17 -07003144 compositionInfo.layer->clear(getRenderEngine());
Mathias Agopiancd60f992012-08-16 16:28:27 -07003145 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003146 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003147 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003148 case HWC2::Composition::Client: {
David Sodmanfb95bcc2017-12-22 15:45:30 -08003149 compositionInfo.layer->mLayer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003150 break;
3151 }
3152 default:
3153 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003154 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003155 } else {
3156 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003157 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003158 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003159 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003160
Chia-I Wud49d6692018-06-27 07:17:41 +08003161 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003162 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003163 }
3164
Mathias Agopianf45c5102012-10-24 16:29:17 -07003165 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003166 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003167 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003168}
3169
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003170void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
3171 const Region& region) const {
3172 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003173 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003174 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003175}
3176
Dan Stoza7d89d062015-04-30 13:29:25 -07003177status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003178 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003179 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003180 const sp<Layer>& lbc,
3181 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003182{
Dan Stoza7d89d062015-04-30 13:29:25 -07003183 // add this layer to the current state list
3184 {
3185 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003186 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003187 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3188 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003189 return NO_MEMORY;
3190 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003191 if (parent == nullptr) {
3192 mCurrentState.layersSortedByZ.add(lbc);
3193 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003194 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003195 ALOGE("addClientLayer called with a removed parent");
3196 return NAME_NOT_FOUND;
3197 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003198 parent->addChild(lbc);
3199 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003200
Yiwei Zhang243b3782018-05-15 17:40:04 -07003201 if (gbc != nullptr) {
3202 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3203 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3204 mMaxGraphicBufferProducerListSize,
3205 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3206 mGraphicBufferProducerList.size(),
3207 mMaxGraphicBufferProducerListSize, mNumLayers);
3208 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003209 mLayersAdded = true;
3210 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003211 }
3212
Mathias Agopian96f08192010-06-02 23:28:45 -07003213 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003214 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003215
Dan Stoza7d89d062015-04-30 13:29:25 -07003216 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003217}
3218
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003219status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003220 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003221 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3222}
Robert Carr7f9b8992017-03-10 11:08:39 -08003223
chaviwca27f252018-02-06 16:46:39 -08003224status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3225 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003226 if (layer->isPendingRemoval()) {
3227 return NO_ERROR;
3228 }
3229
Robert Carr1f0a16a2016-10-24 16:27:39 -07003230 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003231 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003232 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003233 if (topLevelOnly) {
3234 return NO_ERROR;
3235 }
3236
Chia-I Wu98f1c102017-05-30 14:54:08 -07003237 sp<Layer> ancestor = p;
3238 while (ancestor->getParent() != nullptr) {
3239 ancestor = ancestor->getParent();
3240 }
3241 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3242 ALOGE("removeLayer called with a layer whose parent has been removed");
3243 return NAME_NOT_FOUND;
3244 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003245
3246 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003247 } else {
3248 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003249 }
3250
Robert Carr136e2f62017-02-08 17:54:29 -08003251 // As a matter of normal operation, the LayerCleaner will produce a second
3252 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3253 // so we will succeed in promoting it, but it's already been removed
3254 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3255 // otherwise something has gone wrong and we are leaking the layer.
3256 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003257 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3258 layer->getName().string(),
3259 (p != nullptr) ? p->getName().string() : "no-parent");
3260 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003261 } else if (index < 0) {
3262 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003263 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003264
Chia-I Wuc6657022017-08-15 11:18:17 -07003265 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003266 mLayersPendingRemoval.add(layer);
3267 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003268 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003269 setTransactionFlags(eTransactionNeeded);
3270 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003271}
3272
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003273uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003274 return android_atomic_release_load(&mTransactionFlags);
3275}
3276
Mathias Agopian3f844832013-08-07 21:24:32 -07003277uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003278 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3279}
3280
Mathias Agopian3f844832013-08-07 21:24:32 -07003281uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003282 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3283}
3284
3285uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3286 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003287 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003288 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003289 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003290 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003291 }
3292 return old;
3293}
3294
chaviwca27f252018-02-06 16:46:39 -08003295bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3296 for (const ComposerState& state : states) {
3297 // Here we need to check that the interface we're given is indeed
3298 // one of our own. A malicious client could give us a nullptr
3299 // IInterface, or one of its own or even one of our own but a
3300 // different type. All these situations would cause us to crash.
3301 if (state.client == nullptr) {
3302 return true;
3303 }
3304
3305 sp<IBinder> binder = IInterface::asBinder(state.client);
3306 if (binder == nullptr) {
3307 return true;
3308 }
3309
3310 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3311 return true;
3312 }
3313 }
3314 return false;
3315}
3316
Mathias Agopian8b33f032012-07-24 20:43:54 -07003317void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003318 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003319 const Vector<DisplayState>& displays,
3320 uint32_t flags)
3321{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003322 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003323 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003324 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003325
chaviwca27f252018-02-06 16:46:39 -08003326 if (containsAnyInvalidClientState(states)) {
3327 return;
3328 }
3329
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003330 if (flags & eAnimation) {
3331 // For window updates that are part of an animation we must wait for
3332 // previous animation "frames" to be handled.
3333 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003334 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003335 if (CC_UNLIKELY(err != NO_ERROR)) {
3336 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003337 // caller after a few seconds.
3338 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3339 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003340 mAnimTransactionPending = false;
3341 break;
3342 }
3343 }
3344 }
3345
chaviwca27f252018-02-06 16:46:39 -08003346 for (const DisplayState& display : displays) {
3347 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003348 }
3349
chaviwca27f252018-02-06 16:46:39 -08003350 for (const ComposerState& state : states) {
3351 transactionFlags |= setClientStateLocked(state);
3352 }
3353
3354 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3355 // as destroyed should only occur after setting all other states. This is to allow for a
3356 // child re-parent to happen before marking its original parent as destroyed (which would
3357 // then mark the child as destroyed).
3358 for (const ComposerState& state : states) {
3359 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003360 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003361
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003362 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3363 // anyway. This can be used as a flush mechanism for previous async transactions.
3364 // Empty animation transaction can be used to simulate back-pressure, so also force a
3365 // transaction for empty animation transactions.
3366 if (transactionFlags == 0 &&
3367 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003368 transactionFlags = eTransactionNeeded;
3369 }
3370
Mathias Agopian386aa982011-11-07 21:58:03 -08003371 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003372 if (mInterceptor->isEnabled()) {
3373 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003374 }
Irvel468051e2016-06-13 16:44:44 -07003375
Mathias Agopian386aa982011-11-07 21:58:03 -08003376 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003377 const auto start = (flags & eEarlyWakeup)
3378 ? VSyncModulator::TransactionStart::EARLY
3379 : VSyncModulator::TransactionStart::NORMAL;
3380 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003381
3382 // if this is a synchronous transaction, wait for it to take effect
3383 // before returning.
3384 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003385 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003386 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003387 if (flags & eAnimation) {
3388 mAnimTransactionPending = true;
3389 }
3390 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003391 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3392 if (CC_UNLIKELY(err != NO_ERROR)) {
3393 // just in case something goes wrong in SF, return to the
3394 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003395 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3396 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003397 break;
3398 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003399 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003400 }
3401}
3402
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003403uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3404 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3405 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003406
Mathias Agopiane57f2922012-08-09 16:29:12 -07003407 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003408 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3409
3410 const uint32_t what = s.what;
3411 if (what & DisplayState::eSurfaceChanged) {
3412 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3413 state.surface = s.surface;
3414 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003415 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003416 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003417 if (what & DisplayState::eLayerStackChanged) {
3418 if (state.layerStack != s.layerStack) {
3419 state.layerStack = s.layerStack;
3420 flags |= eDisplayTransactionNeeded;
3421 }
3422 }
3423 if (what & DisplayState::eDisplayProjectionChanged) {
3424 if (state.orientation != s.orientation) {
3425 state.orientation = s.orientation;
3426 flags |= eDisplayTransactionNeeded;
3427 }
3428 if (state.frame != s.frame) {
3429 state.frame = s.frame;
3430 flags |= eDisplayTransactionNeeded;
3431 }
3432 if (state.viewport != s.viewport) {
3433 state.viewport = s.viewport;
3434 flags |= eDisplayTransactionNeeded;
3435 }
3436 }
3437 if (what & DisplayState::eDisplaySizeChanged) {
3438 if (state.width != s.width) {
3439 state.width = s.width;
3440 flags |= eDisplayTransactionNeeded;
3441 }
3442 if (state.height != s.height) {
3443 state.height = s.height;
3444 flags |= eDisplayTransactionNeeded;
3445 }
3446 }
3447
Mathias Agopiane57f2922012-08-09 16:29:12 -07003448 return flags;
3449}
3450
Robert Carrd4ae7f32018-06-07 16:10:57 -07003451bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3452 IPCThreadState* ipc = IPCThreadState::self();
3453 const int pid = ipc->getCallingPid();
3454 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003455 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003456 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003457 return false;
3458 }
3459 return true;
3460}
3461
chaviwca27f252018-02-06 16:46:39 -08003462uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3463 const layer_state_t& s = composerState.state;
3464 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3465
Mathias Agopian13127d82013-03-05 17:47:11 -08003466 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003467 if (layer == nullptr) {
3468 return 0;
3469 }
3470
3471 if (layer->isPendingRemoval()) {
3472 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3473 return 0;
3474 }
3475
3476 uint32_t flags = 0;
3477
3478 const uint32_t what = s.what;
3479 bool geometryAppliesWithResize =
3480 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003481
3482 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3483 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003484 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003485 layer->pushPendingState();
3486 }
3487
chaviw8b3871a2017-11-01 17:41:01 -07003488 if (what & layer_state_t::ePositionChanged) {
3489 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3490 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003491 }
chaviw8b3871a2017-11-01 17:41:01 -07003492 }
3493 if (what & layer_state_t::eLayerChanged) {
3494 // NOTE: index needs to be calculated before we update the state
3495 const auto& p = layer->getParent();
3496 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003497 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003498 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003499 mCurrentState.layersSortedByZ.removeAt(idx);
3500 mCurrentState.layersSortedByZ.add(layer);
3501 // we need traversal (state changed)
3502 // AND transaction (list changed)
3503 flags |= eTransactionNeeded|eTraversalNeeded;
3504 }
chaviw8b3871a2017-11-01 17:41:01 -07003505 } else {
3506 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003507 flags |= eTransactionNeeded|eTraversalNeeded;
3508 }
3509 }
chaviw8b3871a2017-11-01 17:41:01 -07003510 }
3511 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003512 // NOTE: index needs to be calculated before we update the state
3513 const auto& p = layer->getParent();
3514 if (p == nullptr) {
3515 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3516 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3517 mCurrentState.layersSortedByZ.removeAt(idx);
3518 mCurrentState.layersSortedByZ.add(layer);
3519 // we need traversal (state changed)
3520 // AND transaction (list changed)
3521 flags |= eTransactionNeeded|eTraversalNeeded;
3522 }
3523 } else {
3524 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3525 flags |= eTransactionNeeded|eTraversalNeeded;
3526 }
chaviw8b3871a2017-11-01 17:41:01 -07003527 }
3528 }
3529 if (what & layer_state_t::eSizeChanged) {
3530 if (layer->setSize(s.w, s.h)) {
3531 flags |= eTraversalNeeded;
3532 }
3533 }
3534 if (what & layer_state_t::eAlphaChanged) {
3535 if (layer->setAlpha(s.alpha))
3536 flags |= eTraversalNeeded;
3537 }
3538 if (what & layer_state_t::eColorChanged) {
3539 if (layer->setColor(s.color))
3540 flags |= eTraversalNeeded;
3541 }
3542 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003543 // TODO: b/109894387
3544 //
3545 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3546 // rotation. To see the problem observe that if we have a square parent, and a child
3547 // of the same size, then we rotate the child 45 degrees around it's center, the child
3548 // must now be cropped to a non rectangular 8 sided region.
3549 //
3550 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3551 // private API, and the WindowManager only uses rotation in one case, which is on a top
3552 // level layer in which cropping is not an issue.
3553 //
3554 // However given that abuse of rotation matrices could lead to surfaces extending outside
3555 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3556 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3557 // transformations.
3558 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003559 flags |= eTraversalNeeded;
3560 }
3561 if (what & layer_state_t::eTransparentRegionChanged) {
3562 if (layer->setTransparentRegionHint(s.transparentRegion))
3563 flags |= eTraversalNeeded;
3564 }
3565 if (what & layer_state_t::eFlagsChanged) {
3566 if (layer->setFlags(s.flags, s.mask))
3567 flags |= eTraversalNeeded;
3568 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003569 if (what & layer_state_t::eCropChanged_legacy) {
3570 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003571 flags |= eTraversalNeeded;
3572 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003573 if (what & layer_state_t::eFinalCropChanged_legacy) {
3574 if (layer->setFinalCrop_legacy(s.finalCrop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003575 flags |= eTraversalNeeded;
3576 }
3577 if (what & layer_state_t::eLayerStackChanged) {
3578 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3579 // We only allow setting layer stacks for top level layers,
3580 // everything else inherits layer stack from its parent.
3581 if (layer->hasParent()) {
3582 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3583 layer->getName().string());
3584 } else if (idx < 0) {
3585 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3586 "that also does not appear in the top level layer list. Something"
3587 " has gone wrong.", layer->getName().string());
3588 } else if (layer->setLayerStack(s.layerStack)) {
3589 mCurrentState.layersSortedByZ.removeAt(idx);
3590 mCurrentState.layersSortedByZ.add(layer);
3591 // we need traversal (state changed)
3592 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003593 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003594 }
3595 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003596 if (what & layer_state_t::eDeferTransaction_legacy) {
3597 if (s.barrierHandle_legacy != nullptr) {
3598 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3599 } else if (s.barrierGbp_legacy != nullptr) {
3600 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003601 if (authenticateSurfaceTextureLocked(gbp)) {
3602 const auto& otherLayer =
3603 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003604 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003605 } else {
3606 ALOGE("Attempt to defer transaction to to an"
3607 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003608 }
3609 }
chaviw8b3871a2017-11-01 17:41:01 -07003610 // We don't trigger a traversal here because if no other state is
3611 // changed, we don't want this to cause any more work
3612 }
3613 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003614 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003615 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003616 if (!hadParent) {
3617 mCurrentState.layersSortedByZ.remove(layer);
3618 }
chaviw8b3871a2017-11-01 17:41:01 -07003619 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003620 }
chaviw8b3871a2017-11-01 17:41:01 -07003621 }
3622 if (what & layer_state_t::eReparentChildren) {
3623 if (layer->reparentChildren(s.reparentHandle)) {
3624 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003625 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003626 }
chaviw8b3871a2017-11-01 17:41:01 -07003627 if (what & layer_state_t::eDetachChildren) {
3628 layer->detachChildren();
3629 }
3630 if (what & layer_state_t::eOverrideScalingModeChanged) {
3631 layer->setOverrideScalingMode(s.overrideScalingMode);
3632 // We don't trigger a traversal here because if no other state is
3633 // changed, we don't want this to cause any more work
3634 }
Marissa Wall61c58622018-07-18 10:12:20 -07003635 if (what & layer_state_t::eTransformChanged) {
3636 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3637 }
3638 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3639 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3640 flags |= eTraversalNeeded;
3641 }
3642 if (what & layer_state_t::eCropChanged) {
3643 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3644 }
3645 if (what & layer_state_t::eBufferChanged) {
3646 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3647 }
3648 if (what & layer_state_t::eAcquireFenceChanged) {
3649 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3650 }
3651 if (what & layer_state_t::eDataspaceChanged) {
3652 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3653 }
3654 if (what & layer_state_t::eHdrMetadataChanged) {
3655 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3656 }
3657 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3658 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3659 }
3660 if (what & layer_state_t::eApiChanged) {
3661 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3662 }
3663 if (what & layer_state_t::eSidebandStreamChanged) {
3664 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3665 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003666 return flags;
3667}
3668
chaviwca27f252018-02-06 16:46:39 -08003669void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3670 const layer_state_t& state = composerState.state;
3671 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3672
3673 sp<Layer> layer(client->getLayerUser(state.surface));
3674 if (layer == nullptr) {
3675 return;
3676 }
3677
3678 if (layer->isPendingRemoval()) {
3679 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3680 return;
3681 }
3682
3683 if (state.what & layer_state_t::eDestroySurface) {
3684 removeLayerLocked(mStateLock, layer);
3685 }
3686}
3687
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003688status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003689 const String8& name,
3690 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003691 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003692 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003693 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003694{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003695 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003696 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003697 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003698 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003699 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003700
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003701 status_t result = NO_ERROR;
3702
3703 sp<Layer> layer;
3704
Cody Northropbc755282017-03-31 12:00:08 -06003705 String8 uniqueName = getUniqueLayerName(name);
3706
Mathias Agopian3165cc22012-08-08 19:42:09 -07003707 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003708 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003709 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3710 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003711
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003712 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003713 case ISurfaceComposerClient::eFXSurfaceBufferState:
3714 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3715 break;
chaviw13fdc492017-06-27 12:40:18 -07003716 case ISurfaceComposerClient::eFXSurfaceColor:
3717 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003718 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003719 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003720 break;
3721 default:
3722 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003723 break;
3724 }
3725
Dan Stoza7d89d062015-04-30 13:29:25 -07003726 if (result != NO_ERROR) {
3727 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003728 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003729
Chia-I Wuab0c3192017-08-01 11:29:00 -07003730 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3731 // TODO b/64227542
3732 if (windowType == 441731) {
3733 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3734 layer->setPrimaryDisplayOnly();
3735 }
3736
Albert Chaulk479c60c2017-01-27 14:21:34 -05003737 layer->setInfo(windowType, ownerUid);
3738
Robert Carr1f0a16a2016-10-24 16:27:39 -07003739 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003740 if (result != NO_ERROR) {
3741 return result;
3742 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003743 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003744
3745 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003746 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003747}
3748
Cody Northropbc755282017-03-31 12:00:08 -06003749String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3750{
3751 bool matchFound = true;
3752 uint32_t dupeCounter = 0;
3753
3754 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3755 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3756
Dan Stoza436ccf32018-06-21 12:10:12 -07003757 // Grab the state lock since we're accessing mCurrentState
3758 Mutex::Autolock lock(mStateLock);
3759
Cody Northropbc755282017-03-31 12:00:08 -06003760 // Loop over layers until we're sure there is no matching name
3761 while (matchFound) {
3762 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003763 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003764 if (layer->getName() == uniqueName) {
3765 matchFound = true;
3766 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3767 }
3768 });
3769 }
3770
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003771 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3772 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003773
3774 return uniqueName;
3775}
3776
Marissa Wallfd668622018-05-10 10:21:13 -07003777status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3778 uint32_t w, uint32_t h, uint32_t flags,
3779 PixelFormat& format, sp<IBinder>* handle,
3780 sp<IGraphicBufferProducer>* gbp,
3781 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003782 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003783 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003784 case PIXEL_FORMAT_TRANSPARENT:
3785 case PIXEL_FORMAT_TRANSLUCENT:
3786 format = PIXEL_FORMAT_RGBA_8888;
3787 break;
3788 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003789 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003790 break;
3791 }
3792
Marissa Wallfd668622018-05-10 10:21:13 -07003793 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3794 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003795 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003796 *handle = layer->getHandle();
3797 *gbp = layer->getProducer();
3798 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003799 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003800
Marissa Wallfd668622018-05-10 10:21:13 -07003801 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003802 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003803}
3804
Marissa Wall61c58622018-07-18 10:12:20 -07003805status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3806 uint32_t w, uint32_t h, uint32_t flags,
3807 sp<IBinder>* handle, sp<Layer>* outLayer) {
3808 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3809 *handle = layer->getHandle();
3810 *outLayer = layer;
3811
3812 return NO_ERROR;
3813}
3814
chaviw13fdc492017-06-27 12:40:18 -07003815status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003816 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003817 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003818{
chaviw13fdc492017-06-27 12:40:18 -07003819 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003820 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003821 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003822}
3823
Mathias Agopianac9fa422013-02-11 16:40:36 -08003824status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003825{
Robert Carr9524cb32017-02-13 11:32:32 -08003826 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003827 status_t err = NO_ERROR;
3828 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003829 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003830 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003831 err = removeLayer(l);
3832 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3833 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003834 }
3835 return err;
3836}
3837
Mathias Agopian13127d82013-03-05 17:47:11 -08003838status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003839{
Mathias Agopian67106042013-03-14 19:18:13 -07003840 // called by ~LayerCleaner() when all references to the IBinder (handle)
3841 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003842 sp<Layer> l = layer.promote();
3843 if (l == nullptr) {
3844 // The layer has already been removed, carry on
3845 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003846 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003847 // If we have a parent, then we can continue to live as long as it does.
3848 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003849}
3850
Mathias Agopianb60314a2012-04-10 22:09:54 -07003851// ---------------------------------------------------------------------------
3852
Andy McFadden13a082e2012-08-24 10:16:42 -07003853void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003854 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3855 if (!displayToken) return;
3856
Jesse Hall01e29052013-02-19 16:13:35 -08003857 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003858 Vector<ComposerState> state;
3859 Vector<DisplayState> displays;
3860 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003861 d.what = DisplayState::eDisplayProjectionChanged |
3862 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003863 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003864 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003865 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003866 d.frame.makeInvalid();
3867 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003868 d.width = 0;
3869 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003870 displays.add(d);
3871 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003872
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003873 const auto display = getDisplayDevice(displayToken);
3874 if (!display) return;
3875
3876 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3877
3878 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003879 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003880 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003881
Brian Andersond0010582017-03-07 13:20:31 -08003882 // Use phase of 0 since phase is not known.
3883 // Use latency of 0, which will snap to the ideal latency.
3884 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003885}
3886
3887void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003888 // Async since we may be called from the main thread.
3889 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003890}
3891
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003892void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3893 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003894 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003895 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003896
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003897 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003898 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003899 return;
3900 }
3901
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003902 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003903 ALOGW("Trying to set power mode for virtual display");
3904 return;
3905 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003906
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003907 display->setPowerMode(mode);
3908
Lloyd Pique4dccc412018-01-22 17:21:36 -08003909 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003910 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003911 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003912 if (idx < 0) {
3913 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3914 return;
3915 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003916 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003917 }
3918
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003919 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003920 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003921 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003922 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003923 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003924 // FIXME: eventthread only knows about the main display right now
3925 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003926 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003927 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003928
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003929 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003930 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003931 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003932
3933 struct sched_param param = {0};
3934 param.sched_priority = 1;
3935 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3936 ALOGW("Couldn't set SCHED_FIFO on display on");
3937 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003938 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003939 // Turn off the display
3940 struct sched_param param = {0};
3941 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3942 ALOGW("Couldn't set SCHED_OTHER on display off");
3943 }
3944
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003945 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003946 disableHardwareVsync(true); // also cancels any in-progress resync
3947
Mathias Agopiancde87a32012-09-13 14:09:01 -07003948 // FIXME: eventthread only knows about the main display right now
3949 mEventThread->onScreenReleased();
3950 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003951
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003952 getHwComposer().setPowerMode(type, mode);
3953 mVisibleRegionsDirty = true;
3954 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003955 } else if (mode == HWC_POWER_MODE_DOZE ||
3956 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003957 // Update display while dozing
3958 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003959 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003960 // FIXME: eventthread only knows about the main display right now
3961 mEventThread->onScreenAcquired();
3962 resyncToHardwareVsync(true);
3963 }
3964 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3965 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003966 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003967 disableHardwareVsync(true); // also cancels any in-progress resync
3968 // FIXME: eventthread only knows about the main display right now
3969 mEventThread->onScreenReleased();
3970 }
3971 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003972 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003973 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003974 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003975 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003976
3977 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003978}
3979
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003980void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003981 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003982 const auto display = getDisplayDevice(displayToken);
3983 if (!display) {
3984 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3985 displayToken.get());
3986 } else if (display->isVirtual()) {
3987 ALOGW("Attempt to set power mode %d for virtual display", mode);
3988 } else {
3989 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003990 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003991 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003992}
3993
3994// ---------------------------------------------------------------------------
3995
Lloyd Pique755e3192018-01-31 16:46:15 -08003996status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3997 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003998 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003999
Mathias Agopianbd115332013-04-18 16:41:04 -07004000 IPCThreadState* ipc = IPCThreadState::self();
4001 const int pid = ipc->getCallingPid();
4002 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004003
Mathias Agopianbd115332013-04-18 16:41:04 -07004004 if ((uid != AID_SHELL) &&
4005 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004006 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07004007 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004008 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004009 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004010 // (this would indicate SF is stuck, but we want to be able to
4011 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004012 status_t err = mStateLock.timedLock(s2ns(1));
4013 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004014 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004015 result.appendFormat(
4016 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4017 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004018 }
4019
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004020 bool dumpAll = true;
4021 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004022 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004023
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004024 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004025 if ((index < numArgs) &&
4026 (args[index] == String16("--list"))) {
4027 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004028 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004029 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004030 }
4031
4032 if ((index < numArgs) &&
4033 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004034 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004035 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004036 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004037 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004038
4039 if ((index < numArgs) &&
4040 (args[index] == String16("--latency-clear"))) {
4041 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004042 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004043 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004044 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004045
4046 if ((index < numArgs) &&
4047 (args[index] == String16("--dispsync"))) {
4048 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004049 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004050 dumpAll = false;
4051 }
Dan Stozab90cf072015-03-05 11:05:59 -08004052
4053 if ((index < numArgs) &&
4054 (args[index] == String16("--static-screen"))) {
4055 index++;
4056 dumpStaticScreenStats(result);
4057 dumpAll = false;
4058 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004059
4060 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004061 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004062 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004063 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004064 dumpAll = false;
4065 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004066
4067 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4068 index++;
4069 dumpWideColorInfo(result);
4070 dumpAll = false;
4071 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004072
4073 if ((index < numArgs) &&
4074 (args[index] == String16("--enable-layer-stats"))) {
4075 index++;
4076 mLayerStats.enable();
4077 dumpAll = false;
4078 }
4079
4080 if ((index < numArgs) &&
4081 (args[index] == String16("--disable-layer-stats"))) {
4082 index++;
4083 mLayerStats.disable();
4084 dumpAll = false;
4085 }
4086
4087 if ((index < numArgs) &&
4088 (args[index] == String16("--clear-layer-stats"))) {
4089 index++;
4090 mLayerStats.clear();
4091 dumpAll = false;
4092 }
4093
4094 if ((index < numArgs) &&
4095 (args[index] == String16("--dump-layer-stats"))) {
4096 index++;
4097 mLayerStats.dump(result);
4098 dumpAll = false;
4099 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004100
4101 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004102 (args[index] == String16("--frame-composition"))) {
4103 index++;
4104 dumpFrameCompositionInfo(result);
4105 dumpAll = false;
4106 }
4107
4108 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004109 (args[index] == String16("--display-identification"))) {
4110 index++;
4111 dumpDisplayIdentificationData(result);
4112 dumpAll = false;
4113 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004114
4115 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4116 index++;
4117 mTimeStats.parseArgs(asProto, args, index, result);
4118 dumpAll = false;
4119 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004120 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004121
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004122 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004123 if (asProto) {
4124 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4125 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4126 } else {
4127 dumpAllLocked(args, index, result);
4128 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004129 }
4130
Mathias Agopian9795c422009-08-26 16:36:26 -07004131 if (locked) {
4132 mStateLock.unlock();
4133 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004134 }
4135 write(fd, result.string(), result.size());
4136 return NO_ERROR;
4137}
4138
Dan Stozac7014012014-02-14 15:03:43 -08004139void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4140 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004141{
Robert Carr2047fae2016-11-28 14:09:09 -08004142 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004143 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004144 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004145}
4146
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004147void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004148 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004149{
4150 String8 name;
4151 if (index < args.size()) {
4152 name = String8(args[index]);
4153 index++;
4154 }
4155
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004156 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4157 getHwComposer().isConnected(displayId)) {
4158 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4159 const nsecs_t period = activeConfig->getVsyncPeriod();
4160 result.appendFormat("%" PRId64 "\n", period);
4161 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004162
4163 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004164 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004165 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004166 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004167 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004168 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004169 }
Robert Carr2047fae2016-11-28 14:09:09 -08004170 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004171 }
4172}
4173
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004174void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004175 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004176{
4177 String8 name;
4178 if (index < args.size()) {
4179 name = String8(args[index]);
4180 index++;
4181 }
4182
Robert Carr2047fae2016-11-28 14:09:09 -08004183 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004184 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004185 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004186 }
Robert Carr2047fae2016-11-28 14:09:09 -08004187 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004188
Svetoslavd85084b2014-03-20 10:28:31 -07004189 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004190}
4191
Jamie Gennis6547ff42013-07-16 20:12:42 -07004192// This should only be called from the main thread. Otherwise it would need
4193// the lock and should use mCurrentState rather than mDrawingState.
4194void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004195 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004196 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004197 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004198
4199 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4200}
4201
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004202void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004203{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004204 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004205
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004206 if (isLayerTripleBufferingDisabled())
4207 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004208
4209 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004210 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004211 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004212 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004213 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4214 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004215 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004216}
4217
Dan Stozab90cf072015-03-05 11:05:59 -08004218void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4219{
4220 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004221 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4222 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004223 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004224 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004225 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4226 b + 1, bucketTimeSec, percent);
4227 }
David Sodman4a36e932017-11-07 14:29:47 -08004228 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004229 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004230 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004231 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004232 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004233}
4234
Dan Stozae77c7662016-05-13 11:37:28 -07004235void SurfaceFlinger::recordBufferingStats(const char* layerName,
4236 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004237 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4238 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004239 for (const auto& segment : history) {
4240 if (!segment.usedThirdBuffer) {
4241 stats.twoBufferTime += segment.totalTime;
4242 }
4243 if (segment.occupancyAverage < 1.0f) {
4244 stats.doubleBufferedTime += segment.totalTime;
4245 } else if (segment.occupancyAverage < 2.0f) {
4246 stats.tripleBufferedTime += segment.totalTime;
4247 }
4248 ++stats.numSegments;
4249 stats.totalTime += segment.totalTime;
4250 }
4251}
4252
Brian Andersond6927fb2016-07-23 23:37:30 -07004253void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4254 result.appendFormat("Layer frame timestamps:\n");
4255
4256 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4257 const size_t count = currentLayers.size();
4258 for (size_t i=0 ; i<count ; i++) {
4259 currentLayers[i]->dumpFrameEvents(result);
4260 }
4261}
4262
Dan Stozae77c7662016-05-13 11:37:28 -07004263void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4264 result.append("Buffering stats:\n");
4265 result.append(" [Layer name] <Active time> <Two buffer> "
4266 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004267 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004268 typedef std::tuple<std::string, float, float, float> BufferTuple;
4269 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004270 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004271 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004272 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004273 if (stats.numSegments == 0) {
4274 continue;
4275 }
4276 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4277 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4278 stats.totalTime;
4279 float doubleBufferRatio = static_cast<float>(
4280 stats.doubleBufferedTime) / stats.totalTime;
4281 float tripleBufferRatio = static_cast<float>(
4282 stats.tripleBufferedTime) / stats.totalTime;
4283 sorted.insert({activeTime, {name, twoBufferRatio,
4284 doubleBufferRatio, tripleBufferRatio}});
4285 }
4286 for (const auto& sortedPair : sorted) {
4287 float activeTime = sortedPair.first;
4288 const BufferTuple& values = sortedPair.second;
4289 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4290 std::get<0>(values).c_str(), activeTime,
4291 std::get<1>(values), std::get<2>(values),
4292 std::get<3>(values));
4293 }
4294 result.append("\n");
4295}
4296
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004297void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004298 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004299 const int32_t displayId = display->getId();
4300 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4301 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004302 continue;
4303 }
4304
Dominik Laskowski7e045462018-05-30 13:02:02 -07004305 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004306 uint8_t port;
4307 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004308 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004309 result.append("no identification data\n");
4310 continue;
4311 }
4312
4313 if (!isEdid(data)) {
4314 result.append("unknown identification data: ");
4315 for (uint8_t byte : data) {
4316 result.appendFormat("%x ", byte);
4317 }
4318 result.append("\n");
4319 continue;
4320 }
4321
4322 const auto edid = parseEdid(data);
4323 if (!edid) {
4324 result.append("invalid EDID: ");
4325 for (uint8_t byte : data) {
4326 result.appendFormat("%x ", byte);
4327 }
4328 result.append("\n");
4329 continue;
4330 }
4331
4332 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4333 result.append(edid->displayName.data(), edid->displayName.length());
4334 result.append("\"\n");
4335 }
4336 result.append("\n");
4337}
4338
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004339void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004340 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4341 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004342 result.appendFormat("DisplayColorSetting: %s\n",
4343 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004344
4345 // TODO: print out if wide-color mode is active or not
4346
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004347 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004348 const int32_t displayId = display->getId();
4349 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004350 continue;
4351 }
4352
Dominik Laskowski7e045462018-05-30 13:02:02 -07004353 result.appendFormat("Display %d color modes:\n", displayId);
4354 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004355 for (auto&& mode : modes) {
4356 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4357 }
4358
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004359 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004360 result.appendFormat(" Current color mode: %s (%d)\n",
4361 decodeColorMode(currentMode).c_str(), currentMode);
4362 }
4363 result.append("\n");
4364}
4365
David Sodman7e4ae112018-02-09 15:02:28 -08004366void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4367 std::string stringResult;
4368
4369 for (const auto& [token, display] : mDisplays) {
4370 const auto displayId = display->getId();
4371 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
4372 continue;
4373 }
4374
4375 const auto& compositionInfoIt = getBE().mEndOfFrameCompositionInfo.find(displayId);
4376 if (compositionInfoIt == getBE().mEndOfFrameCompositionInfo.end()) {
4377 break;
4378 }
4379 const auto& compositionInfoList = compositionInfoIt->second;
4380 stringResult += base::StringPrintf("Display: %d\n", displayId);
4381 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4382 for (const auto& compositionInfo : compositionInfoList) {
4383 compositionInfo.dump(stringResult, nullptr);
4384 stringResult += base::StringPrintf("\n");
4385 }
4386 }
4387
4388 result.append(stringResult.c_str());
4389}
4390
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004391LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004392 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004393 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4394 const State& state = useDrawing ? mDrawingState : mCurrentState;
4395 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004396 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004397 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004398 });
4399
4400 return layersProto;
4401}
4402
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004403LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004404 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004405
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004406 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004407 resolution->set_w(display.getWidth());
4408 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004409
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004410 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4411 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4412 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004413
Dominik Laskowski7e045462018-05-30 13:02:02 -07004414 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004415 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004416 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004417 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004418 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004419 }
4420 });
4421
4422 return layersProto;
4423}
4424
Mathias Agopian74d211a2013-04-22 16:55:35 +02004425void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4426 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004427{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004428 bool colorize = false;
4429 if (index < args.size()
4430 && (args[index] == String16("--color"))) {
4431 colorize = true;
4432 index++;
4433 }
4434
4435 Colorizer colorizer(colorize);
4436
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004437 // figure out if we're stuck somewhere
4438 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004439 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004440 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4441
4442 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004443 * Dump library configuration.
4444 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004445
4446 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004447 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004448 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004449 appendSfConfigString(result);
4450 appendUiConfigString(result);
4451 appendGuiConfigString(result);
4452 result.append("\n");
4453
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004454 result.append("\nDisplay identification data:\n");
4455 dumpDisplayIdentificationData(result);
4456
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004457 result.append("\nWide-Color information:\n");
4458 dumpWideColorInfo(result);
4459
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004460 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004461 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004462 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004463 result.append(SyncFeatures::getInstance().toString());
4464 result.append("\n");
4465
Andy McFadden41d67d72014-04-25 16:58:34 -07004466 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004467 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004468 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004469
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004470 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4471 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004472 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4473 getHwComposer().isConnected(displayId)) {
4474 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004475 result.appendFormat("Display %d: "
4476 "app phase %" PRId64 " ns, "
4477 "sf phase %" PRId64 " ns, "
4478 "early app phase %" PRId64 " ns, "
4479 "early sf phase %" PRId64 " ns, "
4480 "early app gl phase %" PRId64 " ns, "
4481 "early sf gl phase %" PRId64 " ns, "
4482 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4483 displayId,
4484 vsyncPhaseOffsetNs,
4485 sfVsyncPhaseOffsetNs,
4486 appEarlyOffset,
4487 sfEarlyOffset,
4488 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004489 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004490 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004491 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004492 result.append("\n");
4493
Dan Stozab90cf072015-03-05 11:05:59 -08004494 // Dump static screen stats
4495 result.append("\n");
4496 dumpStaticScreenStats(result);
4497 result.append("\n");
4498
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004499 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4500
Dan Stozae77c7662016-05-13 11:37:28 -07004501 dumpBufferingStats(result);
4502
Andy McFadden4803b742012-09-24 19:07:20 -07004503 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004504 * Dump the visible layer list
4505 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004506 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004507 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004508 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4509 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004510 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004511
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004512 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004513 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004514 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004515 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004516
David Sodman7e4ae112018-02-09 15:02:28 -08004517 result.append("\nFrame-Composition information:\n");
4518 dumpFrameCompositionInfo(result);
4519 result.append("\n");
4520
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004521 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004522 * Dump Display state
4523 */
4524
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004525 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004526 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004527 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004528 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004529 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004530 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004531 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004532
4533 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004534 * Dump SurfaceFlinger global state
4535 */
4536
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004537 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004538 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004539 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004540
Mathias Agopian888c8222012-08-04 21:10:38 -07004541 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004542 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004543
David Sodmanbc815282017-11-05 18:57:52 -08004544 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004545
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004546 if (display) {
4547 display->undefinedRegion.dump(result, "undefinedRegion");
4548 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4549 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004550 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004551 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004552 " gpu_to_cpu_unsupported : %d\n",
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004553 mTransactionFlags, !mGpuToCpuSupported);
4554
4555 if (display) {
4556 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4557 result.appendFormat(" refresh-rate : %f fps\n"
4558 " x-dpi : %f\n"
4559 " y-dpi : %f\n",
4560 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4561 activeConfig->getDpiY());
4562 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004563
Mathias Agopian74d211a2013-04-22 16:55:35 +02004564 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004565 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004566
4567 /*
4568 * VSYNC state
4569 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004570 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004571 result.append("\n");
4572
4573 /*
4574 * HWC layer minidump
4575 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004576 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004577 const int32_t displayId = display->getId();
4578 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004579 continue;
4580 }
4581
Dominik Laskowski7e045462018-05-30 13:02:02 -07004582 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004583 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004584 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004585 result.append("\n");
4586 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004587
4588 /*
4589 * Dump HWComposer state
4590 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004591 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004592 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004593 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004594 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004595 result.appendFormat(" h/w composer %s\n",
4596 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004597 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004598
4599 /*
4600 * Dump gralloc state
4601 */
4602 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4603 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004604
4605 /*
4606 * Dump VrFlinger state if in use.
4607 */
4608 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4609 result.append("VrFlinger state:\n");
4610 result.append(mVrFlinger->Dump().c_str());
4611 result.append("\n");
4612 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004613}
4614
Dominik Laskowski7e045462018-05-30 13:02:02 -07004615const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004616 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004617 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004618 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004619 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004620 }
4621 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004622
4623 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4624 static const Vector<sp<Layer>> empty;
4625 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004626}
4627
Keun young Park63f165f2012-08-31 10:53:36 -07004628bool SurfaceFlinger::startDdmConnection()
4629{
4630 void* libddmconnection_dso =
4631 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4632 if (!libddmconnection_dso) {
4633 return false;
4634 }
4635 void (*DdmConnection_start)(const char* name);
4636 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004637 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004638 if (!DdmConnection_start) {
4639 dlclose(libddmconnection_dso);
4640 return false;
4641 }
4642 (*DdmConnection_start)(getServiceName());
4643 return true;
4644}
4645
Chia-I Wu28f320b2018-05-03 11:02:56 -07004646void SurfaceFlinger::updateColorMatrixLocked() {
4647 mat4 colorMatrix;
4648 if (mGlobalSaturationFactor != 1.0f) {
4649 // Rec.709 luma coefficients
4650 float3 luminance{0.213f, 0.715f, 0.072f};
4651 luminance *= 1.0f - mGlobalSaturationFactor;
4652 mat4 saturationMatrix = mat4(
4653 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4654 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4655 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4656 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4657 );
4658 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4659 } else {
4660 colorMatrix = mClientColorMatrix * mDaltonizer();
4661 }
4662
4663 if (mCurrentState.colorMatrix != colorMatrix) {
4664 mCurrentState.colorMatrix = colorMatrix;
4665 mCurrentState.colorMatrixChanged = true;
4666 setTransactionFlags(eTransactionNeeded);
4667 }
4668}
4669
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004670status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004671#pragma clang diagnostic push
4672#pragma clang diagnostic error "-Wswitch-enum"
4673 switch (static_cast<ISurfaceComposerTag>(code)) {
4674 // These methods should at minimum make sure that the client requested
4675 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004676 case BOOT_FINISHED:
4677 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004678 case CREATE_CONNECTION:
4679 case CREATE_DISPLAY:
4680 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004681 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004682 case GET_ACTIVE_COLOR_MODE:
4683 case GET_ANIMATION_FRAME_STATS:
4684 case GET_HDR_CAPABILITIES:
4685 case SET_ACTIVE_CONFIG:
4686 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004687 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004688 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004689 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4690 IPCThreadState* ipc = IPCThreadState::self();
4691 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4692 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004693 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004694 }
Robert Carr1db73f62016-12-21 12:58:51 -08004695 return OK;
4696 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004697 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004698 IPCThreadState* ipc = IPCThreadState::self();
4699 const int pid = ipc->getCallingPid();
4700 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004701 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4702 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004703 return PERMISSION_DENIED;
4704 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004705 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004706 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004707 // Used by apps to hook Choreographer to SurfaceFlinger.
4708 case CREATE_DISPLAY_EVENT_CONNECTION:
4709 // The following calls are currently used by clients that do not
4710 // request necessary permissions. However, they do not expose any secret
4711 // information, so it is OK to pass them.
4712 case AUTHENTICATE_SURFACE:
4713 case GET_ACTIVE_CONFIG:
4714 case GET_BUILT_IN_DISPLAY:
4715 case GET_DISPLAY_COLOR_MODES:
4716 case GET_DISPLAY_CONFIGS:
4717 case GET_DISPLAY_STATS:
Yiwei Zhangcd3f9e92018-08-21 15:15:42 -07004718 case GET_DISPLAY_VIEWPORT:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004719 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4720 // Calling setTransactionState is safe, because you need to have been
4721 // granted a reference to Client* and Handle* to do anything with it.
4722 case SET_TRANSACTION_STATE:
4723 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4724 case CREATE_SCOPED_CONNECTION: {
4725 return OK;
4726 }
4727 case CAPTURE_LAYERS:
4728 case CAPTURE_SCREEN: {
4729 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004730 IPCThreadState* ipc = IPCThreadState::self();
4731 const int pid = ipc->getCallingPid();
4732 const int uid = ipc->getCallingUid();
4733 if ((uid != AID_GRAPHICS) &&
4734 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4735 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4736 return PERMISSION_DENIED;
4737 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004738 return OK;
4739 }
4740 // The following codes are deprecated and should never be allowed to access SF.
4741 case CONNECT_DISPLAY_UNUSED:
4742 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4743 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4744 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004745 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004746 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004747
4748 // These codes are used for the IBinder protocol to either interrogate the recipient
4749 // side of the transaction for its canonical interface descriptor or to dump its state.
4750 // We let them pass by default.
4751 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4752 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4753 code == IBinder::SYSPROPS_TRANSACTION) {
4754 return OK;
4755 }
4756 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4757 // in onTransact verifies that the user is root, and has access to use SF.
4758 if (code >= 1000 && code <= 1029) {
4759 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4760 return OK;
4761 }
4762 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4763 return PERMISSION_DENIED;
4764#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004765}
4766
Ana Krulec13be8ad2018-08-21 02:43:56 +00004767status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4768 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004769 status_t credentialCheck = CheckTransactCodeCredentials(code);
4770 if (credentialCheck != OK) {
4771 return credentialCheck;
4772 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004773
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004774 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4775 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004776 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004777 IPCThreadState* ipc = IPCThreadState::self();
4778 const int uid = ipc->getCallingUid();
4779 if (CC_UNLIKELY(uid != AID_SYSTEM
4780 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004781 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004782 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004783 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004784 return PERMISSION_DENIED;
4785 }
4786 int n;
4787 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004788 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004789 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004790 return NO_ERROR;
4791 case 1002: // SHOW_UPDATES
4792 n = data.readInt32();
4793 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004794 invalidateHwcGeometry();
4795 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004796 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004797 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004798 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004799 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004800 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004801 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004802 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004803 setTransactionFlags(
4804 eTransactionNeeded|
4805 eDisplayTransactionNeeded|
4806 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004807 return NO_ERROR;
4808 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004809 case 1006:{ // send empty update
4810 signalRefresh();
4811 return NO_ERROR;
4812 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004813 case 1008: // toggle use of hw composer
4814 n = data.readInt32();
4815 mDebugDisableHWC = n ? 1 : 0;
4816 invalidateHwcGeometry();
4817 repaintEverything();
4818 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004819 case 1009: // toggle use of transform hint
4820 n = data.readInt32();
4821 mDebugDisableTransformHint = n ? 1 : 0;
4822 invalidateHwcGeometry();
4823 repaintEverything();
4824 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004825 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004826 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004827 reply->writeInt32(0);
4828 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004829 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004830 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004831 return NO_ERROR;
4832 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004833 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004834 if (!display) {
4835 return NAME_NOT_FOUND;
4836 }
4837
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004838 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004839 return NO_ERROR;
4840 }
4841 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004842 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004843 // daltonize
4844 n = data.readInt32();
4845 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004846 case 1:
4847 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4848 break;
4849 case 2:
4850 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4851 break;
4852 case 3:
4853 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4854 break;
4855 default:
4856 mDaltonizer.setType(ColorBlindnessType::None);
4857 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004858 }
4859 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004860 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004861 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004862 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004863 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004864
4865 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004866 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004867 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004868 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004869 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004870 // apply a color matrix
4871 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004872 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004873 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004874 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004875 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004876 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004877 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004878 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004879 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004880 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004881 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004882
4883 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4884 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004885 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004886 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4887 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4888 }
4889
Chia-I Wu28f320b2018-05-03 11:02:56 -07004890 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004891 return NO_ERROR;
4892 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004893 // This is an experimental interface
4894 // Needs to be shifted to proper binder interface when we productize
4895 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004896 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07004897 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004898 return NO_ERROR;
4899 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004900 case 1017: {
4901 n = data.readInt32();
4902 mForceFullDamage = static_cast<bool>(n);
4903 return NO_ERROR;
4904 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004905 case 1018: { // Modify Choreographer's phase offset
4906 n = data.readInt32();
4907 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4908 return NO_ERROR;
4909 }
4910 case 1019: { // Modify SurfaceFlinger's phase offset
4911 n = data.readInt32();
4912 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4913 return NO_ERROR;
4914 }
Irvel468051e2016-06-13 16:44:44 -07004915 case 1020: { // Layer updates interceptor
4916 n = data.readInt32();
4917 if (n) {
4918 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004919 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004920 }
4921 else{
4922 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004923 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004924 }
4925 return NO_ERROR;
4926 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004927 case 1021: { // Disable HWC virtual displays
4928 n = data.readInt32();
4929 mUseHwcVirtualDisplays = !n;
4930 return NO_ERROR;
4931 }
Romain Guy0147a172017-06-01 13:53:56 -07004932 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004933 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004934 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004935
Chia-I Wu28f320b2018-05-03 11:02:56 -07004936 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004937 return NO_ERROR;
4938 }
Romain Guy54f154a2017-10-24 21:40:32 +01004939 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004940 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004941 invalidateHwcGeometry();
4942 repaintEverything();
4943 return NO_ERROR;
4944 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004945 // TODO(b/111505327): Find out whether the usage of 1024 can switch to 1030,
4946 // deprecate 1024 if they can.
4947 case 1024: { // Does device have wide color gamut display?
Romain Guy54f154a2017-10-24 21:40:32 +01004948 reply->writeBool(hasWideColorDisplay);
4949 return NO_ERROR;
4950 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004951 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004952 n = data.readInt32();
4953 if (n) {
4954 ALOGV("LayerTracing enabled");
4955 mTracing.enable();
4956 doTracing("tracing.enable");
4957 reply->writeInt32(NO_ERROR);
4958 } else {
4959 ALOGV("LayerTracing disabled");
4960 status_t err = mTracing.disable();
4961 reply->writeInt32(err);
4962 }
4963 return NO_ERROR;
4964 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004965 case 1026: { // Get layer tracing status
4966 reply->writeBool(mTracing.isEnabled());
4967 return NO_ERROR;
4968 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004969 // Is a DisplayColorSetting supported?
4970 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004971 const auto display = getDefaultDisplayDevice();
4972 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004973 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004974 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004975
4976 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4977 switch (setting) {
4978 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07004979 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004980 break;
4981 case DisplayColorSetting::UNMANAGED:
4982 reply->writeBool(true);
4983 break;
4984 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004985 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004986 break;
4987 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004988 reply->writeBool(
4989 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004990 break;
4991 }
4992 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004993 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004994 // Is VrFlinger active?
4995 case 1028: {
4996 Mutex::Autolock _l(mStateLock);
4997 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4998 return NO_ERROR;
4999 }
David Sodman6d46c1e2018-07-13 12:59:48 -07005000 case 1029: {
5001 // Code 1029 is an experimental feature that allows applications to
5002 // simulate a high frequency panel by setting a multiplier and divisor
5003 // on the VSYNC-sf clock. If either the multiplier or divisor are
David Sodman44b5de02018-08-21 16:28:53 -07005004 // 0, then the code simply return the current multiplier and divisor.
5005 HWC2::Device::FrequencyScaler frequencyScaler;
5006 frequencyScaler.multiplier = data.readInt32();
5007 frequencyScaler.divisor = data.readInt32();
David Sodman6d46c1e2018-07-13 12:59:48 -07005008
David Sodman44b5de02018-08-21 16:28:53 -07005009 if ((frequencyScaler.multiplier == 0) || (frequencyScaler.divisor == 0)) {
5010 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5011 reply->writeInt32(frequencyScaler.multiplier);
5012 reply->writeInt32(frequencyScaler.divisor);
5013 return NO_ERROR;
David Sodman6d46c1e2018-07-13 12:59:48 -07005014 }
5015
David Sodman44b5de02018-08-21 16:28:53 -07005016 if ((frequencyScaler.multiplier == 1) && (frequencyScaler.divisor == 1)) {
David Sodman6d46c1e2018-07-13 12:59:48 -07005017 enableHardwareVsync();
5018 } else {
5019 disableHardwareVsync(true);
5020 }
David Sodman44b5de02018-08-21 16:28:53 -07005021 mPrimaryDispSync->scalePeriod(frequencyScaler);
5022 getBE().mHwc->setDisplayFrequencyScaleParameters(frequencyScaler);
David Sodman6d46c1e2018-07-13 12:59:48 -07005023
David Sodman44b5de02018-08-21 16:28:53 -07005024 ATRACE_INT("PeriodMultiplier", frequencyScaler.multiplier);
5025 ATRACE_INT("PeriodDivisor", frequencyScaler.divisor);
5026
5027 const hwc2_display_t hwcDisplayId = getBE().mHwc->getActiveConfig(
5028 DisplayDevice::DISPLAY_PRIMARY)->getDisplayId();
5029
5030 onHotplugReceived(getBE().mComposerSequenceId,
5031 hwcDisplayId, HWC2::Connection::Disconnected);
5032 onHotplugReceived(getBE().mComposerSequenceId,
5033 hwcDisplayId, HWC2::Connection::Connected);
5034 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5035 reply->writeInt32(frequencyScaler.multiplier);
5036 reply->writeInt32(frequencyScaler.divisor);
5037
David Sodman6d46c1e2018-07-13 12:59:48 -07005038 return NO_ERROR;
5039 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005040 // Is device color managed?
5041 case 1030: {
5042 reply->writeBool(useColorManagement);
5043 return NO_ERROR;
5044 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005045 }
5046 }
5047 return err;
5048}
5049
Steven Thomas6d8110b2017-08-31 18:24:21 -07005050void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07005051 android_atomic_or(1, &mRepaintEverything);
5052 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005053}
5054
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005055// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5056class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005057public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005058 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5059 ~WindowDisconnector() {
5060 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005061 }
5062
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005063private:
5064 ANativeWindow* mWindow;
5065 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005066};
5067
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005068status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
5069 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
5070 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
5071 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005072 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005073 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005074
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005075 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005076
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005077 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5078
Chia-I Wu20261cb2018-08-23 12:55:44 -07005079 sp<DisplayDevice> display;
5080 {
5081 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005082
Chia-I Wu20261cb2018-08-23 12:55:44 -07005083 display = getDisplayDeviceLocked(displayToken);
5084 if (!display) return BAD_VALUE;
5085
5086 const Rect& dispScissor = display->getScissor();
5087 if (!dispScissor.isEmpty()) {
5088 sourceCrop.set(dispScissor);
5089 // adb shell screencap will default reqWidth and reqHeight to zeros.
5090 if (reqWidth == 0 || reqHeight == 0) {
5091 reqWidth = uint32_t(display->getViewport().width());
5092 reqHeight = uint32_t(display->getViewport().height());
5093 }
5094 }
5095
5096 // get screen geometry
5097 uint32_t width = display->getWidth();
5098 uint32_t height = display->getHeight();
5099
5100 if (renderAreaRotation & ui::Transform::ROT_90) {
5101 std::swap(width, height);
5102 }
5103
5104 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5105 std::swap(width, height);
5106 }
5107
5108 if ((reqWidth > width) || (reqHeight > height)) {
5109 ALOGE("size mismatch (%d, %d) > (%d, %d)", reqWidth, reqHeight, width, height);
5110 } else {
5111 if (reqWidth == 0) {
5112 reqWidth = width;
5113 }
5114 if (reqHeight == 0) {
5115 reqHeight = height;
5116 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005117 }
5118 }
5119
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005120 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005121
5122 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005123 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005124 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005125}
5126
5127status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08005128 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005129 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005130 ATRACE_CALL();
5131
5132 class LayerRenderArea : public RenderArea {
5133 public:
Robert Carr578038f2018-03-09 12:25:24 -08005134 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
5135 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
Chia-I Wu9d1abea2018-08-23 13:44:43 -07005136 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08005137 mLayer(layer),
5138 mCrop(crop),
5139 mFlinger(flinger),
5140 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005141 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005142 Rect getBounds() const override {
5143 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005144 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005145 }
Marissa Wall61c58622018-07-18 10:12:20 -07005146 int getHeight() const override {
5147 return mLayer->getActiveHeight(mLayer->getDrawingState());
5148 }
5149 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005150 bool isSecure() const override { return false; }
5151 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005152 Rect getSourceCrop() const override {
5153 if (mCrop.isEmpty()) {
5154 return getBounds();
5155 } else {
5156 return mCrop;
5157 }
5158 }
Robert Carr578038f2018-03-09 12:25:24 -08005159 class ReparentForDrawing {
5160 public:
5161 const sp<Layer>& oldParent;
5162 const sp<Layer>& newParent;
5163
5164 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5165 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005166 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005167 }
Robert Carr15eae092018-03-23 13:43:53 -07005168 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005169 };
5170
5171 void render(std::function<void()> drawLayers) override {
5172 if (!mChildrenOnly) {
5173 mTransform = mLayer->getTransform().inverse();
5174 drawLayers();
5175 } else {
5176 Rect bounds = getBounds();
5177 screenshotParentLayer =
5178 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
5179 bounds.getWidth(), bounds.getHeight(), 0);
5180
5181 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5182 drawLayers();
5183 }
5184 }
chaviwa76b2712017-09-20 12:02:26 -07005185
chaviwa76b2712017-09-20 12:02:26 -07005186 private:
chaviw7206d492017-11-10 16:16:12 -08005187 const sp<Layer> mLayer;
5188 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005189
5190 // In the "childrenOnly" case we reparent the children to a screenshot
5191 // layer which has no properties set and which does not draw.
5192 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005193 ui::Transform mTransform;
Robert Carr578038f2018-03-09 12:25:24 -08005194
5195 SurfaceFlinger* mFlinger;
5196 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005197 };
5198
5199 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5200 auto parent = layerHandle->owner.promote();
5201
chaviw7206d492017-11-10 16:16:12 -08005202 if (parent == nullptr || parent->isPendingRemoval()) {
5203 ALOGE("captureLayers called with a removed parent");
5204 return NAME_NOT_FOUND;
5205 }
5206
Robert Carr578038f2018-03-09 12:25:24 -08005207 const int uid = IPCThreadState::self()->getCallingUid();
5208 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5209 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5210 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5211 return PERMISSION_DENIED;
5212 }
5213
chaviw7206d492017-11-10 16:16:12 -08005214 Rect crop(sourceCrop);
5215 if (sourceCrop.width() <= 0) {
5216 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005217 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005218 }
5219
5220 if (sourceCrop.height() <= 0) {
5221 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005222 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005223 }
5224
5225 int32_t reqWidth = crop.width() * frameScale;
5226 int32_t reqHeight = crop.height() * frameScale;
5227
Chia-I Wu20261cb2018-08-23 12:55:44 -07005228 // really small crop or frameScale
5229 if (reqWidth <= 0) {
5230 reqWidth = 1;
5231 }
5232 if (reqHeight <= 0) {
5233 reqHeight = 1;
5234 }
5235
Robert Carr578038f2018-03-09 12:25:24 -08005236 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005237
Robert Carr578038f2018-03-09 12:25:24 -08005238 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005239 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5240 if (!layer->isVisible()) {
5241 return;
Robert Carr578038f2018-03-09 12:25:24 -08005242 } else if (childrenOnly && layer == parent.get()) {
5243 return;
chaviwa76b2712017-09-20 12:02:26 -07005244 }
5245 visitor(layer);
5246 });
5247 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005248 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005249}
5250
5251status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5252 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005253 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005254 bool useIdentityTransform) {
5255 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005256
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005257 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5258 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5259 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5260 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005261
5262 // This mutex protects syncFd and captureResult for communication of the return values from the
5263 // main thread back to this Binder thread
5264 std::mutex captureMutex;
5265 std::condition_variable captureCondition;
5266 std::unique_lock<std::mutex> captureLock(captureMutex);
5267 int syncFd = -1;
5268 std::optional<status_t> captureResult;
5269
Robert Carr03480e22018-01-04 16:02:06 -08005270 const int uid = IPCThreadState::self()->getCallingUid();
5271 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5272
Dominik Laskowski8c001672018-05-30 16:52:06 -07005273 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005274 // If there is a refresh pending, bug out early and tell the binder thread to try again
5275 // after the refresh.
5276 if (mRefreshPending) {
5277 ATRACE_NAME("Skipping screenshot for now");
5278 std::unique_lock<std::mutex> captureLock(captureMutex);
5279 captureResult = std::make_optional<status_t>(EAGAIN);
5280 captureCondition.notify_one();
5281 return;
5282 }
5283
5284 status_t result = NO_ERROR;
5285 int fd = -1;
5286 {
5287 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005288 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005289 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5290 useIdentityTransform, forSystem, &fd);
5291 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005292 }
5293
5294 {
5295 std::unique_lock<std::mutex> captureLock(captureMutex);
5296 syncFd = fd;
5297 captureResult = std::make_optional<status_t>(result);
5298 captureCondition.notify_one();
5299 }
5300 });
5301
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005302 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005303 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005304 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005305 while (*captureResult == EAGAIN) {
5306 captureResult.reset();
5307 result = postMessageAsync(message);
5308 if (result != NO_ERROR) {
5309 return result;
5310 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005311 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005312 }
5313 result = *captureResult;
5314 }
5315
5316 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005317 sync_wait(syncFd, -1);
5318 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005319 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005320
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005321 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005322}
5323
chaviwa76b2712017-09-20 12:02:26 -07005324void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5325 TraverseLayersFunction traverseLayers, bool yswap,
5326 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005327 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005328
Lloyd Pique144e1162017-12-20 16:44:52 -08005329 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005330
5331 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005332 const auto raWidth = renderArea.getWidth();
5333 const auto raHeight = renderArea.getHeight();
5334
5335 const auto reqWidth = renderArea.getReqWidth();
5336 const auto reqHeight = renderArea.getReqHeight();
5337 Rect sourceCrop = renderArea.getSourceCrop();
5338
Iris Chang7501ed62018-04-30 14:45:42 +08005339 bool filtering = false;
5340 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5341 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5342 static_cast<int32_t>(reqHeight) != raWidth;
5343 } else {
5344 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5345 static_cast<int32_t>(reqHeight) != raHeight;
5346 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005347
Dan Stozac1879002014-05-22 15:59:05 -07005348 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005349 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005350 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005351 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005352 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
Peiyong Linefefaac2018-08-17 12:27:51 -07005353 ui::Transform tr;
Iris Chang7501ed62018-04-30 14:45:42 +08005354 uint32_t flags = 0x00;
5355 switch (mPrimaryDisplayOrientation) {
5356 case DisplayState::eOrientation90:
Peiyong Linefefaac2018-08-17 12:27:51 -07005357 flags = ui::Transform::ROT_90;
Iris Chang7501ed62018-04-30 14:45:42 +08005358 break;
5359 case DisplayState::eOrientation180:
Peiyong Linefefaac2018-08-17 12:27:51 -07005360 flags = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005361 break;
5362 case DisplayState::eOrientation270:
Peiyong Linefefaac2018-08-17 12:27:51 -07005363 flags = ui::Transform::ROT_270;
Iris Chang7501ed62018-04-30 14:45:42 +08005364 break;
5365 }
5366 tr.set(flags, raWidth, raHeight);
5367 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005368 }
5369
5370 // ensure that sourceCrop is inside screen
5371 if (sourceCrop.left < 0) {
5372 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5373 }
chaviwa76b2712017-09-20 12:02:26 -07005374 if (sourceCrop.right > raWidth) {
5375 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005376 }
5377 if (sourceCrop.top < 0) {
5378 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5379 }
chaviwa76b2712017-09-20 12:02:26 -07005380 if (sourceCrop.bottom > raHeight) {
5381 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005382 }
5383
Chia-I Wu36574d92018-05-16 10:54:36 -07005384 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5385 engine.setOutputDataSpace(Dataspace::SRGB);
5386 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005387
Mathias Agopian180f10d2013-04-10 22:55:41 -07005388 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005389 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005390
Peiyong Linefefaac2018-08-17 12:27:51 -07005391 ui::Transform::orientation_flags rotation = renderArea.getRotationFlags();
Iris Chang7501ed62018-04-30 14:45:42 +08005392 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5393 // convert hw orientation into flag presentation
5394 // here inverse transform needed
5395 uint8_t hw_rot_90 = 0x00;
5396 uint8_t hw_flip_hv = 0x00;
5397 switch (mPrimaryDisplayOrientation) {
5398 case DisplayState::eOrientation90:
Peiyong Linefefaac2018-08-17 12:27:51 -07005399 hw_rot_90 = ui::Transform::ROT_90;
5400 hw_flip_hv = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005401 break;
5402 case DisplayState::eOrientation180:
Peiyong Linefefaac2018-08-17 12:27:51 -07005403 hw_flip_hv = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005404 break;
5405 case DisplayState::eOrientation270:
Peiyong Linefefaac2018-08-17 12:27:51 -07005406 hw_rot_90 = ui::Transform::ROT_90;
Iris Chang7501ed62018-04-30 14:45:42 +08005407 break;
5408 }
5409
5410 // transform flags operation
5411 // 1) flip H V if both have ROT_90 flag
5412 // 2) XOR these flags
Peiyong Linefefaac2018-08-17 12:27:51 -07005413 uint8_t rotation_rot_90 = rotation & ui::Transform::ROT_90;
5414 uint8_t rotation_flip_hv = rotation & ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005415 if (rotation_rot_90 & hw_rot_90) {
Peiyong Linefefaac2018-08-17 12:27:51 -07005416 rotation_flip_hv = (~rotation_flip_hv) & ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005417 }
Peiyong Linefefaac2018-08-17 12:27:51 -07005418 rotation = static_cast<ui::Transform::orientation_flags>
Iris Chang7501ed62018-04-30 14:45:42 +08005419 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5420 }
5421
Mathias Agopian180f10d2013-04-10 22:55:41 -07005422 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005423 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005424 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005425 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005426
chaviw50da5042018-04-09 13:49:37 -07005427 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005428 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005429 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005430
chaviwa76b2712017-09-20 12:02:26 -07005431 traverseLayers([&](Layer* layer) {
5432 if (filtering) layer->setFiltering(true);
David Sodmanfb95bcc2017-12-22 15:45:30 -08005433 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005434 if (filtering) layer->setFiltering(false);
5435 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005436}
5437
chaviwa76b2712017-09-20 12:02:26 -07005438status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5439 TraverseLayersFunction traverseLayers,
5440 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005441 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005442 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005443 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005444 ATRACE_CALL();
5445
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005446 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005447
5448 traverseLayers([&](Layer* layer) {
5449 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5450 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005451
Robert Carr03480e22018-01-04 16:02:06 -08005452 // We allow the system server to take screenshots of secure layers for
5453 // use in situations like the Screen-rotation animation and place
5454 // the impetus on WindowManager to not persist them.
5455 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005456 ALOGW("FB is protected: PERMISSION_DENIED");
5457 return PERMISSION_DENIED;
5458 }
5459
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005460 // this binds the given EGLImage as a framebuffer for the
5461 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005462 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005463 if (bufferBond.getStatus() != NO_ERROR) {
5464 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005465 return INVALID_OPERATION;
5466 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005467
Dan Stozaabcda352017-06-01 14:37:39 -07005468 // this will in fact render into our dequeued buffer
5469 // via an FBO, which means we didn't have to create
5470 // an EGLSurface and therefore we're not
5471 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005472 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005473
Dan Stozaabcda352017-06-01 14:37:39 -07005474 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005475 getRenderEngine().finish();
5476 *outSyncFd = -1;
5477
chaviwa76b2712017-09-20 12:02:26 -07005478 const auto reqWidth = renderArea.getReqWidth();
5479 const auto reqHeight = renderArea.getReqHeight();
5480
Dan Stozaabcda352017-06-01 14:37:39 -07005481 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5482 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005483 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005484 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005485 } else {
5486 base::unique_fd syncFd = getRenderEngine().flush();
5487 if (syncFd < 0) {
5488 getRenderEngine().finish();
5489 }
5490 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005491 }
5492
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005493 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005494}
5495
Mathias Agopiand5556842013-09-19 17:08:37 -07005496void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005497 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005498 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005499 for (size_t y = 0; y < h; y++) {
5500 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5501 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005502 if (p[x] != 0xFF000000) return;
5503 }
5504 }
chaviwa76b2712017-09-20 12:02:26 -07005505 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005506
Robert Carr2047fae2016-11-28 14:09:09 -08005507 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005508 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005509 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005510 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5511 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5512 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5513 static_cast<float>(state.color.a));
5514 i++;
5515 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005516 }
5517}
5518
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005519// ---------------------------------------------------------------------------
5520
Dan Stoza412903f2017-04-27 13:42:17 -07005521void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5522 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005523}
5524
Dan Stoza412903f2017-04-27 13:42:17 -07005525void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5526 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005527}
5528
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005529void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5530 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005531 const LayerVector::Visitor& visitor) {
5532 // We loop through the first level of layers without traversing,
5533 // as we need to interpret min/max layer Z in the top level Z space.
5534 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005535 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005536 continue;
5537 }
5538 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005539 // relative layers are traversed in Layer::traverseInZOrder
5540 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005541 continue;
5542 }
5543 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005544 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005545 return;
5546 }
chaviwa76b2712017-09-20 12:02:26 -07005547 if (!layer->isVisible()) {
5548 return;
5549 }
5550 visitor(layer);
5551 });
5552 }
5553}
5554
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005555}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005556
Lloyd Pique074e8122018-07-26 12:57:23 -07005557
Mathias Agopian3f844832013-08-07 21:24:32 -07005558#if defined(__gl_h_)
5559#error "don't include gl/gl.h in this file"
5560#endif
5561
5562#if defined(__gl2_h_)
5563#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005564#endif